Datasets:
AI4M
/

text
stringlengths
0
3.34M
/*****************************************************************************/ /* Solvers for the Least squares problem min_x || B - A*x || */ /*****************************************************************************/ #include <lah.h> /* lah_solveLS * ------------ * Solves the least squares problem by applying the Lapack routine gels * which uses QR or LQ factorization. * Params: - A, B, X: Matrices of the LS problem min_x || B - A*x || */ #ifdef HAVE_LAPACK /* Use a LAPACK package to do the heavy work */ #include <lapacke.h> lah_Return lah_solveLS(koop_mat *A, *B, *X) { lah result = 0; gels('N', A->nR, A->nC, NRHS, A->data, LDA, B, LDB, WORK, LWORK, result); /* Alternative: used for ill conditioned problems * ca. 5 times slower. Could check residuum output to determine which precision to use*/ /* gelsd () */ return result; } #endif
[STATEMENT] lemma oth_class_taut_3_b[PLM]: "[(\<phi> \<^bold>& \<psi>) \<^bold>\<equiv> (\<psi> \<^bold>& \<phi>) in v]" [PROOF STATE] proof (prove) goal (1 subgoal): 1. [\<phi> \<^bold>& \<psi> \<^bold>\<equiv> \<psi> \<^bold>& \<phi> in v] [PROOF STEP] by PLM_solver
lemma cCons_append_Cons_eq [simp]: "x ## xs @ y # ys = x # xs @ y # ys"
SUBROUTINE ANALYTIC & (N, T, PAR, X, W) C --------------------------------------------------------------------------- C Computes an analytic solution to Laplace's equation in the grid C points given by X and stores it in the workspace W. C The kind of analytic solution is determined by the parameter C ANL_TYPE, which is a common block variable in the file anl_params.inc C The analytic solution is stored in the workspace W as follows: C C W (1:N, 1) : PHI C W (1:N, 2) : PHI_T C W (1:N, 3) : PHI_X C W (1:N, 4) : PHI_Z C W (1:N, 5) : PHI_XX C W (1:N, 6) : PHI_XZ C C Due to Laplace's equation we have PHI_XX + PHI_ZZ = 0, so PHI_ZZ C is given implicitly as -PHI_XX C C --------------------------------------------------------------------------- IMPLICIT NONE INCLUDE 'knd_params.inc' INCLUDE 'anl_params.inc' C INTEGER(KIND=IK) N ! Nr. of grid points (IN) REAL (KIND=RK) T ! Time (IN) REAL (KIND=RK) PAR (*) REAL (KIND=RK) X (4, *) ! coordinates of grid points (IN) REAL (KIND=RK) W (*) ! workspace, which will contain ! the analytic solution (OUT) C CHARACTER*35 MSG C IF (ANL_TYPE .EQ. ANL_LINWAVE) THEN CALL LINWAVE & (N, T, PAR, X, W) ELSE IF (ANL_TYPE .EQ. ANL_RFWAVE) THEN CALL RFWAVE & (N, T, PAR, X, W) ELSE IF (ANL_TYPE .EQ. ANL_POLYNOMIAL) THEN CALL POLYNOMIAL & (N, T, PAR, X, W) ELSE IF (ANL_TYPE .EQ. ANL_WAVEMAKER) THEN CALL WAVEMAKER & (N, T, PAR, X, W) ELSE IF (ANL_TYPE .EQ. ANL_PISTON) THEN CALL PISTON_WAVEMAKER & (N, T, PAR, X, W) ELSE IF (ANL_TYPE .EQ. ANL_NOTAVAIL) THEN C THERE'S NO KNOWN SOLUTION, SO W <- 0 CALL NOTAVAIL & (N, W) ELSE WRITE (MSG,'(A,I3)') & 'Analytic solution not implemented:', ANL_TYPE CALL ERROR ('ANALYTIC', MSG) END IF C RETURN END SUBROUTINE NOTAVAIL & (N, ANL) C --------------------------------------------------------------------------- C analytic solution : PHI = 0 C C ANL (1:N, 1) : PHI C ANL (1:N, 2) : PHI_T C ANL (1:N, 3) : PHI_X C ANL (1:N, 4) : PHI_Z C ANL (1:N, 5) : PHI_XX (PHI_ZZ == -PHI_XX, due to Laplace's eqn) C ANL (1:N, 6) : PHI_XZ C --------------------------------------------------------------------------- IMPLICIT NONE INCLUDE 'knd_params.inc' C INTEGER(KIND=IK) N ! Nr. of grid points (IN) REAL (KIND=RK) ANL (N, *) ! Analytic solution (OUT) C INTEGER(KIND=IK) I, J C DO J = 1, 6 DO I = 1, N ANL (I, J) = 0.0D0 END DO END DO C RETURN END SUBROUTINE LINWAVE & (N, T, ANL_PAR, CRD, ANL) C --------------------------------------------------------------------------- C Analytic solution: Linear wave C C A W COSH (K (Z + H)) C PHI = ---- ---------------- * SIN (K (X - X0) - W T) C K SINH (K H) C C A : Wave amplitude [m.] C K : wave number [1/m.] C W : Wave frequency [rad/s.] C H : Water depth [m.] C X0: Wave crest offset [m.] C C ANL (1:N, 1) : PHI C ANL (1:N, 2) : PHI_T C ANL (1:N, 3) : PHI_X C ANL (1:N, 4) : PHI_Z C ANL (1:N, 5) : PHI_XX C ANL (1:N, 6) : PHI_XZ C --------------------------------------------------------------------------- IMPLICIT NONE INCLUDE 'knd_params.inc' INCLUDE 'rle_params.inc' C INTEGER(KIND=IK) N ! Nr. of grid points (IN) REAL (KIND=RK) T ! Time (IN) REAL (KIND=RK) ANL_PAR (*) REAL (KIND=RK) CRD (4, *) ! Grid point coordinates (IN) REAL (KIND=RK) ANL (N, *) ! Analytic solution (OUT) C INTEGER(KIND=IK) I REAL (KIND=RK) A, L, H, X0, K, W REAL (KIND=RK) X, Z, SX, CX, SHZ, CHZ, SHKH, KH, WT, AW C A = ANL_PAR (1) L = ANL_PAR (2) H = ANL_PAR (3) X0 = ANL_PAR (4) C K = TWO_PI / L KH = K * H W = SQRT (Grav * K * TANH (KH)) WT = W * T AW = A * W SHKH = SINH (KH) C DO I = 1, N X = CRD (1, I) - X0 Z = CRD (2, I) SX = SIN (K * X - WT) CX = COS (K * X - WT) SHZ = SINH (K * Z + KH) / SHKH CHZ = COSH (K * Z + KH) / SHKH ANL (I, 1) = AW / K * CHZ * SX ANL (I, 2) = -AW / K * CHZ * CX * W ANL (I, 3) = AW * CHZ * CX ANL (I, 4) = AW * SHZ * SX ANL (I, 5) = -AW * K * CHZ * SX ANL (I, 6) = AW * K * SHZ * CX ANL (I, 7) = A * CX END DO C RETURN END SUBROUTINE RFWAVE & (N, T, ANL_PAR, CRD, ANL) C --------------------------------------------------------------------------- C Analytic solution: Rienecker & Fenton type of wave C C __ N C \ COSH (J K (Z + H)) C PHI = / B ---------------- * SIN (J K (X - X0 - C T)) C -- J COSH (J K H) C J = 1 2 C + (C + B) (X - X0) - (G (R - H) - 1/2 C ) T C 0 C C K : wave number [1/m] C W : Wave frequency [rad/s] C C : Wave phace velocity [m/s] C H : Water depth [m] C X0: Wave crest offset [m] C B : J-th Fourier component [-] C J C G : Gravitational accel. [m/s^2] C R : R&F constant [m] C C ANL (1:N, 1) : PHI C ANL (1:N, 2) : PHI_T C ANL (1:N, 3) : PHI_X C ANL (1:N, 4) : PHI_Z C ANL (1:N, 5) : PHI_XX C ANL (1:N, 6) : PHI_XZ C --------------------------------------------------------------------------- IMPLICIT NONE INCLUDE 'knd_params.inc' INCLUDE 'rle_params.inc' C INTEGER(KIND=IK) N ! Nr. of grid points (IN) REAL (KIND=RK) T ! Time (IN) REAL (KIND=RK) ANL_PAR (*) REAL (KIND=RK) CRD (4, *) ! Grid point coordinates (IN) REAL (KIND=RK) ANL (N, *) ! Analytic solution (OUT) C INTEGER(KIND=IK) I, J, NRF REAL (KIND=RK) L, H, X0, W, K, K2, R, B, B_0, C REAL (KIND=RK) X, Z, AA, SX, CX, SHZ, CHZ, KXT, KZH C L = ANL_PAR (2) H = ANL_PAR (3) X0 = ANL_PAR (4) W = ANL_PAR (5) K = ANL_PAR (6) K2 = K ** 2 C = W / K R = ANL_PAR (7) NRF = INT (ANL_PAR (8)) B = -(GRAV * (R - H) - 0.5D0 * C ** 2) B_0 = ANL_PAR (34) C DO I = 1, N X = CRD (1, I) - X0 Z = CRD (2, I) KXT = K * X - W * T KZH = K * (Z + H) ANL (I, 1) = 0.0D0 ANL (I, 2) = 0.0D0 ANL (I, 3) = 0.0D0 ANL (I, 4) = 0.0D0 ANL (I, 5) = 0.0D0 ANL (I, 6) = 0.0D0 ANL (I, 7) = 0.0D0 DO J = 1, NRF AA = ANL_PAR (J + 34) / COSH (J * K * H) SX = SIN (J * KXT) CX = COS (J * KXT) SHZ = SINH (J * KZH) * AA CHZ = COSH (J * KZH) * AA ANL (I, 1) = ANL (I, 1) + CHZ * SX ANL (I, 3) = ANL (I, 3) + CHZ * CX * J ANL (I, 4) = ANL (I, 4) + SHZ * SX * J ANL (I, 5) = ANL (I, 5) - CHZ * SX * J ** 2 ANL (I, 6) = ANL (I, 6) + SHZ * CX * J ** 2 ANL (I, 7) = ANL (I, 7) + ANL_PAR (J + 67) * CX END DO C NOTE: for all cases we'll be calculating, the constant C C + B_0 will be exactly 0 ANL (I, 1) = ANL (I, 1) + (C + B_0) * X + B * T ANL (I, 2) = -W * ANL (I, 3) + B ANL (I, 3) = K * ANL (I, 3) + (C + B_0) ANL (I, 4) = K * ANL (I, 4) ANL (I, 5) = K2 * ANL (I, 5) ANL (I, 6) = K2 * ANL (I, 6) END DO C RETURN END SUBROUTINE POLYNOMIAL & (N, T, ANL_PAR, CRD, ANL) C --------------------------------------------------------------------------- C Analytic solution : Polynomial C C 4 C __ C \ K C PHI = / Re (A (X + I * Z) ) + A * T C -- K 5 C K = 1 C C where Re means the real part C C ANL (1:N, 1) : PHI C ANL (1:N, 2) : PHI_T C ANL (1:N, 3) : PHI_X C ANL (1:N, 4) : PHI_Z C ANL (1:N, 5) : PHI_XX C ANL (1:N, 6) : PHI_XZ C --------------------------------------------------------------------------- IMPLICIT NONE INCLUDE 'knd_params.inc' C INTEGER(KIND=IK) N ! Nr. of grid points (IN) REAL (KIND=RK) T ! Time (IN) REAL (KIND=RK) ANL_PAR (*) REAL (KIND=RK) CRD (4, *) ! Grid point coordinates (IN) REAL (KIND=RK) ANL (N, *) ! Analytic solution (OUT) C INTEGER(KIND=IK) I DOUBLE COMPLEX Z, DZ, DDZ, Z1, Z2, Z3, Z4, IZ C IZ = COMPLEX (0.0D0, 1.0D0) C DO I = 1, N Z1 = COMPLEX (CRD (1, I), CRD (2, I)) Z2 = Z1 * Z1 Z3 = Z1 * Z2 Z4 = Z2 * Z2 Z = ANL_PAR (1) * Z1 & + ANL_PAR (2) * Z2 & + ANL_PAR (3) * Z3 & + ANL_PAR (4) * Z4 & + ANL_PAR (5) * T ** 3 DZ = ANL_PAR (1) & + ANL_PAR (2) * Z1 * 2.0D0 & + ANL_PAR (3) * Z2 * 3.0D0 & + ANL_PAR (4) * Z3 * 4.0D0 DDZ = ANL_PAR (2) * 2.0D0 & + ANL_PAR (3) * Z1 * 6.0D0 & + ANL_PAR (4) * Z2 * 1.2D1 ANL (I, 1) = DBLE (Z) ANL (I, 2) = 3.0D0 * ANL_PAR (5) ** 2 ANL (I, 3) = DBLE (DZ) ANL (I, 4) = DBLE (DZ * IZ) ANL (I, 5) = DBLE (DDZ) ANL (I, 6) = DBLE (DDZ * IZ) END DO C RETURN END SUBROUTINE WAVEMAKER & (N, T, ANL_PAR, CRD, ANL) C --------------------------------------------------------------------------- C Analytic solution : WAVEMAKER C C ANL (1:N, 1) : PHI C ANL (1:N, 2) : PHI_T C ANL (1:N, 3) : PHI_X C ANL (1:N, 4) : PHI_Z C ANL (1:N, 5) : PHI_XX C ANL (1:N, 6) : PHI_XZ C --------------------------------------------------------------------------- IMPLICIT NONE INCLUDE 'knd_params.inc' INCLUDE 'fle_params.inc' C INTEGER(KIND=IK) N ! Nr. of grid points (IN) REAL (KIND=RK) T ! Time (IN) REAL (KIND=RK) ANL_PAR (17) REAL (KIND=RK) CRD (4, *) ! Grid point coordinates (IN) REAL (KIND=RK) ANL (N, *) ! Analytic solution (OUT) C IF (ANL_PAR (17) .GT. 0.0) THEN CALL INTERP_WVM (N, WVM_IN, T, ANL_PAR, CRD (1, 1), CRD, ANL) WRITE (*, *) 'BEG->', ANL_PAR (1), T, ANL_PAR (2) ELSE CALL INTERP_WVM (N, WVM_IN, T, ANL_PAR, CRD (1, N), CRD, ANL) WRITE (*, *) 'END->', ANL_PAR (1), T, ANL_PAR (2) END IF C RETURN END SUBROUTINE PISTON_WAVEMAKER & (N, T, ANL_PAR, CRD, ANL) C --------------------------------------------------------------------------- C Analytic solution : WAVEMAKER C C ANL (1:N, 1) : PHI C ANL (1:N, 2) : PHI_T C ANL (1:N, 3) : PHI_X C ANL (1:N, 4) : PHI_Z C ANL (1:N, 5) : PHI_XX C ANL (1:N, 6) : PHI_XZ C --------------------------------------------------------------------------- IMPLICIT NONE INCLUDE 'knd_params.inc' INCLUDE 'fle_params.inc' C INTEGER(KIND=IK) N ! Nr. of grid points (IN) REAL (KIND=RK) T ! Time (IN) REAL (KIND=RK) ANL_PAR (17) REAL (KIND=RK) CRD (4, *) ! Grid point coordinates (IN) REAL (KIND=RK) ANL (N, 6) ! Analytic solution (OUT) C REAL (KIND=RK) AMPLITUDE, THETA, FACTOR, S C AMPLITUDE = ANL_PAR (1) THETA = ANL_PAR (2) FACTOR = ANL_PAR (3) IF (ABS (T - FACTOR * THETA) .LT. 1.0D-12) THEN S = T / THETA AMPLITUDE = AMPLITUDE * S * S * (3.0D0 - 2.0D0 * S) END IF ANL = 0.0D0 ANL (:, 3) = AMPLITUDE * SIN (THETA * T) C END SUBROUTINE PISTON_WAVEMAKER
lemma pred_intros_countable[measurable (raw)]: fixes P :: "'a \<Rightarrow> 'i :: countable \<Rightarrow> bool" shows "(\<And>i. pred M (\<lambda>x. P x i)) \<Longrightarrow> pred M (\<lambda>x. \<forall>i. P x i)" "(\<And>i. pred M (\<lambda>x. P x i)) \<Longrightarrow> pred M (\<lambda>x. \<exists>i. P x i)"
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE Strict #-} {-# LANGUAGE FlexibleContexts #-} module CPVO.Numeric ( integrateAll, sumRow, getY0, delta, integrateToZero, integrateAtomicPDOS ) where import Numeric.LinearAlgebra import Data.List (findIndex,groupBy) import Data.Maybe (fromJust) integrateToZero :: Matrix Double -> Double integrateToZero mP = integrateAll 0 $ (++ ([toList $ getY0 $ takeColumns 2 mP])) $ takeWhile (\(a:_) -> a <= 0) $ toLists $ takeColumns 2 mP integrateAll :: Double -> [[Double]] -> Double integrateAll res [] = res integrateAll res ([enA,nA]:b@[enB,nB]:as) | as == [] = integrateAll (res + (enB - enA)*(nA+nB)*0.5) [] | otherwise = integrateAll (res + (enB - enA)*(nA+nB)*0.5) (b:as) integrateAll _ _ = 99 sumRow :: Matrix Double -> Vector Double sumRow a = a #> konst 1 (cols a) getY0 :: Matrix Double -> Vector Double getY0 dos = getY0' lowPos higNeg where rTDOS = toRows $ dos highestNeg = (+) (-1) $ fromJust $ findIndex (\a -> (atIndex a 0) >= 0) rTDOS lowestPos = highestNeg + 1 higNeg = rTDOS !! highestNeg lowPos = rTDOS !! lowestPos getY0' :: Vector Double -> Vector Double -> Vector Double getY0' a b = a + (scale m v) where v = b - a m = ((*) (-1) $ a ! 0) / ((b ! 0) - (a ! 0)) delta :: Bool -> b -> b -> b delta x y z = if x then y else z integrateAtomicPDOS :: [(Matrix Double, (Int, (String, (Int, String))))] -> [(Double, Double, (Int, (String, (Int, String))))] integrateAtomicPDOS pdosAtomicPilihan = (\[us,ds] -> zipWith (\(iu,b) (idown,_) -> (iu,idown,b)) us ds ) $ groupBy (\(_,(s,_)) (_,(s',_)) -> s == s') -- [[(spin,label,iup)]] $ map (\(mp,b) -> (integrateToZero mp,b)) $ pdosAtomicPilihan
//from: "c:\cpp\boost_1_68_0\boost/spirit/home/x3\support\traits\attribute_type.hpp" /*============================================================================= Copyright (c) 2001-2014 Joel de Guzman http://spirit.sourceforge.net/ Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #if !defined(BOOST_SPIRIT_X3_ATTRIBUTE_TYPE_JAN_5_2012_0358PM) #define BOOST_SPIRIT_X3_ATTRIBUTE_TYPE_JAN_5_2012_0358PM #include <boost/mpl/identity.hpp> namespace boost { namespace spirit { namespace x3 { namespace traits { /////////////////////////////////////////////////////////////////////////// // Retrieve the attribute type to use from the given type // // This is needed to extract the correct attribute type from proxy classes // as utilized in FUSION_ADAPT_ADT et. al. /////////////////////////////////////////////////////////////////////////// template <typename Attribute, typename Enable = void> struct attribute_type : mpl::identity<Attribute> {}; }}}} #endif
/- Copyright (c) 2022 Jesse Reimann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jesse Reimann, Kalle KytΓΆlΓ€ -/ import topology.continuous_function.bounded import topology.sets.compacts /-! # Riesz–Markov–Kakutani representation theorem This file will prove different versions of the Riesz-Markov-Kakutani representation theorem. The theorem is first proven for compact spaces, from which the statements about linear functionals on bounded continuous functions or compactly supported functions on locally compact spaces follow. To make use of the existing API, the measure is constructed from a content `Ξ»` on the compact subsets of the space X, rather than the usual construction of open sets in the literature. ## References * [Walter Rudin, Real and Complex Analysis.][Rud87] -/ noncomputable theory open_locale bounded_continuous_function nnreal ennreal open set function topological_space variables {X : Type*} [topological_space X] variables (Ξ› : (X →ᡇ ℝβ‰₯0) β†’β‚—[ℝβ‰₯0] ℝβ‰₯0) /-! ### Construction of the content: -/ /-- Given a positive linear functional Ξ› on X, for `K βŠ† X` compact define `Ξ»(K) = inf {Ξ›f | 1≀f on K}`. When X is a compact Hausdorff space, this will be shown to be a content, and will be shown to agree with the Riesz measure on the compact subsets `K βŠ† X`. -/ def riesz_content_aux : (compacts X) β†’ ℝβ‰₯0 := Ξ» K, Inf (Ξ› '' {f : X →ᡇ ℝβ‰₯0 | βˆ€ x ∈ K, (1 : ℝβ‰₯0) ≀ f x}) section riesz_monotone /-- For any compact subset `K βŠ† X`, there exist some bounded continuous nonnegative functions f on X such that `f β‰₯ 1` on K. -/ lemma riesz_content_aux_image_nonempty (K : compacts X) : (Ξ› '' {f : X →ᡇ ℝβ‰₯0 | βˆ€ x ∈ K, (1 : ℝβ‰₯0) ≀ f x}).nonempty := begin rw nonempty_image_iff, use (1 : X →ᡇ ℝβ‰₯0), intros x x_in_K, simp only [bounded_continuous_function.coe_one, pi.one_apply], end /-- Riesz content Ξ» (associated with a positive linear functional Ξ›) is monotone: if `K₁ βŠ† Kβ‚‚` are compact subsets in X, then `Ξ»(K₁) ≀ Ξ»(Kβ‚‚)`. -/ lemma riesz_content_aux_mono {K₁ Kβ‚‚ : compacts X} (h : K₁ ≀ Kβ‚‚) : riesz_content_aux Ξ› K₁ ≀ riesz_content_aux Ξ› Kβ‚‚ := cInf_le_cInf (order_bot.bdd_below _) (riesz_content_aux_image_nonempty Ξ› Kβ‚‚) (image_subset Ξ› (set_of_subset_set_of.mpr (Ξ» f f_hyp x x_in_K₁, f_hyp x (h x_in_K₁)))) end riesz_monotone section riesz_subadditive /-- Any bounded continuous nonnegative f such that `f β‰₯ 1` on K gives an upper bound on the content of K; namely `Ξ»(K) ≀ Ξ› f`. -/ lemma riesz_content_aux_le {K : compacts X} {f : X →ᡇ ℝβ‰₯0} (h : βˆ€ x ∈ K, (1 : ℝβ‰₯0) ≀ f x) : riesz_content_aux Ξ› K ≀ Ξ› f := cInf_le (order_bot.bdd_below _) ⟨f, ⟨h, rfl⟩⟩ /-- The Riesz content can be approximated arbitrarily well by evaluating the positive linear functional on test functions: for any `Ξ΅ > 0`, there exists a bounded continuous nonnegative function f on X such that `f β‰₯ 1` on K and such that `Ξ»(K) ≀ Ξ› f < Ξ»(K) + Ξ΅`. -/ lemma exists_lt_riesz_content_aux_add_pos (K : compacts X) {Ξ΅ : ℝβ‰₯0} (Ξ΅pos : 0 < Ξ΅) : βˆƒ (f : X →ᡇ ℝβ‰₯0), (βˆ€ x ∈ K, (1 : ℝβ‰₯0) ≀ f x) ∧ Ξ› f < riesz_content_aux Ξ› K + Ξ΅ := begin --choose a test function `f` s.t. `Ξ›f = Ξ± < Ξ»(K) + Ξ΅` obtain ⟨α, ⟨⟨f, f_hyp⟩, Ξ±_hyp⟩⟩ := exists_lt_of_cInf_lt (riesz_content_aux_image_nonempty Ξ› K) (lt_add_of_pos_right (riesz_content_aux Ξ› K) Ξ΅pos), refine ⟨f, f_hyp.left, _ ⟩, rw f_hyp.right, exact Ξ±_hyp, end /-- The Riesz content Ξ» associated to a given positive linear functional Ξ› is finitely subadditive: `Ξ»(K₁ βˆͺ Kβ‚‚) ≀ Ξ»(K₁) + Ξ»(Kβ‚‚)` for any compact subsets `K₁, Kβ‚‚ βŠ† X`. -/ lemma riesz_content_aux_sup_le (K1 K2 : compacts X) : riesz_content_aux Ξ› (K1 βŠ” K2) ≀ riesz_content_aux Ξ› (K1) + riesz_content_aux Ξ› (K2) := begin apply nnreal.le_of_forall_pos_le_add, intros Ξ΅ Ξ΅pos, --get test functions s.t. `Ξ»(Ki) ≀ Ξ›fi ≀ Ξ»(Ki) + Ξ΅/2, i=1,2` obtain ⟨f1, f_test_function_K1⟩ := exists_lt_riesz_content_aux_add_pos Ξ› K1 (half_pos Ξ΅pos), obtain ⟨f2, f_test_function_K2⟩ := exists_lt_riesz_content_aux_add_pos Ξ› K2 (half_pos Ξ΅pos), --let `f := f1 + f2` test function for the content of `K` have f_test_function_union : (βˆ€ x ∈ (K1 βŠ” K2), (1 : ℝβ‰₯0) ≀ (f1 + f2) x), { rintros x (x_in_K1 | x_in_K2), { exact le_add_right (f_test_function_K1.left x x_in_K1) }, { exact le_add_left (f_test_function_K2.left x x_in_K2) }}, --use that `Ξ›f` is an upper bound for `Ξ»(K1βŠ”K2)` apply (riesz_content_aux_le Ξ› f_test_function_union).trans (le_of_lt _), rw map_add, --use that `Ξ›fi` are lower bounds for `Ξ»(Ki) + Ξ΅/2` apply lt_of_lt_of_le (add_lt_add f_test_function_K1.right f_test_function_K2.right) (le_of_eq _), rw [add_assoc, add_comm (Ξ΅/2), add_assoc, add_halves Ξ΅, add_assoc], end end riesz_subadditive
(* Title: HOL/Library/Multiset.thy Author: Tobias Nipkow, Markus Wenzel, Lawrence C Paulson, Norbert Voelker Author: Andrei Popescu, TU Muenchen Author: Jasmin Blanchette, Inria, LORIA, MPII Author: Dmitriy Traytel, TU Muenchen Author: Mathias Fleury, MPII *) section \<open>(Finite) Multisets\<close> theory Multiset imports Cancellation begin subsection \<open>The type of multisets\<close> typedef 'a multiset = \<open>{f :: 'a \<Rightarrow> nat. finite {x. f x > 0}}\<close> morphisms count Abs_multiset proof show \<open>(\<lambda>x. 0::nat) \<in> {f. finite {x. f x > 0}}\<close> by simp qed setup_lifting type_definition_multiset lemma count_Abs_multiset: \<open>count (Abs_multiset f) = f\<close> if \<open>finite {x. f x > 0}\<close> by (rule Abs_multiset_inverse) (simp add: that) lemma multiset_eq_iff: "M = N \<longleftrightarrow> (\<forall>a. count M a = count N a)" by (simp only: count_inject [symmetric] fun_eq_iff) lemma multiset_eqI: "(\<And>x. count A x = count B x) \<Longrightarrow> A = B" using multiset_eq_iff by auto text \<open>Preservation of the representing set \<^term>\<open>multiset\<close>.\<close> lemma diff_preserves_multiset: \<open>finite {x. 0 < M x - N x}\<close> if \<open>finite {x. 0 < M x}\<close> for M N :: \<open>'a \<Rightarrow> nat\<close> using that by (rule rev_finite_subset) auto lemma filter_preserves_multiset: \<open>finite {x. 0 < (if P x then M x else 0)}\<close> if \<open>finite {x. 0 < M x}\<close> for M N :: \<open>'a \<Rightarrow> nat\<close> using that by (rule rev_finite_subset) auto lemmas in_multiset = diff_preserves_multiset filter_preserves_multiset subsection \<open>Representing multisets\<close> text \<open>Multiset enumeration\<close> instantiation multiset :: (type) cancel_comm_monoid_add begin lift_definition zero_multiset :: \<open>'a multiset\<close> is \<open>\<lambda>a. 0\<close> by simp abbreviation empty_mset :: \<open>'a multiset\<close> (\<open>{#}\<close>) where \<open>empty_mset \<equiv> 0\<close> lift_definition plus_multiset :: \<open>'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset\<close> is \<open>\<lambda>M N a. M a + N a\<close> by simp lift_definition minus_multiset :: \<open>'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset\<close> is \<open>\<lambda>M N a. M a - N a\<close> by (rule diff_preserves_multiset) instance by (standard; transfer) (simp_all add: fun_eq_iff) end context begin qualified definition is_empty :: "'a multiset \<Rightarrow> bool" where [code_abbrev]: "is_empty A \<longleftrightarrow> A = {#}" end lemma add_mset_in_multiset: \<open>finite {x. 0 < (if x = a then Suc (M x) else M x)}\<close> if \<open>finite {x. 0 < M x}\<close> using that by (simp add: flip: insert_Collect) lift_definition add_mset :: "'a \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" is "\<lambda>a M b. if b = a then Suc (M b) else M b" by (rule add_mset_in_multiset) syntax "_multiset" :: "args \<Rightarrow> 'a multiset" ("{#(_)#}") translations "{#x, xs#}" == "CONST add_mset x {#xs#}" "{#x#}" == "CONST add_mset x {#}" lemma count_empty [simp]: "count {#} a = 0" by (simp add: zero_multiset.rep_eq) lemma count_add_mset [simp]: "count (add_mset b A) a = (if b = a then Suc (count A a) else count A a)" by (simp add: add_mset.rep_eq) lemma count_single: "count {#b#} a = (if b = a then 1 else 0)" by simp lemma add_mset_not_empty [simp]: \<open>add_mset a A \<noteq> {#}\<close> and empty_not_add_mset [simp]: "{#} \<noteq> add_mset a A" by (auto simp: multiset_eq_iff) lemma add_mset_add_mset_same_iff [simp]: "add_mset a A = add_mset a B \<longleftrightarrow> A = B" by (auto simp: multiset_eq_iff) lemma add_mset_commute: "add_mset x (add_mset y M) = add_mset y (add_mset x M)" by (auto simp: multiset_eq_iff) subsection \<open>Basic operations\<close> subsubsection \<open>Conversion to set and membership\<close> definition set_mset :: \<open>'a multiset \<Rightarrow> 'a set\<close> where \<open>set_mset M = {x. count M x > 0}\<close> abbreviation member_mset :: \<open>'a \<Rightarrow> 'a multiset \<Rightarrow> bool\<close> where \<open>member_mset a M \<equiv> a \<in> set_mset M\<close> notation member_mset (\<open>'(\<in>#')\<close>) and member_mset (\<open>(_/ \<in># _)\<close> [50, 51] 50) notation (ASCII) member_mset (\<open>'(:#')\<close>) and member_mset (\<open>(_/ :# _)\<close> [50, 51] 50) abbreviation not_member_mset :: \<open>'a \<Rightarrow> 'a multiset \<Rightarrow> bool\<close> where \<open>not_member_mset a M \<equiv> a \<notin> set_mset M\<close> notation not_member_mset (\<open>'(\<notin>#')\<close>) and not_member_mset (\<open>(_/ \<notin># _)\<close> [50, 51] 50) notation (ASCII) not_member_mset (\<open>'(~:#')\<close>) and not_member_mset (\<open>(_/ ~:# _)\<close> [50, 51] 50) context begin qualified abbreviation Ball :: "'a multiset \<Rightarrow> ('a \<Rightarrow> bool) \<Rightarrow> bool" where "Ball M \<equiv> Set.Ball (set_mset M)" qualified abbreviation Bex :: "'a multiset \<Rightarrow> ('a \<Rightarrow> bool) \<Rightarrow> bool" where "Bex M \<equiv> Set.Bex (set_mset M)" end syntax "_MBall" :: "pttrn \<Rightarrow> 'a set \<Rightarrow> bool \<Rightarrow> bool" ("(3\<forall>_\<in>#_./ _)" [0, 0, 10] 10) "_MBex" :: "pttrn \<Rightarrow> 'a set \<Rightarrow> bool \<Rightarrow> bool" ("(3\<exists>_\<in>#_./ _)" [0, 0, 10] 10) syntax (ASCII) "_MBall" :: "pttrn \<Rightarrow> 'a set \<Rightarrow> bool \<Rightarrow> bool" ("(3\<forall>_:#_./ _)" [0, 0, 10] 10) "_MBex" :: "pttrn \<Rightarrow> 'a set \<Rightarrow> bool \<Rightarrow> bool" ("(3\<exists>_:#_./ _)" [0, 0, 10] 10) translations "\<forall>x\<in>#A. P" \<rightleftharpoons> "CONST Multiset.Ball A (\<lambda>x. P)" "\<exists>x\<in>#A. P" \<rightleftharpoons> "CONST Multiset.Bex A (\<lambda>x. P)" print_translation \<open> [Syntax_Trans.preserve_binder_abs2_tr' \<^const_syntax>\<open>Multiset.Ball\<close> \<^syntax_const>\<open>_MBall\<close>, Syntax_Trans.preserve_binder_abs2_tr' \<^const_syntax>\<open>Multiset.Bex\<close> \<^syntax_const>\<open>_MBex\<close>] \<close> \<comment> \<open>to avoid eta-contraction of body\<close> lemma count_eq_zero_iff: "count M x = 0 \<longleftrightarrow> x \<notin># M" by (auto simp add: set_mset_def) lemma not_in_iff: "x \<notin># M \<longleftrightarrow> count M x = 0" by (auto simp add: count_eq_zero_iff) lemma count_greater_zero_iff [simp]: "count M x > 0 \<longleftrightarrow> x \<in># M" by (auto simp add: set_mset_def) lemma count_inI: assumes "count M x = 0 \<Longrightarrow> False" shows "x \<in># M" proof (rule ccontr) assume "x \<notin># M" with assms show False by (simp add: not_in_iff) qed lemma in_countE: assumes "x \<in># M" obtains n where "count M x = Suc n" proof - from assms have "count M x > 0" by simp then obtain n where "count M x = Suc n" using gr0_conv_Suc by blast with that show thesis . qed lemma count_greater_eq_Suc_zero_iff [simp]: "count M x \<ge> Suc 0 \<longleftrightarrow> x \<in># M" by (simp add: Suc_le_eq) lemma count_greater_eq_one_iff [simp]: "count M x \<ge> 1 \<longleftrightarrow> x \<in># M" by simp lemma set_mset_empty [simp]: "set_mset {#} = {}" by (simp add: set_mset_def) lemma set_mset_single: "set_mset {#b#} = {b}" by (simp add: set_mset_def) lemma set_mset_eq_empty_iff [simp]: "set_mset M = {} \<longleftrightarrow> M = {#}" by (auto simp add: multiset_eq_iff count_eq_zero_iff) lemma finite_set_mset [iff]: "finite (set_mset M)" using count [of M] by simp lemma set_mset_add_mset_insert [simp]: \<open>set_mset (add_mset a A) = insert a (set_mset A)\<close> by (auto simp flip: count_greater_eq_Suc_zero_iff split: if_splits) lemma multiset_nonemptyE [elim]: assumes "A \<noteq> {#}" obtains x where "x \<in># A" proof - have "\<exists>x. x \<in># A" by (rule ccontr) (insert assms, auto) with that show ?thesis by blast qed subsubsection \<open>Union\<close> lemma count_union [simp]: "count (M + N) a = count M a + count N a" by (simp add: plus_multiset.rep_eq) lemma set_mset_union [simp]: "set_mset (M + N) = set_mset M \<union> set_mset N" by (simp only: set_eq_iff count_greater_zero_iff [symmetric] count_union) simp lemma union_mset_add_mset_left [simp]: "add_mset a A + B = add_mset a (A + B)" by (auto simp: multiset_eq_iff) lemma union_mset_add_mset_right [simp]: "A + add_mset a B = add_mset a (A + B)" by (auto simp: multiset_eq_iff) lemma add_mset_add_single: \<open>add_mset a A = A + {#a#}\<close> by (subst union_mset_add_mset_right, subst add.comm_neutral) standard subsubsection \<open>Difference\<close> instance multiset :: (type) comm_monoid_diff by standard (transfer; simp add: fun_eq_iff) lemma count_diff [simp]: "count (M - N) a = count M a - count N a" by (simp add: minus_multiset.rep_eq) lemma add_mset_diff_bothsides: \<open>add_mset a M - add_mset a A = M - A\<close> by (auto simp: multiset_eq_iff) lemma in_diff_count: "a \<in># M - N \<longleftrightarrow> count N a < count M a" by (simp add: set_mset_def) lemma count_in_diffI: assumes "\<And>n. count N x = n + count M x \<Longrightarrow> False" shows "x \<in># M - N" proof (rule ccontr) assume "x \<notin># M - N" then have "count N x = (count N x - count M x) + count M x" by (simp add: in_diff_count not_less) with assms show False by auto qed lemma in_diff_countE: assumes "x \<in># M - N" obtains n where "count M x = Suc n + count N x" proof - from assms have "count M x - count N x > 0" by (simp add: in_diff_count) then have "count M x > count N x" by simp then obtain n where "count M x = Suc n + count N x" using less_iff_Suc_add by auto with that show thesis . qed lemma in_diffD: assumes "a \<in># M - N" shows "a \<in># M" proof - have "0 \<le> count N a" by simp also from assms have "count N a < count M a" by (simp add: in_diff_count) finally show ?thesis by simp qed lemma set_mset_diff: "set_mset (M - N) = {a. count N a < count M a}" by (simp add: set_mset_def) lemma diff_empty [simp]: "M - {#} = M \<and> {#} - M = {#}" by rule (fact Groups.diff_zero, fact Groups.zero_diff) lemma diff_cancel: "A - A = {#}" by (fact Groups.diff_cancel) lemma diff_union_cancelR: "M + N - N = (M::'a multiset)" by (fact add_diff_cancel_right') lemma diff_union_cancelL: "N + M - N = (M::'a multiset)" by (fact add_diff_cancel_left') lemma diff_right_commute: fixes M N Q :: "'a multiset" shows "M - N - Q = M - Q - N" by (fact diff_right_commute) lemma diff_add: fixes M N Q :: "'a multiset" shows "M - (N + Q) = M - N - Q" by (rule sym) (fact diff_diff_add) lemma insert_DiffM [simp]: "x \<in># M \<Longrightarrow> add_mset x (M - {#x#}) = M" by (clarsimp simp: multiset_eq_iff) lemma insert_DiffM2: "x \<in># M \<Longrightarrow> (M - {#x#}) + {#x#} = M" by simp lemma diff_union_swap: "a \<noteq> b \<Longrightarrow> add_mset b (M - {#a#}) = add_mset b M - {#a#}" by (auto simp add: multiset_eq_iff) lemma diff_add_mset_swap [simp]: "b \<notin># A \<Longrightarrow> add_mset b M - A = add_mset b (M - A)" by (auto simp add: multiset_eq_iff simp: not_in_iff) lemma diff_union_swap2 [simp]: "y \<in># M \<Longrightarrow> add_mset x M - {#y#} = add_mset x (M - {#y#})" by (metis add_mset_diff_bothsides diff_union_swap diff_zero insert_DiffM) lemma diff_diff_add_mset [simp]: "(M::'a multiset) - N - P = M - (N + P)" by (rule diff_diff_add) lemma diff_union_single_conv: "a \<in># J \<Longrightarrow> I + J - {#a#} = I + (J - {#a#})" by (simp add: multiset_eq_iff Suc_le_eq) lemma mset_add [elim?]: assumes "a \<in># A" obtains B where "A = add_mset a B" proof - from assms have "A = add_mset a (A - {#a#})" by simp with that show thesis . qed lemma union_iff: "a \<in># A + B \<longleftrightarrow> a \<in># A \<or> a \<in># B" by auto subsubsection \<open>Min and Max\<close> abbreviation Min_mset :: "'a::linorder multiset \<Rightarrow> 'a" where "Min_mset m \<equiv> Min (set_mset m)" abbreviation Max_mset :: "'a::linorder multiset \<Rightarrow> 'a" where "Max_mset m \<equiv> Max (set_mset m)" subsubsection \<open>Equality of multisets\<close> lemma single_eq_single [simp]: "{#a#} = {#b#} \<longleftrightarrow> a = b" by (auto simp add: multiset_eq_iff) lemma union_eq_empty [iff]: "M + N = {#} \<longleftrightarrow> M = {#} \<and> N = {#}" by (auto simp add: multiset_eq_iff) lemma empty_eq_union [iff]: "{#} = M + N \<longleftrightarrow> M = {#} \<and> N = {#}" by (auto simp add: multiset_eq_iff) lemma multi_self_add_other_not_self [simp]: "M = add_mset x M \<longleftrightarrow> False" by (auto simp add: multiset_eq_iff) lemma add_mset_remove_trivial [simp]: \<open>add_mset x M - {#x#} = M\<close> by (auto simp: multiset_eq_iff) lemma diff_single_trivial: "\<not> x \<in># M \<Longrightarrow> M - {#x#} = M" by (auto simp add: multiset_eq_iff not_in_iff) lemma diff_single_eq_union: "x \<in># M \<Longrightarrow> M - {#x#} = N \<longleftrightarrow> M = add_mset x N" by auto lemma union_single_eq_diff: "add_mset x M = N \<Longrightarrow> M = N - {#x#}" unfolding add_mset_add_single[of _ M] by (fact add_implies_diff) lemma union_single_eq_member: "add_mset x M = N \<Longrightarrow> x \<in># N" by auto lemma add_mset_remove_trivial_If: "add_mset a (N - {#a#}) = (if a \<in># N then N else add_mset a N)" by (simp add: diff_single_trivial) lemma add_mset_remove_trivial_eq: \<open>N = add_mset a (N - {#a#}) \<longleftrightarrow> a \<in># N\<close> by (auto simp: add_mset_remove_trivial_If) lemma union_is_single: "M + N = {#a#} \<longleftrightarrow> M = {#a#} \<and> N = {#} \<or> M = {#} \<and> N = {#a#}" (is "?lhs = ?rhs") proof show ?lhs if ?rhs using that by auto show ?rhs if ?lhs by (metis Multiset.diff_cancel add.commute add_diff_cancel_left' diff_add_zero diff_single_trivial insert_DiffM that) qed lemma single_is_union: "{#a#} = M + N \<longleftrightarrow> {#a#} = M \<and> N = {#} \<or> M = {#} \<and> {#a#} = N" by (auto simp add: eq_commute [of "{#a#}" "M + N"] union_is_single) lemma add_eq_conv_diff: "add_mset a M = add_mset b N \<longleftrightarrow> M = N \<and> a = b \<or> M = add_mset b (N - {#a#}) \<and> N = add_mset a (M - {#b#})" (is "?lhs \<longleftrightarrow> ?rhs") (* shorter: by (simp add: multiset_eq_iff) fastforce *) proof show ?lhs if ?rhs using that by (auto simp add: add_mset_commute[of a b]) show ?rhs if ?lhs proof (cases "a = b") case True with \<open>?lhs\<close> show ?thesis by simp next case False from \<open>?lhs\<close> have "a \<in># add_mset b N" by (rule union_single_eq_member) with False have "a \<in># N" by auto moreover from \<open>?lhs\<close> have "M = add_mset b N - {#a#}" by (rule union_single_eq_diff) moreover note False ultimately show ?thesis by (auto simp add: diff_right_commute [of _ "{#a#}"]) qed qed lemma add_mset_eq_single [iff]: "add_mset b M = {#a#} \<longleftrightarrow> b = a \<and> M = {#}" by (auto simp: add_eq_conv_diff) lemma single_eq_add_mset [iff]: "{#a#} = add_mset b M \<longleftrightarrow> b = a \<and> M = {#}" by (auto simp: add_eq_conv_diff) lemma insert_noteq_member: assumes BC: "add_mset b B = add_mset c C" and bnotc: "b \<noteq> c" shows "c \<in># B" proof - have "c \<in># add_mset c C" by simp have nc: "\<not> c \<in># {#b#}" using bnotc by simp then have "c \<in># add_mset b B" using BC by simp then show "c \<in># B" using nc by simp qed lemma add_eq_conv_ex: "(add_mset a M = add_mset b N) = (M = N \<and> a = b \<or> (\<exists>K. M = add_mset b K \<and> N = add_mset a K))" by (auto simp add: add_eq_conv_diff) lemma multi_member_split: "x \<in># M \<Longrightarrow> \<exists>A. M = add_mset x A" by (rule exI [where x = "M - {#x#}"]) simp lemma multiset_add_sub_el_shuffle: assumes "c \<in># B" and "b \<noteq> c" shows "add_mset b (B - {#c#}) = add_mset b B - {#c#}" proof - from \<open>c \<in># B\<close> obtain A where B: "B = add_mset c A" by (blast dest: multi_member_split) have "add_mset b A = add_mset c (add_mset b A) - {#c#}" by simp then have "add_mset b A = add_mset b (add_mset c A) - {#c#}" by (simp add: \<open>b \<noteq> c\<close>) then show ?thesis using B by simp qed lemma add_mset_eq_singleton_iff[iff]: "add_mset x M = {#y#} \<longleftrightarrow> M = {#} \<and> x = y" by auto subsubsection \<open>Pointwise ordering induced by count\<close> definition subseteq_mset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "\<subseteq>#" 50) where "A \<subseteq># B \<longleftrightarrow> (\<forall>a. count A a \<le> count B a)" definition subset_mset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "\<subset>#" 50) where "A \<subset># B \<longleftrightarrow> A \<subseteq># B \<and> A \<noteq> B" abbreviation (input) supseteq_mset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "\<supseteq>#" 50) where "supseteq_mset A B \<equiv> B \<subseteq># A" abbreviation (input) supset_mset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "\<supset>#" 50) where "supset_mset A B \<equiv> B \<subset># A" notation (input) subseteq_mset (infix "\<le>#" 50) and supseteq_mset (infix "\<ge>#" 50) notation (ASCII) subseteq_mset (infix "<=#" 50) and subset_mset (infix "<#" 50) and supseteq_mset (infix ">=#" 50) and supset_mset (infix ">#" 50) global_interpretation subset_mset: ordering \<open>(\<subseteq>#)\<close> \<open>(\<subset>#)\<close> by standard (auto simp add: subset_mset_def subseteq_mset_def multiset_eq_iff intro: order.trans order.antisym) interpretation subset_mset: ordered_ab_semigroup_add_imp_le \<open>(+)\<close> \<open>(-)\<close> \<open>(\<subseteq>#)\<close> \<open>(\<subset>#)\<close> by standard (auto simp add: subset_mset_def subseteq_mset_def multiset_eq_iff intro: order_trans antisym) \<comment> \<open>FIXME: avoid junk stemming from type class interpretation\<close> interpretation subset_mset: ordered_ab_semigroup_monoid_add_imp_le "(+)" 0 "(-)" "(\<subseteq>#)" "(\<subset>#)" by standard \<comment> \<open>FIXME: avoid junk stemming from type class interpretation\<close> lemma mset_subset_eqI: "(\<And>a. count A a \<le> count B a) \<Longrightarrow> A \<subseteq># B" by (simp add: subseteq_mset_def) lemma mset_subset_eq_count: "A \<subseteq># B \<Longrightarrow> count A a \<le> count B a" by (simp add: subseteq_mset_def) lemma mset_subset_eq_exists_conv: "(A::'a multiset) \<subseteq># B \<longleftrightarrow> (\<exists>C. B = A + C)" unfolding subseteq_mset_def apply (rule iffI) apply (rule exI [where x = "B - A"]) apply (auto intro: multiset_eq_iff [THEN iffD2]) done interpretation subset_mset: ordered_cancel_comm_monoid_diff "(+)" 0 "(\<subseteq>#)" "(\<subset>#)" "(-)" by standard (simp, fact mset_subset_eq_exists_conv) \<comment> \<open>FIXME: avoid junk stemming from type class interpretation\<close> declare subset_mset.add_diff_assoc[simp] subset_mset.add_diff_assoc2[simp] lemma mset_subset_eq_mono_add_right_cancel: "(A::'a multiset) + C \<subseteq># B + C \<longleftrightarrow> A \<subseteq># B" by (fact subset_mset.add_le_cancel_right) lemma mset_subset_eq_mono_add_left_cancel: "C + (A::'a multiset) \<subseteq># C + B \<longleftrightarrow> A \<subseteq># B" by (fact subset_mset.add_le_cancel_left) lemma mset_subset_eq_mono_add: "(A::'a multiset) \<subseteq># B \<Longrightarrow> C \<subseteq># D \<Longrightarrow> A + C \<subseteq># B + D" by (fact subset_mset.add_mono) lemma mset_subset_eq_add_left: "(A::'a multiset) \<subseteq># A + B" by simp lemma mset_subset_eq_add_right: "B \<subseteq># (A::'a multiset) + B" by simp lemma single_subset_iff [simp]: "{#a#} \<subseteq># M \<longleftrightarrow> a \<in># M" by (auto simp add: subseteq_mset_def Suc_le_eq) lemma mset_subset_eq_single: "a \<in># B \<Longrightarrow> {#a#} \<subseteq># B" by simp lemma mset_subset_eq_add_mset_cancel: \<open>add_mset a A \<subseteq># add_mset a B \<longleftrightarrow> A \<subseteq># B\<close> unfolding add_mset_add_single[of _ A] add_mset_add_single[of _ B] by (rule mset_subset_eq_mono_add_right_cancel) lemma multiset_diff_union_assoc: fixes A B C D :: "'a multiset" shows "C \<subseteq># B \<Longrightarrow> A + B - C = A + (B - C)" by (fact subset_mset.diff_add_assoc) lemma mset_subset_eq_multiset_union_diff_commute: fixes A B C D :: "'a multiset" shows "B \<subseteq># A \<Longrightarrow> A - B + C = A + C - B" by (fact subset_mset.add_diff_assoc2) lemma diff_subset_eq_self[simp]: "(M::'a multiset) - N \<subseteq># M" by (simp add: subseteq_mset_def) lemma mset_subset_eqD: assumes "A \<subseteq># B" and "x \<in># A" shows "x \<in># B" proof - from \<open>x \<in># A\<close> have "count A x > 0" by simp also from \<open>A \<subseteq># B\<close> have "count A x \<le> count B x" by (simp add: subseteq_mset_def) finally show ?thesis by simp qed lemma mset_subsetD: "A \<subset># B \<Longrightarrow> x \<in># A \<Longrightarrow> x \<in># B" by (auto intro: mset_subset_eqD [of A]) lemma set_mset_mono: "A \<subseteq># B \<Longrightarrow> set_mset A \<subseteq> set_mset B" by (metis mset_subset_eqD subsetI) lemma mset_subset_eq_insertD: "add_mset x A \<subseteq># B \<Longrightarrow> x \<in># B \<and> A \<subset># B" apply (rule conjI) apply (simp add: mset_subset_eqD) apply (clarsimp simp: subset_mset_def subseteq_mset_def) apply safe apply (erule_tac x = a in allE) apply (auto split: if_split_asm) done lemma mset_subset_insertD: "add_mset x A \<subset># B \<Longrightarrow> x \<in># B \<and> A \<subset># B" by (rule mset_subset_eq_insertD) simp lemma mset_subset_of_empty[simp]: "A \<subset># {#} \<longleftrightarrow> False" by (simp only: subset_mset.not_less_zero) lemma empty_subset_add_mset[simp]: "{#} \<subset># add_mset x M" by (auto intro: subset_mset.gr_zeroI) lemma empty_le: "{#} \<subseteq># A" by (fact subset_mset.zero_le) lemma insert_subset_eq_iff: "add_mset a A \<subseteq># B \<longleftrightarrow> a \<in># B \<and> A \<subseteq># B - {#a#}" using le_diff_conv2 [of "Suc 0" "count B a" "count A a"] apply (auto simp add: subseteq_mset_def not_in_iff Suc_le_eq) apply (rule ccontr) apply (auto simp add: not_in_iff) done lemma insert_union_subset_iff: "add_mset a A \<subset># B \<longleftrightarrow> a \<in># B \<and> A \<subset># B - {#a#}" by (auto simp add: insert_subset_eq_iff subset_mset_def) lemma subset_eq_diff_conv: "A - C \<subseteq># B \<longleftrightarrow> A \<subseteq># B + C" by (simp add: subseteq_mset_def le_diff_conv) lemma multi_psub_of_add_self [simp]: "A \<subset># add_mset x A" by (auto simp: subset_mset_def subseteq_mset_def) lemma multi_psub_self: "A \<subset># A = False" by simp lemma mset_subset_add_mset [simp]: "add_mset x N \<subset># add_mset x M \<longleftrightarrow> N \<subset># M" unfolding add_mset_add_single[of _ N] add_mset_add_single[of _ M] by (fact subset_mset.add_less_cancel_right) lemma mset_subset_diff_self: "c \<in># B \<Longrightarrow> B - {#c#} \<subset># B" by (auto simp: subset_mset_def elim: mset_add) lemma Diff_eq_empty_iff_mset: "A - B = {#} \<longleftrightarrow> A \<subseteq># B" by (auto simp: multiset_eq_iff subseteq_mset_def) lemma add_mset_subseteq_single_iff[iff]: "add_mset a M \<subseteq># {#b#} \<longleftrightarrow> M = {#} \<and> a = b" proof assume A: "add_mset a M \<subseteq># {#b#}" then have \<open>a = b\<close> by (auto dest: mset_subset_eq_insertD) then show "M={#} \<and> a=b" using A by (simp add: mset_subset_eq_add_mset_cancel) qed simp subsubsection \<open>Intersection and bounded union\<close> definition inter_mset :: \<open>'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset\<close> (infixl \<open>\<inter>#\<close> 70) where \<open>A \<inter># B = A - (A - B)\<close> lemma count_inter_mset [simp]: \<open>count (A \<inter># B) x = min (count A x) (count B x)\<close> by (simp add: inter_mset_def) (*global_interpretation subset_mset: semilattice_order \<open>(\<inter>#)\<close> \<open>(\<subseteq>#)\<close> \<open>(\<subset>#)\<close> by standard (simp_all add: multiset_eq_iff subseteq_mset_def subset_mset_def min_def)*) interpretation subset_mset: semilattice_inf \<open>(\<inter>#)\<close> \<open>(\<subseteq>#)\<close> \<open>(\<subset>#)\<close> by standard (simp_all add: multiset_eq_iff subseteq_mset_def) \<comment> \<open>FIXME: avoid junk stemming from type class interpretation\<close> definition union_mset :: \<open>'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset\<close> (infixl \<open>\<union>#\<close> 70) where \<open>A \<union># B = A + (B - A)\<close> lemma count_union_mset [simp]: \<open>count (A \<union># B) x = max (count A x) (count B x)\<close> by (simp add: union_mset_def) global_interpretation subset_mset: semilattice_neutr_order \<open>(\<union>#)\<close> \<open>{#}\<close> \<open>(\<supseteq>#)\<close> \<open>(\<supset>#)\<close> apply standard apply (simp_all add: multiset_eq_iff subseteq_mset_def subset_mset_def max_def) apply (auto simp add: le_antisym dest: sym) apply (metis nat_le_linear)+ done interpretation subset_mset: semilattice_sup \<open>(\<union>#)\<close> \<open>(\<subseteq>#)\<close> \<open>(\<subset>#)\<close> proof - have [simp]: "m \<le> n \<Longrightarrow> q \<le> n \<Longrightarrow> m + (q - m) \<le> n" for m n q :: nat by arith show "class.semilattice_sup (\<union>#) (\<subseteq>#) (\<subset>#)" by standard (auto simp add: union_mset_def subseteq_mset_def) qed \<comment> \<open>FIXME: avoid junk stemming from type class interpretation\<close> interpretation subset_mset: bounded_lattice_bot "(\<inter>#)" "(\<subseteq>#)" "(\<subset>#)" "(\<union>#)" "{#}" by standard auto \<comment> \<open>FIXME: avoid junk stemming from type class interpretation\<close> subsubsection \<open>Additional intersection facts\<close> lemma set_mset_inter [simp]: "set_mset (A \<inter># B) = set_mset A \<inter> set_mset B" by (simp only: set_mset_def) auto lemma diff_intersect_left_idem [simp]: "M - M \<inter># N = M - N" by (simp add: multiset_eq_iff min_def) lemma diff_intersect_right_idem [simp]: "M - N \<inter># M = M - N" by (simp add: multiset_eq_iff min_def) lemma multiset_inter_single[simp]: "a \<noteq> b \<Longrightarrow> {#a#} \<inter># {#b#} = {#}" by (rule multiset_eqI) auto lemma multiset_union_diff_commute: assumes "B \<inter># C = {#}" shows "A + B - C = A - C + B" proof (rule multiset_eqI) fix x from assms have "min (count B x) (count C x) = 0" by (auto simp add: multiset_eq_iff) then have "count B x = 0 \<or> count C x = 0" unfolding min_def by (auto split: if_splits) then show "count (A + B - C) x = count (A - C + B) x" by auto qed lemma disjunct_not_in: "A \<inter># B = {#} \<longleftrightarrow> (\<forall>a. a \<notin># A \<or> a \<notin># B)" (is "?P \<longleftrightarrow> ?Q") proof assume ?P show ?Q proof fix a from \<open>?P\<close> have "min (count A a) (count B a) = 0" by (simp add: multiset_eq_iff) then have "count A a = 0 \<or> count B a = 0" by (cases "count A a \<le> count B a") (simp_all add: min_def) then show "a \<notin># A \<or> a \<notin># B" by (simp add: not_in_iff) qed next assume ?Q show ?P proof (rule multiset_eqI) fix a from \<open>?Q\<close> have "count A a = 0 \<or> count B a = 0" by (auto simp add: not_in_iff) then show "count (A \<inter># B) a = count {#} a" by auto qed qed lemma inter_mset_empty_distrib_right: "A \<inter># (B + C) = {#} \<longleftrightarrow> A \<inter># B = {#} \<and> A \<inter># C = {#}" by (meson disjunct_not_in union_iff) lemma inter_mset_empty_distrib_left: "(A + B) \<inter># C = {#} \<longleftrightarrow> A \<inter># C = {#} \<and> B \<inter># C = {#}" by (meson disjunct_not_in union_iff) lemma add_mset_inter_add_mset [simp]: "add_mset a A \<inter># add_mset a B = add_mset a (A \<inter># B)" by (rule multiset_eqI) simp lemma add_mset_disjoint [simp]: "add_mset a A \<inter># B = {#} \<longleftrightarrow> a \<notin># B \<and> A \<inter># B = {#}" "{#} = add_mset a A \<inter># B \<longleftrightarrow> a \<notin># B \<and> {#} = A \<inter># B" by (auto simp: disjunct_not_in) lemma disjoint_add_mset [simp]: "B \<inter># add_mset a A = {#} \<longleftrightarrow> a \<notin># B \<and> B \<inter># A = {#}" "{#} = A \<inter># add_mset b B \<longleftrightarrow> b \<notin># A \<and> {#} = A \<inter># B" by (auto simp: disjunct_not_in) lemma inter_add_left1: "\<not> x \<in># N \<Longrightarrow> (add_mset x M) \<inter># N = M \<inter># N" by (simp add: multiset_eq_iff not_in_iff) lemma inter_add_left2: "x \<in># N \<Longrightarrow> (add_mset x M) \<inter># N = add_mset x (M \<inter># (N - {#x#}))" by (auto simp add: multiset_eq_iff elim: mset_add) lemma inter_add_right1: "\<not> x \<in># N \<Longrightarrow> N \<inter># (add_mset x M) = N \<inter># M" by (simp add: multiset_eq_iff not_in_iff) lemma inter_add_right2: "x \<in># N \<Longrightarrow> N \<inter># (add_mset x M) = add_mset x ((N - {#x#}) \<inter># M)" by (auto simp add: multiset_eq_iff elim: mset_add) lemma disjunct_set_mset_diff: assumes "M \<inter># N = {#}" shows "set_mset (M - N) = set_mset M" proof (rule set_eqI) fix a from assms have "a \<notin># M \<or> a \<notin># N" by (simp add: disjunct_not_in) then show "a \<in># M - N \<longleftrightarrow> a \<in># M" by (auto dest: in_diffD) (simp add: in_diff_count not_in_iff) qed lemma at_most_one_mset_mset_diff: assumes "a \<notin># M - {#a#}" shows "set_mset (M - {#a#}) = set_mset M - {a}" using assms by (auto simp add: not_in_iff in_diff_count set_eq_iff) lemma more_than_one_mset_mset_diff: assumes "a \<in># M - {#a#}" shows "set_mset (M - {#a#}) = set_mset M" proof (rule set_eqI) fix b have "Suc 0 < count M b \<Longrightarrow> count M b > 0" by arith then show "b \<in># M - {#a#} \<longleftrightarrow> b \<in># M" using assms by (auto simp add: in_diff_count) qed lemma inter_iff: "a \<in># A \<inter># B \<longleftrightarrow> a \<in># A \<and> a \<in># B" by simp lemma inter_union_distrib_left: "A \<inter># B + C = (A + C) \<inter># (B + C)" by (simp add: multiset_eq_iff min_add_distrib_left) lemma inter_union_distrib_right: "C + A \<inter># B = (C + A) \<inter># (C + B)" using inter_union_distrib_left [of A B C] by (simp add: ac_simps) lemma inter_subset_eq_union: "A \<inter># B \<subseteq># A + B" by (auto simp add: subseteq_mset_def) subsubsection \<open>Additional bounded union facts\<close> lemma set_mset_sup [simp]: \<open>set_mset (A \<union># B) = set_mset A \<union> set_mset B\<close> by (simp only: set_mset_def) (auto simp add: less_max_iff_disj) lemma sup_union_left1 [simp]: "\<not> x \<in># N \<Longrightarrow> (add_mset x M) \<union># N = add_mset x (M \<union># N)" by (simp add: multiset_eq_iff not_in_iff) lemma sup_union_left2: "x \<in># N \<Longrightarrow> (add_mset x M) \<union># N = add_mset x (M \<union># (N - {#x#}))" by (simp add: multiset_eq_iff) lemma sup_union_right1 [simp]: "\<not> x \<in># N \<Longrightarrow> N \<union># (add_mset x M) = add_mset x (N \<union># M)" by (simp add: multiset_eq_iff not_in_iff) lemma sup_union_right2: "x \<in># N \<Longrightarrow> N \<union># (add_mset x M) = add_mset x ((N - {#x#}) \<union># M)" by (simp add: multiset_eq_iff) lemma sup_union_distrib_left: "A \<union># B + C = (A + C) \<union># (B + C)" by (simp add: multiset_eq_iff max_add_distrib_left) lemma union_sup_distrib_right: "C + A \<union># B = (C + A) \<union># (C + B)" using sup_union_distrib_left [of A B C] by (simp add: ac_simps) lemma union_diff_inter_eq_sup: "A + B - A \<inter># B = A \<union># B" by (auto simp add: multiset_eq_iff) lemma union_diff_sup_eq_inter: "A + B - A \<union># B = A \<inter># B" by (auto simp add: multiset_eq_iff) lemma add_mset_union: \<open>add_mset a A \<union># add_mset a B = add_mset a (A \<union># B)\<close> by (auto simp: multiset_eq_iff max_def) subsection \<open>Replicate and repeat operations\<close> definition replicate_mset :: "nat \<Rightarrow> 'a \<Rightarrow> 'a multiset" where "replicate_mset n x = (add_mset x ^^ n) {#}" lemma replicate_mset_0[simp]: "replicate_mset 0 x = {#}" unfolding replicate_mset_def by simp lemma replicate_mset_Suc [simp]: "replicate_mset (Suc n) x = add_mset x (replicate_mset n x)" unfolding replicate_mset_def by (induct n) (auto intro: add.commute) lemma count_replicate_mset[simp]: "count (replicate_mset n x) y = (if y = x then n else 0)" unfolding replicate_mset_def by (induct n) auto lift_definition repeat_mset :: \<open>nat \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset\<close> is \<open>\<lambda>n M a. n * M a\<close> by simp lemma count_repeat_mset [simp]: "count (repeat_mset i A) a = i * count A a" by transfer rule lemma repeat_mset_0 [simp]: \<open>repeat_mset 0 M = {#}\<close> by transfer simp lemma repeat_mset_Suc [simp]: \<open>repeat_mset (Suc n) M = M + repeat_mset n M\<close> by transfer simp lemma repeat_mset_right [simp]: "repeat_mset a (repeat_mset b A) = repeat_mset (a * b) A" by (auto simp: multiset_eq_iff left_diff_distrib') lemma left_diff_repeat_mset_distrib': \<open>repeat_mset (i - j) u = repeat_mset i u - repeat_mset j u\<close> by (auto simp: multiset_eq_iff left_diff_distrib') lemma left_add_mult_distrib_mset: "repeat_mset i u + (repeat_mset j u + k) = repeat_mset (i+j) u + k" by (auto simp: multiset_eq_iff add_mult_distrib) lemma repeat_mset_distrib: "repeat_mset (m + n) A = repeat_mset m A + repeat_mset n A" by (auto simp: multiset_eq_iff Nat.add_mult_distrib) lemma repeat_mset_distrib2[simp]: "repeat_mset n (A + B) = repeat_mset n A + repeat_mset n B" by (auto simp: multiset_eq_iff add_mult_distrib2) lemma repeat_mset_replicate_mset[simp]: "repeat_mset n {#a#} = replicate_mset n a" by (auto simp: multiset_eq_iff) lemma repeat_mset_distrib_add_mset[simp]: "repeat_mset n (add_mset a A) = replicate_mset n a + repeat_mset n A" by (auto simp: multiset_eq_iff) lemma repeat_mset_empty[simp]: "repeat_mset n {#} = {#}" by transfer simp subsubsection \<open>Simprocs\<close> lemma repeat_mset_iterate_add: \<open>repeat_mset n M = iterate_add n M\<close> unfolding iterate_add_def by (induction n) auto lemma mset_subseteq_add_iff1: "j \<le> (i::nat) \<Longrightarrow> (repeat_mset i u + m \<subseteq># repeat_mset j u + n) = (repeat_mset (i-j) u + m \<subseteq># n)" by (auto simp add: subseteq_mset_def nat_le_add_iff1) lemma mset_subseteq_add_iff2: "i \<le> (j::nat) \<Longrightarrow> (repeat_mset i u + m \<subseteq># repeat_mset j u + n) = (m \<subseteq># repeat_mset (j-i) u + n)" by (auto simp add: subseteq_mset_def nat_le_add_iff2) lemma mset_subset_add_iff1: "j \<le> (i::nat) \<Longrightarrow> (repeat_mset i u + m \<subset># repeat_mset j u + n) = (repeat_mset (i-j) u + m \<subset># n)" unfolding subset_mset_def repeat_mset_iterate_add by (simp add: iterate_add_eq_add_iff1 mset_subseteq_add_iff1[unfolded repeat_mset_iterate_add]) lemma mset_subset_add_iff2: "i \<le> (j::nat) \<Longrightarrow> (repeat_mset i u + m \<subset># repeat_mset j u + n) = (m \<subset># repeat_mset (j-i) u + n)" unfolding subset_mset_def repeat_mset_iterate_add by (simp add: iterate_add_eq_add_iff2 mset_subseteq_add_iff2[unfolded repeat_mset_iterate_add]) ML_file \<open>multiset_simprocs.ML\<close> lemma add_mset_replicate_mset_safe[cancelation_simproc_pre]: \<open>NO_MATCH {#} M \<Longrightarrow> add_mset a M = {#a#} + M\<close> by simp declare repeat_mset_iterate_add[cancelation_simproc_pre] declare iterate_add_distrib[cancelation_simproc_pre] declare repeat_mset_iterate_add[symmetric, cancelation_simproc_post] declare add_mset_not_empty[cancelation_simproc_eq_elim] empty_not_add_mset[cancelation_simproc_eq_elim] subset_mset.le_zero_eq[cancelation_simproc_eq_elim] empty_not_add_mset[cancelation_simproc_eq_elim] add_mset_not_empty[cancelation_simproc_eq_elim] subset_mset.le_zero_eq[cancelation_simproc_eq_elim] le_zero_eq[cancelation_simproc_eq_elim] simproc_setup mseteq_cancel ("(l::'a multiset) + m = n" | "(l::'a multiset) = m + n" | "add_mset a m = n" | "m = add_mset a n" | "replicate_mset p a = n" | "m = replicate_mset p a" | "repeat_mset p m = n" | "m = repeat_mset p m") = \<open>fn phi => Cancel_Simprocs.eq_cancel\<close> simproc_setup msetsubset_cancel ("(l::'a multiset) + m \<subset># n" | "(l::'a multiset) \<subset># m + n" | "add_mset a m \<subset># n" | "m \<subset># add_mset a n" | "replicate_mset p r \<subset># n" | "m \<subset># replicate_mset p r" | "repeat_mset p m \<subset># n" | "m \<subset># repeat_mset p m") = \<open>fn phi => Multiset_Simprocs.subset_cancel_msets\<close> simproc_setup msetsubset_eq_cancel ("(l::'a multiset) + m \<subseteq># n" | "(l::'a multiset) \<subseteq># m + n" | "add_mset a m \<subseteq># n" | "m \<subseteq># add_mset a n" | "replicate_mset p r \<subseteq># n" | "m \<subseteq># replicate_mset p r" | "repeat_mset p m \<subseteq># n" | "m \<subseteq># repeat_mset p m") = \<open>fn phi => Multiset_Simprocs.subseteq_cancel_msets\<close> simproc_setup msetdiff_cancel ("((l::'a multiset) + m) - n" | "(l::'a multiset) - (m + n)" | "add_mset a m - n" | "m - add_mset a n" | "replicate_mset p r - n" | "m - replicate_mset p r" | "repeat_mset p m - n" | "m - repeat_mset p m") = \<open>fn phi => Cancel_Simprocs.diff_cancel\<close> subsubsection \<open>Conditionally complete lattice\<close> instantiation multiset :: (type) Inf begin lift_definition Inf_multiset :: "'a multiset set \<Rightarrow> 'a multiset" is "\<lambda>A i. if A = {} then 0 else Inf ((\<lambda>f. f i) ` A)" proof - fix A :: "('a \<Rightarrow> nat) set" assume *: "\<And>f. f \<in> A \<Longrightarrow> finite {x. 0 < f x}" show \<open>finite {i. 0 < (if A = {} then 0 else INF f\<in>A. f i)}\<close> proof (cases "A = {}") case False then obtain f where "f \<in> A" by blast hence "{i. Inf ((\<lambda>f. f i) ` A) > 0} \<subseteq> {i. f i > 0}" by (auto intro: less_le_trans[OF _ cInf_lower]) moreover from \<open>f \<in> A\<close> * have "finite \<dots>" by simp ultimately have "finite {i. Inf ((\<lambda>f. f i) ` A) > 0}" by (rule finite_subset) with False show ?thesis by simp qed simp_all qed instance .. end lemma Inf_multiset_empty: "Inf {} = {#}" by transfer simp_all lemma count_Inf_multiset_nonempty: "A \<noteq> {} \<Longrightarrow> count (Inf A) x = Inf ((\<lambda>X. count X x) ` A)" by transfer simp_all instantiation multiset :: (type) Sup begin definition Sup_multiset :: "'a multiset set \<Rightarrow> 'a multiset" where "Sup_multiset A = (if A \<noteq> {} \<and> subset_mset.bdd_above A then Abs_multiset (\<lambda>i. Sup ((\<lambda>X. count X i) ` A)) else {#})" lemma Sup_multiset_empty: "Sup {} = {#}" by (simp add: Sup_multiset_def) lemma Sup_multiset_unbounded: "\<not> subset_mset.bdd_above A \<Longrightarrow> Sup A = {#}" by (simp add: Sup_multiset_def) instance .. end lemma bdd_above_multiset_imp_bdd_above_count: assumes "subset_mset.bdd_above (A :: 'a multiset set)" shows "bdd_above ((\<lambda>X. count X x) ` A)" proof - from assms obtain Y where Y: "\<forall>X\<in>A. X \<subseteq># Y" by (meson subset_mset.bdd_above.E) hence "count X x \<le> count Y x" if "X \<in> A" for X using that by (auto intro: mset_subset_eq_count) thus ?thesis by (intro bdd_aboveI[of _ "count Y x"]) auto qed lemma bdd_above_multiset_imp_finite_support: assumes "A \<noteq> {}" "subset_mset.bdd_above (A :: 'a multiset set)" shows "finite (\<Union>X\<in>A. {x. count X x > 0})" proof - from assms obtain Y where Y: "\<forall>X\<in>A. X \<subseteq># Y" by (meson subset_mset.bdd_above.E) hence "count X x \<le> count Y x" if "X \<in> A" for X x using that by (auto intro: mset_subset_eq_count) hence "(\<Union>X\<in>A. {x. count X x > 0}) \<subseteq> {x. count Y x > 0}" by safe (erule less_le_trans) moreover have "finite \<dots>" by simp ultimately show ?thesis by (rule finite_subset) qed lemma Sup_multiset_in_multiset: \<open>finite {i. 0 < (SUP M\<in>A. count M i)}\<close> if \<open>A \<noteq> {}\<close> \<open>subset_mset.bdd_above A\<close> proof - have "{i. Sup ((\<lambda>X. count X i) ` A) > 0} \<subseteq> (\<Union>X\<in>A. {i. 0 < count X i})" proof safe fix i assume pos: "(SUP X\<in>A. count X i) > 0" show "i \<in> (\<Union>X\<in>A. {i. 0 < count X i})" proof (rule ccontr) assume "i \<notin> (\<Union>X\<in>A. {i. 0 < count X i})" hence "\<forall>X\<in>A. count X i \<le> 0" by (auto simp: count_eq_zero_iff) with that have "(SUP X\<in>A. count X i) \<le> 0" by (intro cSup_least bdd_above_multiset_imp_bdd_above_count) auto with pos show False by simp qed qed moreover from that have "finite \<dots>" by (rule bdd_above_multiset_imp_finite_support) ultimately show "finite {i. Sup ((\<lambda>X. count X i) ` A) > 0}" by (rule finite_subset) qed lemma count_Sup_multiset_nonempty: \<open>count (Sup A) x = (SUP X\<in>A. count X x)\<close> if \<open>A \<noteq> {}\<close> \<open>subset_mset.bdd_above A\<close> using that by (simp add: Sup_multiset_def Sup_multiset_in_multiset count_Abs_multiset) interpretation subset_mset: conditionally_complete_lattice Inf Sup "(\<inter>#)" "(\<subseteq>#)" "(\<subset>#)" "(\<union>#)" proof fix X :: "'a multiset" and A assume "X \<in> A" show "Inf A \<subseteq># X" proof (rule mset_subset_eqI) fix x from \<open>X \<in> A\<close> have "A \<noteq> {}" by auto hence "count (Inf A) x = (INF X\<in>A. count X x)" by (simp add: count_Inf_multiset_nonempty) also from \<open>X \<in> A\<close> have "\<dots> \<le> count X x" by (intro cInf_lower) simp_all finally show "count (Inf A) x \<le> count X x" . qed next fix X :: "'a multiset" and A assume nonempty: "A \<noteq> {}" and le: "\<And>Y. Y \<in> A \<Longrightarrow> X \<subseteq># Y" show "X \<subseteq># Inf A" proof (rule mset_subset_eqI) fix x from nonempty have "count X x \<le> (INF X\<in>A. count X x)" by (intro cInf_greatest) (auto intro: mset_subset_eq_count le) also from nonempty have "\<dots> = count (Inf A) x" by (simp add: count_Inf_multiset_nonempty) finally show "count X x \<le> count (Inf A) x" . qed next fix X :: "'a multiset" and A assume X: "X \<in> A" and bdd: "subset_mset.bdd_above A" show "X \<subseteq># Sup A" proof (rule mset_subset_eqI) fix x from X have "A \<noteq> {}" by auto have "count X x \<le> (SUP X\<in>A. count X x)" by (intro cSUP_upper X bdd_above_multiset_imp_bdd_above_count bdd) also from count_Sup_multiset_nonempty[OF \<open>A \<noteq> {}\<close> bdd] have "(SUP X\<in>A. count X x) = count (Sup A) x" by simp finally show "count X x \<le> count (Sup A) x" . qed next fix X :: "'a multiset" and A assume nonempty: "A \<noteq> {}" and ge: "\<And>Y. Y \<in> A \<Longrightarrow> Y \<subseteq># X" from ge have bdd: "subset_mset.bdd_above A" by blast show "Sup A \<subseteq># X" proof (rule mset_subset_eqI) fix x from count_Sup_multiset_nonempty[OF \<open>A \<noteq> {}\<close> bdd] have "count (Sup A) x = (SUP X\<in>A. count X x)" . also from nonempty have "\<dots> \<le> count X x" by (intro cSup_least) (auto intro: mset_subset_eq_count ge) finally show "count (Sup A) x \<le> count X x" . qed qed \<comment> \<open>FIXME: avoid junk stemming from type class interpretation\<close> lemma set_mset_Inf: assumes "A \<noteq> {}" shows "set_mset (Inf A) = (\<Inter>X\<in>A. set_mset X)" proof safe fix x X assume "x \<in># Inf A" "X \<in> A" hence nonempty: "A \<noteq> {}" by (auto simp: Inf_multiset_empty) from \<open>x \<in># Inf A\<close> have "{#x#} \<subseteq># Inf A" by auto also from \<open>X \<in> A\<close> have "\<dots> \<subseteq># X" by (rule subset_mset.cInf_lower) simp_all finally show "x \<in># X" by simp next fix x assume x: "x \<in> (\<Inter>X\<in>A. set_mset X)" hence "{#x#} \<subseteq># X" if "X \<in> A" for X using that by auto from assms and this have "{#x#} \<subseteq># Inf A" by (rule subset_mset.cInf_greatest) thus "x \<in># Inf A" by simp qed lemma in_Inf_multiset_iff: assumes "A \<noteq> {}" shows "x \<in># Inf A \<longleftrightarrow> (\<forall>X\<in>A. x \<in># X)" proof - from assms have "set_mset (Inf A) = (\<Inter>X\<in>A. set_mset X)" by (rule set_mset_Inf) also have "x \<in> \<dots> \<longleftrightarrow> (\<forall>X\<in>A. x \<in># X)" by simp finally show ?thesis . qed lemma in_Inf_multisetD: "x \<in># Inf A \<Longrightarrow> X \<in> A \<Longrightarrow> x \<in># X" by (subst (asm) in_Inf_multiset_iff) auto lemma set_mset_Sup: assumes "subset_mset.bdd_above A" shows "set_mset (Sup A) = (\<Union>X\<in>A. set_mset X)" proof safe fix x assume "x \<in># Sup A" hence nonempty: "A \<noteq> {}" by (auto simp: Sup_multiset_empty) show "x \<in> (\<Union>X\<in>A. set_mset X)" proof (rule ccontr) assume x: "x \<notin> (\<Union>X\<in>A. set_mset X)" have "count X x \<le> count (Sup A) x" if "X \<in> A" for X x using that by (intro mset_subset_eq_count subset_mset.cSup_upper assms) with x have "X \<subseteq># Sup A - {#x#}" if "X \<in> A" for X using that by (auto simp: subseteq_mset_def algebra_simps not_in_iff) hence "Sup A \<subseteq># Sup A - {#x#}" by (intro subset_mset.cSup_least nonempty) with \<open>x \<in># Sup A\<close> show False by (auto simp: subseteq_mset_def simp flip: count_greater_zero_iff dest!: spec[of _ x]) qed next fix x X assume "x \<in> set_mset X" "X \<in> A" hence "{#x#} \<subseteq># X" by auto also have "X \<subseteq># Sup A" by (intro subset_mset.cSup_upper \<open>X \<in> A\<close> assms) finally show "x \<in> set_mset (Sup A)" by simp qed lemma in_Sup_multiset_iff: assumes "subset_mset.bdd_above A" shows "x \<in># Sup A \<longleftrightarrow> (\<exists>X\<in>A. x \<in># X)" proof - from assms have "set_mset (Sup A) = (\<Union>X\<in>A. set_mset X)" by (rule set_mset_Sup) also have "x \<in> \<dots> \<longleftrightarrow> (\<exists>X\<in>A. x \<in># X)" by simp finally show ?thesis . qed lemma in_Sup_multisetD: assumes "x \<in># Sup A" shows "\<exists>X\<in>A. x \<in># X" proof - have "subset_mset.bdd_above A" by (rule ccontr) (insert assms, simp_all add: Sup_multiset_unbounded) with assms show ?thesis by (simp add: in_Sup_multiset_iff) qed interpretation subset_mset: distrib_lattice "(\<inter>#)" "(\<subseteq>#)" "(\<subset>#)" "(\<union>#)" proof fix A B C :: "'a multiset" show "A \<union># (B \<inter># C) = A \<union># B \<inter># (A \<union># C)" by (intro multiset_eqI) simp_all qed \<comment> \<open>FIXME: avoid junk stemming from type class interpretation\<close> subsubsection \<open>Filter (with comprehension syntax)\<close> text \<open>Multiset comprehension\<close> lift_definition filter_mset :: "('a \<Rightarrow> bool) \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" is "\<lambda>P M. \<lambda>x. if P x then M x else 0" by (rule filter_preserves_multiset) syntax (ASCII) "_MCollect" :: "pttrn \<Rightarrow> 'a multiset \<Rightarrow> bool \<Rightarrow> 'a multiset" ("(1{#_ :# _./ _#})") syntax "_MCollect" :: "pttrn \<Rightarrow> 'a multiset \<Rightarrow> bool \<Rightarrow> 'a multiset" ("(1{#_ \<in># _./ _#})") translations "{#x \<in># M. P#}" == "CONST filter_mset (\<lambda>x. P) M" lemma count_filter_mset [simp]: "count (filter_mset P M) a = (if P a then count M a else 0)" by (simp add: filter_mset.rep_eq) lemma set_mset_filter [simp]: "set_mset (filter_mset P M) = {a \<in> set_mset M. P a}" by (simp only: set_eq_iff count_greater_zero_iff [symmetric] count_filter_mset) simp lemma filter_empty_mset [simp]: "filter_mset P {#} = {#}" by (rule multiset_eqI) simp lemma filter_single_mset: "filter_mset P {#x#} = (if P x then {#x#} else {#})" by (rule multiset_eqI) simp lemma filter_union_mset [simp]: "filter_mset P (M + N) = filter_mset P M + filter_mset P N" by (rule multiset_eqI) simp lemma filter_diff_mset [simp]: "filter_mset P (M - N) = filter_mset P M - filter_mset P N" by (rule multiset_eqI) simp lemma filter_inter_mset [simp]: "filter_mset P (M \<inter># N) = filter_mset P M \<inter># filter_mset P N" by (rule multiset_eqI) simp lemma filter_sup_mset[simp]: "filter_mset P (A \<union># B) = filter_mset P A \<union># filter_mset P B" by (rule multiset_eqI) simp lemma filter_mset_add_mset [simp]: "filter_mset P (add_mset x A) = (if P x then add_mset x (filter_mset P A) else filter_mset P A)" by (auto simp: multiset_eq_iff) lemma multiset_filter_subset[simp]: "filter_mset f M \<subseteq># M" by (simp add: mset_subset_eqI) lemma multiset_filter_mono: assumes "A \<subseteq># B" shows "filter_mset f A \<subseteq># filter_mset f B" proof - from assms[unfolded mset_subset_eq_exists_conv] obtain C where B: "B = A + C" by auto show ?thesis unfolding B by auto qed lemma filter_mset_eq_conv: "filter_mset P M = N \<longleftrightarrow> N \<subseteq># M \<and> (\<forall>b\<in>#N. P b) \<and> (\<forall>a\<in>#M - N. \<not> P a)" (is "?P \<longleftrightarrow> ?Q") proof assume ?P then show ?Q by auto (simp add: multiset_eq_iff in_diff_count) next assume ?Q then obtain Q where M: "M = N + Q" by (auto simp add: mset_subset_eq_exists_conv) then have MN: "M - N = Q" by simp show ?P proof (rule multiset_eqI) fix a from \<open>?Q\<close> MN have *: "\<not> P a \<Longrightarrow> a \<notin># N" "P a \<Longrightarrow> a \<notin># Q" by auto show "count (filter_mset P M) a = count N a" proof (cases "a \<in># M") case True with * show ?thesis by (simp add: not_in_iff M) next case False then have "count M a = 0" by (simp add: not_in_iff) with M show ?thesis by simp qed qed qed lemma filter_filter_mset: "filter_mset P (filter_mset Q M) = {#x \<in># M. Q x \<and> P x#}" by (auto simp: multiset_eq_iff) lemma filter_mset_True[simp]: "{#y \<in># M. True#} = M" and filter_mset_False[simp]: "{#y \<in># M. False#} = {#}" by (auto simp: multiset_eq_iff) subsubsection \<open>Size\<close> definition wcount where "wcount f M = (\<lambda>x. count M x * Suc (f x))" lemma wcount_union: "wcount f (M + N) a = wcount f M a + wcount f N a" by (auto simp: wcount_def add_mult_distrib) lemma wcount_add_mset: "wcount f (add_mset x M) a = (if x = a then Suc (f a) else 0) + wcount f M a" unfolding add_mset_add_single[of _ M] wcount_union by (auto simp: wcount_def) definition size_multiset :: "('a \<Rightarrow> nat) \<Rightarrow> 'a multiset \<Rightarrow> nat" where "size_multiset f M = sum (wcount f M) (set_mset M)" lemmas size_multiset_eq = size_multiset_def[unfolded wcount_def] instantiation multiset :: (type) size begin definition size_multiset where size_multiset_overloaded_def: "size_multiset = Multiset.size_multiset (\<lambda>_. 0)" instance .. end lemmas size_multiset_overloaded_eq = size_multiset_overloaded_def[THEN fun_cong, unfolded size_multiset_eq, simplified] lemma size_multiset_empty [simp]: "size_multiset f {#} = 0" by (simp add: size_multiset_def) lemma size_empty [simp]: "size {#} = 0" by (simp add: size_multiset_overloaded_def) lemma size_multiset_single : "size_multiset f {#b#} = Suc (f b)" by (simp add: size_multiset_eq) lemma size_single: "size {#b#} = 1" by (simp add: size_multiset_overloaded_def size_multiset_single) lemma sum_wcount_Int: "finite A \<Longrightarrow> sum (wcount f N) (A \<inter> set_mset N) = sum (wcount f N) A" by (induct rule: finite_induct) (simp_all add: Int_insert_left wcount_def count_eq_zero_iff) lemma size_multiset_union [simp]: "size_multiset f (M + N::'a multiset) = size_multiset f M + size_multiset f N" apply (simp add: size_multiset_def sum_Un_nat sum.distrib sum_wcount_Int wcount_union) apply (subst Int_commute) apply (simp add: sum_wcount_Int) done lemma size_multiset_add_mset [simp]: "size_multiset f (add_mset a M) = Suc (f a) + size_multiset f M" unfolding add_mset_add_single[of _ M] size_multiset_union by (auto simp: size_multiset_single) lemma size_add_mset [simp]: "size (add_mset a A) = Suc (size A)" by (simp add: size_multiset_overloaded_def wcount_add_mset) lemma size_union [simp]: "size (M + N::'a multiset) = size M + size N" by (auto simp add: size_multiset_overloaded_def) lemma size_multiset_eq_0_iff_empty [iff]: "size_multiset f M = 0 \<longleftrightarrow> M = {#}" by (auto simp add: size_multiset_eq count_eq_zero_iff) lemma size_eq_0_iff_empty [iff]: "(size M = 0) = (M = {#})" by (auto simp add: size_multiset_overloaded_def) lemma nonempty_has_size: "(S \<noteq> {#}) = (0 < size S)" by (metis gr0I gr_implies_not0 size_empty size_eq_0_iff_empty) lemma size_eq_Suc_imp_elem: "size M = Suc n \<Longrightarrow> \<exists>a. a \<in># M" apply (unfold size_multiset_overloaded_eq) apply (drule sum_SucD) apply auto done lemma size_eq_Suc_imp_eq_union: assumes "size M = Suc n" shows "\<exists>a N. M = add_mset a N" proof - from assms obtain a where "a \<in># M" by (erule size_eq_Suc_imp_elem [THEN exE]) then have "M = add_mset a (M - {#a#})" by simp then show ?thesis by blast qed lemma size_mset_mono: fixes A B :: "'a multiset" assumes "A \<subseteq># B" shows "size A \<le> size B" proof - from assms[unfolded mset_subset_eq_exists_conv] obtain C where B: "B = A + C" by auto show ?thesis unfolding B by (induct C) auto qed lemma size_filter_mset_lesseq[simp]: "size (filter_mset f M) \<le> size M" by (rule size_mset_mono[OF multiset_filter_subset]) lemma size_Diff_submset: "M \<subseteq># M' \<Longrightarrow> size (M' - M) = size M' - size(M::'a multiset)" by (metis add_diff_cancel_left' size_union mset_subset_eq_exists_conv) subsection \<open>Induction and case splits\<close> theorem multiset_induct [case_names empty add, induct type: multiset]: assumes empty: "P {#}" assumes add: "\<And>x M. P M \<Longrightarrow> P (add_mset x M)" shows "P M" proof (induct "size M" arbitrary: M) case 0 thus "P M" by (simp add: empty) next case (Suc k) obtain N x where "M = add_mset x N" using \<open>Suc k = size M\<close> [symmetric] using size_eq_Suc_imp_eq_union by fast with Suc add show "P M" by simp qed lemma multiset_induct_min[case_names empty add]: fixes M :: "'a::linorder multiset" assumes empty: "P {#}" and add: "\<And>x M. P M \<Longrightarrow> (\<forall>y \<in># M. y \<ge> x) \<Longrightarrow> P (add_mset x M)" shows "P M" proof (induct "size M" arbitrary: M) case (Suc k) note ih = this(1) and Sk_eq_sz_M = this(2) let ?y = "Min_mset M" let ?N = "M - {#?y#}" have M: "M = add_mset ?y ?N" by (metis Min_in Sk_eq_sz_M finite_set_mset insert_DiffM lessI not_less_zero set_mset_eq_empty_iff size_empty) show ?case by (subst M, rule add, rule ih, metis M Sk_eq_sz_M nat.inject size_add_mset, meson Min_le finite_set_mset in_diffD) qed (simp add: empty) lemma multiset_induct_max[case_names empty add]: fixes M :: "'a::linorder multiset" assumes empty: "P {#}" and add: "\<And>x M. P M \<Longrightarrow> (\<forall>y \<in># M. y \<le> x) \<Longrightarrow> P (add_mset x M)" shows "P M" proof (induct "size M" arbitrary: M) case (Suc k) note ih = this(1) and Sk_eq_sz_M = this(2) let ?y = "Max_mset M" let ?N = "M - {#?y#}" have M: "M = add_mset ?y ?N" by (metis Max_in Sk_eq_sz_M finite_set_mset insert_DiffM lessI not_less_zero set_mset_eq_empty_iff size_empty) show ?case by (subst M, rule add, rule ih, metis M Sk_eq_sz_M nat.inject size_add_mset, meson Max_ge finite_set_mset in_diffD) qed (simp add: empty) lemma multi_nonempty_split: "M \<noteq> {#} \<Longrightarrow> \<exists>A a. M = add_mset a A" by (induct M) auto lemma multiset_cases [cases type]: obtains (empty) "M = {#}" | (add) x N where "M = add_mset x N" by (induct M) simp_all lemma multi_drop_mem_not_eq: "c \<in># B \<Longrightarrow> B - {#c#} \<noteq> B" by (cases "B = {#}") (auto dest: multi_member_split) lemma union_filter_mset_complement[simp]: "\<forall>x. P x = (\<not> Q x) \<Longrightarrow> filter_mset P M + filter_mset Q M = M" by (subst multiset_eq_iff) auto lemma multiset_partition: "M = {#x \<in># M. P x#} + {#x \<in># M. \<not> P x#}" by simp lemma mset_subset_size: "A \<subset># B \<Longrightarrow> size A < size B" proof (induct A arbitrary: B) case empty then show ?case using nonempty_has_size by auto next case (add x A) have "add_mset x A \<subseteq># B" by (meson add.prems subset_mset_def) then show ?case by (metis (no_types) add.prems add.right_neutral add_diff_cancel_left' leD nat_neq_iff size_Diff_submset size_eq_0_iff_empty size_mset_mono subset_mset.le_iff_add subset_mset_def) qed lemma size_1_singleton_mset: "size M = 1 \<Longrightarrow> \<exists>a. M = {#a#}" by (cases M) auto subsubsection \<open>Strong induction and subset induction for multisets\<close> text \<open>Well-foundedness of strict subset relation\<close> lemma wf_subset_mset_rel: "wf {(M, N :: 'a multiset). M \<subset># N}" apply (rule wf_measure [THEN wf_subset, where f1=size]) apply (clarsimp simp: measure_def inv_image_def mset_subset_size) done lemma full_multiset_induct [case_names less]: assumes ih: "\<And>B. \<forall>(A::'a multiset). A \<subset># B \<longrightarrow> P A \<Longrightarrow> P B" shows "P B" apply (rule wf_subset_mset_rel [THEN wf_induct]) apply (rule ih, auto) done lemma multi_subset_induct [consumes 2, case_names empty add]: assumes "F \<subseteq># A" and empty: "P {#}" and insert: "\<And>a F. a \<in># A \<Longrightarrow> P F \<Longrightarrow> P (add_mset a F)" shows "P F" proof - from \<open>F \<subseteq># A\<close> show ?thesis proof (induct F) show "P {#}" by fact next fix x F assume P: "F \<subseteq># A \<Longrightarrow> P F" and i: "add_mset x F \<subseteq># A" show "P (add_mset x F)" proof (rule insert) from i show "x \<in># A" by (auto dest: mset_subset_eq_insertD) from i have "F \<subseteq># A" by (auto dest: mset_subset_eq_insertD) with P show "P F" . qed qed qed subsection \<open>The fold combinator\<close> definition fold_mset :: "('a \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'b \<Rightarrow> 'a multiset \<Rightarrow> 'b" where "fold_mset f s M = Finite_Set.fold (\<lambda>x. f x ^^ count M x) s (set_mset M)" lemma fold_mset_empty [simp]: "fold_mset f s {#} = s" by (simp add: fold_mset_def) context comp_fun_commute begin lemma fold_mset_add_mset [simp]: "fold_mset f s (add_mset x M) = f x (fold_mset f s M)" proof - interpret mset: comp_fun_commute "\<lambda>y. f y ^^ count M y" by (fact comp_fun_commute_funpow) interpret mset_union: comp_fun_commute "\<lambda>y. f y ^^ count (add_mset x M) y" by (fact comp_fun_commute_funpow) show ?thesis proof (cases "x \<in> set_mset M") case False then have *: "count (add_mset x M) x = 1" by (simp add: not_in_iff) from False have "Finite_Set.fold (\<lambda>y. f y ^^ count (add_mset x M) y) s (set_mset M) = Finite_Set.fold (\<lambda>y. f y ^^ count M y) s (set_mset M)" by (auto intro!: Finite_Set.fold_cong comp_fun_commute_on_funpow) with False * show ?thesis by (simp add: fold_mset_def del: count_add_mset) next case True define N where "N = set_mset M - {x}" from N_def True have *: "set_mset M = insert x N" "x \<notin> N" "finite N" by auto then have "Finite_Set.fold (\<lambda>y. f y ^^ count (add_mset x M) y) s N = Finite_Set.fold (\<lambda>y. f y ^^ count M y) s N" by (auto intro!: Finite_Set.fold_cong comp_fun_commute_on_funpow) with * show ?thesis by (simp add: fold_mset_def del: count_add_mset) simp qed qed corollary fold_mset_single: "fold_mset f s {#x#} = f x s" by simp lemma fold_mset_fun_left_comm: "f x (fold_mset f s M) = fold_mset f (f x s) M" by (induct M) (simp_all add: fun_left_comm) lemma fold_mset_union [simp]: "fold_mset f s (M + N) = fold_mset f (fold_mset f s M) N" by (induct M) (simp_all add: fold_mset_fun_left_comm) lemma fold_mset_fusion: assumes "comp_fun_commute g" and *: "\<And>x y. h (g x y) = f x (h y)" shows "h (fold_mset g w A) = fold_mset f (h w) A" proof - interpret comp_fun_commute g by (fact assms) from * show ?thesis by (induct A) auto qed end lemma union_fold_mset_add_mset: "A + B = fold_mset add_mset A B" proof - interpret comp_fun_commute add_mset by standard auto show ?thesis by (induction B) auto qed text \<open> A note on code generation: When defining some function containing a subterm \<^term>\<open>fold_mset F\<close>, code generation is not automatic. When interpreting locale \<open>left_commutative\<close> with \<open>F\<close>, the would be code thms for \<^const>\<open>fold_mset\<close> become thms like \<^term>\<open>fold_mset F z {#} = z\<close> where \<open>F\<close> is not a pattern but contains defined symbols, i.e.\ is not a code thm. Hence a separate constant with its own code thms needs to be introduced for \<open>F\<close>. See the image operator below. \<close> subsection \<open>Image\<close> definition image_mset :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a multiset \<Rightarrow> 'b multiset" where "image_mset f = fold_mset (add_mset \<circ> f) {#}" lemma comp_fun_commute_mset_image: "comp_fun_commute (add_mset \<circ> f)" by unfold_locales (simp add: fun_eq_iff) lemma image_mset_empty [simp]: "image_mset f {#} = {#}" by (simp add: image_mset_def) lemma image_mset_single: "image_mset f {#x#} = {#f x#}" by (simp add: comp_fun_commute.fold_mset_add_mset comp_fun_commute_mset_image image_mset_def) lemma image_mset_union [simp]: "image_mset f (M + N) = image_mset f M + image_mset f N" proof - interpret comp_fun_commute "add_mset \<circ> f" by (fact comp_fun_commute_mset_image) show ?thesis by (induct N) (simp_all add: image_mset_def) qed corollary image_mset_add_mset [simp]: "image_mset f (add_mset a M) = add_mset (f a) (image_mset f M)" unfolding image_mset_union add_mset_add_single[of a M] by (simp add: image_mset_single) lemma set_image_mset [simp]: "set_mset (image_mset f M) = image f (set_mset M)" by (induct M) simp_all lemma size_image_mset [simp]: "size (image_mset f M) = size M" by (induct M) simp_all lemma image_mset_is_empty_iff [simp]: "image_mset f M = {#} \<longleftrightarrow> M = {#}" by (cases M) auto lemma image_mset_If: "image_mset (\<lambda>x. if P x then f x else g x) A = image_mset f (filter_mset P A) + image_mset g (filter_mset (\<lambda>x. \<not>P x) A)" by (induction A) auto lemma image_mset_Diff: assumes "B \<subseteq># A" shows "image_mset f (A - B) = image_mset f A - image_mset f B" proof - have "image_mset f (A - B + B) = image_mset f (A - B) + image_mset f B" by simp also from assms have "A - B + B = A" by (simp add: subset_mset.diff_add) finally show ?thesis by simp qed lemma count_image_mset: \<open>count (image_mset f A) x = (\<Sum>y\<in>f -` {x} \<inter> set_mset A. count A y)\<close> proof (induction A) case empty then show ?case by simp next case (add x A) moreover have *: "(if x = y then Suc n else n) = n + (if x = y then 1 else 0)" for n y by simp ultimately show ?case by (auto simp: sum.distrib intro!: sum.mono_neutral_left) qed lemma count_image_mset': \<open>count (image_mset f X) y = (\<Sum>x | x \<in># X \<and> y = f x. count X x)\<close> by (auto simp add: count_image_mset simp flip: singleton_conv2 simp add: Collect_conj_eq ac_simps) lemma image_mset_subseteq_mono: "A \<subseteq># B \<Longrightarrow> image_mset f A \<subseteq># image_mset f B" by (metis image_mset_union subset_mset.le_iff_add) lemma image_mset_subset_mono: "M \<subset># N \<Longrightarrow> image_mset f M \<subset># image_mset f N" by (metis (no_types) Diff_eq_empty_iff_mset image_mset_Diff image_mset_is_empty_iff image_mset_subseteq_mono subset_mset.less_le_not_le) syntax (ASCII) "_comprehension_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> 'a multiset" ("({#_/. _ :# _#})") syntax "_comprehension_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> 'a multiset" ("({#_/. _ \<in># _#})") translations "{#e. x \<in># M#}" \<rightleftharpoons> "CONST image_mset (\<lambda>x. e) M" syntax (ASCII) "_comprehension_mset'" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> bool \<Rightarrow> 'a multiset" ("({#_/ | _ :# _./ _#})") syntax "_comprehension_mset'" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> bool \<Rightarrow> 'a multiset" ("({#_/ | _ \<in># _./ _#})") translations "{#e | x\<in>#M. P#}" \<rightharpoonup> "{#e. x \<in># {# x\<in>#M. P#}#}" text \<open> This allows to write not just filters like \<^term>\<open>{#x\<in>#M. x<c#}\<close> but also images like \<^term>\<open>{#x+x. x\<in>#M #}\<close> and @{term [source] "{#x+x|x\<in>#M. x<c#}"}, where the latter is currently displayed as \<^term>\<open>{#x+x|x\<in>#M. x<c#}\<close>. \<close> lemma in_image_mset: "y \<in># {#f x. x \<in># M#} \<longleftrightarrow> y \<in> f ` set_mset M" by simp functor image_mset: image_mset proof - fix f g show "image_mset f \<circ> image_mset g = image_mset (f \<circ> g)" proof fix A show "(image_mset f \<circ> image_mset g) A = image_mset (f \<circ> g) A" by (induct A) simp_all qed show "image_mset id = id" proof fix A show "image_mset id A = id A" by (induct A) simp_all qed qed declare image_mset.id [simp] image_mset.identity [simp] lemma image_mset_id[simp]: "image_mset id x = x" unfolding id_def by auto lemma image_mset_cong: "(\<And>x. x \<in># M \<Longrightarrow> f x = g x) \<Longrightarrow> {#f x. x \<in># M#} = {#g x. x \<in># M#}" by (induct M) auto lemma image_mset_cong_pair: "(\<forall>x y. (x, y) \<in># M \<longrightarrow> f x y = g x y) \<Longrightarrow> {#f x y. (x, y) \<in># M#} = {#g x y. (x, y) \<in># M#}" by (metis image_mset_cong split_cong) lemma image_mset_const_eq: "{#c. a \<in># M#} = replicate_mset (size M) c" by (induct M) simp_all subsection \<open>Further conversions\<close> primrec mset :: "'a list \<Rightarrow> 'a multiset" where "mset [] = {#}" | "mset (a # x) = add_mset a (mset x)" lemma in_multiset_in_set: "x \<in># mset xs \<longleftrightarrow> x \<in> set xs" by (induct xs) simp_all lemma count_mset: "count (mset xs) x = length (filter (\<lambda>y. x = y) xs)" by (induct xs) simp_all lemma mset_zero_iff[simp]: "(mset x = {#}) = (x = [])" by (induct x) auto lemma mset_zero_iff_right[simp]: "({#} = mset x) = (x = [])" by (induct x) auto lemma count_mset_gt_0: "x \<in> set xs \<Longrightarrow> count (mset xs) x > 0" by (induction xs) auto lemma count_mset_0_iff [simp]: "count (mset xs) x = 0 \<longleftrightarrow> x \<notin> set xs" by (induction xs) auto lemma mset_single_iff[iff]: "mset xs = {#x#} \<longleftrightarrow> xs = [x]" by (cases xs) auto lemma mset_single_iff_right[iff]: "{#x#} = mset xs \<longleftrightarrow> xs = [x]" by (cases xs) auto lemma set_mset_mset[simp]: "set_mset (mset xs) = set xs" by (induct xs) auto lemma set_mset_comp_mset [simp]: "set_mset \<circ> mset = set" by (simp add: fun_eq_iff) lemma size_mset [simp]: "size (mset xs) = length xs" by (induct xs) simp_all lemma mset_append [simp]: "mset (xs @ ys) = mset xs + mset ys" by (induct xs arbitrary: ys) auto lemma mset_filter[simp]: "mset (filter P xs) = {#x \<in># mset xs. P x #}" by (induct xs) simp_all lemma mset_rev [simp]: "mset (rev xs) = mset xs" by (induct xs) simp_all lemma surj_mset: "surj mset" apply (unfold surj_def) apply (rule allI) apply (rule_tac M = y in multiset_induct) apply auto apply (rule_tac x = "x # xa" in exI) apply auto done lemma distinct_count_atmost_1: "distinct x = (\<forall>a. count (mset x) a = (if a \<in> set x then 1 else 0))" proof (induct x) case Nil then show ?case by simp next case (Cons x xs) show ?case (is "?lhs \<longleftrightarrow> ?rhs") proof assume ?lhs then show ?rhs using Cons by simp next assume ?rhs then have "x \<notin> set xs" by (simp split: if_splits) moreover from \<open>?rhs\<close> have "(\<forall>a. count (mset xs) a = (if a \<in> set xs then 1 else 0))" by (auto split: if_splits simp add: count_eq_zero_iff) ultimately show ?lhs using Cons by simp qed qed lemma mset_eq_setD: assumes "mset xs = mset ys" shows "set xs = set ys" proof - from assms have "set_mset (mset xs) = set_mset (mset ys)" by simp then show ?thesis by simp qed lemma set_eq_iff_mset_eq_distinct: \<open>distinct x \<Longrightarrow> distinct y \<Longrightarrow> set x = set y \<longleftrightarrow> mset x = mset y\<close> by (auto simp: multiset_eq_iff distinct_count_atmost_1) lemma set_eq_iff_mset_remdups_eq: \<open>set x = set y \<longleftrightarrow> mset (remdups x) = mset (remdups y)\<close> apply (rule iffI) apply (simp add: set_eq_iff_mset_eq_distinct[THEN iffD1]) apply (drule distinct_remdups [THEN distinct_remdups [THEN set_eq_iff_mset_eq_distinct [THEN iffD2]]]) apply simp done lemma mset_eq_imp_distinct_iff: \<open>distinct xs \<longleftrightarrow> distinct ys\<close> if \<open>mset xs = mset ys\<close> using that by (auto simp add: distinct_count_atmost_1 dest: mset_eq_setD) lemma nth_mem_mset: "i < length ls \<Longrightarrow> (ls ! i) \<in># mset ls" proof (induct ls arbitrary: i) case Nil then show ?case by simp next case Cons then show ?case by (cases i) auto qed lemma mset_remove1[simp]: "mset (remove1 a xs) = mset xs - {#a#}" by (induct xs) (auto simp add: multiset_eq_iff) lemma mset_eq_length: assumes "mset xs = mset ys" shows "length xs = length ys" using assms by (metis size_mset) lemma mset_eq_length_filter: assumes "mset xs = mset ys" shows "length (filter (\<lambda>x. z = x) xs) = length (filter (\<lambda>y. z = y) ys)" using assms by (metis count_mset) lemma fold_multiset_equiv: \<open>List.fold f xs = List.fold f ys\<close> if f: \<open>\<And>x y. x \<in> set xs \<Longrightarrow> y \<in> set xs \<Longrightarrow> f x \<circ> f y = f y \<circ> f x\<close> and \<open>mset xs = mset ys\<close> using f \<open>mset xs = mset ys\<close> [symmetric] proof (induction xs arbitrary: ys) case Nil then show ?case by simp next case (Cons x xs) then have *: \<open>set ys = set (x # xs)\<close> by (blast dest: mset_eq_setD) have \<open>\<And>x y. x \<in> set ys \<Longrightarrow> y \<in> set ys \<Longrightarrow> f x \<circ> f y = f y \<circ> f x\<close> by (rule Cons.prems(1)) (simp_all add: *) moreover from * have \<open>x \<in> set ys\<close> by simp ultimately have \<open>List.fold f ys = List.fold f (remove1 x ys) \<circ> f x\<close> by (fact fold_remove1_split) moreover from Cons.prems have \<open>List.fold f xs = List.fold f (remove1 x ys)\<close> by (auto intro: Cons.IH) ultimately show ?case by simp qed lemma fold_permuted_eq: \<open>List.fold (\<odot>) xs z = List.fold (\<odot>) ys z\<close> if \<open>mset xs = mset ys\<close> and \<open>P z\<close> and P: \<open>\<And>x z. x \<in> set xs \<Longrightarrow> P z \<Longrightarrow> P (x \<odot> z)\<close> and f: \<open>\<And>x y z. x \<in> set xs \<Longrightarrow> y \<in> set xs \<Longrightarrow> P z \<Longrightarrow> x \<odot> (y \<odot> z) = y \<odot> (x \<odot> z)\<close> for f (infixl \<open>\<odot>\<close> 70) using \<open>P z\<close> P f \<open>mset xs = mset ys\<close> [symmetric] proof (induction xs arbitrary: ys z) case Nil then show ?case by simp next case (Cons x xs) then have *: \<open>set ys = set (x # xs)\<close> by (blast dest: mset_eq_setD) have \<open>P z\<close> by (fact Cons.prems(1)) moreover have \<open>\<And>x z. x \<in> set ys \<Longrightarrow> P z \<Longrightarrow> P (x \<odot> z)\<close> by (rule Cons.prems(2)) (simp_all add: *) moreover have \<open>\<And>x y z. x \<in> set ys \<Longrightarrow> y \<in> set ys \<Longrightarrow> P z \<Longrightarrow> x \<odot> (y \<odot> z) = y \<odot> (x \<odot> z)\<close> by (rule Cons.prems(3)) (simp_all add: *) moreover from * have \<open>x \<in> set ys\<close> by simp ultimately have \<open>fold (\<odot>) ys z = fold (\<odot>) (remove1 x ys) (x \<odot> z)\<close> by (induction ys arbitrary: z) auto moreover from Cons.prems have \<open>fold (\<odot>) xs (x \<odot> z) = fold (\<odot>) (remove1 x ys) (x \<odot> z)\<close> by (auto intro: Cons.IH) ultimately show ?case by simp qed lemma mset_shuffles: "zs \<in> shuffles xs ys \<Longrightarrow> mset zs = mset xs + mset ys" by (induction xs ys arbitrary: zs rule: shuffles.induct) auto lemma mset_insort [simp]: "mset (insort x xs) = add_mset x (mset xs)" by (induct xs) simp_all lemma mset_map[simp]: "mset (map f xs) = image_mset f (mset xs)" by (induct xs) simp_all global_interpretation mset_set: folding add_mset "{#}" defines mset_set = "folding_on.F add_mset {#}" by standard (simp add: fun_eq_iff) lemma sum_multiset_singleton [simp]: "sum (\<lambda>n. {#n#}) A = mset_set A" by (induction A rule: infinite_finite_induct) auto lemma count_mset_set [simp]: "finite A \<Longrightarrow> x \<in> A \<Longrightarrow> count (mset_set A) x = 1" (is "PROP ?P") "\<not> finite A \<Longrightarrow> count (mset_set A) x = 0" (is "PROP ?Q") "x \<notin> A \<Longrightarrow> count (mset_set A) x = 0" (is "PROP ?R") proof - have *: "count (mset_set A) x = 0" if "x \<notin> A" for A proof (cases "finite A") case False then show ?thesis by simp next case True from True \<open>x \<notin> A\<close> show ?thesis by (induct A) auto qed then show "PROP ?P" "PROP ?Q" "PROP ?R" by (auto elim!: Set.set_insert) qed \<comment> \<open>TODO: maybe define \<^const>\<open>mset_set\<close> also in terms of \<^const>\<open>Abs_multiset\<close>\<close> lemma elem_mset_set[simp, intro]: "finite A \<Longrightarrow> x \<in># mset_set A \<longleftrightarrow> x \<in> A" by (induct A rule: finite_induct) simp_all lemma mset_set_Union: "finite A \<Longrightarrow> finite B \<Longrightarrow> A \<inter> B = {} \<Longrightarrow> mset_set (A \<union> B) = mset_set A + mset_set B" by (induction A rule: finite_induct) auto lemma filter_mset_mset_set [simp]: "finite A \<Longrightarrow> filter_mset P (mset_set A) = mset_set {x\<in>A. P x}" proof (induction A rule: finite_induct) case (insert x A) from insert.hyps have "filter_mset P (mset_set (insert x A)) = filter_mset P (mset_set A) + mset_set (if P x then {x} else {})" by simp also have "filter_mset P (mset_set A) = mset_set {x\<in>A. P x}" by (rule insert.IH) also from insert.hyps have "\<dots> + mset_set (if P x then {x} else {}) = mset_set ({x \<in> A. P x} \<union> (if P x then {x} else {}))" (is "_ = mset_set ?A") by (intro mset_set_Union [symmetric]) simp_all also from insert.hyps have "?A = {y\<in>insert x A. P y}" by auto finally show ?case . qed simp_all lemma mset_set_Diff: assumes "finite A" "B \<subseteq> A" shows "mset_set (A - B) = mset_set A - mset_set B" proof - from assms have "mset_set ((A - B) \<union> B) = mset_set (A - B) + mset_set B" by (intro mset_set_Union) (auto dest: finite_subset) also from assms have "A - B \<union> B = A" by blast finally show ?thesis by simp qed lemma mset_set_set: "distinct xs \<Longrightarrow> mset_set (set xs) = mset xs" by (induction xs) simp_all lemma count_mset_set': "count (mset_set A) x = (if finite A \<and> x \<in> A then 1 else 0)" by auto lemma subset_imp_msubset_mset_set: assumes "A \<subseteq> B" "finite B" shows "mset_set A \<subseteq># mset_set B" proof (rule mset_subset_eqI) fix x :: 'a from assms have "finite A" by (rule finite_subset) with assms show "count (mset_set A) x \<le> count (mset_set B) x" by (cases "x \<in> A"; cases "x \<in> B") auto qed lemma mset_set_set_mset_msubset: "mset_set (set_mset A) \<subseteq># A" proof (rule mset_subset_eqI) fix x show "count (mset_set (set_mset A)) x \<le> count A x" by (cases "x \<in># A") simp_all qed lemma mset_set_upto_eq_mset_upto: \<open>mset_set {..<n} = mset [0..<n]\<close> by (induction n) (auto simp: ac_simps lessThan_Suc) context linorder begin definition sorted_list_of_multiset :: "'a multiset \<Rightarrow> 'a list" where "sorted_list_of_multiset M = fold_mset insort [] M" lemma sorted_list_of_multiset_empty [simp]: "sorted_list_of_multiset {#} = []" by (simp add: sorted_list_of_multiset_def) lemma sorted_list_of_multiset_singleton [simp]: "sorted_list_of_multiset {#x#} = [x]" proof - interpret comp_fun_commute insort by (fact comp_fun_commute_insort) show ?thesis by (simp add: sorted_list_of_multiset_def) qed lemma sorted_list_of_multiset_insert [simp]: "sorted_list_of_multiset (add_mset x M) = List.insort x (sorted_list_of_multiset M)" proof - interpret comp_fun_commute insort by (fact comp_fun_commute_insort) show ?thesis by (simp add: sorted_list_of_multiset_def) qed end lemma mset_sorted_list_of_multiset[simp]: "mset (sorted_list_of_multiset M) = M" by (induct M) simp_all lemma sorted_list_of_multiset_mset[simp]: "sorted_list_of_multiset (mset xs) = sort xs" by (induct xs) simp_all lemma finite_set_mset_mset_set[simp]: "finite A \<Longrightarrow> set_mset (mset_set A) = A" by auto lemma mset_set_empty_iff: "mset_set A = {#} \<longleftrightarrow> A = {} \<or> infinite A" using finite_set_mset_mset_set by fastforce lemma infinite_set_mset_mset_set: "\<not> finite A \<Longrightarrow> set_mset (mset_set A) = {}" by simp lemma set_sorted_list_of_multiset [simp]: "set (sorted_list_of_multiset M) = set_mset M" by (induct M) (simp_all add: set_insort_key) lemma sorted_list_of_mset_set [simp]: "sorted_list_of_multiset (mset_set A) = sorted_list_of_set A" by (cases "finite A") (induct A rule: finite_induct, simp_all) lemma mset_upt [simp]: "mset [m..<n] = mset_set {m..<n}" by (induction n) (simp_all add: atLeastLessThanSuc) lemma image_mset_map_of: "distinct (map fst xs) \<Longrightarrow> {#the (map_of xs i). i \<in># mset (map fst xs)#} = mset (map snd xs)" proof (induction xs) case (Cons x xs) have "{#the (map_of (x # xs) i). i \<in># mset (map fst (x # xs))#} = add_mset (snd x) {#the (if i = fst x then Some (snd x) else map_of xs i). i \<in># mset (map fst xs)#}" (is "_ = add_mset _ ?A") by simp also from Cons.prems have "?A = {#the (map_of xs i). i :# mset (map fst xs)#}" by (cases x, intro image_mset_cong) (auto simp: in_multiset_in_set) also from Cons.prems have "\<dots> = mset (map snd xs)" by (intro Cons.IH) simp_all finally show ?case by simp qed simp_all lemma msubset_mset_set_iff[simp]: assumes "finite A" "finite B" shows "mset_set A \<subseteq># mset_set B \<longleftrightarrow> A \<subseteq> B" using assms set_mset_mono subset_imp_msubset_mset_set by fastforce lemma mset_set_eq_iff[simp]: assumes "finite A" "finite B" shows "mset_set A = mset_set B \<longleftrightarrow> A = B" using assms by (fastforce dest: finite_set_mset_mset_set) lemma image_mset_mset_set: \<^marker>\<open>contributor \<open>Lukas Bulwahn\<close>\<close> assumes "inj_on f A" shows "image_mset f (mset_set A) = mset_set (f ` A)" proof cases assume "finite A" from this \<open>inj_on f A\<close> show ?thesis by (induct A) auto next assume "infinite A" from this \<open>inj_on f A\<close> have "infinite (f ` A)" using finite_imageD by blast from \<open>infinite A\<close> \<open>infinite (f ` A)\<close> show ?thesis by simp qed subsection \<open>More properties of the replicate and repeat operations\<close> lemma in_replicate_mset[simp]: "x \<in># replicate_mset n y \<longleftrightarrow> n > 0 \<and> x = y" unfolding replicate_mset_def by (induct n) auto lemma set_mset_replicate_mset_subset[simp]: "set_mset (replicate_mset n x) = (if n = 0 then {} else {x})" by (auto split: if_splits) lemma size_replicate_mset[simp]: "size (replicate_mset n M) = n" by (induct n, simp_all) lemma count_le_replicate_mset_subset_eq: "n \<le> count M x \<longleftrightarrow> replicate_mset n x \<subseteq># M" by (auto simp add: mset_subset_eqI) (metis count_replicate_mset subseteq_mset_def) lemma filter_eq_replicate_mset: "{#y \<in># D. y = x#} = replicate_mset (count D x) x" by (induct D) simp_all lemma replicate_count_mset_eq_filter_eq: "replicate (count (mset xs) k) k = filter (HOL.eq k) xs" by (induct xs) auto lemma replicate_mset_eq_empty_iff [simp]: "replicate_mset n a = {#} \<longleftrightarrow> n = 0" by (induct n) simp_all lemma replicate_mset_eq_iff: "replicate_mset m a = replicate_mset n b \<longleftrightarrow> m = 0 \<and> n = 0 \<or> m = n \<and> a = b" by (auto simp add: multiset_eq_iff) lemma repeat_mset_cancel1: "repeat_mset a A = repeat_mset a B \<longleftrightarrow> A = B \<or> a = 0" by (auto simp: multiset_eq_iff) lemma repeat_mset_cancel2: "repeat_mset a A = repeat_mset b A \<longleftrightarrow> a = b \<or> A = {#}" by (auto simp: multiset_eq_iff) lemma repeat_mset_eq_empty_iff: "repeat_mset n A = {#} \<longleftrightarrow> n = 0 \<or> A = {#}" by (cases n) auto lemma image_replicate_mset [simp]: "image_mset f (replicate_mset n a) = replicate_mset n (f a)" by (induct n) simp_all lemma replicate_mset_msubseteq_iff: "replicate_mset m a \<subseteq># replicate_mset n b \<longleftrightarrow> m = 0 \<or> a = b \<and> m \<le> n" by (cases m) (auto simp: insert_subset_eq_iff simp flip: count_le_replicate_mset_subset_eq) lemma msubseteq_replicate_msetE: assumes "A \<subseteq># replicate_mset n a" obtains m where "m \<le> n" and "A = replicate_mset m a" proof (cases "n = 0") case True with assms that show thesis by simp next case False from assms have "set_mset A \<subseteq> set_mset (replicate_mset n a)" by (rule set_mset_mono) with False have "set_mset A \<subseteq> {a}" by simp then have "\<exists>m. A = replicate_mset m a" proof (induction A) case empty then show ?case by simp next case (add b A) then obtain m where "A = replicate_mset m a" by auto with add.prems show ?case by (auto intro: exI [of _ "Suc m"]) qed then obtain m where A: "A = replicate_mset m a" .. with assms have "m \<le> n" by (auto simp add: replicate_mset_msubseteq_iff) then show thesis using A .. qed subsection \<open>Big operators\<close> locale comm_monoid_mset = comm_monoid begin interpretation comp_fun_commute f by standard (simp add: fun_eq_iff left_commute) interpretation comp?: comp_fun_commute "f \<circ> g" by (fact comp_comp_fun_commute) context begin definition F :: "'a multiset \<Rightarrow> 'a" where eq_fold: "F M = fold_mset f \<^bold>1 M" lemma empty [simp]: "F {#} = \<^bold>1" by (simp add: eq_fold) lemma singleton [simp]: "F {#x#} = x" proof - interpret comp_fun_commute by standard (simp add: fun_eq_iff left_commute) show ?thesis by (simp add: eq_fold) qed lemma union [simp]: "F (M + N) = F M \<^bold>* F N" proof - interpret comp_fun_commute f by standard (simp add: fun_eq_iff left_commute) show ?thesis by (induct N) (simp_all add: left_commute eq_fold) qed lemma add_mset [simp]: "F (add_mset x N) = x \<^bold>* F N" unfolding add_mset_add_single[of x N] union by (simp add: ac_simps) lemma insert [simp]: shows "F (image_mset g (add_mset x A)) = g x \<^bold>* F (image_mset g A)" by (simp add: eq_fold) lemma remove: assumes "x \<in># A" shows "F A = x \<^bold>* F (A - {#x#})" using multi_member_split[OF assms] by auto lemma neutral: "\<forall>x\<in>#A. x = \<^bold>1 \<Longrightarrow> F A = \<^bold>1" by (induct A) simp_all lemma neutral_const [simp]: "F (image_mset (\<lambda>_. \<^bold>1) A) = \<^bold>1" by (simp add: neutral) private lemma F_image_mset_product: "F {#g x j \<^bold>* F {#g i j. i \<in># A#}. j \<in># B#} = F (image_mset (g x) B) \<^bold>* F {#F {#g i j. i \<in># A#}. j \<in># B#}" by (induction B) (simp_all add: left_commute semigroup.assoc semigroup_axioms) lemma swap: "F (image_mset (\<lambda>i. F (image_mset (g i) B)) A) = F (image_mset (\<lambda>j. F (image_mset (\<lambda>i. g i j) A)) B)" apply (induction A, simp) apply (induction B, auto simp add: F_image_mset_product ac_simps) done lemma distrib: "F (image_mset (\<lambda>x. g x \<^bold>* h x) A) = F (image_mset g A) \<^bold>* F (image_mset h A)" by (induction A) (auto simp: ac_simps) lemma union_disjoint: "A \<inter># B = {#} \<Longrightarrow> F (image_mset g (A \<union># B)) = F (image_mset g A) \<^bold>* F (image_mset g B)" by (induction A) (auto simp: ac_simps) end end lemma comp_fun_commute_plus_mset[simp]: "comp_fun_commute ((+) :: 'a multiset \<Rightarrow> _ \<Rightarrow> _)" by standard (simp add: add_ac comp_def) declare comp_fun_commute.fold_mset_add_mset[OF comp_fun_commute_plus_mset, simp] lemma in_mset_fold_plus_iff[iff]: "x \<in># fold_mset (+) M NN \<longleftrightarrow> x \<in># M \<or> (\<exists>N. N \<in># NN \<and> x \<in># N)" by (induct NN) auto context comm_monoid_add begin sublocale sum_mset: comm_monoid_mset plus 0 defines sum_mset = sum_mset.F .. lemma sum_unfold_sum_mset: "sum f A = sum_mset (image_mset f (mset_set A))" by (cases "finite A") (induct A rule: finite_induct, simp_all) end notation sum_mset ("\<Sum>\<^sub>#") syntax (ASCII) "_sum_mset_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add" ("(3SUM _:#_. _)" [0, 51, 10] 10) syntax "_sum_mset_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add" ("(3\<Sum>_\<in>#_. _)" [0, 51, 10] 10) translations "\<Sum>i \<in># A. b" \<rightleftharpoons> "CONST sum_mset (CONST image_mset (\<lambda>i. b) A)" context comm_monoid_add begin lemma sum_mset_sum_list: "sum_mset (mset xs) = sum_list xs" by (induction xs) auto end context canonically_ordered_monoid_add begin lemma sum_mset_0_iff [simp]: "sum_mset M = 0 \<longleftrightarrow> (\<forall>x \<in> set_mset M. x = 0)" by (induction M) auto end context ordered_comm_monoid_add begin lemma sum_mset_mono: "sum_mset (image_mset f K) \<le> sum_mset (image_mset g K)" if "\<And>i. i \<in># K \<Longrightarrow> f i \<le> g i" using that by (induction K) (simp_all add: add_mono) end context cancel_comm_monoid_add begin lemma sum_mset_diff: "sum_mset (M - N) = sum_mset M - sum_mset N" if "N \<subseteq># M" for M N :: "'a multiset" using that by (auto simp add: subset_mset.le_iff_add) end context semiring_0 begin lemma sum_mset_distrib_left: "c * (\<Sum>x \<in># M. f x) = (\<Sum>x \<in># M. c * f(x))" by (induction M) (simp_all add: algebra_simps) lemma sum_mset_distrib_right: "(\<Sum>x \<in># M. f x) * c = (\<Sum>x \<in># M. f x * c)" by (induction M) (simp_all add: algebra_simps) end lemma sum_mset_product: fixes f :: "'a::{comm_monoid_add,times} \<Rightarrow> 'b::semiring_0" shows "(\<Sum>i \<in># A. f i) * (\<Sum>i \<in># B. g i) = (\<Sum>i\<in>#A. \<Sum>j\<in>#B. f i * g j)" by (subst sum_mset.swap) (simp add: sum_mset_distrib_left sum_mset_distrib_right) context semiring_1 begin lemma sum_mset_replicate_mset [simp]: "sum_mset (replicate_mset n a) = of_nat n * a" by (induction n) (simp_all add: algebra_simps) lemma sum_mset_delta: "sum_mset (image_mset (\<lambda>x. if x = y then c else 0) A) = c * of_nat (count A y)" by (induction A) (simp_all add: algebra_simps) lemma sum_mset_delta': "sum_mset (image_mset (\<lambda>x. if y = x then c else 0) A) = c * of_nat (count A y)" by (induction A) (simp_all add: algebra_simps) end lemma of_nat_sum_mset [simp]: "of_nat (sum_mset A) = sum_mset (image_mset of_nat A)" by (induction A) auto lemma size_eq_sum_mset: "size M = (\<Sum>a\<in>#M. 1)" using image_mset_const_eq [of "1::nat" M] by simp lemma size_mset_set [simp]: "size (mset_set A) = card A" by (simp only: size_eq_sum_mset card_eq_sum sum_unfold_sum_mset) lemma sum_mset_constant [simp]: fixes y :: "'b::semiring_1" shows \<open>(\<Sum>x\<in>#A. y) = of_nat (size A) * y\<close> by (induction A) (auto simp: algebra_simps) lemma set_mset_Union_mset[simp]: "set_mset (\<Sum>\<^sub># MM) = (\<Union>M \<in> set_mset MM. set_mset M)" by (induct MM) auto lemma in_Union_mset_iff[iff]: "x \<in># \<Sum>\<^sub># MM \<longleftrightarrow> (\<exists>M. M \<in># MM \<and> x \<in># M)" by (induct MM) auto lemma count_sum: "count (sum f A) x = sum (\<lambda>a. count (f a) x) A" by (induct A rule: infinite_finite_induct) simp_all lemma sum_eq_empty_iff: assumes "finite A" shows "sum f A = {#} \<longleftrightarrow> (\<forall>a\<in>A. f a = {#})" using assms by induct simp_all lemma Union_mset_empty_conv[simp]: "\<Sum>\<^sub># M = {#} \<longleftrightarrow> (\<forall>i\<in>#M. i = {#})" by (induction M) auto lemma Union_image_single_mset[simp]: "\<Sum>\<^sub># (image_mset (\<lambda>x. {#x#}) m) = m" by(induction m) auto context comm_monoid_mult begin sublocale prod_mset: comm_monoid_mset times 1 defines prod_mset = prod_mset.F .. lemma prod_mset_empty: "prod_mset {#} = 1" by (fact prod_mset.empty) lemma prod_mset_singleton: "prod_mset {#x#} = x" by (fact prod_mset.singleton) lemma prod_mset_Un: "prod_mset (A + B) = prod_mset A * prod_mset B" by (fact prod_mset.union) lemma prod_mset_prod_list: "prod_mset (mset xs) = prod_list xs" by (induct xs) auto lemma prod_mset_replicate_mset [simp]: "prod_mset (replicate_mset n a) = a ^ n" by (induct n) simp_all lemma prod_unfold_prod_mset: "prod f A = prod_mset (image_mset f (mset_set A))" by (cases "finite A") (induct A rule: finite_induct, simp_all) lemma prod_mset_multiplicity: "prod_mset M = prod (\<lambda>x. x ^ count M x) (set_mset M)" by (simp add: fold_mset_def prod.eq_fold prod_mset.eq_fold funpow_times_power comp_def) lemma prod_mset_delta: "prod_mset (image_mset (\<lambda>x. if x = y then c else 1) A) = c ^ count A y" by (induction A) simp_all lemma prod_mset_delta': "prod_mset (image_mset (\<lambda>x. if y = x then c else 1) A) = c ^ count A y" by (induction A) simp_all lemma prod_mset_subset_imp_dvd: assumes "A \<subseteq># B" shows "prod_mset A dvd prod_mset B" proof - from assms have "B = (B - A) + A" by (simp add: subset_mset.diff_add) also have "prod_mset \<dots> = prod_mset (B - A) * prod_mset A" by simp also have "prod_mset A dvd \<dots>" by simp finally show ?thesis . qed lemma dvd_prod_mset: assumes "x \<in># A" shows "x dvd prod_mset A" using assms prod_mset_subset_imp_dvd [of "{#x#}" A] by simp end notation prod_mset ("\<Prod>\<^sub>#") syntax (ASCII) "_prod_mset_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult" ("(3PROD _:#_. _)" [0, 51, 10] 10) syntax "_prod_mset_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult" ("(3\<Prod>_\<in>#_. _)" [0, 51, 10] 10) translations "\<Prod>i \<in># A. b" \<rightleftharpoons> "CONST prod_mset (CONST image_mset (\<lambda>i. b) A)" lemma prod_mset_constant [simp]: "(\<Prod>_\<in>#A. c) = c ^ size A" by (simp add: image_mset_const_eq) lemma (in semidom) prod_mset_zero_iff [iff]: "prod_mset A = 0 \<longleftrightarrow> 0 \<in># A" by (induct A) auto lemma (in semidom_divide) prod_mset_diff: assumes "B \<subseteq># A" and "0 \<notin># B" shows "prod_mset (A - B) = prod_mset A div prod_mset B" proof - from assms obtain C where "A = B + C" by (metis subset_mset.add_diff_inverse) with assms show ?thesis by simp qed lemma (in semidom_divide) prod_mset_minus: assumes "a \<in># A" and "a \<noteq> 0" shows "prod_mset (A - {#a#}) = prod_mset A div a" using assms prod_mset_diff [of "{#a#}" A] by auto lemma (in normalization_semidom) normalize_prod_mset_normalize: "normalize (prod_mset (image_mset normalize A)) = normalize (prod_mset A)" proof (induction A) case (add x A) have "normalize (prod_mset (image_mset normalize (add_mset x A))) = normalize (x * normalize (prod_mset (image_mset normalize A)))" by simp also note add.IH finally show ?case by simp qed auto lemma (in algebraic_semidom) is_unit_prod_mset_iff: "is_unit (prod_mset A) \<longleftrightarrow> (\<forall>x \<in># A. is_unit x)" by (induct A) (auto simp: is_unit_mult_iff) lemma (in normalization_semidom_multiplicative) normalize_prod_mset: "normalize (prod_mset A) = prod_mset (image_mset normalize A)" by (induct A) (simp_all add: normalize_mult) lemma (in normalization_semidom_multiplicative) normalized_prod_msetI: assumes "\<And>a. a \<in># A \<Longrightarrow> normalize a = a" shows "normalize (prod_mset A) = prod_mset A" proof - from assms have "image_mset normalize A = A" by (induct A) simp_all then show ?thesis by (simp add: normalize_prod_mset) qed subsection \<open>Multiset as order-ignorant lists\<close> context linorder begin lemma mset_insort [simp]: "mset (insort_key k x xs) = add_mset x (mset xs)" by (induct xs) simp_all lemma mset_sort [simp]: "mset (sort_key k xs) = mset xs" by (induct xs) simp_all text \<open> This lemma shows which properties suffice to show that a function \<open>f\<close> with \<open>f xs = ys\<close> behaves like sort. \<close> lemma properties_for_sort_key: assumes "mset ys = mset xs" and "\<And>k. k \<in> set ys \<Longrightarrow> filter (\<lambda>x. f k = f x) ys = filter (\<lambda>x. f k = f x) xs" and "sorted (map f ys)" shows "sort_key f xs = ys" using assms proof (induct xs arbitrary: ys) case Nil then show ?case by simp next case (Cons x xs) from Cons.prems(2) have "\<forall>k \<in> set ys. filter (\<lambda>x. f k = f x) (remove1 x ys) = filter (\<lambda>x. f k = f x) xs" by (simp add: filter_remove1) with Cons.prems have "sort_key f xs = remove1 x ys" by (auto intro!: Cons.hyps simp add: sorted_map_remove1) moreover from Cons.prems have "x \<in># mset ys" by auto then have "x \<in> set ys" by simp ultimately show ?case using Cons.prems by (simp add: insort_key_remove1) qed lemma properties_for_sort: assumes multiset: "mset ys = mset xs" and "sorted ys" shows "sort xs = ys" proof (rule properties_for_sort_key) from multiset show "mset ys = mset xs" . from \<open>sorted ys\<close> show "sorted (map (\<lambda>x. x) ys)" by simp from multiset have "length (filter (\<lambda>y. k = y) ys) = length (filter (\<lambda>x. k = x) xs)" for k by (rule mset_eq_length_filter) then have "replicate (length (filter (\<lambda>y. k = y) ys)) k = replicate (length (filter (\<lambda>x. k = x) xs)) k" for k by simp then show "k \<in> set ys \<Longrightarrow> filter (\<lambda>y. k = y) ys = filter (\<lambda>x. k = x) xs" for k by (simp add: replicate_length_filter) qed lemma sort_key_inj_key_eq: assumes mset_equal: "mset xs = mset ys" and "inj_on f (set xs)" and "sorted (map f ys)" shows "sort_key f xs = ys" proof (rule properties_for_sort_key) from mset_equal show "mset ys = mset xs" by simp from \<open>sorted (map f ys)\<close> show "sorted (map f ys)" . show "[x\<leftarrow>ys . f k = f x] = [x\<leftarrow>xs . f k = f x]" if "k \<in> set ys" for k proof - from mset_equal have set_equal: "set xs = set ys" by (rule mset_eq_setD) with that have "insert k (set ys) = set ys" by auto with \<open>inj_on f (set xs)\<close> have inj: "inj_on f (insert k (set ys))" by (simp add: set_equal) from inj have "[x\<leftarrow>ys . f k = f x] = filter (HOL.eq k) ys" by (auto intro!: inj_on_filter_key_eq) also have "\<dots> = replicate (count (mset ys) k) k" by (simp add: replicate_count_mset_eq_filter_eq) also have "\<dots> = replicate (count (mset xs) k) k" using mset_equal by simp also have "\<dots> = filter (HOL.eq k) xs" by (simp add: replicate_count_mset_eq_filter_eq) also have "\<dots> = [x\<leftarrow>xs . f k = f x]" using inj by (auto intro!: inj_on_filter_key_eq [symmetric] simp add: set_equal) finally show ?thesis . qed qed lemma sort_key_eq_sort_key: assumes "mset xs = mset ys" and "inj_on f (set xs)" shows "sort_key f xs = sort_key f ys" by (rule sort_key_inj_key_eq) (simp_all add: assms) lemma sort_key_by_quicksort: "sort_key f xs = sort_key f [x\<leftarrow>xs. f x < f (xs ! (length xs div 2))] @ [x\<leftarrow>xs. f x = f (xs ! (length xs div 2))] @ sort_key f [x\<leftarrow>xs. f x > f (xs ! (length xs div 2))]" (is "sort_key f ?lhs = ?rhs") proof (rule properties_for_sort_key) show "mset ?rhs = mset ?lhs" by (rule multiset_eqI) auto show "sorted (map f ?rhs)" by (auto simp add: sorted_append intro: sorted_map_same) next fix l assume "l \<in> set ?rhs" let ?pivot = "f (xs ! (length xs div 2))" have *: "\<And>x. f l = f x \<longleftrightarrow> f x = f l" by auto have "[x \<leftarrow> sort_key f xs . f x = f l] = [x \<leftarrow> xs. f x = f l]" unfolding filter_sort by (rule properties_for_sort_key) (auto intro: sorted_map_same) with * have **: "[x \<leftarrow> sort_key f xs . f l = f x] = [x \<leftarrow> xs. f l = f x]" by simp have "\<And>x P. P (f x) ?pivot \<and> f l = f x \<longleftrightarrow> P (f l) ?pivot \<and> f l = f x" by auto then have "\<And>P. [x \<leftarrow> sort_key f xs . P (f x) ?pivot \<and> f l = f x] = [x \<leftarrow> sort_key f xs. P (f l) ?pivot \<and> f l = f x]" by simp note *** = this [of "(<)"] this [of "(>)"] this [of "(=)"] show "[x \<leftarrow> ?rhs. f l = f x] = [x \<leftarrow> ?lhs. f l = f x]" proof (cases "f l" ?pivot rule: linorder_cases) case less then have "f l \<noteq> ?pivot" and "\<not> f l > ?pivot" by auto with less show ?thesis by (simp add: filter_sort [symmetric] ** ***) next case equal then show ?thesis by (simp add: * less_le) next case greater then have "f l \<noteq> ?pivot" and "\<not> f l < ?pivot" by auto with greater show ?thesis by (simp add: filter_sort [symmetric] ** ***) qed qed lemma sort_by_quicksort: "sort xs = sort [x\<leftarrow>xs. x < xs ! (length xs div 2)] @ [x\<leftarrow>xs. x = xs ! (length xs div 2)] @ sort [x\<leftarrow>xs. x > xs ! (length xs div 2)]" (is "sort ?lhs = ?rhs") using sort_key_by_quicksort [of "\<lambda>x. x", symmetric] by simp text \<open>A stable parameterized quicksort\<close> definition part :: "('b \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> 'b list \<Rightarrow> 'b list \<times> 'b list \<times> 'b list" where "part f pivot xs = ([x \<leftarrow> xs. f x < pivot], [x \<leftarrow> xs. f x = pivot], [x \<leftarrow> xs. pivot < f x])" lemma part_code [code]: "part f pivot [] = ([], [], [])" "part f pivot (x # xs) = (let (lts, eqs, gts) = part f pivot xs; x' = f x in if x' < pivot then (x # lts, eqs, gts) else if x' > pivot then (lts, eqs, x # gts) else (lts, x # eqs, gts))" by (auto simp add: part_def Let_def split_def) lemma sort_key_by_quicksort_code [code]: "sort_key f xs = (case xs of [] \<Rightarrow> [] | [x] \<Rightarrow> xs | [x, y] \<Rightarrow> (if f x \<le> f y then xs else [y, x]) | _ \<Rightarrow> let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs in sort_key f lts @ eqs @ sort_key f gts)" proof (cases xs) case Nil then show ?thesis by simp next case (Cons _ ys) note hyps = Cons show ?thesis proof (cases ys) case Nil with hyps show ?thesis by simp next case (Cons _ zs) note hyps = hyps Cons show ?thesis proof (cases zs) case Nil with hyps show ?thesis by auto next case Cons from sort_key_by_quicksort [of f xs] have "sort_key f xs = (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs in sort_key f lts @ eqs @ sort_key f gts)" by (simp only: split_def Let_def part_def fst_conv snd_conv) with hyps Cons show ?thesis by (simp only: list.cases) qed qed qed end hide_const (open) part lemma mset_remdups_subset_eq: "mset (remdups xs) \<subseteq># mset xs" by (induct xs) (auto intro: subset_mset.order_trans) lemma mset_update: "i < length ls \<Longrightarrow> mset (ls[i := v]) = add_mset v (mset ls - {#ls ! i#})" proof (induct ls arbitrary: i) case Nil then show ?case by simp next case (Cons x xs) show ?case proof (cases i) case 0 then show ?thesis by simp next case (Suc i') with Cons show ?thesis by (cases \<open>x = xs ! i'\<close>) auto qed qed lemma mset_swap: "i < length ls \<Longrightarrow> j < length ls \<Longrightarrow> mset (ls[j := ls ! i, i := ls ! j]) = mset ls" by (cases "i = j") (simp_all add: mset_update nth_mem_mset) lemma mset_eq_finite: \<open>finite {ys. mset ys = mset xs}\<close> proof - have \<open>{ys. mset ys = mset xs} \<subseteq> {ys. set ys \<subseteq> set xs \<and> length ys \<le> length xs}\<close> by (auto simp add: dest: mset_eq_setD mset_eq_length) moreover have \<open>finite {ys. set ys \<subseteq> set xs \<and> length ys \<le> length xs}\<close> using finite_lists_length_le by blast ultimately show ?thesis by (rule finite_subset) qed subsection \<open>The multiset order\<close> subsubsection \<open>Well-foundedness\<close> definition mult1 :: "('a \<times> 'a) set \<Rightarrow> ('a multiset \<times> 'a multiset) set" where "mult1 r = {(N, M). \<exists>a M0 K. M = add_mset a M0 \<and> N = M0 + K \<and> (\<forall>b. b \<in># K \<longrightarrow> (b, a) \<in> r)}" definition mult :: "('a \<times> 'a) set \<Rightarrow> ('a multiset \<times> 'a multiset) set" where "mult r = (mult1 r)\<^sup>+" lemma mult1I: assumes "M = add_mset a M0" and "N = M0 + K" and "\<And>b. b \<in># K \<Longrightarrow> (b, a) \<in> r" shows "(N, M) \<in> mult1 r" using assms unfolding mult1_def by blast lemma mult1E: assumes "(N, M) \<in> mult1 r" obtains a M0 K where "M = add_mset a M0" "N = M0 + K" "\<And>b. b \<in># K \<Longrightarrow> (b, a) \<in> r" using assms unfolding mult1_def by blast lemma mono_mult1: assumes "r \<subseteq> r'" shows "mult1 r \<subseteq> mult1 r'" unfolding mult1_def using assms by blast lemma mono_mult: assumes "r \<subseteq> r'" shows "mult r \<subseteq> mult r'" unfolding mult_def using mono_mult1[OF assms] trancl_mono by blast lemma not_less_empty [iff]: "(M, {#}) \<notin> mult1 r" by (simp add: mult1_def) lemma less_add: assumes mult1: "(N, add_mset a M0) \<in> mult1 r" shows "(\<exists>M. (M, M0) \<in> mult1 r \<and> N = add_mset a M) \<or> (\<exists>K. (\<forall>b. b \<in># K \<longrightarrow> (b, a) \<in> r) \<and> N = M0 + K)" proof - let ?r = "\<lambda>K a. \<forall>b. b \<in># K \<longrightarrow> (b, a) \<in> r" let ?R = "\<lambda>N M. \<exists>a M0 K. M = add_mset a M0 \<and> N = M0 + K \<and> ?r K a" obtain a' M0' K where M0: "add_mset a M0 = add_mset a' M0'" and N: "N = M0' + K" and r: "?r K a'" using mult1 unfolding mult1_def by auto show ?thesis (is "?case1 \<or> ?case2") proof - from M0 consider "M0 = M0'" "a = a'" | K' where "M0 = add_mset a' K'" "M0' = add_mset a K'" by atomize_elim (simp only: add_eq_conv_ex) then show ?thesis proof cases case 1 with N r have "?r K a \<and> N = M0 + K" by simp then have ?case2 .. then show ?thesis .. next case 2 from N 2(2) have n: "N = add_mset a (K' + K)" by simp with r 2(1) have "?R (K' + K) M0" by blast with n have ?case1 by (simp add: mult1_def) then show ?thesis .. qed qed qed lemma all_accessible: assumes "wf r" shows "\<forall>M. M \<in> Wellfounded.acc (mult1 r)" proof let ?R = "mult1 r" let ?W = "Wellfounded.acc ?R" { fix M M0 a assume M0: "M0 \<in> ?W" and wf_hyp: "\<And>b. (b, a) \<in> r \<Longrightarrow> (\<forall>M \<in> ?W. add_mset b M \<in> ?W)" and acc_hyp: "\<forall>M. (M, M0) \<in> ?R \<longrightarrow> add_mset a M \<in> ?W" have "add_mset a M0 \<in> ?W" proof (rule accI [of "add_mset a M0"]) fix N assume "(N, add_mset a M0) \<in> ?R" then consider M where "(M, M0) \<in> ?R" "N = add_mset a M" | K where "\<forall>b. b \<in># K \<longrightarrow> (b, a) \<in> r" "N = M0 + K" by atomize_elim (rule less_add) then show "N \<in> ?W" proof cases case 1 from acc_hyp have "(M, M0) \<in> ?R \<longrightarrow> add_mset a M \<in> ?W" .. from this and \<open>(M, M0) \<in> ?R\<close> have "add_mset a M \<in> ?W" .. then show "N \<in> ?W" by (simp only: \<open>N = add_mset a M\<close>) next case 2 from this(1) have "M0 + K \<in> ?W" proof (induct K) case empty from M0 show "M0 + {#} \<in> ?W" by simp next case (add x K) from add.prems have "(x, a) \<in> r" by simp with wf_hyp have "\<forall>M \<in> ?W. add_mset x M \<in> ?W" by blast moreover from add have "M0 + K \<in> ?W" by simp ultimately have "add_mset x (M0 + K) \<in> ?W" .. then show "M0 + (add_mset x K) \<in> ?W" by simp qed then show "N \<in> ?W" by (simp only: 2(2)) qed qed } note tedious_reasoning = this show "M \<in> ?W" for M proof (induct M) show "{#} \<in> ?W" proof (rule accI) fix b assume "(b, {#}) \<in> ?R" with not_less_empty show "b \<in> ?W" by contradiction qed fix M a assume "M \<in> ?W" from \<open>wf r\<close> have "\<forall>M \<in> ?W. add_mset a M \<in> ?W" proof induct fix a assume r: "\<And>b. (b, a) \<in> r \<Longrightarrow> (\<forall>M \<in> ?W. add_mset b M \<in> ?W)" show "\<forall>M \<in> ?W. add_mset a M \<in> ?W" proof fix M assume "M \<in> ?W" then show "add_mset a M \<in> ?W" by (rule acc_induct) (rule tedious_reasoning [OF _ r]) qed qed from this and \<open>M \<in> ?W\<close> show "add_mset a M \<in> ?W" .. qed qed theorem wf_mult1: "wf r \<Longrightarrow> wf (mult1 r)" by (rule acc_wfI) (rule all_accessible) theorem wf_mult: "wf r \<Longrightarrow> wf (mult r)" unfolding mult_def by (rule wf_trancl) (rule wf_mult1) subsubsection \<open>Closure-free presentation\<close> text \<open>One direction.\<close> lemma mult_implies_one_step: assumes trans: "trans r" and MN: "(M, N) \<in> mult r" shows "\<exists>I J K. N = I + J \<and> M = I + K \<and> J \<noteq> {#} \<and> (\<forall>k \<in> set_mset K. \<exists>j \<in> set_mset J. (k, j) \<in> r)" using MN unfolding mult_def mult1_def proof (induction rule: converse_trancl_induct) case (base y) then show ?case by force next case (step y z) note yz = this(1) and zN = this(2) and N_decomp = this(3) obtain I J K where N: "N = I + J" "z = I + K" "J \<noteq> {#}" "\<forall>k\<in>#K. \<exists>j\<in>#J. (k, j) \<in> r" using N_decomp by blast obtain a M0 K' where z: "z = add_mset a M0" and y: "y = M0 + K'" and K: "\<forall>b. b \<in># K' \<longrightarrow> (b, a) \<in> r" using yz by blast show ?case proof (cases "a \<in># K") case True moreover have "\<exists>j\<in>#J. (k, j) \<in> r" if "k \<in># K'" for k using K N trans True by (meson that transE) ultimately show ?thesis by (rule_tac x = I in exI, rule_tac x = J in exI, rule_tac x = "(K - {#a#}) + K'" in exI) (use z y N in \<open>auto simp del: subset_mset.add_diff_assoc2 dest: in_diffD\<close>) next case False then have "a \<in># I" by (metis N(2) union_iff union_single_eq_member z) moreover have "M0 = I + K - {#a#}" using N(2) z by force ultimately show ?thesis by (rule_tac x = "I - {#a#}" in exI, rule_tac x = "add_mset a J" in exI, rule_tac x = "K + K'" in exI) (use z y N False K in \<open>auto simp: add.assoc\<close>) qed qed lemma one_step_implies_mult: assumes "J \<noteq> {#}" and "\<forall>k \<in> set_mset K. \<exists>j \<in> set_mset J. (k, j) \<in> r" shows "(I + K, I + J) \<in> mult r" using assms proof (induction "size J" arbitrary: I J K) case 0 then show ?case by auto next case (Suc n) note IH = this(1) and size_J = this(2)[THEN sym] obtain J' a where J: "J = add_mset a J'" using size_J by (blast dest: size_eq_Suc_imp_eq_union) show ?case proof (cases "J' = {#}") case True then show ?thesis using J Suc by (fastforce simp add: mult_def mult1_def) next case [simp]: False have K: "K = {#x \<in># K. (x, a) \<in> r#} + {#x \<in># K. (x, a) \<notin> r#}" by simp have "(I + K, (I + {# x \<in># K. (x, a) \<in> r #}) + J') \<in> mult r" using IH[of J' "{# x \<in># K. (x, a) \<notin> r#}" "I + {# x \<in># K. (x, a) \<in> r#}"] J Suc.prems K size_J by (auto simp: ac_simps) moreover have "(I + {#x \<in># K. (x, a) \<in> r#} + J', I + J) \<in> mult r" by (fastforce simp: J mult1_def mult_def) ultimately show ?thesis unfolding mult_def by simp qed qed lemma subset_implies_mult: assumes sub: "A \<subset># B" shows "(A, B) \<in> mult r" proof - have ApBmA: "A + (B - A) = B" using sub by simp have BmA: "B - A \<noteq> {#}" using sub by (simp add: Diff_eq_empty_iff_mset subset_mset.less_le_not_le) thus ?thesis by (rule one_step_implies_mult[of "B - A" "{#}" _ A, unfolded ApBmA, simplified]) qed subsection \<open>The multiset extension is cancellative for multiset union\<close> lemma mult_cancel: assumes "trans s" and "irrefl s" shows "(X + Z, Y + Z) \<in> mult s \<longleftrightarrow> (X, Y) \<in> mult s" (is "?L \<longleftrightarrow> ?R") proof assume ?L thus ?R proof (induct Z) case (add z Z) obtain X' Y' Z' where *: "add_mset z X + Z = Z' + X'" "add_mset z Y + Z = Z' + Y'" "Y' \<noteq> {#}" "\<forall>x \<in> set_mset X'. \<exists>y \<in> set_mset Y'. (x, y) \<in> s" using mult_implies_one_step[OF \<open>trans s\<close> add(2)] by auto consider Z2 where "Z' = add_mset z Z2" | X2 Y2 where "X' = add_mset z X2" "Y' = add_mset z Y2" using *(1,2) by (metis add_mset_remove_trivial_If insert_iff set_mset_add_mset_insert union_iff) thus ?case proof (cases) case 1 thus ?thesis using * one_step_implies_mult[of Y' X' s Z2] by (auto simp: add.commute[of _ "{#_#}"] add.assoc intro: add(1)) next case 2 then obtain y where "y \<in> set_mset Y2" "(z, y) \<in> s" using *(4) \<open>irrefl s\<close> by (auto simp: irrefl_def) moreover from this transD[OF \<open>trans s\<close> _ this(2)] have "x' \<in> set_mset X2 \<Longrightarrow> \<exists>y \<in> set_mset Y2. (x', y) \<in> s" for x' using 2 *(4)[rule_format, of x'] by auto ultimately show ?thesis using * one_step_implies_mult[of Y2 X2 s Z'] 2 by (force simp: add.commute[of "{#_#}"] add.assoc[symmetric] intro: add(1)) qed qed auto next assume ?R then obtain I J K where "Y = I + J" "X = I + K" "J \<noteq> {#}" "\<forall>k \<in> set_mset K. \<exists>j \<in> set_mset J. (k, j) \<in> s" using mult_implies_one_step[OF \<open>trans s\<close>] by blast thus ?L using one_step_implies_mult[of J K s "I + Z"] by (auto simp: ac_simps) qed lemmas mult_cancel_add_mset = mult_cancel[of _ _ "{#_#}", unfolded union_mset_add_mset_right add.comm_neutral] lemma mult_cancel_max: assumes "trans s" and "irrefl s" shows "(X, Y) \<in> mult s \<longleftrightarrow> (X - X \<inter># Y, Y - X \<inter># Y) \<in> mult s" (is "?L \<longleftrightarrow> ?R") proof - have "X - X \<inter># Y + X \<inter># Y = X" "Y - X \<inter># Y + X \<inter># Y = Y" by (auto simp flip: count_inject) thus ?thesis using mult_cancel[OF assms, of "X - X \<inter># Y" "X \<inter># Y" "Y - X \<inter># Y"] by auto qed subsection \<open>Quasi-executable version of the multiset extension\<close> text \<open> Predicate variants of \<open>mult\<close> and the reflexive closure of \<open>mult\<close>, which are executable whenever the given predicate \<open>P\<close> is. Together with the standard code equations for \<open>(\<inter>#\<close>) and \<open>(-\<close>) this should yield quadratic (with respect to calls to \<open>P\<close>) implementations of \<open>multp\<close> and \<open>multeqp\<close>. \<close> definition multp :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" where "multp P N M = (let Z = M \<inter># N; X = M - Z in X \<noteq> {#} \<and> (let Y = N - Z in (\<forall>y \<in> set_mset Y. \<exists>x \<in> set_mset X. P y x)))" definition multeqp :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" where "multeqp P N M = (let Z = M \<inter># N; X = M - Z; Y = N - Z in (\<forall>y \<in> set_mset Y. \<exists>x \<in> set_mset X. P y x))" lemma multp_iff: assumes "irrefl R" and "trans R" and [simp]: "\<And>x y. P x y \<longleftrightarrow> (x, y) \<in> R" shows "multp P N M \<longleftrightarrow> (N, M) \<in> mult R" (is "?L \<longleftrightarrow> ?R") proof - have *: "M \<inter># N + (N - M \<inter># N) = N" "M \<inter># N + (M - M \<inter># N) = M" "(M - M \<inter># N) \<inter># (N - M \<inter># N) = {#}" by (auto simp flip: count_inject) show ?thesis proof assume ?L thus ?R using one_step_implies_mult[of "M - M \<inter># N" "N - M \<inter># N" R "M \<inter># N"] * by (auto simp: multp_def Let_def) next { fix I J K :: "'a multiset" assume "(I + J) \<inter># (I + K) = {#}" then have "I = {#}" by (metis inter_union_distrib_right union_eq_empty) } note [dest!] = this assume ?R thus ?L using mult_implies_one_step[OF assms(2), of "N - M \<inter># N" "M - M \<inter># N"] mult_cancel_max[OF assms(2,1), of "N" "M"] * by (auto simp: multp_def) qed qed lemma multeqp_iff: assumes "irrefl R" and "trans R" and "\<And>x y. P x y \<longleftrightarrow> (x, y) \<in> R" shows "multeqp P N M \<longleftrightarrow> (N, M) \<in> (mult R)\<^sup>=" proof - { assume "N \<noteq> M" "M - M \<inter># N = {#}" then obtain y where "count N y \<noteq> count M y" by (auto simp flip: count_inject) then have "\<exists>y. count M y < count N y" using \<open>M - M \<inter># N = {#}\<close> by (auto simp flip: count_inject dest!: le_neq_implies_less fun_cong[of _ _ y]) } then have "multeqp P N M \<longleftrightarrow> multp P N M \<or> N = M" by (auto simp: multeqp_def multp_def Let_def in_diff_count) thus ?thesis using multp_iff[OF assms] by simp qed subsubsection \<open>Partial-order properties\<close> lemma (in preorder) mult1_lessE: assumes "(N, M) \<in> mult1 {(a, b). a < b}" obtains a M0 K where "M = add_mset a M0" "N = M0 + K" "a \<notin># K" "\<And>b. b \<in># K \<Longrightarrow> b < a" proof - from assms obtain a M0 K where "M = add_mset a M0" "N = M0 + K" and *: "b \<in># K \<Longrightarrow> b < a" for b by (blast elim: mult1E) moreover from * [of a] have "a \<notin># K" by auto ultimately show thesis by (auto intro: that) qed instantiation multiset :: (preorder) order begin definition less_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" where "M' < M \<longleftrightarrow> (M', M) \<in> mult {(x', x). x' < x}" definition less_eq_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" where "less_eq_multiset M' M \<longleftrightarrow> M' < M \<or> M' = M" instance proof - have irrefl: "\<not> M < M" for M :: "'a multiset" proof assume "M < M" then have MM: "(M, M) \<in> mult {(x, y). x < y}" by (simp add: less_multiset_def) have "trans {(x'::'a, x). x' < x}" by (metis (mono_tags, lifting) case_prodD case_prodI less_trans mem_Collect_eq transI) moreover note MM ultimately have "\<exists>I J K. M = I + J \<and> M = I + K \<and> J \<noteq> {#} \<and> (\<forall>k\<in>set_mset K. \<exists>j\<in>set_mset J. (k, j) \<in> {(x, y). x < y})" by (rule mult_implies_one_step) then obtain I J K where "M = I + J" and "M = I + K" and "J \<noteq> {#}" and "(\<forall>k\<in>set_mset K. \<exists>j\<in>set_mset J. (k, j) \<in> {(x, y). x < y})" by blast then have *: "K \<noteq> {#}" and **: "\<forall>k\<in>set_mset K. \<exists>j\<in>set_mset K. k < j" by auto have "finite (set_mset K)" by simp moreover note ** ultimately have "set_mset K = {}" by (induct rule: finite_induct) (auto intro: order_less_trans) with * show False by simp qed have trans: "K < M \<Longrightarrow> M < N \<Longrightarrow> K < N" for K M N :: "'a multiset" unfolding less_multiset_def mult_def by (blast intro: trancl_trans) show "OFCLASS('a multiset, order_class)" by standard (auto simp add: less_eq_multiset_def irrefl dest: trans) qed end lemma mset_le_irrefl [elim!]: fixes M :: "'a::preorder multiset" shows "M < M \<Longrightarrow> R" by simp subsubsection \<open>Monotonicity of multiset union\<close> lemma mult1_union: "(B, D) \<in> mult1 r \<Longrightarrow> (C + B, C + D) \<in> mult1 r" by (force simp: mult1_def) lemma union_le_mono2: "B < D \<Longrightarrow> C + B < C + (D::'a::preorder multiset)" apply (unfold less_multiset_def mult_def) apply (erule trancl_induct) apply (blast intro: mult1_union) apply (blast intro: mult1_union trancl_trans) done lemma union_le_mono1: "B < D \<Longrightarrow> B + C < D + (C::'a::preorder multiset)" apply (subst add.commute [of B C]) apply (subst add.commute [of D C]) apply (erule union_le_mono2) done lemma union_less_mono: fixes A B C D :: "'a::preorder multiset" shows "A < C \<Longrightarrow> B < D \<Longrightarrow> A + B < C + D" by (blast intro!: union_le_mono1 union_le_mono2 less_trans) instantiation multiset :: (preorder) ordered_ab_semigroup_add begin instance by standard (auto simp add: less_eq_multiset_def intro: union_le_mono2) end subsubsection \<open>Termination proofs with multiset orders\<close> lemma multi_member_skip: "x \<in># XS \<Longrightarrow> x \<in># {# y #} + XS" and multi_member_this: "x \<in># {# x #} + XS" and multi_member_last: "x \<in># {# x #}" by auto definition "ms_strict = mult pair_less" definition "ms_weak = ms_strict \<union> Id" lemma ms_reduction_pair: "reduction_pair (ms_strict, ms_weak)" unfolding reduction_pair_def ms_strict_def ms_weak_def pair_less_def by (auto intro: wf_mult1 wf_trancl simp: mult_def) lemma smsI: "(set_mset A, set_mset B) \<in> max_strict \<Longrightarrow> (Z + A, Z + B) \<in> ms_strict" unfolding ms_strict_def by (rule one_step_implies_mult) (auto simp add: max_strict_def pair_less_def elim!:max_ext.cases) lemma wmsI: "(set_mset A, set_mset B) \<in> max_strict \<or> A = {#} \<and> B = {#} \<Longrightarrow> (Z + A, Z + B) \<in> ms_weak" unfolding ms_weak_def ms_strict_def by (auto simp add: pair_less_def max_strict_def elim!:max_ext.cases intro: one_step_implies_mult) inductive pw_leq where pw_leq_empty: "pw_leq {#} {#}" | pw_leq_step: "\<lbrakk>(x,y) \<in> pair_leq; pw_leq X Y \<rbrakk> \<Longrightarrow> pw_leq ({#x#} + X) ({#y#} + Y)" lemma pw_leq_lstep: "(x, y) \<in> pair_leq \<Longrightarrow> pw_leq {#x#} {#y#}" by (drule pw_leq_step) (rule pw_leq_empty, simp) lemma pw_leq_split: assumes "pw_leq X Y" shows "\<exists>A B Z. X = A + Z \<and> Y = B + Z \<and> ((set_mset A, set_mset B) \<in> max_strict \<or> (B = {#} \<and> A = {#}))" using assms proof induct case pw_leq_empty thus ?case by auto next case (pw_leq_step x y X Y) then obtain A B Z where [simp]: "X = A + Z" "Y = B + Z" and 1[simp]: "(set_mset A, set_mset B) \<in> max_strict \<or> (B = {#} \<and> A = {#})" by auto from pw_leq_step consider "x = y" | "(x, y) \<in> pair_less" unfolding pair_leq_def by auto thus ?case proof cases case [simp]: 1 have "{#x#} + X = A + ({#y#}+Z) \<and> {#y#} + Y = B + ({#y#}+Z) \<and> ((set_mset A, set_mset B) \<in> max_strict \<or> (B = {#} \<and> A = {#}))" by auto thus ?thesis by blast next case 2 let ?A' = "{#x#} + A" and ?B' = "{#y#} + B" have "{#x#} + X = ?A' + Z" "{#y#} + Y = ?B' + Z" by auto moreover have "(set_mset ?A', set_mset ?B') \<in> max_strict" using 1 2 unfolding max_strict_def by (auto elim!: max_ext.cases) ultimately show ?thesis by blast qed qed lemma assumes pwleq: "pw_leq Z Z'" shows ms_strictI: "(set_mset A, set_mset B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_strict" and ms_weakI1: "(set_mset A, set_mset B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_weak" and ms_weakI2: "(Z + {#}, Z' + {#}) \<in> ms_weak" proof - from pw_leq_split[OF pwleq] obtain A' B' Z'' where [simp]: "Z = A' + Z''" "Z' = B' + Z''" and mx_or_empty: "(set_mset A', set_mset B') \<in> max_strict \<or> (A' = {#} \<and> B' = {#})" by blast { assume max: "(set_mset A, set_mset B) \<in> max_strict" from mx_or_empty have "(Z'' + (A + A'), Z'' + (B + B')) \<in> ms_strict" proof assume max': "(set_mset A', set_mset B') \<in> max_strict" with max have "(set_mset (A + A'), set_mset (B + B')) \<in> max_strict" by (auto simp: max_strict_def intro: max_ext_additive) thus ?thesis by (rule smsI) next assume [simp]: "A' = {#} \<and> B' = {#}" show ?thesis by (rule smsI) (auto intro: max) qed thus "(Z + A, Z' + B) \<in> ms_strict" by (simp add: ac_simps) thus "(Z + A, Z' + B) \<in> ms_weak" by (simp add: ms_weak_def) } from mx_or_empty have "(Z'' + A', Z'' + B') \<in> ms_weak" by (rule wmsI) thus "(Z + {#}, Z' + {#}) \<in> ms_weak" by (simp add: ac_simps) qed lemma empty_neutral: "{#} + x = x" "x + {#} = x" and nonempty_plus: "{# x #} + rs \<noteq> {#}" and nonempty_single: "{# x #} \<noteq> {#}" by auto setup \<open> let fun msetT T = \<^Type>\<open>multiset T\<close>; fun mk_mset T [] = \<^instantiate>\<open>'a = T in term \<open>{#}\<close>\<close> | mk_mset T [x] = \<^instantiate>\<open>'a = T and x in term \<open>{#x#}\<close>\<close> | mk_mset T (x :: xs) = \<^Const>\<open>plus \<open>msetT T\<close> for \<open>mk_mset T [x]\<close> \<open>mk_mset T xs\<close>\<close> fun mset_member_tac ctxt m i = if m <= 0 then resolve_tac ctxt @{thms multi_member_this} i ORELSE resolve_tac ctxt @{thms multi_member_last} i else resolve_tac ctxt @{thms multi_member_skip} i THEN mset_member_tac ctxt (m - 1) i fun mset_nonempty_tac ctxt = resolve_tac ctxt @{thms nonempty_plus} ORELSE' resolve_tac ctxt @{thms nonempty_single} fun regroup_munion_conv ctxt = Function_Lib.regroup_conv ctxt \<^const_abbrev>\<open>empty_mset\<close> \<^const_name>\<open>plus\<close> (map (fn t => t RS eq_reflection) (@{thms ac_simps} @ @{thms empty_neutral})) fun unfold_pwleq_tac ctxt i = (resolve_tac ctxt @{thms pw_leq_step} i THEN (fn st => unfold_pwleq_tac ctxt (i + 1) st)) ORELSE (resolve_tac ctxt @{thms pw_leq_lstep} i) ORELSE (resolve_tac ctxt @{thms pw_leq_empty} i) val set_mset_simps = [@{thm set_mset_empty}, @{thm set_mset_single}, @{thm set_mset_union}, @{thm Un_insert_left}, @{thm Un_empty_left}] in ScnpReconstruct.multiset_setup (ScnpReconstruct.Multiset { msetT=msetT, mk_mset=mk_mset, mset_regroup_conv=regroup_munion_conv, mset_member_tac=mset_member_tac, mset_nonempty_tac=mset_nonempty_tac, mset_pwleq_tac=unfold_pwleq_tac, set_of_simps=set_mset_simps, smsI'= @{thm ms_strictI}, wmsI2''= @{thm ms_weakI2}, wmsI1= @{thm ms_weakI1}, reduction_pair = @{thm ms_reduction_pair} }) end \<close> subsection \<open>Legacy theorem bindings\<close> lemmas multi_count_eq = multiset_eq_iff [symmetric] lemma union_commute: "M + N = N + (M::'a multiset)" by (fact add.commute) lemma union_assoc: "(M + N) + K = M + (N + (K::'a multiset))" by (fact add.assoc) lemma union_lcomm: "M + (N + K) = N + (M + (K::'a multiset))" by (fact add.left_commute) lemmas union_ac = union_assoc union_commute union_lcomm add_mset_commute lemma union_right_cancel: "M + K = N + K \<longleftrightarrow> M = (N::'a multiset)" by (fact add_right_cancel) lemma union_left_cancel: "K + M = K + N \<longleftrightarrow> M = (N::'a multiset)" by (fact add_left_cancel) lemma multi_union_self_other_eq: "(A::'a multiset) + X = A + Y \<Longrightarrow> X = Y" by (fact add_left_imp_eq) lemma mset_subset_trans: "(M::'a multiset) \<subset># K \<Longrightarrow> K \<subset># N \<Longrightarrow> M \<subset># N" by (fact subset_mset.less_trans) lemma multiset_inter_commute: "A \<inter># B = B \<inter># A" by (fact subset_mset.inf.commute) lemma multiset_inter_assoc: "A \<inter># (B \<inter># C) = A \<inter># B \<inter># C" by (fact subset_mset.inf.assoc [symmetric]) lemma multiset_inter_left_commute: "A \<inter># (B \<inter># C) = B \<inter># (A \<inter># C)" by (fact subset_mset.inf.left_commute) lemmas multiset_inter_ac = multiset_inter_commute multiset_inter_assoc multiset_inter_left_commute lemma mset_le_not_refl: "\<not> M < (M::'a::preorder multiset)" by (fact less_irrefl) lemma mset_le_trans: "K < M \<Longrightarrow> M < N \<Longrightarrow> K < (N::'a::preorder multiset)" by (fact less_trans) lemma mset_le_not_sym: "M < N \<Longrightarrow> \<not> N < (M::'a::preorder multiset)" by (fact less_not_sym) lemma mset_le_asym: "M < N \<Longrightarrow> (\<not> P \<Longrightarrow> N < (M::'a::preorder multiset)) \<Longrightarrow> P" by (fact less_asym) declaration \<open> let fun multiset_postproc _ maybe_name all_values (T as Type (_, [elem_T])) (Const _ $ t') = let val (maybe_opt, ps) = Nitpick_Model.dest_plain_fun t' ||> (~~) ||> map (apsnd (snd o HOLogic.dest_number)) fun elems_for t = (case AList.lookup (=) ps t of SOME n => replicate n t | NONE => [Const (maybe_name, elem_T --> elem_T) $ t]) in (case maps elems_for (all_values elem_T) @ (if maybe_opt then [Const (Nitpick_Model.unrep_mixfix (), elem_T)] else []) of [] => \<^Const>\<open>Groups.zero T\<close> | ts => foldl1 (fn (s, t) => \<^Const>\<open>add_mset elem_T for s t\<close>) ts) end | multiset_postproc _ _ _ _ t = t in Nitpick_Model.register_term_postprocessor \<^typ>\<open>'a multiset\<close> multiset_postproc end \<close> subsection \<open>Naive implementation using lists\<close> code_datatype mset lemma [code]: "add_mset x (mset xs) = mset (x # xs)" by simp lemma [code]: "Multiset.is_empty (mset xs) \<longleftrightarrow> List.null xs" by (simp add: Multiset.is_empty_def List.null_def) lemma union_code [code]: "mset xs + mset ys = mset (xs @ ys)" by simp lemma [code]: "image_mset f (mset xs) = mset (map f xs)" by simp lemma [code]: "filter_mset f (mset xs) = mset (filter f xs)" by simp lemma [code]: "mset xs - mset ys = mset (fold remove1 ys xs)" by (rule sym, induct ys arbitrary: xs) (simp_all add: diff_add diff_right_commute diff_diff_add) lemma [code]: "mset xs \<inter># mset ys = mset (snd (fold (\<lambda>x (ys, zs). if x \<in> set ys then (remove1 x ys, x # zs) else (ys, zs)) xs (ys, [])))" proof - have "\<And>zs. mset (snd (fold (\<lambda>x (ys, zs). if x \<in> set ys then (remove1 x ys, x # zs) else (ys, zs)) xs (ys, zs))) = (mset xs \<inter># mset ys) + mset zs" by (induct xs arbitrary: ys) (auto simp add: inter_add_right1 inter_add_right2 ac_simps) then show ?thesis by simp qed lemma [code]: "mset xs \<union># mset ys = mset (case_prod append (fold (\<lambda>x (ys, zs). (remove1 x ys, x # zs)) xs (ys, [])))" proof - have "\<And>zs. mset (case_prod append (fold (\<lambda>x (ys, zs). (remove1 x ys, x # zs)) xs (ys, zs))) = (mset xs \<union># mset ys) + mset zs" by (induct xs arbitrary: ys) (simp_all add: multiset_eq_iff) then show ?thesis by simp qed declare in_multiset_in_set [code_unfold] lemma [code]: "count (mset xs) x = fold (\<lambda>y. if x = y then Suc else id) xs 0" proof - have "\<And>n. fold (\<lambda>y. if x = y then Suc else id) xs n = count (mset xs) x + n" by (induct xs) simp_all then show ?thesis by simp qed declare set_mset_mset [code] declare sorted_list_of_multiset_mset [code] lemma [code]: \<comment> \<open>not very efficient, but representation-ignorant!\<close> "mset_set A = mset (sorted_list_of_set A)" apply (cases "finite A") apply simp_all apply (induct A rule: finite_induct) apply simp_all done declare size_mset [code] fun subset_eq_mset_impl :: "'a list \<Rightarrow> 'a list \<Rightarrow> bool option" where "subset_eq_mset_impl [] ys = Some (ys \<noteq> [])" | "subset_eq_mset_impl (Cons x xs) ys = (case List.extract ((=) x) ys of None \<Rightarrow> None | Some (ys1,_,ys2) \<Rightarrow> subset_eq_mset_impl xs (ys1 @ ys2))" lemma subset_eq_mset_impl: "(subset_eq_mset_impl xs ys = None \<longleftrightarrow> \<not> mset xs \<subseteq># mset ys) \<and> (subset_eq_mset_impl xs ys = Some True \<longleftrightarrow> mset xs \<subset># mset ys) \<and> (subset_eq_mset_impl xs ys = Some False \<longrightarrow> mset xs = mset ys)" proof (induct xs arbitrary: ys) case (Nil ys) show ?case by (auto simp: subset_mset.zero_less_iff_neq_zero) next case (Cons x xs ys) show ?case proof (cases "List.extract ((=) x) ys") case None hence x: "x \<notin> set ys" by (simp add: extract_None_iff) { assume "mset (x # xs) \<subseteq># mset ys" from set_mset_mono[OF this] x have False by simp } note nle = this moreover { assume "mset (x # xs) \<subset># mset ys" hence "mset (x # xs) \<subseteq># mset ys" by auto from nle[OF this] have False . } ultimately show ?thesis using None by auto next case (Some res) obtain ys1 y ys2 where res: "res = (ys1,y,ys2)" by (cases res, auto) note Some = Some[unfolded res] from extract_SomeE[OF Some] have "ys = ys1 @ x # ys2" by simp hence id: "mset ys = add_mset x (mset (ys1 @ ys2))" by auto show ?thesis unfolding subset_eq_mset_impl.simps unfolding Some option.simps split unfolding id using Cons[of "ys1 @ ys2"] unfolding subset_mset_def subseteq_mset_def by auto qed qed lemma [code]: "mset xs \<subseteq># mset ys \<longleftrightarrow> subset_eq_mset_impl xs ys \<noteq> None" using subset_eq_mset_impl[of xs ys] by (cases "subset_eq_mset_impl xs ys", auto) lemma [code]: "mset xs \<subset># mset ys \<longleftrightarrow> subset_eq_mset_impl xs ys = Some True" using subset_eq_mset_impl[of xs ys] by (cases "subset_eq_mset_impl xs ys", auto) instantiation multiset :: (equal) equal begin definition [code del]: "HOL.equal A (B :: 'a multiset) \<longleftrightarrow> A = B" lemma [code]: "HOL.equal (mset xs) (mset ys) \<longleftrightarrow> subset_eq_mset_impl xs ys = Some False" unfolding equal_multiset_def using subset_eq_mset_impl[of xs ys] by (cases "subset_eq_mset_impl xs ys", auto) instance by standard (simp add: equal_multiset_def) end declare sum_mset_sum_list [code] lemma [code]: "prod_mset (mset xs) = fold times xs 1" proof - have "\<And>x. fold times xs x = prod_mset (mset xs) * x" by (induct xs) (simp_all add: ac_simps) then show ?thesis by simp qed text \<open> Exercise for the casual reader: add implementations for \<^term>\<open>(\<le>)\<close> and \<^term>\<open>(<)\<close> (multiset order). \<close> text \<open>Quickcheck generators\<close> context includes term_syntax begin definition msetify :: "'a::typerep list \<times> (unit \<Rightarrow> Code_Evaluation.term) \<Rightarrow> 'a multiset \<times> (unit \<Rightarrow> Code_Evaluation.term)" where [code_unfold]: "msetify xs = Code_Evaluation.valtermify mset {\<cdot>} xs" end instantiation multiset :: (random) random begin context includes state_combinator_syntax begin definition "Quickcheck_Random.random i = Quickcheck_Random.random i \<circ>\<rightarrow> (\<lambda>xs. Pair (msetify xs))" instance .. end end instantiation multiset :: (full_exhaustive) full_exhaustive begin definition full_exhaustive_multiset :: "('a multiset \<times> (unit \<Rightarrow> term) \<Rightarrow> (bool \<times> term list) option) \<Rightarrow> natural \<Rightarrow> (bool \<times> term list) option" where "full_exhaustive_multiset f i = Quickcheck_Exhaustive.full_exhaustive (\<lambda>xs. f (msetify xs)) i" instance .. end hide_const (open) msetify subsection \<open>BNF setup\<close> definition rel_mset where "rel_mset R X Y \<longleftrightarrow> (\<exists>xs ys. mset xs = X \<and> mset ys = Y \<and> list_all2 R xs ys)" lemma mset_zip_take_Cons_drop_twice: assumes "length xs = length ys" "j \<le> length xs" shows "mset (zip (take j xs @ x # drop j xs) (take j ys @ y # drop j ys)) = add_mset (x,y) (mset (zip xs ys))" using assms proof (induct xs ys arbitrary: x y j rule: list_induct2) case Nil thus ?case by simp next case (Cons x xs y ys) thus ?case proof (cases "j = 0") case True thus ?thesis by simp next case False then obtain k where k: "j = Suc k" by (cases j) simp hence "k \<le> length xs" using Cons.prems by auto hence "mset (zip (take k xs @ x # drop k xs) (take k ys @ y # drop k ys)) = add_mset (x,y) (mset (zip xs ys))" by (rule Cons.hyps(2)) thus ?thesis unfolding k by auto qed qed lemma ex_mset_zip_left: assumes "length xs = length ys" "mset xs' = mset xs" shows "\<exists>ys'. length ys' = length xs' \<and> mset (zip xs' ys') = mset (zip xs ys)" using assms proof (induct xs ys arbitrary: xs' rule: list_induct2) case Nil thus ?case by auto next case (Cons x xs y ys xs') obtain j where j_len: "j < length xs'" and nth_j: "xs' ! j = x" by (metis Cons.prems in_set_conv_nth list.set_intros(1) mset_eq_setD) define xsa where "xsa = take j xs' @ drop (Suc j) xs'" have "mset xs' = {#x#} + mset xsa" unfolding xsa_def using j_len nth_j by (metis Cons_nth_drop_Suc union_mset_add_mset_right add_mset_remove_trivial add_diff_cancel_left' append_take_drop_id mset.simps(2) mset_append) hence ms_x: "mset xsa = mset xs" by (simp add: Cons.prems) then obtain ysa where len_a: "length ysa = length xsa" and ms_a: "mset (zip xsa ysa) = mset (zip xs ys)" using Cons.hyps(2) by blast define ys' where "ys' = take j ysa @ y # drop j ysa" have xs': "xs' = take j xsa @ x # drop j xsa" using ms_x j_len nth_j Cons.prems xsa_def by (metis append_eq_append_conv append_take_drop_id diff_Suc_Suc Cons_nth_drop_Suc length_Cons length_drop size_mset) have j_len': "j \<le> length xsa" using j_len xs' xsa_def by (metis add_Suc_right append_take_drop_id length_Cons length_append less_eq_Suc_le not_less) have "length ys' = length xs'" unfolding ys'_def using Cons.prems len_a ms_x by (metis add_Suc_right append_take_drop_id length_Cons length_append mset_eq_length) moreover have "mset (zip xs' ys') = mset (zip (x # xs) (y # ys))" unfolding xs' ys'_def by (rule trans[OF mset_zip_take_Cons_drop_twice]) (auto simp: len_a ms_a j_len') ultimately show ?case by blast qed lemma list_all2_reorder_left_invariance: assumes rel: "list_all2 R xs ys" and ms_x: "mset xs' = mset xs" shows "\<exists>ys'. list_all2 R xs' ys' \<and> mset ys' = mset ys" proof - have len: "length xs = length ys" using rel list_all2_conv_all_nth by auto obtain ys' where len': "length xs' = length ys'" and ms_xy: "mset (zip xs' ys') = mset (zip xs ys)" using len ms_x by (metis ex_mset_zip_left) have "list_all2 R xs' ys'" using assms(1) len' ms_xy unfolding list_all2_iff by (blast dest: mset_eq_setD) moreover have "mset ys' = mset ys" using len len' ms_xy map_snd_zip mset_map by metis ultimately show ?thesis by blast qed lemma ex_mset: "\<exists>xs. mset xs = X" by (induct X) (simp, metis mset.simps(2)) inductive pred_mset :: "('a \<Rightarrow> bool) \<Rightarrow> 'a multiset \<Rightarrow> bool" where "pred_mset P {#}" | "\<lbrakk>P a; pred_mset P M\<rbrakk> \<Longrightarrow> pred_mset P (add_mset a M)" lemma pred_mset_iff: \<comment> \<open>TODO: alias for \<^const>\<open>Multiset.Ball\<close>\<close> \<open>pred_mset P M \<longleftrightarrow> Multiset.Ball M P\<close> (is \<open>?P \<longleftrightarrow> ?Q\<close>) proof assume ?P then show ?Q by induction simp_all next assume ?Q then show ?P by (induction M) (auto intro: pred_mset.intros) qed bnf "'a multiset" map: image_mset sets: set_mset bd: natLeq wits: "{#}" rel: rel_mset pred: pred_mset proof - show "image_mset id = id" by (rule image_mset.id) show "image_mset (g \<circ> f) = image_mset g \<circ> image_mset f" for f g unfolding comp_def by (rule ext) (simp add: comp_def image_mset.compositionality) show "(\<And>z. z \<in> set_mset X \<Longrightarrow> f z = g z) \<Longrightarrow> image_mset f X = image_mset g X" for f g X by (induct X) simp_all show "set_mset \<circ> image_mset f = (`) f \<circ> set_mset" for f by auto show "card_order natLeq" by (rule natLeq_card_order) show "BNF_Cardinal_Arithmetic.cinfinite natLeq" by (rule natLeq_cinfinite) show "ordLeq3 (card_of (set_mset X)) natLeq" for X by transfer (auto intro!: ordLess_imp_ordLeq simp: finite_iff_ordLess_natLeq[symmetric]) show "rel_mset R OO rel_mset S \<le> rel_mset (R OO S)" for R S unfolding rel_mset_def[abs_def] OO_def apply clarify subgoal for X Z Y xs ys' ys zs apply (drule list_all2_reorder_left_invariance [where xs = ys' and ys = zs and xs' = ys]) apply (auto intro: list_all2_trans) done done show "rel_mset R = (\<lambda>x y. \<exists>z. set_mset z \<subseteq> {(x, y). R x y} \<and> image_mset fst z = x \<and> image_mset snd z = y)" for R unfolding rel_mset_def[abs_def] apply (rule ext)+ apply safe apply (rule_tac x = "mset (zip xs ys)" in exI; auto simp: in_set_zip list_all2_iff simp flip: mset_map) apply (rename_tac XY) apply (cut_tac X = XY in ex_mset) apply (erule exE) apply (rename_tac xys) apply (rule_tac x = "map fst xys" in exI) apply (auto simp: mset_map) apply (rule_tac x = "map snd xys" in exI) apply (auto simp: mset_map list_all2I subset_eq zip_map_fst_snd) done show "z \<in> set_mset {#} \<Longrightarrow> False" for z by auto show "pred_mset P = (\<lambda>x. Ball (set_mset x) P)" for P by (simp add: fun_eq_iff pred_mset_iff) qed inductive rel_mset' :: \<open>('a \<Rightarrow> 'b \<Rightarrow> bool) \<Rightarrow> 'a multiset \<Rightarrow> 'b multiset \<Rightarrow> bool\<close> where Zero[intro]: "rel_mset' R {#} {#}" | Plus[intro]: "\<lbrakk>R a b; rel_mset' R M N\<rbrakk> \<Longrightarrow> rel_mset' R (add_mset a M) (add_mset b N)" lemma rel_mset_Zero: "rel_mset R {#} {#}" unfolding rel_mset_def Grp_def by auto declare multiset.count[simp] declare count_Abs_multiset[simp] declare multiset.count_inverse[simp] lemma rel_mset_Plus: assumes ab: "R a b" and MN: "rel_mset R M N" shows "rel_mset R (add_mset a M) (add_mset b N)" proof - have "\<exists>ya. add_mset a (image_mset fst y) = image_mset fst ya \<and> add_mset b (image_mset snd y) = image_mset snd ya \<and> set_mset ya \<subseteq> {(x, y). R x y}" if "R a b" and "set_mset y \<subseteq> {(x, y). R x y}" for y using that by (intro exI[of _ "add_mset (a,b) y"]) auto thus ?thesis using assms unfolding multiset.rel_compp_Grp Grp_def by blast qed lemma rel_mset'_imp_rel_mset: "rel_mset' R M N \<Longrightarrow> rel_mset R M N" by (induct rule: rel_mset'.induct) (auto simp: rel_mset_Zero rel_mset_Plus) lemma rel_mset_size: "rel_mset R M N \<Longrightarrow> size M = size N" unfolding multiset.rel_compp_Grp Grp_def by auto lemma rel_mset_Zero_iff [simp]: shows "rel_mset rel {#} Y \<longleftrightarrow> Y = {#}" and "rel_mset rel X {#} \<longleftrightarrow> X = {#}" by (auto simp add: rel_mset_Zero dest: rel_mset_size) lemma multiset_induct2[case_names empty addL addR]: assumes empty: "P {#} {#}" and addL: "\<And>a M N. P M N \<Longrightarrow> P (add_mset a M) N" and addR: "\<And>a M N. P M N \<Longrightarrow> P M (add_mset a N)" shows "P M N" apply(induct N rule: multiset_induct) apply(induct M rule: multiset_induct, rule empty, erule addL) apply(induct M rule: multiset_induct, erule addR, erule addR) done lemma multiset_induct2_size[consumes 1, case_names empty add]: assumes c: "size M = size N" and empty: "P {#} {#}" and add: "\<And>a b M N a b. P M N \<Longrightarrow> P (add_mset a M) (add_mset b N)" shows "P M N" using c proof (induct M arbitrary: N rule: measure_induct_rule[of size]) case (less M) show ?case proof(cases "M = {#}") case True hence "N = {#}" using less.prems by auto thus ?thesis using True empty by auto next case False then obtain M1 a where M: "M = add_mset a M1" by (metis multi_nonempty_split) have "N \<noteq> {#}" using False less.prems by auto then obtain N1 b where N: "N = add_mset b N1" by (metis multi_nonempty_split) have "size M1 = size N1" using less.prems unfolding M N by auto thus ?thesis using M N less.hyps add by auto qed qed lemma msed_map_invL: assumes "image_mset f (add_mset a M) = N" shows "\<exists>N1. N = add_mset (f a) N1 \<and> image_mset f M = N1" proof - have "f a \<in># N" using assms multiset.set_map[of f "add_mset a M"] by auto then obtain N1 where N: "N = add_mset (f a) N1" using multi_member_split by metis have "image_mset f M = N1" using assms unfolding N by simp thus ?thesis using N by blast qed lemma msed_map_invR: assumes "image_mset f M = add_mset b N" shows "\<exists>M1 a. M = add_mset a M1 \<and> f a = b \<and> image_mset f M1 = N" proof - obtain a where a: "a \<in># M" and fa: "f a = b" using multiset.set_map[of f M] unfolding assms by (metis image_iff union_single_eq_member) then obtain M1 where M: "M = add_mset a M1" using multi_member_split by metis have "image_mset f M1 = N" using assms unfolding M fa[symmetric] by simp thus ?thesis using M fa by blast qed lemma msed_rel_invL: assumes "rel_mset R (add_mset a M) N" shows "\<exists>N1 b. N = add_mset b N1 \<and> R a b \<and> rel_mset R M N1" proof - obtain K where KM: "image_mset fst K = add_mset a M" and KN: "image_mset snd K = N" and sK: "set_mset K \<subseteq> {(a, b). R a b}" using assms unfolding multiset.rel_compp_Grp Grp_def by auto obtain K1 ab where K: "K = add_mset ab K1" and a: "fst ab = a" and K1M: "image_mset fst K1 = M" using msed_map_invR[OF KM] by auto obtain N1 where N: "N = add_mset (snd ab) N1" and K1N1: "image_mset snd K1 = N1" using msed_map_invL[OF KN[unfolded K]] by auto have Rab: "R a (snd ab)" using sK a unfolding K by auto have "rel_mset R M N1" using sK K1M K1N1 unfolding K multiset.rel_compp_Grp Grp_def by auto thus ?thesis using N Rab by auto qed lemma msed_rel_invR: assumes "rel_mset R M (add_mset b N)" shows "\<exists>M1 a. M = add_mset a M1 \<and> R a b \<and> rel_mset R M1 N" proof - obtain K where KN: "image_mset snd K = add_mset b N" and KM: "image_mset fst K = M" and sK: "set_mset K \<subseteq> {(a, b). R a b}" using assms unfolding multiset.rel_compp_Grp Grp_def by auto obtain K1 ab where K: "K = add_mset ab K1" and b: "snd ab = b" and K1N: "image_mset snd K1 = N" using msed_map_invR[OF KN] by auto obtain M1 where M: "M = add_mset (fst ab) M1" and K1M1: "image_mset fst K1 = M1" using msed_map_invL[OF KM[unfolded K]] by auto have Rab: "R (fst ab) b" using sK b unfolding K by auto have "rel_mset R M1 N" using sK K1N K1M1 unfolding K multiset.rel_compp_Grp Grp_def by auto thus ?thesis using M Rab by auto qed lemma rel_mset_imp_rel_mset': assumes "rel_mset R M N" shows "rel_mset' R M N" using assms proof(induct M arbitrary: N rule: measure_induct_rule[of size]) case (less M) have c: "size M = size N" using rel_mset_size[OF less.prems] . show ?case proof(cases "M = {#}") case True hence "N = {#}" using c by simp thus ?thesis using True rel_mset'.Zero by auto next case False then obtain M1 a where M: "M = add_mset a M1" by (metis multi_nonempty_split) obtain N1 b where N: "N = add_mset b N1" and R: "R a b" and ms: "rel_mset R M1 N1" using msed_rel_invL[OF less.prems[unfolded M]] by auto have "rel_mset' R M1 N1" using less.hyps[of M1 N1] ms unfolding M by simp thus ?thesis using rel_mset'.Plus[of R a b, OF R] unfolding M N by simp qed qed lemma rel_mset_rel_mset': "rel_mset R M N = rel_mset' R M N" using rel_mset_imp_rel_mset' rel_mset'_imp_rel_mset by auto text \<open>The main end product for \<^const>\<open>rel_mset\<close>: inductive characterization:\<close> lemmas rel_mset_induct[case_names empty add, induct pred: rel_mset] = rel_mset'.induct[unfolded rel_mset_rel_mset'[symmetric]] subsection \<open>Size setup\<close> lemma size_multiset_o_map: "size_multiset g \<circ> image_mset f = size_multiset (g \<circ> f)" apply (rule ext) subgoal for x by (induct x) auto done setup \<open> BNF_LFP_Size.register_size_global \<^type_name>\<open>multiset\<close> \<^const_name>\<open>size_multiset\<close> @{thm size_multiset_overloaded_def} @{thms size_multiset_empty size_multiset_single size_multiset_union size_empty size_single size_union} @{thms size_multiset_o_map} \<close> subsection \<open>Lemmas about Size\<close> lemma size_mset_SucE: "size A = Suc n \<Longrightarrow> (\<And>a B. A = {#a#} + B \<Longrightarrow> size B = n \<Longrightarrow> P) \<Longrightarrow> P" by (cases A) (auto simp add: ac_simps) lemma size_Suc_Diff1: "x \<in># M \<Longrightarrow> Suc (size (M - {#x#})) = size M" using arg_cong[OF insert_DiffM, of _ _ size] by simp lemma size_Diff_singleton: "x \<in># M \<Longrightarrow> size (M - {#x#}) = size M - 1" by (simp flip: size_Suc_Diff1) lemma size_Diff_singleton_if: "size (A - {#x#}) = (if x \<in># A then size A - 1 else size A)" by (simp add: diff_single_trivial size_Diff_singleton) lemma size_Un_Int: "size A + size B = size (A \<union># B) + size (A \<inter># B)" by (metis inter_subset_eq_union size_union subset_mset.diff_add union_diff_inter_eq_sup) lemma size_Un_disjoint: "A \<inter># B = {#} \<Longrightarrow> size (A \<union># B) = size A + size B" using size_Un_Int[of A B] by simp lemma size_Diff_subset_Int: "size (M - M') = size M - size (M \<inter># M')" by (metis diff_intersect_left_idem size_Diff_submset subset_mset.inf_le1) lemma diff_size_le_size_Diff: "size (M :: _ multiset) - size M' \<le> size (M - M')" by (simp add: diff_le_mono2 size_Diff_subset_Int size_mset_mono) lemma size_Diff1_less: "x\<in># M \<Longrightarrow> size (M - {#x#}) < size M" by (rule Suc_less_SucD) (simp add: size_Suc_Diff1) lemma size_Diff2_less: "x\<in># M \<Longrightarrow> y\<in># M \<Longrightarrow> size (M - {#x#} - {#y#}) < size M" by (metis less_imp_diff_less size_Diff1_less size_Diff_subset_Int) lemma size_Diff1_le: "size (M - {#x#}) \<le> size M" by (cases "x \<in># M") (simp_all add: size_Diff1_less less_imp_le diff_single_trivial) lemma size_psubset: "M \<subseteq># M' \<Longrightarrow> size M < size M' \<Longrightarrow> M \<subset># M'" using less_irrefl subset_mset_def by blast hide_const (open) wcount (**************) definition "isMset \<equiv> \<lambda>f. finite {x. (0::nat) < f x}" lemma type_definition_multiset: "type_definition count Abs_multiset (Collect isMset)" by (metis (no_types, lifting) Collect_cong isMset_def type_definition_multiset) lemma isMset_aux: "isMset = isMset " .. local_setup \<open>RLTHM @{binding isMset_rlt_aux} @{thm isMset_aux}\<close> lemma isMset_rlt_simp': "neper R \<Longrightarrow> isMset_rlt R f = finite_rlt R {x. R x x \<and> 0 < f x}" unfolding isMset_rlt_def by (simp add: zero_nat_rlt_eq less_nat_rlt_eq) thm finite_rlt_simp lemma rel_fun_closed_less: "neper R \<Longrightarrow> rel_fun R (=) f f \<Longrightarrow> closed R {x. R x x \<and> 0 < f x}" unfolding closed_def rel_fun_def by simp (metis neper_def per_def) lemma isMset_rlt_simp[simp]: "neper R \<Longrightarrow> rel_fun R (=) f f \<Longrightarrow> isMset_rlt R f = finite {getRepr R x | x . R x x \<and> 0 < f x}" apply(subst isMset_rlt_simp') subgoal by simp subgoal apply(subst finite_rlt_simp) subgoal . subgoal unfolding rel_fun_def rel_set_def by auto subgoal using rel_fun_closed_less by blast subgoal by auto . . lemmas finite_rlt_subset = finite_rlt_subset'[simped] find_theorems type_definition name: multiset term Abs_multiset term count find_theorems "rel_mset" count lemma neper_rel_mset[simp]: "neper R \<Longrightarrow> neper (rel_mset R)" apply(rule relator_pres_neper[of rel_mset]) subgoal using multiset.rel_compp by blast subgoal using multiset.rel_conversep . subgoal using rel_mset_Zero by blast subgoal . . (* *) definition gg :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> ('a multiset) \<Rightarrow> ('a \<Rightarrow> nat)" where "gg \<equiv> \<lambda>R M. \<lambda>x. sum (count M) {y . y \<in># M \<and> R x y}" lemma rel_fun_eq_constant[simp,intro!]: "rel_fun R (=) (\<lambda>_. a) (\<lambda>_. a)" unfolding rel_fun_def by auto (* *) lemma neper_rel_mset_sum_count: assumes R: "neper R" and RAA': "rel_mset R A A'" shows "sum (count A) {y. y \<in># A \<and> R a y} = sum (count A') {y'. y' \<in># A' \<and> R a y'}" using RAA' R proof(induction rule: rel_mset_induct) case (empty R) then show ?case by auto next case (add R x x' M M') note R = `neper R` note IH = add.IH[OF R] {assume "R a x" "x \<in># M" note x = this have 0: "{y. y \<in># add_mset x M \<and> R a y} = {y. y \<in># M \<and> R a y}" "{y. y \<in># add_mset x M \<and> R a y} = insert x {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y}" "{y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y} = {y. y \<noteq> x \<and> y \<in># M \<and> R a y}" "{y. y \<in># M \<and> R a y} = insert x {y. y \<noteq> x \<and> y \<in># M \<and> R a y}" using x by auto have "sum (count (add_mset x M)) {y. y \<in># add_mset x M \<and> R a y} = Suc (count M x) + sum (count (add_mset x M)) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y}" unfolding 0 apply(subst comm_monoid_add_class.sum.insert) by auto also have "sum (count (add_mset x M)) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y} = sum (count M) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y}" apply(rule comm_monoid_add_class.sum.cong) by auto also have "Suc (count M x) + sum (count M) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y} = Suc (count M x + sum (count M) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y})" by simp also have "sum (count M) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y} = sum (count M) {y. y \<noteq> x \<and> y \<in># M \<and> R a y}" unfolding 0 .. also have "count M x + sum (count M) {y. y \<noteq> x \<and> y \<in># M \<and> R a y} = sum (count M) {y. y \<in># M \<and> R a y}" unfolding 0 apply(subst comm_monoid_add_class.sum.insert) by auto ultimately have mainx: "sum (count (add_mset x M)) {y. y \<in># add_mset x M \<and> R a y} = Suc (sum (count M) {y. y \<in># M \<and> R a y})" by auto } note fact1 = this {assume "R a x" "\<not> x \<in># M" note x = this have 0: "{y. y \<in># add_mset x M \<and> R a y} = insert x {y. y \<in># M \<and> R a y}" "{y. y \<in># add_mset x M \<and> R a y} = insert x {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y}" "{y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y} = {y. y \<noteq> x \<and> y \<in># M \<and> R a y}" "{y. y \<in># M \<and> R a y} = {y. y \<noteq> x \<and> y \<in># M \<and> R a y}" using x by auto have "sum (count (add_mset x M)) {y. y \<in># add_mset x M \<and> R a y} = Suc (count M x) + sum (count (add_mset x M)) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y}" unfolding 0 apply(subst comm_monoid_add_class.sum.insert) by auto also have "sum (count (add_mset x M)) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y} = sum (count M) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y}" apply(rule comm_monoid_add_class.sum.cong) by auto also have "Suc (count M x) + sum (count M) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y} = Suc (count M x + sum (count M) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y})" by simp also have "sum (count M) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y} = sum (count M) {y. y \<noteq> x \<and> y \<in># M \<and> R a y}" unfolding 0 .. also have "sum (count M) {y. y \<noteq> x \<and> y \<in># M \<and> R a y} = sum (count M) {y. y \<in># M \<and> R a y}" unfolding 0 .. also have "count M x = 0" using x by (simp add: not_in_iff) ultimately have mainx: "sum (count (add_mset x M)) {y. y \<in># add_mset x M \<and> R a y} = Suc (sum (count M) {y. y \<in># M \<and> R a y})" by auto } note fact2 = this {assume "\<not> R a x" note x = this have 0: "{y. y \<in># add_mset x M \<and> R a y} = {y. y \<in># M \<and> R a y}" "{y. y \<in># add_mset x M \<and> R a y} = {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y}" "{y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y} = {y. y \<noteq> x \<and> y \<in># M \<and> R a y}" "{y. y \<in># M \<and> R a y} = {y. y \<noteq> x \<and> y \<in># M \<and> R a y}" using x by auto have "sum (count (add_mset x M)) {y. y \<in># add_mset x M \<and> R a y} = sum (count (add_mset x M)) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y}" unfolding 0 .. also have "sum (count (add_mset x M)) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y} = sum (count M) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y}" apply(rule comm_monoid_add_class.sum.cong) by auto also have "sum (count M) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y} = sum (count M) {y. y \<noteq> x \<and> y \<in># M \<and> R a y}" unfolding 0 .. also have "sum (count M) {y. y \<noteq> x \<and> y \<in># M \<and> R a y} = sum (count M) {y. y \<in># M \<and> R a y}" unfolding 0 .. ultimately have mainx: "sum (count (add_mset x M)) {y. y \<in># add_mset x M \<and> R a y} = sum (count M) {y. y \<in># M \<and> R a y}" by auto } note fact3 = this (* *) {assume "R a x'" "x' \<in># M'" note x' = this have 0: "{y. y \<in># add_mset x' M' \<and> R a y} = {y. y \<in># M' \<and> R a y}" "{y. y \<in># add_mset x' M' \<and> R a y} = insert x' {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y}" "{y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y} = {y. y \<noteq> x' \<and> y \<in># M' \<and> R a y}" "{y. y \<in># M' \<and> R a y} = insert x' {y. y \<noteq> x' \<and> y \<in># M' \<and> R a y}" using x' by auto have "sum (count (add_mset x' M')) {y. y \<in># add_mset x' M' \<and> R a y} = Suc (count M' x') + sum (count (add_mset x' M')) {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y}" unfolding 0 apply(subst comm_monoid_add_class.sum.insert) by auto also have "sum (count (add_mset x' M')) {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y} = sum (count M') {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y}" apply(rule comm_monoid_add_class.sum.cong) by auto also have "Suc (count M' x') + sum (count M') {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y} = Suc (count M' x' + sum (count M') {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y})" by simp also have "sum (count M') {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y} = sum (count M') {y. y \<noteq> x' \<and> y \<in># M' \<and> R a y}" unfolding 0 .. also have "count M' x' + sum (count M') {y. y \<noteq> x' \<and> y \<in># M' \<and> R a y} = sum (count M') {y. y \<in># M' \<and> R a y}" unfolding 0 apply(subst comm_monoid_add_class.sum.insert) by auto ultimately have mainx': "sum (count (add_mset x' M')) {y. y \<in># add_mset x' M' \<and> R a y} = Suc (sum (count M') {y. y \<in># M' \<and> R a y})" by auto } note fact1' = this {assume "R a x'" "\<not> x' \<in># M'" note x' = this have 0: "{y. y \<in># add_mset x' M' \<and> R a y} = insert x' {y. y \<in># M' \<and> R a y}" "{y. y \<in># add_mset x' M' \<and> R a y} = insert x' {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y}" "{y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y} = {y. y \<noteq> x' \<and> y \<in># M' \<and> R a y}" "{y. y \<in># M' \<and> R a y} = {y. y \<noteq> x' \<and> y \<in># M' \<and> R a y}" using x' by auto have "sum (count (add_mset x' M')) {y. y \<in># add_mset x' M' \<and> R a y} = Suc (count M' x') + sum (count (add_mset x' M')) {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y}" unfolding 0 apply(subst comm_monoid_add_class.sum.insert) by auto also have "sum (count (add_mset x' M')) {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y} = sum (count M') {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y}" apply(rule comm_monoid_add_class.sum.cong) by auto also have "Suc (count M' x') + sum (count M') {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y} = Suc (count M' x' + sum (count M') {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y})" by simp also have "sum (count M') {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y} = sum (count M') {y. y \<noteq> x' \<and> y \<in># M' \<and> R a y}" unfolding 0 .. also have "sum (count M') {y. y \<noteq> x' \<and> y \<in># M' \<and> R a y} = sum (count M') {y. y \<in># M' \<and> R a y}" unfolding 0 .. also have "count M' x' = 0" using x' by (simp add: not_in_iff) ultimately have mainx': "sum (count (add_mset x' M')) {y. y \<in># add_mset x' M' \<and> R a y} = Suc (sum (count M') {y. y \<in># M' \<and> R a y})" by auto } note fact2' = this {assume "\<not> R a x'" note x' = this have 0: "{y. y \<in># add_mset x' M' \<and> R a y} = {y. y \<in># M' \<and> R a y}" "{y. y \<in># add_mset x' M' \<and> R a y} = {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y}" "{y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y} = {y. y \<noteq> x' \<and> y \<in># M' \<and> R a y}" "{y. y \<in># M' \<and> R a y} = {y. y \<noteq> x' \<and> y \<in># M' \<and> R a y}" using x' by auto have "sum (count (add_mset x' M')) {y. y \<in># add_mset x' M' \<and> R a y} = sum (count (add_mset x' M')) {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y}" unfolding 0 .. also have "sum (count (add_mset x' M')) {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y} = sum (count M') {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y}" apply(rule comm_monoid_add_class.sum.cong) by auto also have "sum (count M') {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y} = sum (count M') {y. y \<noteq> x' \<and> y \<in># M' \<and> R a y}" unfolding 0 .. also have "sum (count M') {y. y \<noteq> x' \<and> y \<in># M' \<and> R a y} = sum (count M') {y. y \<in># M' \<and> R a y}" unfolding 0 .. ultimately have mainx': "sum (count (add_mset x' M')) {y. y \<in># add_mset x' M' \<and> R a y} = sum (count M') {y. y \<in># M' \<and> R a y}" by auto } note fact3' = this show ?case proof(cases "R a x") case True note x = True hence x': "R a x'" using R add.hyps(1) neper_classes_eq by fastforce show ?thesis proof(cases "x \<in># M") case True note x = x True show ?thesis proof(cases "x' \<in># M'") case True note x' = x' True show ?thesis unfolding fact1[OF x] fact1'[OF x'] IH .. next case False note x' = x' False show ?thesis unfolding fact1[OF x] fact2'[OF x'] IH .. qed next case False note x = x False show ?thesis proof(cases "x' \<in># M'") case True note x' = x' True show ?thesis unfolding fact2[OF x] fact1'[OF x'] IH .. next case False note x' = x' False show ?thesis unfolding fact2[OF x] fact2'[OF x'] IH .. qed qed next case False note x = False hence x': "\<not> R a x'" by (metis R add.hyps(1) neper_per per_def) show ?thesis unfolding fact3[OF x] fact3'[OF x'] IH .. qed qed lemma neper_rel_mset_set_mset: assumes R: "neper R" and r: "rel_mset R A A'" shows "set_mset A \<subseteq> {a. R a a} \<and> set_mset A' \<subseteq> {a. R a a}" proof- have "rel_mset R A A" "rel_mset R A' A'" apply (metis (full_types) R r msed_rel_invL multi_member_split multiset.rel_refl_strong neper_per per_def) by (metis CollectD CollectI R r neper_classes_eq neper_rel_mset) thus ?thesis by (smt (verit, best) Ball_Collect CollectD CollectI R insert_DiffM msed_rel_invR neper_classes_eq) qed lemma neper_sum_count_rel_mset: assumes R: "neper R" and AA': "set_mset A \<subseteq> {a. R a a }" "set_mset A' \<subseteq> {a. R a a}" and s: "\<forall>a. R a a \<longrightarrow> sum (count A) {y. y \<in># A \<and> R a y} = sum (count A') {y'. y' \<in># A' \<and> R a y'}" shows "rel_mset R A A'" using AA' s proof(induction A arbitrary: A' rule: multiset_induct) case empty then show ?case by auto (metis CollectD multiset_nonemptyE not_in_iff subset_eq) next case (add x M A') hence Rx: "R x x" by auto have 0: "sum (count (add_mset x M)) {y. y \<in># add_mset x M \<and> R x y} = sum (count A') {y'. y' \<in># A' \<and> R x y'}" using Rx add by auto have "sum (count A') {y'. y' \<in># A' \<and> R x y'} > 0" unfolding 0[symmetric] apply(rule ordered_comm_monoid_add_class.sum_pos2[of _ x]) using Rx by auto then obtain x' where x': "x' \<in># A'" "R x x'" by (metis (mono_tags, lifting) CollectD leD sum_nonpos) then obtain M' where A': "A' = add_mset x' M'" by (meson mset_add) {fix a assume "R a x" "x \<in># M" note x = this have 0: "{y. y \<in># add_mset x M \<and> R a y} = {y. y \<in># M \<and> R a y}" "{y. y \<in># add_mset x M \<and> R a y} = insert x {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y}" "{y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y} = {y. y \<noteq> x \<and> y \<in># M \<and> R a y}" "{y. y \<in># M \<and> R a y} = insert x {y. y \<noteq> x \<and> y \<in># M \<and> R a y}" using x by auto have "sum (count (add_mset x M)) {y. y \<in># add_mset x M \<and> R a y} = Suc (count M x) + sum (count (add_mset x M)) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y}" unfolding 0 apply(subst comm_monoid_add_class.sum.insert) by auto also have "sum (count (add_mset x M)) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y} = sum (count M) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y}" apply(rule comm_monoid_add_class.sum.cong) by auto also have "Suc (count M x) + sum (count M) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y} = Suc (count M x + sum (count M) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y})" by simp also have "sum (count M) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y} = sum (count M) {y. y \<noteq> x \<and> y \<in># M \<and> R a y}" unfolding 0 .. also have "count M x + sum (count M) {y. y \<noteq> x \<and> y \<in># M \<and> R a y} = sum (count M) {y. y \<in># M \<and> R a y}" unfolding 0 apply(subst comm_monoid_add_class.sum.insert) by auto ultimately have mainx: "sum (count (add_mset x M)) {y. y \<in># add_mset x M \<and> R a y} = Suc (sum (count M) {y. y \<in># M \<and> R a y})" by auto } note fact1 = this {fix a assume "R a x" "\<not> x \<in># M" note x = this have 0: "{y. y \<in># add_mset x M \<and> R a y} = insert x {y. y \<in># M \<and> R a y}" "{y. y \<in># add_mset x M \<and> R a y} = insert x {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y}" "{y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y} = {y. y \<noteq> x \<and> y \<in># M \<and> R a y}" "{y. y \<in># M \<and> R a y} = {y. y \<noteq> x \<and> y \<in># M \<and> R a y}" using x by auto have "sum (count (add_mset x M)) {y. y \<in># add_mset x M \<and> R a y} = Suc (count M x) + sum (count (add_mset x M)) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y}" unfolding 0 apply(subst comm_monoid_add_class.sum.insert) by auto also have "sum (count (add_mset x M)) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y} = sum (count M) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y}" apply(rule comm_monoid_add_class.sum.cong) by auto also have "Suc (count M x) + sum (count M) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y} = Suc (count M x + sum (count M) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y})" by simp also have "sum (count M) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y} = sum (count M) {y. y \<noteq> x \<and> y \<in># M \<and> R a y}" unfolding 0 .. also have "sum (count M) {y. y \<noteq> x \<and> y \<in># M \<and> R a y} = sum (count M) {y. y \<in># M \<and> R a y}" unfolding 0 .. also have "count M x = 0" using x by (simp add: not_in_iff) ultimately have mainx: "sum (count (add_mset x M)) {y. y \<in># add_mset x M \<and> R a y} = Suc (sum (count M) {y. y \<in># M \<and> R a y})" by auto } note fact2 = this {fix a assume "\<not> R a x" note x = this have 0: "{y. y \<in># add_mset x M \<and> R a y} = {y. y \<in># M \<and> R a y}" "{y. y \<in># add_mset x M \<and> R a y} = {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y}" "{y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y} = {y. y \<noteq> x \<and> y \<in># M \<and> R a y}" "{y. y \<in># M \<and> R a y} = {y. y \<noteq> x \<and> y \<in># M \<and> R a y}" using x by auto have "sum (count (add_mset x M)) {y. y \<in># add_mset x M \<and> R a y} = sum (count (add_mset x M)) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y}" unfolding 0 .. also have "sum (count (add_mset x M)) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y} = sum (count M) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y}" apply(rule comm_monoid_add_class.sum.cong) by auto also have "sum (count M) {y. y \<noteq> x \<and> y \<in># add_mset x M \<and> R a y} = sum (count M) {y. y \<noteq> x \<and> y \<in># M \<and> R a y}" unfolding 0 .. also have "sum (count M) {y. y \<noteq> x \<and> y \<in># M \<and> R a y} = sum (count M) {y. y \<in># M \<and> R a y}" unfolding 0 .. ultimately have mainx: "sum (count (add_mset x M)) {y. y \<in># add_mset x M \<and> R a y} = sum (count M) {y. y \<in># M \<and> R a y}" by auto } note fact3 = this (* *) {fix a assume "R a x'" "x' \<in># M'" note x' = this have 0: "{y. y \<in># add_mset x' M' \<and> R a y} = {y. y \<in># M' \<and> R a y}" "{y. y \<in># add_mset x' M' \<and> R a y} = insert x' {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y}" "{y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y} = {y. y \<noteq> x' \<and> y \<in># M' \<and> R a y}" "{y. y \<in># M' \<and> R a y} = insert x' {y. y \<noteq> x' \<and> y \<in># M' \<and> R a y}" using x' by auto have "sum (count (add_mset x' M')) {y. y \<in># add_mset x' M' \<and> R a y} = Suc (count M' x') + sum (count (add_mset x' M')) {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y}" unfolding 0 apply(subst comm_monoid_add_class.sum.insert) by auto also have "sum (count (add_mset x' M')) {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y} = sum (count M') {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y}" apply(rule comm_monoid_add_class.sum.cong) by auto also have "Suc (count M' x') + sum (count M') {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y} = Suc (count M' x' + sum (count M') {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y})" by simp also have "sum (count M') {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y} = sum (count M') {y. y \<noteq> x' \<and> y \<in># M' \<and> R a y}" unfolding 0 .. also have "count M' x' + sum (count M') {y. y \<noteq> x' \<and> y \<in># M' \<and> R a y} = sum (count M') {y. y \<in># M' \<and> R a y}" unfolding 0 apply(subst comm_monoid_add_class.sum.insert) by auto ultimately have mainx': "sum (count A') {y. y \<in># A' \<and> R a y} = Suc (sum (count M') {y. y \<in># M' \<and> R a y})" unfolding A' by auto } note fact1' = this {fix a assume "R a x'" "\<not> x' \<in># M'" note x' = this have 0: "{y. y \<in># add_mset x' M' \<and> R a y} = insert x' {y. y \<in># M' \<and> R a y}" "{y. y \<in># add_mset x' M' \<and> R a y} = insert x' {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y}" "{y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y} = {y. y \<noteq> x' \<and> y \<in># M' \<and> R a y}" "{y. y \<in># M' \<and> R a y} = {y. y \<noteq> x' \<and> y \<in># M' \<and> R a y}" using x' by auto have "sum (count (add_mset x' M')) {y. y \<in># add_mset x' M' \<and> R a y} = Suc (count M' x') + sum (count (add_mset x' M')) {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y}" unfolding 0 apply(subst comm_monoid_add_class.sum.insert) by auto also have "sum (count (add_mset x' M')) {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y} = sum (count M') {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y}" apply(rule comm_monoid_add_class.sum.cong) by auto also have "Suc (count M' x') + sum (count M') {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y} = Suc (count M' x' + sum (count M') {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y})" by simp also have "sum (count M') {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y} = sum (count M') {y. y \<noteq> x' \<and> y \<in># M' \<and> R a y}" unfolding 0 .. also have "sum (count M') {y. y \<noteq> x' \<and> y \<in># M' \<and> R a y} = sum (count M') {y. y \<in># M' \<and> R a y}" unfolding 0 .. also have "count M' x' = 0" using x' by (simp add: not_in_iff) ultimately have mainx': "sum (count A') {y. y \<in># A' \<and> R a y} = Suc (sum (count M') {y. y \<in># M' \<and> R a y})" unfolding A' by auto } note fact2' = this {fix a assume "\<not> R a x'" note x' = this have 0: "{y. y \<in># add_mset x' M' \<and> R a y} = {y. y \<in># M' \<and> R a y}" "{y. y \<in># add_mset x' M' \<and> R a y} = {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y}" "{y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y} = {y. y \<noteq> x' \<and> y \<in># M' \<and> R a y}" "{y. y \<in># M' \<and> R a y} = {y. y \<noteq> x' \<and> y \<in># M' \<and> R a y}" using x' by auto have "sum (count (add_mset x' M')) {y. y \<in># add_mset x' M' \<and> R a y} = sum (count (add_mset x' M')) {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y}" unfolding 0 .. also have "sum (count (add_mset x' M')) {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y} = sum (count M') {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y}" apply(rule comm_monoid_add_class.sum.cong) by auto also have "sum (count M') {y. y \<noteq> x' \<and> y \<in># add_mset x' M' \<and> R a y} = sum (count M') {y. y \<noteq> x' \<and> y \<in># M' \<and> R a y}" unfolding 0 .. also have "sum (count M') {y. y \<noteq> x' \<and> y \<in># M' \<and> R a y} = sum (count M') {y. y \<in># M' \<and> R a y}" unfolding 0 .. ultimately have mainx': "sum (count A') {y. y \<in># A' \<and> R a y} = sum (count M') {y. y \<in># M' \<and> R a y}" unfolding A' by auto } note fact3' = this {fix a assume Ra: "R a a" have 0: "sum (count (add_mset x M)) {y. y \<in># add_mset x M \<and> R a y} = sum (count A') {y'. y' \<in># A' \<and> R a y'}" using Ra Rx add by auto have "sum (count M) {y. y \<in># M \<and> R a y} = sum (count M') {y'. y' \<in># M' \<and> R a y'}" proof(cases "R a x") case True note x = True hence x': "R a x'" using R Ra neper_classes_eq x'(2) by fastforce show ?thesis proof(cases "x \<in># M") case True note x = x True show ?thesis proof(cases "x' \<in># M'") case True note x' = x' True show ?thesis using 0[unfolded fact1[OF x] fact1'[OF x']] by simp next case False note x' = x' False show ?thesis using 0[unfolded fact1[OF x] fact2'[OF x']] by simp qed next case False note x = x False show ?thesis proof(cases "x' \<in># M'") case True note x' = x' True show ?thesis using 0[unfolded fact2[OF x] fact1'[OF x']] by simp next case False note x' = x' False show ?thesis using 0[unfolded fact2[OF x] fact2'[OF x']] by simp qed qed next case False note x = False hence x': "\<not> R a x'" by (metis R Rx mem_Collect_eq neper_classes_eq x'(2)) show ?thesis using 0[unfolded fact3[OF x] fact3'[OF x']] by simp qed } note 2 = this have "rel_mset R M M'" apply(rule add.IH) using 2 A' add.prems(1,2)by auto from this show ?case unfolding A' by (simp add: rel_mset_Plus x'(2)) qed (* Crucial characterisation of rel_mset for NEPERs: *) proposition neper_rel_mset_iff: assumes R: "neper R" shows "rel_mset R A A' \<longleftrightarrow> set_mset A \<subseteq> {a. R a a } \<and> set_mset A' \<subseteq> {a. R a a} \<and> (\<forall>x. R x x \<longrightarrow> sum (count A) {a. a \<in># A \<and> R x a} = sum (count A') {a'. a' \<in># A' \<and> R x a'})" using assms neper_sum_count_rel_mset[OF R] neper_rel_mset_sum_count[OF R] neper_rel_mset_set_mset[OF R] by meson lemma neper_gg_eq: "neper R \<Longrightarrow> R x y \<Longrightarrow> gg R A x = gg R A y" unfolding gg_def by (metis (no_types, opaque_lifting) mem_Collect_eq neper_classes_eq) lemma bij_upto_gg: assumes R: "neper R" shows "bij_upto (rel_mset R) (restr (rel_fun R (=)) (isMset_rlt R)) (gg R)" proof(rule bij_uptoI) show "neper (restr (rel_fun R (=)) (isMset_rlt R))" apply(rule neper_restr) subgoal using R by auto subgoal apply(rule exI[of _ "\<lambda>_.0"]) using R by auto . next fix A A' assume RAA': "rel_mset R A A'" show "restr (rel_fun R (=)) (isMset_rlt R) (gg R A) (gg R A')" unfolding restr_def proof safe show "rel_fun R (=) (gg R A) (gg R A')" unfolding rel_fun_def proof safe fix x y assume "R x y" hence 1: "R x x" and 2:"gg R A' y = gg R A' x" apply (metis assms neper_def per_def) using \<open>R x y\<close> assms neper_gg_eq by fastforce show "gg R A x = gg R A' y" using 1 unfolding 2 unfolding gg_def by (simp add: RAA' assms neper_rel_mset_sum_count) qed hence 0: "rel_fun R (=) (gg R A) (gg R A)" "rel_fun R (=) (gg R A') (gg R A')" by (metis (mono_tags, lifting) assms neper_per per_def per_rel_fun)+ have "{getRepr R x |x. R x x \<and> 0 < gg R A x} \<subseteq> getRepr R ` (set_mset A)" unfolding gg_def by auto (smt (verit, best) Collect_empty_eq assms empty_iff image_iff int_ops(1) less_imp_of_nat_less neper_getRepr_eq sum.neutral) thus "isMset_rlt R (gg R A)" unfolding isMset_rlt_simp[OF R 0(1)] by (simp add: finite_subset) have "{getRepr R x |x. R x x \<and> 0 < gg R A' x} \<subseteq> getRepr R ` (set_mset A')" unfolding gg_def by auto (smt (verit, best) Collect_empty_eq assms empty_iff image_iff int_ops(1) less_imp_of_nat_less neper_getRepr_eq sum.neutral) thus "isMset_rlt R (gg R A')" unfolding isMset_rlt_simp[OF R 0(2)] by (simp add: finite_subset) qed next fix A A' assume RAA: "rel_mset R A A" and RAA': "rel_mset R A' A'" and "restr (rel_fun R (=)) (isMset_rlt R) (gg R A) (gg R A')" hence 1: "rel_fun R (=) (gg R A) (gg R A')" and 2: "isMset_rlt R (gg R A)" "isMset_rlt R (gg R A')" unfolding restr_def by auto hence 0: "rel_fun R (=) (gg R A) (gg R A)" "rel_fun R (=) (gg R A') (gg R A')" by (metis (mono_tags, lifting) assms neper_per per_def per_rel_fun)+ hence 2: "finite {getRepr R x |x. R x x \<and> 0 < gg R A x}" "finite {getRepr R x |x. R x x \<and> 0 < gg R A x}" using 2 unfolding isMset_rlt_simp[OF R 0(1)] isMset_rlt_simp[OF R 0(2)] by auto show "rel_mset R A A'" using 1 RAA RAA' assms neper_rel_mset_iff unfolding gg_def rel_fun_def by blast next fix f assume "restr (rel_fun R (=)) (isMset_rlt R) f f" hence 1: "rel_fun R (=) f f" and "isMset_rlt R f" unfolding restr_def by auto hence 2: "finite {getRepr R x |x. R x x \<and> 0 < f x}" using R isMset_rlt_simp by blast let ?f = "\<lambda>x. if R x x \<and> x = getRepr R x then f x else 0" define M where "M \<equiv> Abs_multiset ?f" have "{x. ?f x > 0} \<subseteq> {getRepr R x |x. R x x \<and> 0 < f x}" by auto hence "isMset ?f" unfolding isMset_def using 2 by (smt (verit, del_insts) Collect_mono infinite_super) hence cM: "count M = ?f" by (simp add: M_def isMset_def) have inM: "\<And>x. x \<in># M \<longleftrightarrow> ?f x > 0" using cM not_in_iff zero_less_iff_neq_zero by force have gr: "\<And>x y. R x y \<Longrightarrow> R (getRepr R x) (getRepr R x) \<and> getRepr R x = getRepr R (getRepr R x)" by (metis assms getRepr_neper mem_Collect_eq neper_classes_eq neper_getRepr_eq) show "\<exists>M. rel_mset R M M \<and> restr (rel_fun R (=)) (isMset_rlt R) f (gg R M)" proof(rule exI[of _ M], unfold restr_def, safe) show "rel_mset R M M" unfolding neper_rel_mset_iff[OF R] by safe (meson cM not_in_iff)+ show "rel_fun R (=) f (gg R M)" unfolding rel_fun_def gg_def cM apply safe subgoal for x y apply(subst comm_monoid_add_class.sum.mono_neutral_cong[of "{getRepr R x}" "{ya. ya \<in># M \<and> R y ya}" f]) apply safe subgoal by simp subgoal unfolding inM using gr by auto subgoal using gr by (metis assms getRepr_neper mem_Collect_eq neper_classes_eq neper_getRepr_eq) subgoal by (metis assms cM count_eq_zero_iff neper_getRepr_eq) subgoal using inM by fastforce subgoal by simp (metis (mono_tags, lifting) "1" assms getRepr_neper mem_Collect_eq neper_classes_eq neper_getRepr_eq rel_funD) . . hence 0: "rel_fun R (=) (gg R M) (gg R M)" by (metis CollectD CollectI assms neper_classes_eq neper_eq neper_rel_fun) show "isMset_rlt R f" by fact have "finite {getRepr R x |x. R x x \<and> 0 < gg R M x}" using 2 by (smt (verit, best) Collect_cong \<open>rel_fun R (=) f (gg R M)\<close> rel_funD2) thus "isMset_rlt R (gg R M)" unfolding isMset_rlt_simp[OF R 0] . qed qed lemma gg_eq[simp]: "gg (=) = count" proof- have [simp]: "\<And>x M. {y. x = y \<and> y \<in># M} = (if x \<in># M then {x} else {})" by auto show ?thesis unfolding gg_def fun_eq_iff by (simp add: not_in_iff) qed lemmas multiset_wide_aux = meta_eq_to_obj_eq[OF isMset_rlt_def[symmetric], unfolded fun_eq_iff, rule_format] declare multiset.rel_eq[simp] wide_typedef multiset rel: rel_mset rep: gg unfolding multiset_wide_aux subgoal using neper_rel_mset . subgoal using multiset.rel_eq . subgoal using bij_upto_gg . subgoal using gg_eq . . end
[STATEMENT] lemma index_not_zero_impl_diff_group: "ps \<subseteq> \<V> \<Longrightarrow> card ps = 2 \<Longrightarrow> \<B> index ps = \<Lambda> \<Longrightarrow> (\<And> G . G \<in> \<G> \<Longrightarrow> \<not> ps \<subseteq> G)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>ps \<subseteq> \<V>; card ps = 2; int (\<B> index ps) = \<Lambda>\<rbrakk> \<Longrightarrow> (\<And>G. G \<in> \<G> \<Longrightarrow> \<not> ps \<subseteq> G) [PROOF STEP] using index_ge_1 index_together_alt_ss [PROOF STATE] proof (prove) using this: 1 \<le> \<Lambda> \<lbrakk>?ps \<subseteq> ?G; ?G \<in> \<G>; card ?ps = 2\<rbrakk> \<Longrightarrow> \<B> index ?ps = 0 goal (1 subgoal): 1. \<lbrakk>ps \<subseteq> \<V>; card ps = 2; int (\<B> index ps) = \<Lambda>\<rbrakk> \<Longrightarrow> (\<And>G. G \<in> \<G> \<Longrightarrow> \<not> ps \<subseteq> G) [PROOF STEP] by auto
/- Copyright (c) 2022 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying, RΓ©my Degenne ! This file was ported from Lean 3 source module probability.process.hitting_time ! leanprover-community/mathlib commit f2ce6086713c78a7f880485f7917ea547a215982 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathbin.Probability.Process.Stopping /-! # Hitting time Given a stochastic process, the hitting time provides the first time the process ``hits'' some subset of the state space. The hitting time is a stopping time in the case that the time index is discrete and the process is adapted (this is true in a far more general setting however we have only proved it for the discrete case so far). ## Main definition * `measure_theory.hitting`: the hitting time of a stochastic process ## Main results * `measure_theory.hitting_is_stopping_time`: a discrete hitting time of an adapted process is a stopping time ## Implementation notes In the definition of the hitting time, we bound the hitting time by an upper and lower bound. This is to ensure that our result is meaningful in the case we are taking the infimum of an empty set or the infimum of a set which is unbounded from below. With this, we can talk about hitting times indexed by the natural numbers or the reals. By taking the bounds to be `⊀` and `βŠ₯`, we obtain the standard definition in the case that the index is `β„•βˆž` or `ℝβ‰₯0∞`. -/ open Filter Order TopologicalSpace open Classical MeasureTheory NNReal ENNReal Topology BigOperators namespace MeasureTheory variable {Ξ© Ξ² ΞΉ : Type _} {m : MeasurableSpace Ξ©} /-- Hitting time: given a stochastic process `u` and a set `s`, `hitting u s n m` is the first time `u` is in `s` after time `n` and before time `m` (if `u` does not hit `s` after time `n` and before `m` then the hitting time is simply `m`). The hitting time is a stopping time if the process is adapted and discrete. -/ noncomputable def hitting [Preorder ΞΉ] [InfSet ΞΉ] (u : ΞΉ β†’ Ξ© β†’ Ξ²) (s : Set Ξ²) (n m : ΞΉ) : Ξ© β†’ ΞΉ := fun x => if βˆƒ j ∈ Set.Icc n m, u j x ∈ s then infβ‚› (Set.Icc n m ∩ { i : ΞΉ | u i x ∈ s }) else m #align measure_theory.hitting MeasureTheory.hitting section Inequalities variable [ConditionallyCompleteLinearOrder ΞΉ] {u : ΞΉ β†’ Ξ© β†’ Ξ²} {s : Set Ξ²} {n i : ΞΉ} {Ο‰ : Ξ©} /-- This lemma is strictly weaker than `hitting_of_le`. -/ theorem hitting_of_lt {m : ΞΉ} (h : m < n) : hitting u s n m Ο‰ = m := by simp_rw [hitting] have h_not : Β¬βˆƒ (j : ΞΉ)(H : j ∈ Set.Icc n m), u j Ο‰ ∈ s := by push_neg intro j rw [Set.Icc_eq_empty_of_lt h] simp only [Set.mem_empty_iff_false, IsEmpty.forall_iff] simp only [h_not, if_false] #align measure_theory.hitting_of_lt MeasureTheory.hitting_of_lt theorem hitting_le {m : ΞΉ} (Ο‰ : Ξ©) : hitting u s n m Ο‰ ≀ m := by cases' le_or_lt n m with h_le h_lt Β· simp only [hitting] split_ifs Β· obtain ⟨j, hj₁, hjβ‚‚βŸ© := h exact (cinfβ‚›_le (BddBelow.inter_of_left bddBelow_Icc) (Set.mem_inter hj₁ hjβ‚‚)).trans hj₁.2 Β· exact le_rfl Β· rw [hitting_of_lt h_lt] #align measure_theory.hitting_le MeasureTheory.hitting_le theorem not_mem_of_lt_hitting {m k : ΞΉ} (hk₁ : k < hitting u s n m Ο‰) (hkβ‚‚ : n ≀ k) : u k Ο‰ βˆ‰ s := by classical intro h have hexists : βˆƒ j ∈ Set.Icc n m, u j Ο‰ ∈ s refine' ⟨k, ⟨hkβ‚‚, le_trans hk₁.le <| hitting_le _⟩, h⟩ refine' not_le.2 hk₁ _ simp_rw [hitting, if_pos hexists] exact cinfβ‚›_le bdd_below_Icc.inter_of_left ⟨⟨hkβ‚‚, le_trans hk₁.le <| hitting_le _⟩, h⟩ #align measure_theory.not_mem_of_lt_hitting MeasureTheory.not_mem_of_lt_hitting theorem hitting_eq_end_iff {m : ΞΉ} : hitting u s n m Ο‰ = m ↔ (βˆƒ j ∈ Set.Icc n m, u j Ο‰ ∈ s) β†’ infβ‚› (Set.Icc n m ∩ { i : ΞΉ | u i Ο‰ ∈ s }) = m := by rw [hitting, ite_eq_right_iff] #align measure_theory.hitting_eq_end_iff MeasureTheory.hitting_eq_end_iff theorem hitting_of_le {m : ΞΉ} (hmn : m ≀ n) : hitting u s n m Ο‰ = m := by obtain rfl | h := le_iff_eq_or_lt.1 hmn Β· simp only [hitting, Set.Icc_self, ite_eq_right_iff, Set.mem_Icc, exists_prop, forall_exists_index, and_imp] intro i hi₁ hiβ‚‚ hi rw [Set.inter_eq_left_iff_subset.2, cinfβ‚›_singleton] exact Set.singleton_subset_iff.2 (le_antisymm hiβ‚‚ hi₁ β–Έ hi) Β· exact hitting_of_lt h #align measure_theory.hitting_of_le MeasureTheory.hitting_of_le theorem le_hitting {m : ΞΉ} (hnm : n ≀ m) (Ο‰ : Ξ©) : n ≀ hitting u s n m Ο‰ := by simp only [hitting] split_ifs Β· refine' le_cinfβ‚› _ fun b hb => _ Β· obtain ⟨k, hk_Icc, hk_s⟩ := h exact ⟨k, hk_Icc, hk_s⟩ Β· rw [Set.mem_inter_iff] at hb exact hb.1.1 Β· exact hnm #align measure_theory.le_hitting MeasureTheory.le_hitting theorem le_hitting_of_exists {m : ΞΉ} (h_exists : βˆƒ j ∈ Set.Icc n m, u j Ο‰ ∈ s) : n ≀ hitting u s n m Ο‰ := by refine' le_hitting _ Ο‰ by_contra rw [Set.Icc_eq_empty_of_lt (not_le.mp h)] at h_exists simpa using h_exists #align measure_theory.le_hitting_of_exists MeasureTheory.le_hitting_of_exists theorem hitting_mem_Icc {m : ΞΉ} (hnm : n ≀ m) (Ο‰ : Ξ©) : hitting u s n m Ο‰ ∈ Set.Icc n m := ⟨le_hitting hnm Ο‰, hitting_le Ο‰βŸ© #align measure_theory.hitting_mem_Icc MeasureTheory.hitting_mem_Icc theorem hitting_mem_set [IsWellOrder ΞΉ (Β· < Β·)] {m : ΞΉ} (h_exists : βˆƒ j ∈ Set.Icc n m, u j Ο‰ ∈ s) : u (hitting u s n m Ο‰) Ο‰ ∈ s := by simp_rw [hitting, if_pos h_exists] have h_nonempty : (Set.Icc n m ∩ { i : ΞΉ | u i Ο‰ ∈ s }).Nonempty := by obtain ⟨k, hk₁, hkβ‚‚βŸ© := h_exists exact ⟨k, Set.mem_inter hk₁ hkβ‚‚βŸ© have h_mem := cinfβ‚›_mem h_nonempty rw [Set.mem_inter_iff] at h_mem exact h_mem.2 #align measure_theory.hitting_mem_set MeasureTheory.hitting_mem_set theorem hitting_mem_set_of_hitting_lt [IsWellOrder ΞΉ (Β· < Β·)] {m : ΞΉ} (hl : hitting u s n m Ο‰ < m) : u (hitting u s n m Ο‰) Ο‰ ∈ s := by by_cases h : βˆƒ j ∈ Set.Icc n m, u j Ο‰ ∈ s Β· exact hitting_mem_set h Β· simp_rw [hitting, if_neg h] at hl exact False.elim (hl.ne rfl) #align measure_theory.hitting_mem_set_of_hitting_lt MeasureTheory.hitting_mem_set_of_hitting_lt theorem hitting_le_of_mem {m : ΞΉ} (hin : n ≀ i) (him : i ≀ m) (his : u i Ο‰ ∈ s) : hitting u s n m Ο‰ ≀ i := by have h_exists : βˆƒ k ∈ Set.Icc n m, u k Ο‰ ∈ s := ⟨i, ⟨hin, him⟩, his⟩ simp_rw [hitting, if_pos h_exists] exact cinfβ‚›_le (BddBelow.inter_of_left bddBelow_Icc) (Set.mem_inter ⟨hin, him⟩ his) #align measure_theory.hitting_le_of_mem MeasureTheory.hitting_le_of_mem theorem hitting_le_iff_of_exists [IsWellOrder ΞΉ (Β· < Β·)] {m : ΞΉ} (h_exists : βˆƒ j ∈ Set.Icc n m, u j Ο‰ ∈ s) : hitting u s n m Ο‰ ≀ i ↔ βˆƒ j ∈ Set.Icc n i, u j Ο‰ ∈ s := by constructor <;> intro h' Β· exact ⟨hitting u s n m Ο‰, ⟨le_hitting_of_exists h_exists, h'⟩, hitting_mem_set h_exists⟩ Β· have h'' : βˆƒ k ∈ Set.Icc n (min m i), u k Ο‰ ∈ s := by obtain ⟨k₁, hk₁_mem, hk₁_s⟩ := h_exists obtain ⟨kβ‚‚, hkβ‚‚_mem, hkβ‚‚_s⟩ := h' refine' ⟨min k₁ kβ‚‚, ⟨le_min hk₁_mem.1 hkβ‚‚_mem.1, min_le_min hk₁_mem.2 hkβ‚‚_mem.2⟩, _⟩ exact min_rec' (fun j => u j Ο‰ ∈ s) hk₁_s hkβ‚‚_s obtain ⟨k, hk₁, hkβ‚‚βŸ© := h'' refine' le_trans _ (hk₁.2.trans (min_le_right _ _)) exact hitting_le_of_mem hk₁.1 (hk₁.2.trans (min_le_left _ _)) hkβ‚‚ #align measure_theory.hitting_le_iff_of_exists MeasureTheory.hitting_le_iff_of_exists theorem hitting_le_iff_of_lt [IsWellOrder ΞΉ (Β· < Β·)] {m : ΞΉ} (i : ΞΉ) (hi : i < m) : hitting u s n m Ο‰ ≀ i ↔ βˆƒ j ∈ Set.Icc n i, u j Ο‰ ∈ s := by by_cases h_exists : βˆƒ j ∈ Set.Icc n m, u j Ο‰ ∈ s Β· rw [hitting_le_iff_of_exists h_exists] Β· simp_rw [hitting, if_neg h_exists] push_neg at h_exists simp only [not_le.mpr hi, Set.mem_Icc, false_iff_iff, not_exists, and_imp] exact fun k hkn hki => h_exists k ⟨hkn, hki.trans hi.le⟩ #align measure_theory.hitting_le_iff_of_lt MeasureTheory.hitting_le_iff_of_lt theorem hitting_lt_iff [IsWellOrder ΞΉ (Β· < Β·)] {m : ΞΉ} (i : ΞΉ) (hi : i ≀ m) : hitting u s n m Ο‰ < i ↔ βˆƒ j ∈ Set.Ico n i, u j Ο‰ ∈ s := by constructor <;> intro h' Β· have h : βˆƒ j ∈ Set.Icc n m, u j Ο‰ ∈ s := by by_contra simp_rw [hitting, if_neg h, ← not_le] at h' exact h' hi exact ⟨hitting u s n m Ο‰, ⟨le_hitting_of_exists h, h'⟩, hitting_mem_set h⟩ Β· obtain ⟨k, hk₁, hkβ‚‚βŸ© := h' refine' lt_of_le_of_lt _ hk₁.2 exact hitting_le_of_mem hk₁.1 (hk₁.2.le.trans hi) hkβ‚‚ #align measure_theory.hitting_lt_iff MeasureTheory.hitting_lt_iff theorem hitting_eq_hitting_of_exists {m₁ mβ‚‚ : ΞΉ} (h : m₁ ≀ mβ‚‚) (h' : βˆƒ j ∈ Set.Icc n m₁, u j Ο‰ ∈ s) : hitting u s n m₁ Ο‰ = hitting u s n mβ‚‚ Ο‰ := by simp only [hitting, if_pos h'] obtain ⟨j, hj₁, hjβ‚‚βŸ© := h' rw [if_pos] Β· refine' le_antisymm _ (cinfβ‚›_le_cinfβ‚› bdd_below_Icc.inter_of_left ⟨j, hj₁, hjβ‚‚βŸ© (Set.inter_subset_inter_left _ (Set.Icc_subset_Icc_right h))) refine' le_cinfβ‚› ⟨j, Set.Icc_subset_Icc_right h hj₁, hjβ‚‚βŸ© fun i hi => _ by_cases hi' : i ≀ m₁ Β· exact cinfβ‚›_le bdd_below_Icc.inter_of_left ⟨⟨hi.1.1, hi'⟩, hi.2⟩ Β· exact ((cinfβ‚›_le bdd_below_Icc.inter_of_left ⟨hj₁, hjβ‚‚βŸ©).trans (hj₁.2.trans le_rfl)).trans (le_of_lt (not_le.1 hi')) exact ⟨j, ⟨hj₁.1, hj₁.2.trans h⟩, hjβ‚‚βŸ© #align measure_theory.hitting_eq_hitting_of_exists MeasureTheory.hitting_eq_hitting_of_exists theorem hitting_mono {m₁ mβ‚‚ : ΞΉ} (hm : m₁ ≀ mβ‚‚) : hitting u s n m₁ Ο‰ ≀ hitting u s n mβ‚‚ Ο‰ := by by_cases h : βˆƒ j ∈ Set.Icc n m₁, u j Ο‰ ∈ s Β· exact (hitting_eq_hitting_of_exists hm h).le Β· simp_rw [hitting, if_neg h] split_ifs with h' Β· obtain ⟨j, hj₁, hjβ‚‚βŸ© := h' refine' le_cinfβ‚› ⟨j, hj₁, hjβ‚‚βŸ© _ by_contra hneg push_neg at hneg obtain ⟨i, hi₁, hiβ‚‚βŸ© := hneg exact h ⟨i, ⟨hi₁.1.1, hiβ‚‚.le⟩, hi₁.2⟩ Β· exact hm #align measure_theory.hitting_mono MeasureTheory.hitting_mono end Inequalities /-- A discrete hitting time is a stopping time. -/ theorem hitting_isStoppingTime [ConditionallyCompleteLinearOrder ΞΉ] [IsWellOrder ΞΉ (Β· < Β·)] [Countable ΞΉ] [TopologicalSpace Ξ²] [PseudoMetrizableSpace Ξ²] [MeasurableSpace Ξ²] [BorelSpace Ξ²] {f : Filtration ΞΉ m} {u : ΞΉ β†’ Ξ© β†’ Ξ²} {s : Set Ξ²} {n n' : ΞΉ} (hu : Adapted f u) (hs : MeasurableSet s) : IsStoppingTime f (hitting u s n n') := by intro i cases' le_or_lt n' i with hi hi Β· have h_le : βˆ€ Ο‰, hitting u s n n' Ο‰ ≀ i := fun x => (hitting_le x).trans hi simp [h_le] Β· have h_set_eq_Union : { Ο‰ | hitting u s n n' Ο‰ ≀ i } = ⋃ j ∈ Set.Icc n i, u j ⁻¹' s := by ext x rw [Set.mem_setOf_eq, hitting_le_iff_of_lt _ hi] simp only [Set.mem_Icc, exists_prop, Set.mem_unionα΅’, Set.mem_preimage] rw [h_set_eq_Union] exact MeasurableSet.unionα΅’ fun j => MeasurableSet.unionα΅’ fun hj => f.mono hj.2 _ ((hu j).Measurable hs) #align measure_theory.hitting_is_stopping_time MeasureTheory.hitting_isStoppingTime theorem stoppedValue_hitting_mem [ConditionallyCompleteLinearOrder ΞΉ] [IsWellOrder ΞΉ (Β· < Β·)] {u : ΞΉ β†’ Ξ© β†’ Ξ²} {s : Set Ξ²} {n m : ΞΉ} {Ο‰ : Ξ©} (h : βˆƒ j ∈ Set.Icc n m, u j Ο‰ ∈ s) : stoppedValue u (hitting u s n m) Ο‰ ∈ s := by simp only [stopped_value, hitting, if_pos h] obtain ⟨j, hj₁, hjβ‚‚βŸ© := h have : Inf (Set.Icc n m ∩ { i | u i Ο‰ ∈ s }) ∈ Set.Icc n m ∩ { i | u i Ο‰ ∈ s } := cinfβ‚›_mem (Set.nonempty_of_mem ⟨hj₁, hjβ‚‚βŸ©) exact this.2 #align measure_theory.stopped_value_hitting_mem MeasureTheory.stoppedValue_hitting_mem /-- The hitting time of a discrete process with the starting time indexed by a stopping time is a stopping time. -/ theorem isStoppingTime_hitting_isStoppingTime [ConditionallyCompleteLinearOrder ΞΉ] [IsWellOrder ΞΉ (Β· < Β·)] [Countable ΞΉ] [TopologicalSpace ΞΉ] [OrderTopology ΞΉ] [FirstCountableTopology ΞΉ] [TopologicalSpace Ξ²] [PseudoMetrizableSpace Ξ²] [MeasurableSpace Ξ²] [BorelSpace Ξ²] {f : Filtration ΞΉ m} {u : ΞΉ β†’ Ξ© β†’ Ξ²} {Ο„ : Ξ© β†’ ΞΉ} (hΟ„ : IsStoppingTime f Ο„) {N : ΞΉ} (hΟ„bdd : βˆ€ x, Ο„ x ≀ N) {s : Set Ξ²} (hs : MeasurableSet s) (hf : Adapted f u) : IsStoppingTime f fun x => hitting u s (Ο„ x) N x := by intro n have h₁ : { x | hitting u s (Ο„ x) N x ≀ n } = (⋃ i ≀ n, { x | Ο„ x = i } ∩ { x | hitting u s i N x ≀ n }) βˆͺ ⋃ i > n, { x | Ο„ x = i } ∩ { x | hitting u s i N x ≀ n } := by ext x simp [← exists_or, ← or_and_right, le_or_lt] have hβ‚‚ : (⋃ i > n, { x | Ο„ x = i } ∩ { x | hitting u s i N x ≀ n }) = βˆ… := by ext x simp only [gt_iff_lt, Set.mem_unionα΅’, Set.mem_inter_iff, Set.mem_setOf_eq, exists_prop, Set.mem_empty_iff_false, iff_false_iff, not_exists, not_and, not_le] rintro m hm rfl exact lt_of_lt_of_le hm (le_hitting (hΟ„bdd _) _) rw [h₁, hβ‚‚, Set.union_empty] exact MeasurableSet.unionα΅’ fun i => MeasurableSet.unionα΅’ fun hi => (f.mono hi _ (hΟ„.measurable_set_eq i)).inter (hitting_is_stopping_time hf hs n) #align measure_theory.is_stopping_time_hitting_is_stopping_time MeasureTheory.isStoppingTime_hitting_isStoppingTime section CompleteLattice variable [CompleteLattice ΞΉ] {u : ΞΉ β†’ Ξ© β†’ Ξ²} {s : Set Ξ²} {f : Filtration ΞΉ m} theorem hitting_eq_infβ‚› (Ο‰ : Ξ©) : hitting u s βŠ₯ ⊀ Ο‰ = infβ‚› { i : ΞΉ | u i Ο‰ ∈ s } := by simp only [hitting, Set.mem_Icc, bot_le, le_top, and_self_iff, exists_true_left, Set.Icc_bot, Set.Iic_top, Set.univ_inter, ite_eq_left_iff, not_exists] intro h_nmem_s symm rw [infβ‚›_eq_top] exact fun i hi_mem_s => absurd hi_mem_s (h_nmem_s i) #align measure_theory.hitting_eq_Inf MeasureTheory.hitting_eq_infβ‚› end CompleteLattice section ConditionallyCompleteLinearOrderBot variable [ConditionallyCompleteLinearOrderBot ΞΉ] [IsWellOrder ΞΉ (Β· < Β·)] variable {u : ΞΉ β†’ Ξ© β†’ Ξ²} {s : Set Ξ²} {f : Filtration β„• m} theorem hitting_bot_le_iff {i n : ΞΉ} {Ο‰ : Ξ©} (hx : βˆƒ j, j ≀ n ∧ u j Ο‰ ∈ s) : hitting u s βŠ₯ n Ο‰ ≀ i ↔ βˆƒ j ≀ i, u j Ο‰ ∈ s := by cases' lt_or_le i n with hi hi Β· rw [hitting_le_iff_of_lt _ hi] simp Β· simp only [(hitting_le Ο‰).trans hi, true_iff_iff] obtain ⟨j, hj₁, hjβ‚‚βŸ© := hx exact ⟨j, hj₁.trans hi, hjβ‚‚βŸ© #align measure_theory.hitting_bot_le_iff MeasureTheory.hitting_bot_le_iff end ConditionallyCompleteLinearOrderBot end MeasureTheory
Require Import progs.ghost. Require Import mailbox.verif_atomics. Require Import progs.conclib. Require Import floyd.library. Require Import floyd.sublist. Require Import mailbox.kvnode. Set Bullet Behavior "Strict Subproofs". Instance CompSpecs : compspecs. make_compspecs prog. Defined. Definition Vprog : varspecs. mk_varspecs prog. Defined. (*Definition release2_spec := DECLARE _release2 release2_spec. Definition freelock2_spec := DECLARE _freelock2 (freelock2_spec _). Definition spawn_spec := DECLARE _spawn spawn_spec.*) Definition tnode := Tstruct _node noattr. Opaque upto. Definition make_loads lv := map (fun v => Load (vint v)) lv. (* Invariant for version number: Every write increases it, and the version of each data location is at least the most recently read version. *) (* Invariant for each location: The "rounded up" version number is at least the location's version. *) Definition round_up i := i + i mod 2. Definition round_down i := i - i mod 2. (* Do we really need the hists? *) (* Ghost vars act as write permissions. *) Definition ver_R g gsh gv lg (h : list hist_el) v := ghost_master v g * ghost_var gsh v gv * fold_right sepcon emp (map (ghost_snap (round_down v)) lg). Definition loc_R g gsh gl gv (h : list hist_el) (v : Z) := EX ver : Z, EX ver' : Z, !!(repable_signed ver' /\ ver <= round_up ver') && ghost_master ver g * ghost_var gsh ver gl * ghost_snap ver' gv. Notation "'WITH' x1 : t1 , x2 : t2 , x3 : t3 , x4 : t4 , x5 : t5 , x6 : t6 , x7 : t7 , x8 : t8 , x9 : t9 , x10 : t10 , x11 : t11 , x12 : t12 , x13 : t13 , x14 : t14 , x15 : t15 'PRE' [ u , .. , v ] P 'POST' [ tz ] Q" := (NDmk_funspec ((cons u%formals .. (cons v%formals nil) ..), tz) cc_default (t1*t2*t3*t4*t5*t6*t7*t8*t9*t10*t11*t12*t13*t14*t15) (fun x => match x with (x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15) => P%assert end) (fun x => match x with (x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15) => Q%assert end)) (at level 200, x1 at level 0, x2 at level 0, x3 at level 0, x4 at level 0, x5 at level 0, x6 at level 0, x7 at level 0, x8 at level 0, x9 at level 0, x10 at level 0, x11 at level 0, x12 at level 0, x13 at level 0, x14 at level 0, x15 at level 0, P at level 100, Q at level 100). Definition read_spec := DECLARE _read WITH n : val, out : val, sh : share, version : val, locs : list val, gv : val, gsh : share, gv' : val, gv2 : val, lg : list val, lgl : list val, hv : hist, ghosts : list val, hists : list hist, v0 : Z PRE [ _n OF tptr tnode, _out OF tptr tint ] PROP (readable_share sh; Zlength lg = 8; Zlength ghosts = 8; Zlength hists = 8; v0 mod 2 = 0) LOCAL (temp _n n; temp _out out) SEP (data_at sh tnode (version, locs) n; data_at_ Tsh (tarray tint 8) out; atomic_loc_hist sh version gv 0 (ver_R gv2 gsh gv' lg) hv; ghost_snap v0 gv2; fold_right sepcon emp (map (fun i => atomic_loc_hist sh (Znth i locs Vundef) (Znth i ghosts Vundef) 0 (loc_R (Znth i lg Vundef) gsh (Znth i lgl Vundef) gv2) (Znth i hists [])) (upto 8)); fold_right sepcon emp (map (ghost_snap v0) lg)) POST [ tvoid ] EX failvs : list Z, EX loops : Z, EX v : Z, EX hv' : hist, EX vals : list Z, EX hists' : list hist, PROP (v mod 2 = 0; add_events hv (make_loads (failvs ++ [v; v])) hv'; Forall repable_signed failvs; Forall repable_signed vals; Zlength hists' = 8; loops <= Zlength failvs) LOCAL () SEP (data_at sh tnode (version, locs) n; data_at Tsh (tarray tint 8) (map (fun x => vint x) vals) out; atomic_loc_hist sh version gv 0 (ver_R gv2 gsh gv' lg) hv'; ghost_snap v gv2; fold_right sepcon emp (map (fun i => EX fails : list Z, !!(add_events (Znth i hists []) (make_loads (fails ++ [Znth i vals 0])) (Znth i hists' []) /\ Zlength fails = loops) && atomic_loc_hist sh (Znth i locs Vundef) (Znth i ghosts Vundef) 0 (loc_R (Znth i lg Vundef) gsh (Znth i lgl Vundef) gv2) (Znth i hists' [])) (upto 8)); fold_right sepcon emp (map (ghost_snap v) lg)). Notation "'WITH' x1 : t1 , x2 : t2 , x3 : t3 , x4 : t4 , x5 : t5 , x6 : t6 , x7 : t7 , x8 : t8 , x9 : t9 , x10 : t10 , x11 : t11 , x12 : t12 , x13 : t13 , x14 : t14 , x15 : t15 , x16 : t16 , x17 : t17 'PRE' [ u , .. , v ] P 'POST' [ tz ] Q" := (NDmk_funspec ((cons u%formals .. (cons v%formals nil) ..), tz) cc_default (t1*t2*t3*t4*t5*t6*t7*t8*t9*t10*t11*t12*t13*t14*t15*t16*t17) (fun x => match x with (x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16,x17) => P%assert end) (fun x => match x with (x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16,x17) => Q%assert end)) (at level 200, x1 at level 0, x2 at level 0, x3 at level 0, x4 at level 0, x5 at level 0, x6 at level 0, x7 at level 0, x8 at level 0, x9 at level 0, x10 at level 0, x11 at level 0, x12 at level 0, x13 at level 0, x14 at level 0, x15 at level 0, x16 at level 0, x17 at level 0, P at level 100, Q at level 100). (* For now, we guarantee only one writer by using a ghost variable as a write permission. *) Definition write_spec := DECLARE _write WITH n : val, input : val, sh : share, version : val, locs : list val, vals : list Z, gv : val, gv2 : val, gsh1 : share, gsh2 : share, gv' : val, lg : list val, lgl : list val, hv : hist, ghosts : list val, hists : list hist, v : Z PRE [ _n OF tptr tnode, _in OF tptr tint ] PROP (readable_share sh; Forall repable_signed vals; Zlength lg = 8; Zlength lgl = 8; Zlength ghosts = 8; Zlength hists = 8; v mod 2 = 0; readable_share gsh1; readable_share gsh2; sepalg.join gsh1 gsh2 Tsh) LOCAL (temp _n n; temp _in input) SEP (data_at sh tnode (version, locs) n; data_at Tsh (tarray tint 8) (map (fun x => vint x) vals) input; atomic_loc_hist sh version gv 0 (ver_R gv2 gsh2 gv' lg) hv; ghost_snap v gv2; ghost_var gsh1 v gv'; fold_right sepcon emp (map (fun i => atomic_loc_hist sh (Znth i locs Vundef) (Znth i ghosts Vundef) 0 (loc_R (Znth i lg Vundef) gsh2 (Znth i lgl Vundef) gv2) (Znth i hists [])) (upto 8)); fold_right sepcon emp (map (ghost_snap v) lg); fold_right sepcon emp (map (ghost_var gsh1 v) lgl)) POST [ tvoid ] EX hv' : hist, EX hists' : list hist, PROP (add_events hv [Load (vint v); Store (vint (v + 1)); Store (vint (v + 2))] hv'; Zlength hists' = 8; (v + 2) mod 2 = 0) LOCAL () SEP (data_at sh tnode (version, locs) n; data_at Tsh (tarray tint 8) (map (fun x => vint x) vals) input; atomic_loc_hist sh version gv 0 (ver_R gv2 gsh2 gv' lg) hv'; ghost_snap (v + 2) gv2; ghost_var gsh1 (v + 2) gv'; fold_right sepcon emp (map (fun i => !!(add_events (Znth i hists []) [Store (vint (Znth i vals 0))] (Znth i hists' [])) && atomic_loc_hist sh (Znth i locs Vundef) (Znth i ghosts Vundef) 0 (loc_R (Znth i lg Vundef) gsh2 (Znth i lgl Vundef) gv2) (Znth i hists' [])) (upto 8)); fold_right sepcon emp (map (ghost_snap (v + 2)) lg); fold_right sepcon emp (map (ghost_var gsh1 (v + 2)) lgl)). Definition Gprog : funspecs := ltac:(with_library prog [load_SC_spec; store_SC_spec; read_spec; write_spec]). Ltac cancel_for_forward_call ::= repeat (rewrite ?sepcon_andp_prop', ?sepcon_andp_prop); repeat (apply andp_right; [auto; apply prop_right; auto|]); fast_cancel. Lemma snap_snap_max : forall v1 v2 p, ghost_snap v1 p * ghost_snap v2 p = ghost_snap v1 p * ghost_snap (Z.max v1 v2) p. Proof. intros; rewrite ghost_snap_join'. replace (Z.max v1 v2) with (Z.max v1 (Z.max v1 v2)) at 1. rewrite <- ghost_snap_join'; auto. { rewrite Z.max_r, Z.max_comm; auto. apply Z.le_max_l. } Qed. Lemma snaps_snaps_max : forall {cs : compspecs} (v1 v2 : Z) lg, @view_shift cs (fold_right sepcon emp (map (ghost_snap v1) lg) * fold_right sepcon emp (map (ghost_snap v2) lg)) (fold_right sepcon emp (map (ghost_snap v1) lg) * fold_right sepcon emp (map (ghost_snap (Z.max v1 v2)) lg)). Proof. induction lg; simpl; repeat intro; auto. rewrite <- sepcon_assoc, (sepcon_comm _ (ghost_snap _ _)), <- sepcon_assoc. rewrite (sepcon_comm (ghost_snap _ _)), snap_snap_max. rewrite sepcon_assoc, sepcon_comm, flatten_sepcon_in_SEP. eapply IHlg, semax_pre; [|eauto]. go_lowerx; entailer!. Qed. Lemma snaps_snaps_le : forall {cs : compspecs} v lg (lv : list Z) (Hlen : Zlength lv = Zlength lg), @view_shift cs (fold_right sepcon emp (map (ghost_snap v) lg) * fold_right sepcon emp (map (fun '(v, g) => ghost_snap v g) (combine lv lg))) (fold_right sepcon emp (map (ghost_snap v) lg) * EX lv : list Z, !!(Zlength lv = Zlength lg /\ Forall (fun v' => v <= v') lv) && fold_right sepcon emp (map (fun '(v, g) => ghost_snap v g) (combine lv lg))). Proof. induction lg; simpl; repeat intro. - apply Zlength_nil_inv in Hlen; subst; simpl. eapply semax_pre; [|eauto]. go_lowerx. Exists (@nil Z); entailer!. - destruct lv; [symmetry in Hlen; apply Zlength_nil_inv in Hlen; discriminate | simpl]. rewrite <- sepcon_assoc, (sepcon_comm _ (ghost_snap _ _)), <- sepcon_assoc. rewrite (sepcon_comm _ (ghost_snap _ _)), snap_snap_max. rewrite sepcon_assoc, sepcon_comm, flatten_sepcon_in_SEP. apply IHlg; auto. { rewrite !Zlength_cons in *; omega. } eapply semax_pre; [|eauto]; go_lowerx. Intros lv'; Exists (Z.max v z :: lv'); simpl; entailer!. split; [rewrite !Zlength_cons; omega|]. constructor; auto. apply Zmax_bound_l; omega. Qed. Lemma land_1 : forall i, Z.land i 1 = i mod 2. Proof. intros; apply Z.land_ones with (n := 1); omega. Qed. Lemma round_down_mono : forall v1 v2, v1 <= v2 -> round_down v1 <= round_down v2. Proof. intros; unfold round_down. destruct (eq_dec v1 v2); [subst; omega|]. exploit (Z_mod_lt v1 2); [computable|]. exploit (Z_mod_lt v2 2); [computable|]. omega. Qed. Lemma round_up_max_distr : forall v1 v2, round_up (Z.max v1 v2) = Z.max (round_up v1) (round_up v2). Proof. intros; unfold round_up. exploit (Z_mod_lt v1 2); [computable|]. exploit (Z_mod_lt v2 2); [computable|]. intros; destruct (Z.max_spec v1 v2) as [(? & ->) | (? & ->)]; [rewrite Z.max_r | rewrite Z.max_l]; auto; try omega. destruct (eq_dec v1 v2); subst; omega. Qed. Lemma body_read : semax_body Vprog Gprog f_read read_spec. Proof. start_function. apply semax_pre with (P' := EX failvs : list Z, EX loops : Z, EX hv' : hist, EX hists' : list hist, EX v0 : Z, PROP (add_events hv (make_loads failvs) hv'; Forall repable_signed failvs; Zlength hists' = 8; loops <= Zlength failvs) LOCAL (temp _n n; temp _out out) SEP (@data_at CompSpecs sh tnode (version, locs) n; data_at_ Tsh (tarray tint 8) out; atomic_loc_hist sh version gv 0 (ver_R gv2 gsh gv' lg) hv'; ghost_snap v0 gv2; fold_right sepcon emp (map (fun i => EX fails : list Z, !!(add_events (Znth i hists []) (make_loads fails) (Znth i hists' []) /\ Zlength fails = loops) && atomic_loc_hist sh (Znth i locs Vundef) (Znth i ghosts Vundef) 0 (loc_R (Znth i lg Vundef) gsh (Znth i lgl Vundef) gv2) (Znth i hists' [])) (upto 8)); EX lv : list Z, !!(Zlength lv = 8) && fold_right sepcon emp (map (fun '(v, g) => ghost_snap v g) (combine lv lg)))). { Exists (@nil Z) 0 hv hists v0 (repeat v0 8). rewrite combine_const2, map_map by (simpl; omega); entailer!. apply sepcon_derives; auto. apply sepcon_list_derives; rewrite !Zlength_map; auto; intros. erewrite !Znth_map, !Znth_upto by (auto; rewrite Zlength_upto in *; omega). Exists (@nil Z); entailer!. } eapply semax_loop; [|forward; unfold loop2_ret_assert; apply drop_tc_environ]. - Intros failvs loops hv' hists' v1 lv. forward. unfold atomic_loc_hist at 1; rewrite atomic_loc_isptr; Intros. forward. assert (sh <> Share.bot) by (intro; subst; contradiction unreadable_bot). forward_call (AL_witness sh version gv 0 (ver_R gv2 gsh gv' lg) hv' (ghost_snap v1 gv2 * fold_right sepcon emp (map (fun '(v, g) => ghost_snap v g) (combine lv lg))) (fun v => !!(v1 <= v) && ghost_snap v gv2 * EX lv : list Z, !!(Zlength lv = 8 /\ Forall (fun v' => round_down v <= v') lv) && fold_right sepcon emp (map (fun '(v, g) => ghost_snap v g) (combine lv lg)))). { split; auto. apply AL_hist_spec; auto; repeat intro. unfold ver_R in *. rewrite <- !sepcon_assoc, (sepcon_comm _ (ghost_snap _ _)), <- 2sepcon_assoc. rewrite sepcon_assoc, 2flatten_sepcon_in_SEP. assert_PROP (v1 <= v). { rewrite snap_master_join'; go_lowerx; entailer!. } eapply snap_master_update' with (v' := v); [omega|]. focus_SEP 2; apply snaps_snaps_le; [omega|]. eapply semax_pre; [|eauto]. go_lowerx. Intros lv'; Exists lv'; entailer!. } Intros v; simpl; Intros hv1 lv1. match goal with |-semax _ (PROP () (LOCALx ?Q (SEPx ?R))) _ _ => forward_if (PROP (Z.testbit v 0 = false) (LOCALx Q (SEPx R))) end. { eapply semax_pre; [|apply semax_continue]. unfold POSTCONDITION, abbreviate, overridePost. destruct (eq_dec EK_continue EK_normal); [discriminate|]. unfold loop1_ret_assert. Exists (failvs ++ [v]) loops hv1 hists' v; entailer!. - split; [unfold make_loads; rewrite map_app; eapply add_events_trans; eauto|]. split; [rewrite Forall_app; auto|]. rewrite Zlength_app, Zlength_cons, Zlength_nil; omega. - Exists lv1; entailer!. } { forward. entailer!. unfold Int.one in *; rewrite and_repr, land_1, Zmod_odd in *. destruct (Z.odd v); auto; discriminate. } Intros. forward_for_simple_bound 8 (EX i : Z, EX vals : list Z, PROP (Zlength vals = i; Forall repable_signed vals) LOCAL (temp _snap (vint v); temp _ver version; temp _n n; temp _out out) SEP (atomic_loc_hist sh version gv 0 (ver_R gv2 gsh gv' lg) hv1; @data_at CompSpecs sh tnode (version, locs) n; data_at Tsh (tarray tint 8) (map (fun x : Z => vint x) vals ++ repeat Vundef (Z.to_nat (8 - i))) out; EX hists'' : list hist, !!(Zlength hists'' = 8 /\ sublist i 8 hists'' = sublist i 8 hists') && fold_right sepcon emp (map (fun j => EX fails : list Z, !!(add_events (Znth j hists []) (if zlt j i then make_loads (fails ++ [Znth j vals 0]) else make_loads fails) (Znth j hists'' []) /\ Zlength fails = loops) && atomic_loc_hist sh (Znth j locs Vundef) (Znth j ghosts Vundef) 0 (loc_R (Znth j lg Vundef) gsh (Znth j lgl Vundef) gv2) (Znth j hists'' [])) (upto 8)); EX v' : Z, EX lv' : list Z, !!(repable_signed v' /\ Zlength lv' = 8 /\ Forall (fun vl => round_down v <= vl) lv' /\ Forall (fun vl => vl <= round_up v') (sublist 0 i lv')) && ghost_snap v' gv2 * fold_right sepcon emp (map (fun '(v, g) => ghost_snap v g) (combine lv' lg)))). { Exists (@nil Z) hists' v lv1; unfold atomic_loc_hist at 2; rewrite data_at__eq, sublist_nil; entailer!. } + (* loop body *) Intros hists'' v' lv'. rewrite extract_nth_sepcon with (i := i) by (rewrite Zlength_map; auto). erewrite Znth_map, Znth_upto by (auto; simpl; omega); Intros. destruct (zlt i i); [omega|]. Intros fails. rewrite extract_nth_sepcon with (i := i)(l := map _ _) by (rewrite Zlength_map, Zlength_combine, Z.min_l; auto; omega). rewrite Znth_map with (d' := (0, Vundef)), Znth_combine by (rewrite ?Zlength_combine, ?Z.min_l; omega). unfold atomic_loc_hist at 2; rewrite (atomic_loc_isptr _ (Znth i locs Vundef)); Intros. forward. assert (round_down v <= Znth i lv' 0) by (apply Forall_Znth; auto; omega). forward_call (AL_witness sh (Znth i locs Vundef) (Znth i ghosts Vundef) 0 (loc_R (Znth i lg Vundef) gsh (Znth i lgl Vundef) gv2) (Znth i hists'' []) (ghost_snap v' gv2 * ghost_snap (Znth i lv' 0) (Znth i lg Vundef)) (fun _ => EX ver : Z, EX ver' : Z, !!(repable_signed ver' /\ round_down v <= ver <= round_up ver') && ghost_snap (Z.max ver' v') gv2 * ghost_snap ver (Znth i lg Vundef))). { split; auto. apply AL_hist_spec; auto; repeat intro. unfold loc_R in *. erewrite exp_sepcon1, extract_nth_exists_in_SEP with (n := O); [|simpl; eauto]. Intro ver; simpl. erewrite exp_sepcon1, extract_nth_exists_in_SEP with (n := O); [|simpl; eauto]. Intro ver'; simpl. erewrite !sepcon_andp_prop', extract_prop_in_SEP with (n := O); [|simpl; eauto]. Intros; simpl. rewrite <- !sepcon_assoc, sepcon_comm, <- !sepcon_assoc. rewrite sepcon_assoc, 2flatten_sepcon_in_SEP. assert_PROP (Znth i lv' 0 <= ver). { rewrite snap_master_join'; go_lowerx; entailer!. } eapply snap_master_update' with (v'0 := ver); [omega|]. rewrite snap_snap_max. eapply semax_pre; [|eauto]. go_lowerx. Exists ver ver' ver ver'; entailer!. } Intros vi; simpl; Intros hi vers; destruct vers as (ver, ver'). gather_SEP 3 8; rewrite replace_nth_sepcon. forward. Exists (x ++ [vi]) (upd_Znth i hists'' hi) (Z.max ver' v') (upd_Znth i lv' ver). rewrite map_app. replace (8 - (i + 1)) with (8 - (Zlength (map (fun x => vint x) x ++ [vint vi]))) by (rewrite Zlength_app, Zlength_cons, Zlength_nil, Zlength_map; subst; auto). simpl map; rewrite <- upd_complete_gen by (rewrite Zlength_map; omega). match goal with H : sublist _ _ hists'' = sublist _ _ hists' |- _ => rewrite sublist_next with (i0 := i)(l := hists'')(d := []), sublist_next with (i0 := i)(l := hists')(d := []) in H by (auto; omega); inv H end. rewrite combine_upd_Znth1 with (d := Vundef), <- upd_Znth_map by omega. subst; rewrite Zlength_map, !Zlength_app, !Zlength_cons, !Zlength_nil; entailer!. { split; [rewrite Forall_app; auto|]. rewrite !upd_Znth_Zlength by omega. split; [|split]. * split; auto. rewrite sublist_upd_Znth_r by omega; auto. * destruct (Z.max_spec ver' v') as [(? & ->) | (? & ->)]; auto. * split; auto. rewrite sublist_upd_Znth_lr, Z.sub_0_r by omega. split; [apply Forall_upd_Znth; auto; tauto|]. rewrite sublist_split with (mid := Zlength x) by omega. rewrite upd_Znth_app2; rewrite !Zlength_sublist; try omega. rewrite Z.sub_0_r, Zminus_diag, sublist_len_1 with (d := 0), upd_Znth0, sublist_1_cons by omega. rewrite Zlength_cons, sublist_nil, Forall_app; repeat constructor. -- eapply Forall_impl; [|eauto]; simpl; intros. rewrite round_up_max_distr; apply Zmax_bound_r; tauto. -- rewrite round_up_max_distr; apply Zmax_bound_l; tauto. } rewrite replace_nth_sepcon; apply sepcon_list_derives; rewrite upd_Znth_Zlength; rewrite !Zlength_map; auto; intros. erewrite Znth_map, Znth_upto by (auto; rewrite Zlength_upto in *; omega). destruct (eq_dec i (Zlength x)). * subst; rewrite !upd_Znth_same by (rewrite ?Zlength_map; auto; omega). Exists fails. destruct (zlt (Zlength x) (Zlength x + 1)); [|omega]. rewrite app_Znth2, Zminus_diag, Znth_0_cons by omega. entailer!. unfold make_loads; rewrite map_app; eapply add_events_trans; eauto. * rewrite !upd_Znth_diff' by (rewrite ?Zlength_map; auto; omega). erewrite Znth_map, Znth_upto by (auto; rewrite Zlength_upto in *; omega). Intros fails'; Exists fails'; entailer!. destruct (zlt i (Zlength x)), (zlt i (Zlength x + 1)); try omega; auto. rewrite app_Znth1; auto. + Intros vals hists'' v' lv'. unfold atomic_loc_hist at 1; Intros. forward_call (AL_witness sh version gv 0 (ver_R gv2 gsh gv' lg) hv1 (ghost_snap v' gv2) (fun v => !!(v' <= v) && ghost_snap v gv2)). { split; auto. apply AL_hist_spec; auto; repeat intro. unfold ver_R in *. rewrite sepcon_comm, <- !sepcon_assoc. assert_PROP (v' <= v2). { rewrite snap_master_join'; go_lowerx; entailer!. } rewrite 2flatten_sepcon_in_SEP. eapply snap_master_update' with (v'0 := v2); [omega|]. eapply semax_pre; [|eauto]. go_lowerx; entailer!. } Intros v2; simpl; Intros hv2. rewrite app_nil_r. rewrite Z.testbit_false, Zdiv_1_r in * by omega. match goal with |-semax _ (PROP () (LOCALx ?Q (SEPx ?R))) _ _ => forward_if (PROP (v2 <> v) (LOCALx Q (SEPx R))) end. * forward. Exists failvs loops v hv2 vals hists''; unfold atomic_loc_hist at 2; entailer!. { unfold make_loads; rewrite map_app; eapply add_events_trans; eauto. eapply add_events_trans with (le := [_]); eauto. } apply sepcon_derives; [auto|]. apply sepcon_list_derives; rewrite !Zlength_map, Zlength_combine, Z.min_l; try omega. intros; erewrite Znth_map with (d' := (0, Vundef)), Znth_map, Znth_combine by (rewrite ?Zlength_combine, ?Z.min_l; omega). replace (Znth i lv' 0) with v; auto. match goal with H : Forall _ lv' |- _ => apply Forall_Znth with (i0 := i)(d := 0) in H end; auto. match goal with H : Forall _ (sublist _ _ lv') |- _ => rewrite sublist_same in H by (auto; omega); apply Forall_Znth with (i0 := i)(d := 0) in H end; auto. unfold round_down, round_up in *. exploit (Z_mod_lt v' 2); [computable|]. destruct (eq_dec v' v); subst; omega. * forward. entailer!. * intros; unfold overridePost. destruct (eq_dec ek EK_normal); [subst | apply drop_tc_environ]. unfold POSTCONDITION, abbreviate, loop1_ret_assert. Intros; Exists (failvs ++ [v; v2]) (loops + 1) hv2 hists'' v2; unfold atomic_loc_hist at 2; entailer!. { rewrite Forall_app, Zlength_app, !Zlength_cons, Zlength_nil; repeat (constructor; auto); [|omega]. unfold make_loads; rewrite map_app; eapply add_events_trans; eauto. eapply add_events_trans with (le := [_]); eauto. } Exists lv'; entailer!. apply sepcon_list_derives; rewrite !Zlength_map; auto; intros. erewrite !Znth_map, !Znth_upto by (auto; rewrite Zlength_upto in *; omega). Intros fails; Exists (fails ++ [Znth i vals 0]); entailer!. destruct (zlt i 8); [|rewrite Zlength_upto in *; simpl in *; omega]. rewrite Zlength_app, Zlength_cons, Zlength_nil; split; auto. Qed. Lemma ver_R_precise : forall g gsh gv lg v, precise (EX h : _, ver_R g gsh gv lg h v). Proof. intros; unfold ver_R. rewrite exp_trivial by (exact []). unfold ghost_snap, ghost_master; repeat apply precise_sepcon; auto. { apply ghost_precise. } apply precise_fold_right. rewrite Forall_map, Forall_forall; simpl; intros. apply ghost_precise. Qed. Hint Resolve ver_R_precise. Lemma loc_R_precise : forall g gsh gl gv v, precise (EX h : _, loc_R g gsh gl gv h v). Proof. intros; unfold loc_R. rewrite exp_trivial by (exact []). unfold ghost_master, ghost_snap. apply derives_precise' with (Q := (EX sm : (option Z * option Z), ghost sm g) * (EX v : Z, ghost_var gsh v gl) * (EX sm : (option Z * option Z), ghost sm gv)); [|repeat apply precise_sepcon; try apply ex_ghost_precise; apply ghost_var_precise]. Intros ver ver'; Exists (@None Z, Some ver) (Some ver', @None Z) ver; auto. Qed. Hint Resolve loc_R_precise. Lemma body_write : semax_body Vprog Gprog f_write write_spec. Proof. start_function. unfold atomic_loc_hist at 1; Intros. rewrite atomic_loc_isptr; Intros. forward. assert (sh <> Share.bot) by (intro; subst; contradiction unreadable_bot). (* The ghost_var guarantees that no one else has changed the version. *) forward_call (AL_witness sh version gv 0 (ver_R gv2 gsh2 gv' lg) hv (ghost_var gsh1 v gv') (fun v' => !!(v' = v) && ghost_var gsh1 v gv')). { split; auto. apply AL_hist_spec; auto; repeat intro. unfold ver_R in *. rewrite !flatten_sepcon_in_SEP. gather_SEP 3 1. assert_PROP (v = v0). { go_lowerx; apply sepcon_derives_prop, ghost_var_inj; auto. } eapply semax_pre; [|eauto]. go_lowerx; entailer!. } Intros v'; simpl; Intros hv1; subst. assert (repable_signed (v + 1)) by admit. (* version stays in range *) assert ((v + 1) mod 2 = 1) as Hdirty. { rewrite Zplus_mod; replace (v mod 2) with 0. rewrite !Zmod_small by (try apply Z_mod_lt; computable); auto. } forward_call (AS_witness sh version gv 0 (ver_R gv2 gsh2 gv' lg) hv1 (v + 1) (ghost_snap v gv2 * ghost_var gsh1 v gv') (ghost_snap (v + 1) gv2 * ghost_var gsh1 (v + 1) gv')). { split; [|split; auto]. apply AS_hist_spec; auto. repeat intro. unfold ver_R in *. rewrite <- !sepcon_assoc, !flatten_sepcon_in_SEP. gather_SEP 4 1. assert_PROP (v = v'). { go_lowerx; apply sepcon_derives_prop, ghost_var_inj; auto. } subst v'; erewrite ghost_var_share_join by eauto. apply ghost_var_update with (v' := v + 1). erewrite <- (ghost_var_share_join _ _ _ _ _ SH2). gather_SEP 3 1. apply snap_master_update' with (v' := v + 1); [omega|]. eapply semax_pre; [|eauto]. unfold round_down. replace (v mod 2) with 0; rewrite Hdirty, Z.sub_0_r, Z.add_simpl_r. go_lowerx; entailer!. } Intros hv2. exploit (add_events_trans hv); eauto; intro. assert_PROP (Zlength vals = 8). { entailer!. rewrite Zlength_map in *; auto. } rewrite <- seq_assoc. forward_for_simple_bound 8 (EX i : Z, EX hists' : list hist, PROP (Zlength hists' = i) LOCAL (temp _v (vint v); temp _ver version; temp _n n; temp _in input) SEP (atomic_loc_hist sh version gv 0 (ver_R gv2 gsh2 gv' lg) hv2; ghost_snap (v + 1) gv2; ghost_var gsh1 (v + 1) gv'; @data_at CompSpecs sh tnode (version, locs) n; data_at Tsh (tarray tint 8) (map (fun x : Z => vint x) vals) input; fold_right sepcon emp (map (fun j => !!(j < i -> add_events (Znth j hists []) [Store (vint (Znth j vals 0))] (Znth j hists' [])) && atomic_loc_hist sh (Znth j locs Vundef) (Znth j ghosts Vundef) 0 (loc_R (Znth j lg Vundef) gsh2 (Znth j lgl Vundef) gv2) (if zlt j i then Znth j hists' [] else Znth j hists [])) (upto 8)); fold_right sepcon emp (map (ghost_snap (v + 2)) (sublist 0 i lg)); fold_right sepcon emp (map (ghost_var gsh1 (v + 2)) (sublist 0 i lgl)); fold_right sepcon emp (map (ghost_snap v) (sublist i 8 lg)); fold_right sepcon emp (map (ghost_var gsh1 v) (sublist i 8 lgl)))). { Exists (@nil hist); rewrite !sublist_nil, !sublist_same by auto; unfold atomic_loc_hist at 2; entailer!. apply sepcon_list_derives; rewrite !Zlength_map; auto; intros. erewrite !Znth_map, !Znth_upto by (auto; rewrite Zlength_upto in *; omega). apply andp_right; [apply prop_right; omega|]. destruct (zlt i 0); [omega | auto]. } - (* loop body *) rewrite extract_nth_sepcon with (i := i) by (rewrite Zlength_map; auto). erewrite Znth_map, Znth_upto by (auto; simpl; omega); Intros. destruct (zlt i i); [omega|]. rewrite sublist_next with (i0 := i)(d := Vundef) by (auto; omega); simpl. rewrite sublist_next with (i0 := i)(d := Vundef) by (auto; omega); simpl. unfold atomic_loc_hist at 2; rewrite (atomic_loc_isptr _ (Znth i locs Vundef)); Intros. forward. forward. forward_call (AS_witness sh (Znth i locs Vundef) (Znth i ghosts Vundef) 0 (loc_R (Znth i lg Vundef) gsh2 (Znth i lgl Vundef) gv2) (Znth i hists []) (Znth i vals 0) (ghost_snap (v + 1) gv2 * ghost_snap v (Znth i lg Vundef) * ghost_var gsh1 v (Znth i lgl Vundef)) (ghost_snap (v + 1) gv2 * ghost_snap (v + 2) (Znth i lg Vundef) * ghost_var gsh1 (v + 2) (Znth i lgl Vundef))). { split; [|split; auto; apply Forall_Znth; auto; omega]. apply AS_hist_spec; auto. repeat intro. unfold loc_R in *. erewrite exp_sepcon1, extract_nth_exists_in_SEP with (n := O); [|simpl; eauto]. Intro ver; simpl. erewrite exp_sepcon1, extract_nth_exists_in_SEP with (n := O); [|simpl; eauto]. Intro ver'; simpl. erewrite !sepcon_andp_prop', extract_prop_in_SEP with (n := O); [|simpl; eauto]. Intros; simpl. rewrite <- !sepcon_assoc, !flatten_sepcon_in_SEP. gather_SEP 1 5. assert_PROP (ver = v). { go_lowerx; apply sepcon_derives_prop, ghost_var_inj; auto. } subst; erewrite ghost_var_share_join by eauto. apply ghost_var_update with (v'0 := v + 2). erewrite <- (ghost_var_share_join _ _ _ _ _ SH2). gather_SEP 4 1. apply snap_master_update' with (v'0 := v + 2); [omega|]. gather_SEP 3 2; rewrite snap_snap_max. eapply semax_pre; [|eauto]. go_lowerx. Exists (v + 2) (Z.max (v + 1) ver'); entailer!. split; [destruct (Z.max_spec (v + 1) ver') as [(? & ->) | (? & ->)]; auto|]. rewrite round_up_max_distr; apply Zmax_bound_l. unfold round_up; replace (v mod 2) with 0; rewrite Hdirty; omega. } rewrite sublist_split with (mid := i)(hi := i + 1), sublist_len_1 with (d := Vundef), map_app, sepcon_app by omega. rewrite sublist_split with (mid := i)(hi := i + 1), sublist_len_1 with (d := Vundef), map_app, sepcon_app by omega. Intros h'; Exists (x ++ [h']); rewrite Zlength_app, Zlength_cons, Zlength_nil; entailer!. rewrite replace_nth_sepcon; apply sepcon_list_derives; rewrite upd_Znth_Zlength; rewrite !Zlength_map; auto. intros. erewrite Znth_map, Znth_upto by (auto; rewrite Zlength_upto in *; omega). destruct (eq_dec i (Zlength x)). + subst; rewrite upd_Znth_same by (rewrite Zlength_map; auto). destruct (zlt (Zlength x) (Zlength x + 1)); [|omega]. rewrite app_Znth2, Zminus_diag, Znth_0_cons by omega. apply andp_right; auto. apply prop_right; auto. + rewrite upd_Znth_diff' by (rewrite ?Zlength_map; auto). erewrite Znth_map, Znth_upto by (auto; rewrite Zlength_upto in *; omega). Intros. destruct (zlt i (Zlength x)), (zlt i (Zlength x + 1)); try omega. * rewrite app_Znth1 by auto. apply andp_right; auto. apply prop_right; auto. * apply andp_right; auto. apply prop_right; omega. - Intros hists'. unfold atomic_loc_hist at 1; Intros. rewrite !sublist_nil, !sublist_same by auto. assert ((v + 2) mod 2 = 0) as Hclean. { rewrite Zplus_mod. replace (v mod 2) with 0; rewrite Z_mod_same_full, Zmod_0_l; auto. } forward_call (AS_witness sh version gv 0 (ver_R gv2 gsh2 gv' lg) hv2 (v + 2) (ghost_snap (v + 1) gv2 * ghost_var gsh1 (v + 1) gv' * fold_right sepcon emp (map (ghost_snap (v + 2)) lg)) (ghost_snap (v + 2) gv2 * ghost_var gsh1 (v + 2) gv' * fold_right sepcon emp (map (ghost_snap (v + 2)) lg))). { split; [|split; auto]. apply AS_hist_spec; auto. repeat intro. unfold ver_R in *. rewrite <- !sepcon_assoc, !flatten_sepcon_in_SEP. gather_SEP 4 1. assert_PROP (v + 1 = v'). { go_lowerx; apply sepcon_derives_prop, ghost_var_inj; auto. } subst v'; erewrite ghost_var_share_join by eauto. apply ghost_var_update with (v' := v + 2). erewrite <- (ghost_var_share_join _ _ _ _ _ SH2). gather_SEP 3 1. apply snap_master_update' with (v' := v + 2); [omega|]. gather_SEP 3 2. apply snaps_snaps_max; rewrite Z.max_l by (unfold round_down; omega). eapply semax_pre; [|eauto]. unfold round_down; rewrite Hclean, Z.sub_0_r. go_lowerx; entailer!. { admit. (* version stays in range *) } } Intros hv3. forward. Exists hv3 hists'; unfold atomic_loc_hist at 2; entailer!. + eapply add_events_trans with (le := [_; _]); eauto. + apply sepcon_list_derives; rewrite !Zlength_map; auto; intros. erewrite !Znth_map, !Znth_upto by (auto; rewrite Zlength_upto in *; omega). Intros; destruct (zlt i 8); [|rewrite Zlength_upto in *; simpl in *; omega]. apply andp_right; auto. apply prop_right; auto. Admitted. (*(* Steps to linearizability: A single thread sees a sequence of reads and writes. The join of a collection of sequences of reads and writes, if consistent, is equivalent to a sequence of reads and writes. *) Inductive lin_op := Read (v : Z) (vals : list Z) | Write (v : Z) (vals : list Z). Fixpoint do_op h1 op h2 := match op with | Read v vals => Z.testbit v 0 = false /\ exists failvs, Forall repable_signed failvs /\ add_events (fst h1) (make_loads (failvs ++ [v; v])) (fst h2) /\ exists loops, forall i, 0 <= i < 8 -> exists fails, Zlength fails = loops /\ add_events (Znth i (snd h1) []) (make_loads (fails ++ [Znth i vals 0])) (Znth i (snd h2) []) | Write v vals => add_events (fst h1) [Load (vint v); Store (vint (Z.lor v 1)); Store (vint (v + 2))] (fst h2) /\ forall i, 0 <= i < 8 -> add_events (Znth i (snd h1) []) [Store (vint (Znth i vals 0))] (Znth i (snd h2) []) end. Inductive do_ops h : list lin_op -> hist * list hist -> Prop := | do_ops_nil : do_ops h [] h | do_ops_cons : forall a la h' h'' (Hh' : do_op h a h') (Hh'' : do_ops h' la h''), do_ops h (a :: la) h''. (* For now, we're relying on there being only one writer. *) Lemma full_hist_writes : forall w lr v (Hv : full_hist' (concat (w :: lr)) v) (Hw : NoDup (map fst w)) (Hr : Forall (fun h => exists lv, map snd h = make_loads lv) lr), full_hist' w v. Proof. intros; eapply full_hist'_drop; eauto. { simpl; apply incl_appl, incl_refl. } simpl; intros ?? Hin Hout ??. rewrite in_app in Hin; destruct Hin as [? | Hin]; [contradiction|]. rewrite in_concat in Hin; destruct Hin as (h & ? & ?). rewrite Forall_forall in Hr; exploit Hr; eauto; intros (? & Hsnd). assert (In e (map snd h)) as He by (rewrite in_map_iff; do 2 eexists; eauto; auto). unfold make_loads in Hsnd; rewrite Hsnd, in_map_iff in He; destruct He as (? & ? & ?); subst; contradiction. Qed. Definition empty_state := ([] : hist, repeat ([] : hist) 8). Definition make_reads le := map (fun '(v, lv) => Read v lv) le. Definition make_writes le := map (fun '(v, lv) => Write v lv) le. Lemma read_written : forall w lr writes reads v vals (Hw : do_ops empty_state (make_writes writes) w) (Hlr : Forall2 (fun rs r => do_ops empty_state (make_reads rs) r) reads lr) (Hfullv : full_hist' (concat (map fst (w :: lr))) v) (Hvals : Zlength vals = 8) (Hfullvs : forall i, 0 <= i < 8 -> full_hist' (concat (map (fun l => Znth i (snd l) []) (w :: lr))) (vint (Znth i vals 0))), incl (concat reads) writes. Proof. repeat intro. rewrite in_concat in H; destruct H as (r & Hr & Hin). (* We actually need the memory model here. Since there's no connection between histories on different locations, we don't know that the write of the version number happens before the writes to the bodies. How can we recover this information? With a ghost variable marking the version number on each location? *) *)
Formal statement is: lemma algebraic_int_minus_iff [simp]: "algebraic_int (-x) \<longleftrightarrow> algebraic_int (x :: 'a :: field_char_0)" Informal statement is: If $x$ is an algebraic integer, then $-x$ is an algebraic integer.
For any real-valued field $a$ and any natural number $n$, $|a \cdot n| = |a| \cdot n$.
-- Andreas, 2020-03-20, issue #4482, reported by gallai -- Precise range for unexpected implicit argument. _ : Set β†’ {A : Set} β†’ {B : Set} β†’ {C : Set} β†’ Set _ = Ξ» { _ {B = B} {A = A} β†’ {!!} } -- Unexpected implicit argument -- when checking the clause left hand side -- .extendedlambda0 _ {B = B} {A = A} -- ^ highlight this
theory Ex3_1 imports Main begin primrec pow :: "nat \<Rightarrow> nat \<Rightarrow> nat" where "pow _ 0 = 1"| "pow b (Suc e) = b * pow b e" lemma lem1 : "pow 1 n = 1" by (induction n ; simp) lemma lem2 : "pow x (n + m) = pow x n * pow x m" proof (induction n arbitrary : m) case 0 then show ?case by simp next case (Suc n) assume hyp:"\<And> m . pow x (n + m) = pow x n * pow x m" then show ?case by simp qed lemma lem3 : "pow (x * y) n = pow x n * pow y n" by (induction n; simp) theorem pow_mult : "pow x (m * n) = pow (pow x m) n" proof (induction m) case 0 then show ?case using lem1 by simp next case (Suc m) assume hyp:"pow x (m * n) = pow (pow x m) n" have "pow x (Suc m * n) = pow x ((m + 1) * n)" by simp also have "\<dots> = pow x (m * n + n)" by (simp add: semiring_normalization_rules(2)) also have "\<dots> = pow x (m * n) * pow x n" by (simp add : lem2) also have "\<dots> = pow (pow x m) n * pow x n" by (simp add : hyp) finally have tmp:"pow x (Suc m * n) = pow (pow x m) n * pow x n" by assumption have "pow (pow x (Suc m)) n = pow (x * pow x m) n" by simp also have "\<dots> = pow x n * pow (pow x m) n" using lem3 by simp finally show ?case using tmp by simp qed primrec sum :: "nat list \<Rightarrow> nat" where "sum [] = 0"| "sum (x#xs) = x + sum xs" lemma lem4 : "sum (xs @ ys) = sum xs + sum ys" by (induction xs ; simp) theorem sum_rev : "sum (rev ns) = sum ns" by (induction ns ; simp add : lem4) primrec Sum :: "(nat \<Rightarrow> nat ) \<Rightarrow> nat \<Rightarrow> nat" where "Sum f 0 = 0"| "Sum f (Suc k) = f k + Sum f k" theorem "Sum (\<lambda>i . f i + g i) k = Sum f k + Sum g k" by (induction k ; simp) theorem "Sum f (k + l) = Sum f k + Sum (\<lambda>x .f (k + x)) l" by (induction l; simp) theorem "Sum f k = sum (map f [0 ..<k])" proof (induction k) case 0 then show ?case by simp next case (Suc k) then show ?case by (simp add: lem4) qed
example (a b : Nat) : 1 ≀ 2 := have : 1 ≀ a + b := by rfl have : a + b ≀ b := by rfl have : b ≀ 2 := by rfl by decide example (a b : Nat) : 1 ≀ 2 := calc 1 ≀ a + b := by rfl _ ≀ b := by rfl _ ≀ 2 := by rfl
(*************************************************************) (* Copyright Dominique Larchey-Wendling [*] *) (* *) (* [*] Affiliation LORIA -- CNRS *) (*************************************************************) (* This file is distributed under the terms of the *) (* CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT *) (*************************************************************) Require Import Undecidability.Synthetic.Undecidability. Require Import Undecidability.Synthetic.ReducibilityFacts. Require Import Undecidability.TM.TM. From Undecidability.MinskyMachines Require Import MM BSM_MM. From Undecidability Require TM.Reductions.HaltTM_1_to_SBTM_HALT StackMachines.Reductions.SBTM_HALT_to_HaltBSM. Theorem HaltTM_to_MM_HALTS_ON_ZERO : HaltTM 1 βͺ― MM_HALTS_ON_ZERO. Proof. eapply reduces_transitive. { exact HaltTM_1_to_SBTM_HALT.reduction. } eapply reduces_transitive. { exact SBTM_HALT_to_HaltBSM.reduction. } exact BSM_MM_HALTS_ON_ZERO. Qed. Theorem HaltTM_to_MM_HALTING : HaltTM 1 βͺ― MM_HALTING. Proof. eapply reduces_transitive. { exact HaltTM_1_to_SBTM_HALT.reduction. } eapply reduces_transitive. { exact SBTM_HALT_to_HaltBSM.reduction. } exact BSM_MM_HALTING. Qed.
[STATEMENT] lemma lemma_conf_temporal [rule_format (no_asm)]: "\<lbrakk> A \<notin> bad; B \<notin> bad; evs \<in> bankerb_gets \<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs \<longrightarrow> Key K \<in> analz (knows Spy evs) \<longrightarrow> expiredK Tk evs" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>A \<notin> bad; B \<notin> bad; evs \<in> bankerb_gets\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs \<longrightarrow> Key K \<in> analz (knows Spy evs) \<longrightarrow> expiredK Tk evs [PROOF STEP] apply (erule bankerb_gets.induct) [PROOF STATE] proof (prove) goal (8 subgoals): 1. \<lbrakk>A \<notin> bad; B \<notin> bad\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set [] \<longrightarrow> Key K \<in> analz (knows Spy []) \<longrightarrow> expiredK Tk [] 2. \<And>evsf X Ba. \<lbrakk>A \<notin> bad; B \<notin> bad; evsf \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evsf \<longrightarrow> Key K \<in> analz (knows Spy evsf) \<longrightarrow> expiredK Tk evsf; X \<in> synth (analz (knows Spy evsf))\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set (Says Spy Ba X # evsf) \<longrightarrow> Key K \<in> analz (knows Spy (Says Spy Ba X # evsf)) \<longrightarrow> expiredK Tk (Says Spy Ba X # evsf) 3. \<And>evsr Aa Ba X. \<lbrakk>A \<notin> bad; B \<notin> bad; evsr \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evsr \<longrightarrow> Key K \<in> analz (knows Spy evsr) \<longrightarrow> expiredK Tk evsr; Says Aa Ba X \<in> set evsr\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set (Gets Ba X # evsr) \<longrightarrow> Key K \<in> analz (knows Spy (Gets Ba X # evsr)) \<longrightarrow> expiredK Tk (Gets Ba X # evsr) 4. \<And>evs1 Aa Ba. \<lbrakk>A \<notin> bad; B \<notin> bad; evs1 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs1 \<longrightarrow> Key K \<in> analz (knows Spy evs1) \<longrightarrow> expiredK Tk evs1\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set (Says Aa Server \<lbrace>Agent Aa, Agent Ba\<rbrace> # evs1) \<longrightarrow> Key K \<in> analz (knows Spy (Says Aa Server \<lbrace>Agent Aa, Agent Ba\<rbrace> # evs1)) \<longrightarrow> expiredK Tk (Says Aa Server \<lbrace>Agent Aa, Agent Ba\<rbrace> # evs1) 5. \<And>evs2 Ka Aa Ba. \<lbrakk>A \<notin> bad; B \<notin> bad; evs2 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs2 \<longrightarrow> Key K \<in> analz (knows Spy evs2) \<longrightarrow> expiredK Tk evs2; Key Ka \<notin> used evs2; Ka \<in> symKeys; Gets Server \<lbrace>Agent Aa, Agent Ba\<rbrace> \<in> set evs2\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set (Says Server Aa (Crypt (shrK Aa) \<lbrace>Number (CT evs2), Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number (CT evs2), Agent Aa, Key Ka\<rbrace>\<rbrace>) # evs2) \<longrightarrow> Key K \<in> analz (knows Spy (Says Server Aa (Crypt (shrK Aa) \<lbrace>Number (CT evs2), Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number (CT evs2), Agent Aa, Key Ka\<rbrace>\<rbrace>) # evs2)) \<longrightarrow> expiredK Tk (Says Server Aa (Crypt (shrK Aa) \<lbrace>Number (CT evs2), Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number (CT evs2), Agent Aa, Key Ka\<rbrace>\<rbrace>) # evs2) 6. \<And>evs3 Aa Tka Ba Ka Ticket. \<lbrakk>A \<notin> bad; B \<notin> bad; evs3 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs3 \<longrightarrow> Key K \<in> analz (knows Spy evs3) \<longrightarrow> expiredK Tk evs3; Gets Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Ticket\<rbrace>) \<in> set evs3; Says Aa Server \<lbrace>Agent Aa, Agent Ba\<rbrace> \<in> set evs3; \<not> expiredK Tka evs3\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set (Says Aa Ba \<lbrace>Ticket, Crypt Ka \<lbrace>Agent Aa, Number (CT evs3)\<rbrace>\<rbrace> # evs3) \<longrightarrow> Key K \<in> analz (knows Spy (Says Aa Ba \<lbrace>Ticket, Crypt Ka \<lbrace>Agent Aa, Number (CT evs3)\<rbrace>\<rbrace> # evs3)) \<longrightarrow> expiredK Tk (Says Aa Ba \<lbrace>Ticket, Crypt Ka \<lbrace>Agent Aa, Number (CT evs3)\<rbrace>\<rbrace> # evs3) 7. \<And>evs4 Ba Tka Aa Ka Ta. \<lbrakk>A \<notin> bad; B \<notin> bad; evs4 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs4 \<longrightarrow> Key K \<in> analz (knows Spy evs4) \<longrightarrow> expiredK Tk evs4; Gets Ba \<lbrace>Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>, Crypt Ka \<lbrace>Agent Aa, Number Ta\<rbrace>\<rbrace> \<in> set evs4; \<not> expiredK Tka evs4; \<not> expiredA Ta evs4\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set (Says Ba Aa (Crypt Ka (Number Ta)) # evs4) \<longrightarrow> Key K \<in> analz (knows Spy (Says Ba Aa (Crypt Ka (Number Ta)) # evs4)) \<longrightarrow> expiredK Tk (Says Ba Aa (Crypt Ka (Number Ta)) # evs4) 8. \<And>evso Aa Tka Ba Ka Ticket. \<lbrakk>A \<notin> bad; B \<notin> bad; evso \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evso \<longrightarrow> Key K \<in> analz (knows Spy evso) \<longrightarrow> expiredK Tk evso; Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Ticket\<rbrace>) \<in> set evso; expiredK Tka evso\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set (Notes Spy \<lbrace>Number Tka, Key Ka\<rbrace> # evso) \<longrightarrow> Key K \<in> analz (knows Spy (Notes Spy \<lbrace>Number Tka, Key Ka\<rbrace> # evso)) \<longrightarrow> expiredK Tk (Notes Spy \<lbrace>Number Tka, Key Ka\<rbrace> # evso) [PROOF STEP] apply (frule_tac [8] Says_Server_message_form) [PROOF STATE] proof (prove) goal (9 subgoals): 1. \<lbrakk>A \<notin> bad; B \<notin> bad\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set [] \<longrightarrow> Key K \<in> analz (knows Spy []) \<longrightarrow> expiredK Tk [] 2. \<And>evsf X Ba. \<lbrakk>A \<notin> bad; B \<notin> bad; evsf \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evsf \<longrightarrow> Key K \<in> analz (knows Spy evsf) \<longrightarrow> expiredK Tk evsf; X \<in> synth (analz (knows Spy evsf))\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set (Says Spy Ba X # evsf) \<longrightarrow> Key K \<in> analz (knows Spy (Says Spy Ba X # evsf)) \<longrightarrow> expiredK Tk (Says Spy Ba X # evsf) 3. \<And>evsr Aa Ba X. \<lbrakk>A \<notin> bad; B \<notin> bad; evsr \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evsr \<longrightarrow> Key K \<in> analz (knows Spy evsr) \<longrightarrow> expiredK Tk evsr; Says Aa Ba X \<in> set evsr\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set (Gets Ba X # evsr) \<longrightarrow> Key K \<in> analz (knows Spy (Gets Ba X # evsr)) \<longrightarrow> expiredK Tk (Gets Ba X # evsr) 4. \<And>evs1 Aa Ba. \<lbrakk>A \<notin> bad; B \<notin> bad; evs1 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs1 \<longrightarrow> Key K \<in> analz (knows Spy evs1) \<longrightarrow> expiredK Tk evs1\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set (Says Aa Server \<lbrace>Agent Aa, Agent Ba\<rbrace> # evs1) \<longrightarrow> Key K \<in> analz (knows Spy (Says Aa Server \<lbrace>Agent Aa, Agent Ba\<rbrace> # evs1)) \<longrightarrow> expiredK Tk (Says Aa Server \<lbrace>Agent Aa, Agent Ba\<rbrace> # evs1) 5. \<And>evs2 Ka Aa Ba. \<lbrakk>A \<notin> bad; B \<notin> bad; evs2 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs2 \<longrightarrow> Key K \<in> analz (knows Spy evs2) \<longrightarrow> expiredK Tk evs2; Key Ka \<notin> used evs2; Ka \<in> symKeys; Gets Server \<lbrace>Agent Aa, Agent Ba\<rbrace> \<in> set evs2\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set (Says Server Aa (Crypt (shrK Aa) \<lbrace>Number (CT evs2), Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number (CT evs2), Agent Aa, Key Ka\<rbrace>\<rbrace>) # evs2) \<longrightarrow> Key K \<in> analz (knows Spy (Says Server Aa (Crypt (shrK Aa) \<lbrace>Number (CT evs2), Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number (CT evs2), Agent Aa, Key Ka\<rbrace>\<rbrace>) # evs2)) \<longrightarrow> expiredK Tk (Says Server Aa (Crypt (shrK Aa) \<lbrace>Number (CT evs2), Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number (CT evs2), Agent Aa, Key Ka\<rbrace>\<rbrace>) # evs2) 6. \<And>evs3 Aa Tka Ba Ka Ticket. \<lbrakk>A \<notin> bad; B \<notin> bad; evs3 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs3 \<longrightarrow> Key K \<in> analz (knows Spy evs3) \<longrightarrow> expiredK Tk evs3; Gets Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Ticket\<rbrace>) \<in> set evs3; Says Aa Server \<lbrace>Agent Aa, Agent Ba\<rbrace> \<in> set evs3; \<not> expiredK Tka evs3\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set (Says Aa Ba \<lbrace>Ticket, Crypt Ka \<lbrace>Agent Aa, Number (CT evs3)\<rbrace>\<rbrace> # evs3) \<longrightarrow> Key K \<in> analz (knows Spy (Says Aa Ba \<lbrace>Ticket, Crypt Ka \<lbrace>Agent Aa, Number (CT evs3)\<rbrace>\<rbrace> # evs3)) \<longrightarrow> expiredK Tk (Says Aa Ba \<lbrace>Ticket, Crypt Ka \<lbrace>Agent Aa, Number (CT evs3)\<rbrace>\<rbrace> # evs3) 7. \<And>evs4 Ba Tka Aa Ka Ta. \<lbrakk>A \<notin> bad; B \<notin> bad; evs4 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs4 \<longrightarrow> Key K \<in> analz (knows Spy evs4) \<longrightarrow> expiredK Tk evs4; Gets Ba \<lbrace>Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>, Crypt Ka \<lbrace>Agent Aa, Number Ta\<rbrace>\<rbrace> \<in> set evs4; \<not> expiredK Tka evs4; \<not> expiredA Ta evs4\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set (Says Ba Aa (Crypt Ka (Number Ta)) # evs4) \<longrightarrow> Key K \<in> analz (knows Spy (Says Ba Aa (Crypt Ka (Number Ta)) # evs4)) \<longrightarrow> expiredK Tk (Says Ba Aa (Crypt Ka (Number Ta)) # evs4) 8. \<And>evso Aa Tka Ba Ka Ticket. \<lbrakk>A \<notin> bad; B \<notin> bad; evso \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evso \<longrightarrow> Key K \<in> analz (knows Spy evso) \<longrightarrow> expiredK Tk evso; Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Ticket\<rbrace>) \<in> set evso; expiredK Tka evso\<rbrakk> \<Longrightarrow> evso \<in> bankerb_gets 9. \<And>evso Aa Tka Ba Ka Ticket. \<lbrakk>A \<notin> bad; B \<notin> bad; evso \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evso \<longrightarrow> Key K \<in> analz (knows Spy evso) \<longrightarrow> expiredK Tk evso; Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Ticket\<rbrace>) \<in> set evso; expiredK Tka evso; shrK Aa = shrK Aa \<and> Ka \<notin> range shrK \<and> Ticket = Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace> \<and> Key Ka \<notin> used before Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Ticket\<rbrace>) on evso \<and> Tka = CT before Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Ticket\<rbrace>) on evso\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set (Notes Spy \<lbrace>Number Tka, Key Ka\<rbrace> # evso) \<longrightarrow> Key K \<in> analz (knows Spy (Notes Spy \<lbrace>Number Tka, Key Ka\<rbrace> # evso)) \<longrightarrow> expiredK Tk (Notes Spy \<lbrace>Number Tka, Key Ka\<rbrace> # evso) [PROOF STEP] apply (frule_tac [6] Gets_Server_message_form [THEN disjE]) [PROOF STATE] proof (prove) goal (12 subgoals): 1. \<lbrakk>A \<notin> bad; B \<notin> bad\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set [] \<longrightarrow> Key K \<in> analz (knows Spy []) \<longrightarrow> expiredK Tk [] 2. \<And>evsf X Ba. \<lbrakk>A \<notin> bad; B \<notin> bad; evsf \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evsf \<longrightarrow> Key K \<in> analz (knows Spy evsf) \<longrightarrow> expiredK Tk evsf; X \<in> synth (analz (knows Spy evsf))\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set (Says Spy Ba X # evsf) \<longrightarrow> Key K \<in> analz (knows Spy (Says Spy Ba X # evsf)) \<longrightarrow> expiredK Tk (Says Spy Ba X # evsf) 3. \<And>evsr Aa Ba X. \<lbrakk>A \<notin> bad; B \<notin> bad; evsr \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evsr \<longrightarrow> Key K \<in> analz (knows Spy evsr) \<longrightarrow> expiredK Tk evsr; Says Aa Ba X \<in> set evsr\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set (Gets Ba X # evsr) \<longrightarrow> Key K \<in> analz (knows Spy (Gets Ba X # evsr)) \<longrightarrow> expiredK Tk (Gets Ba X # evsr) 4. \<And>evs1 Aa Ba. \<lbrakk>A \<notin> bad; B \<notin> bad; evs1 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs1 \<longrightarrow> Key K \<in> analz (knows Spy evs1) \<longrightarrow> expiredK Tk evs1\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set (Says Aa Server \<lbrace>Agent Aa, Agent Ba\<rbrace> # evs1) \<longrightarrow> Key K \<in> analz (knows Spy (Says Aa Server \<lbrace>Agent Aa, Agent Ba\<rbrace> # evs1)) \<longrightarrow> expiredK Tk (Says Aa Server \<lbrace>Agent Aa, Agent Ba\<rbrace> # evs1) 5. \<And>evs2 Ka Aa Ba. \<lbrakk>A \<notin> bad; B \<notin> bad; evs2 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs2 \<longrightarrow> Key K \<in> analz (knows Spy evs2) \<longrightarrow> expiredK Tk evs2; Key Ka \<notin> used evs2; Ka \<in> symKeys; Gets Server \<lbrace>Agent Aa, Agent Ba\<rbrace> \<in> set evs2\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set (Says Server Aa (Crypt (shrK Aa) \<lbrace>Number (CT evs2), Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number (CT evs2), Agent Aa, Key Ka\<rbrace>\<rbrace>) # evs2) \<longrightarrow> Key K \<in> analz (knows Spy (Says Server Aa (Crypt (shrK Aa) \<lbrace>Number (CT evs2), Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number (CT evs2), Agent Aa, Key Ka\<rbrace>\<rbrace>) # evs2)) \<longrightarrow> expiredK Tk (Says Server Aa (Crypt (shrK Aa) \<lbrace>Number (CT evs2), Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number (CT evs2), Agent Aa, Key Ka\<rbrace>\<rbrace>) # evs2) 6. \<And>evs3 Aa Tka Ba Ka Ticket. \<lbrakk>A \<notin> bad; B \<notin> bad; evs3 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs3 \<longrightarrow> Key K \<in> analz (knows Spy evs3) \<longrightarrow> expiredK Tk evs3; Gets Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Ticket\<rbrace>) \<in> set evs3; Says Aa Server \<lbrace>Agent Aa, Agent Ba\<rbrace> \<in> set evs3; \<not> expiredK Tka evs3\<rbrakk> \<Longrightarrow> evs3 \<in> bankerb_gets 7. \<And>evs3 Aa Tka Ba Ka Ticket. \<lbrakk>A \<notin> bad; B \<notin> bad; evs3 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs3 \<longrightarrow> Key K \<in> analz (knows Spy evs3) \<longrightarrow> expiredK Tk evs3; Gets Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Ticket\<rbrace>) \<in> set evs3; Says Aa Server \<lbrace>Agent Aa, Agent Ba\<rbrace> \<in> set evs3; \<not> expiredK Tka evs3; Ka \<notin> range shrK \<and> Ticket = Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrakk> \<Longrightarrow> ?R10 evs3 Aa Tka Ba Ka Ticket 8. \<And>evs3 Aa Tka Ba Ka Ticket. \<lbrakk>A \<notin> bad; B \<notin> bad; evs3 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs3 \<longrightarrow> Key K \<in> analz (knows Spy evs3) \<longrightarrow> expiredK Tk evs3; Gets Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Ticket\<rbrace>) \<in> set evs3; Says Aa Server \<lbrace>Agent Aa, Agent Ba\<rbrace> \<in> set evs3; \<not> expiredK Tka evs3; Ticket \<in> analz (knows Spy evs3)\<rbrakk> \<Longrightarrow> ?R10 evs3 Aa Tka Ba Ka Ticket 9. \<And>evs3 Aa Tka Ba Ka Ticket. \<lbrakk>A \<notin> bad; B \<notin> bad; evs3 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs3 \<longrightarrow> Key K \<in> analz (knows Spy evs3) \<longrightarrow> expiredK Tk evs3; Gets Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Ticket\<rbrace>) \<in> set evs3; Says Aa Server \<lbrace>Agent Aa, Agent Ba\<rbrace> \<in> set evs3; \<not> expiredK Tka evs3; ?R10 evs3 Aa Tka Ba Ka Ticket\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set (Says Aa Ba \<lbrace>Ticket, Crypt Ka \<lbrace>Agent Aa, Number (CT evs3)\<rbrace>\<rbrace> # evs3) \<longrightarrow> Key K \<in> analz (knows Spy (Says Aa Ba \<lbrace>Ticket, Crypt Ka \<lbrace>Agent Aa, Number (CT evs3)\<rbrace>\<rbrace> # evs3)) \<longrightarrow> expiredK Tk (Says Aa Ba \<lbrace>Ticket, Crypt Ka \<lbrace>Agent Aa, Number (CT evs3)\<rbrace>\<rbrace> # evs3) 10. \<And>evs4 Ba Tka Aa Ka Ta. \<lbrakk>A \<notin> bad; B \<notin> bad; evs4 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs4 \<longrightarrow> Key K \<in> analz (knows Spy evs4) \<longrightarrow> expiredK Tk evs4; Gets Ba \<lbrace>Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>, Crypt Ka \<lbrace>Agent Aa, Number Ta\<rbrace>\<rbrace> \<in> set evs4; \<not> expiredK Tka evs4; \<not> expiredA Ta evs4\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set (Says Ba Aa (Crypt Ka (Number Ta)) # evs4) \<longrightarrow> Key K \<in> analz (knows Spy (Says Ba Aa (Crypt Ka (Number Ta)) # evs4)) \<longrightarrow> expiredK Tk (Says Ba Aa (Crypt Ka (Number Ta)) # evs4) A total of 12 subgoals... [PROOF STEP] apply (simp_all (no_asm_simp) add: less_SucI analz_insert_eq analz_insert_freshK pushes) [PROOF STATE] proof (prove) goal (4 subgoals): 1. \<And>evsf X. \<lbrakk>A \<notin> bad; B \<notin> bad; evsf \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evsf \<longrightarrow> Key K \<in> analz (knows Spy evsf) \<longrightarrow> expiredK Tk evsf; X \<in> synth (analz (knows Spy evsf))\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evsf \<longrightarrow> Key K \<in> analz (insert X (knows Spy evsf)) \<longrightarrow> sesKlife + Tk < Suc (CT evsf) 2. \<And>evs2 Ka Aa Ba. \<lbrakk>A \<notin> bad; B \<notin> bad; evs2 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs2 \<longrightarrow> Key K \<in> analz (knows Spy evs2) \<longrightarrow> expiredK Tk evs2; Key Ka \<notin> used evs2; Ka \<in> symKeys; Gets Server \<lbrace>Agent Aa, Agent Ba\<rbrace> \<in> set evs2\<rbrakk> \<Longrightarrow> (shrK Ba = Ka \<longrightarrow> (Aa \<in> bad \<longrightarrow> (A = Aa \<and> Tk = CT evs2 \<and> B = Ba \<and> K = Ka \<and> B = Ba \<and> Tk = CT evs2 \<and> A = Aa \<and> K = Ka \<longrightarrow> sesKlife = 0) \<and> (Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs2 \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evs2))) \<and> (Aa \<notin> bad \<longrightarrow> A = Aa \<and> Tk = CT evs2 \<and> B = Ba \<and> K = Ka \<and> B = Ba \<and> Tk = CT evs2 \<and> A = Aa \<and> K = Ka \<longrightarrow> Key Ka \<in> analz (knows Spy evs2) \<longrightarrow> sesKlife = 0)) \<and> (Ba \<in> bad \<longrightarrow> (Aa \<in> bad \<longrightarrow> (A = Aa \<and> Tk = CT evs2 \<and> B = Ba \<and> K = Ka \<and> B = Ba \<and> Tk = CT evs2 \<and> A = Aa \<and> K = Ka \<longrightarrow> sesKlife = 0) \<and> (Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs2 \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evs2))) \<and> (Aa \<notin> bad \<longrightarrow> A = Aa \<and> Tk = CT evs2 \<and> B = Ba \<and> K = Ka \<and> B = Ba \<and> Tk = CT evs2 \<and> A = Aa \<and> K = Ka \<longrightarrow> Key Ka \<in> analz (knows Spy evs2) \<longrightarrow> sesKlife = 0)) \<and> (shrK Ba \<noteq> Ka \<and> Ba \<notin> bad \<longrightarrow> (Aa \<in> bad \<longrightarrow> (A = Aa \<and> Tk = CT evs2 \<and> B = Ba \<and> K = Ka \<and> B = Ba \<and> Tk = CT evs2 \<and> A = Aa \<and> K = Ka \<longrightarrow> sesKlife = 0) \<and> (Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs2 \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evs2))) \<and> (Aa \<notin> bad \<longrightarrow> A = Aa \<and> Tk = CT evs2 \<and> B = Ba \<and> K = Ka \<and> B = Ba \<and> Tk = CT evs2 \<and> A = Aa \<and> K = Ka \<longrightarrow> Key Ka \<in> analz (knows Spy evs2) \<longrightarrow> sesKlife = 0)) 3. \<And>evs3 Aa Tka Ba Ka. \<lbrakk>A \<notin> bad; B \<notin> bad; evs3 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs3 \<longrightarrow> Key K \<in> analz (knows Spy evs3) \<longrightarrow> expiredK Tk evs3; Gets Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) \<in> set evs3; Says Aa Server \<lbrace>Agent Aa, Agent Ba\<rbrace> \<in> set evs3; \<not> expiredK Tka evs3; Ka \<notin> range shrK\<rbrakk> \<Longrightarrow> Ba \<in> bad \<longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs3 \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evs3) 4. \<And>evso Aa Tka Ba Ka. \<lbrakk>A \<notin> bad; B \<notin> bad; evso \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evso \<longrightarrow> Key K \<in> analz (knows Spy evso) \<longrightarrow> expiredK Tk evso; Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) \<in> set evso; expiredK Tka evso; shrK Aa = shrK Aa \<and> Ka \<notin> range shrK \<and> Key Ka \<notin> used before Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) on evso \<and> Tka = CT before Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) on evso\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evso \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evso) [PROOF STEP] txt\<open>Fake\<close> [PROOF STATE] proof (prove) goal (4 subgoals): 1. \<And>evsf X. \<lbrakk>A \<notin> bad; B \<notin> bad; evsf \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evsf \<longrightarrow> Key K \<in> analz (knows Spy evsf) \<longrightarrow> expiredK Tk evsf; X \<in> synth (analz (knows Spy evsf))\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evsf \<longrightarrow> Key K \<in> analz (insert X (knows Spy evsf)) \<longrightarrow> sesKlife + Tk < Suc (CT evsf) 2. \<And>evs2 Ka Aa Ba. \<lbrakk>A \<notin> bad; B \<notin> bad; evs2 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs2 \<longrightarrow> Key K \<in> analz (knows Spy evs2) \<longrightarrow> expiredK Tk evs2; Key Ka \<notin> used evs2; Ka \<in> symKeys; Gets Server \<lbrace>Agent Aa, Agent Ba\<rbrace> \<in> set evs2\<rbrakk> \<Longrightarrow> (shrK Ba = Ka \<longrightarrow> (Aa \<in> bad \<longrightarrow> (A = Aa \<and> Tk = CT evs2 \<and> B = Ba \<and> K = Ka \<and> B = Ba \<and> Tk = CT evs2 \<and> A = Aa \<and> K = Ka \<longrightarrow> sesKlife = 0) \<and> (Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs2 \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evs2))) \<and> (Aa \<notin> bad \<longrightarrow> A = Aa \<and> Tk = CT evs2 \<and> B = Ba \<and> K = Ka \<and> B = Ba \<and> Tk = CT evs2 \<and> A = Aa \<and> K = Ka \<longrightarrow> Key Ka \<in> analz (knows Spy evs2) \<longrightarrow> sesKlife = 0)) \<and> (Ba \<in> bad \<longrightarrow> (Aa \<in> bad \<longrightarrow> (A = Aa \<and> Tk = CT evs2 \<and> B = Ba \<and> K = Ka \<and> B = Ba \<and> Tk = CT evs2 \<and> A = Aa \<and> K = Ka \<longrightarrow> sesKlife = 0) \<and> (Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs2 \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evs2))) \<and> (Aa \<notin> bad \<longrightarrow> A = Aa \<and> Tk = CT evs2 \<and> B = Ba \<and> K = Ka \<and> B = Ba \<and> Tk = CT evs2 \<and> A = Aa \<and> K = Ka \<longrightarrow> Key Ka \<in> analz (knows Spy evs2) \<longrightarrow> sesKlife = 0)) \<and> (shrK Ba \<noteq> Ka \<and> Ba \<notin> bad \<longrightarrow> (Aa \<in> bad \<longrightarrow> (A = Aa \<and> Tk = CT evs2 \<and> B = Ba \<and> K = Ka \<and> B = Ba \<and> Tk = CT evs2 \<and> A = Aa \<and> K = Ka \<longrightarrow> sesKlife = 0) \<and> (Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs2 \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evs2))) \<and> (Aa \<notin> bad \<longrightarrow> A = Aa \<and> Tk = CT evs2 \<and> B = Ba \<and> K = Ka \<and> B = Ba \<and> Tk = CT evs2 \<and> A = Aa \<and> K = Ka \<longrightarrow> Key Ka \<in> analz (knows Spy evs2) \<longrightarrow> sesKlife = 0)) 3. \<And>evs3 Aa Tka Ba Ka. \<lbrakk>A \<notin> bad; B \<notin> bad; evs3 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs3 \<longrightarrow> Key K \<in> analz (knows Spy evs3) \<longrightarrow> expiredK Tk evs3; Gets Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) \<in> set evs3; Says Aa Server \<lbrace>Agent Aa, Agent Ba\<rbrace> \<in> set evs3; \<not> expiredK Tka evs3; Ka \<notin> range shrK\<rbrakk> \<Longrightarrow> Ba \<in> bad \<longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs3 \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evs3) 4. \<And>evso Aa Tka Ba Ka. \<lbrakk>A \<notin> bad; B \<notin> bad; evso \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evso \<longrightarrow> Key K \<in> analz (knows Spy evso) \<longrightarrow> expiredK Tk evso; Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) \<in> set evso; expiredK Tka evso; shrK Aa = shrK Aa \<and> Ka \<notin> range shrK \<and> Key Ka \<notin> used before Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) on evso \<and> Tka = CT before Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) on evso\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evso \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evso) [PROOF STEP] apply spy_analz [PROOF STATE] proof (prove) goal (3 subgoals): 1. \<And>evs2 Ka Aa Ba. \<lbrakk>A \<notin> bad; B \<notin> bad; evs2 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs2 \<longrightarrow> Key K \<in> analz (knows Spy evs2) \<longrightarrow> expiredK Tk evs2; Key Ka \<notin> used evs2; Ka \<in> symKeys; Gets Server \<lbrace>Agent Aa, Agent Ba\<rbrace> \<in> set evs2\<rbrakk> \<Longrightarrow> (shrK Ba = Ka \<longrightarrow> (Aa \<in> bad \<longrightarrow> (A = Aa \<and> Tk = CT evs2 \<and> B = Ba \<and> K = Ka \<and> B = Ba \<and> Tk = CT evs2 \<and> A = Aa \<and> K = Ka \<longrightarrow> sesKlife = 0) \<and> (Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs2 \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evs2))) \<and> (Aa \<notin> bad \<longrightarrow> A = Aa \<and> Tk = CT evs2 \<and> B = Ba \<and> K = Ka \<and> B = Ba \<and> Tk = CT evs2 \<and> A = Aa \<and> K = Ka \<longrightarrow> Key Ka \<in> analz (knows Spy evs2) \<longrightarrow> sesKlife = 0)) \<and> (Ba \<in> bad \<longrightarrow> (Aa \<in> bad \<longrightarrow> (A = Aa \<and> Tk = CT evs2 \<and> B = Ba \<and> K = Ka \<and> B = Ba \<and> Tk = CT evs2 \<and> A = Aa \<and> K = Ka \<longrightarrow> sesKlife = 0) \<and> (Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs2 \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evs2))) \<and> (Aa \<notin> bad \<longrightarrow> A = Aa \<and> Tk = CT evs2 \<and> B = Ba \<and> K = Ka \<and> B = Ba \<and> Tk = CT evs2 \<and> A = Aa \<and> K = Ka \<longrightarrow> Key Ka \<in> analz (knows Spy evs2) \<longrightarrow> sesKlife = 0)) \<and> (shrK Ba \<noteq> Ka \<and> Ba \<notin> bad \<longrightarrow> (Aa \<in> bad \<longrightarrow> (A = Aa \<and> Tk = CT evs2 \<and> B = Ba \<and> K = Ka \<and> B = Ba \<and> Tk = CT evs2 \<and> A = Aa \<and> K = Ka \<longrightarrow> sesKlife = 0) \<and> (Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs2 \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evs2))) \<and> (Aa \<notin> bad \<longrightarrow> A = Aa \<and> Tk = CT evs2 \<and> B = Ba \<and> K = Ka \<and> B = Ba \<and> Tk = CT evs2 \<and> A = Aa \<and> K = Ka \<longrightarrow> Key Ka \<in> analz (knows Spy evs2) \<longrightarrow> sesKlife = 0)) 2. \<And>evs3 Aa Tka Ba Ka. \<lbrakk>A \<notin> bad; B \<notin> bad; evs3 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs3 \<longrightarrow> Key K \<in> analz (knows Spy evs3) \<longrightarrow> expiredK Tk evs3; Gets Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) \<in> set evs3; Says Aa Server \<lbrace>Agent Aa, Agent Ba\<rbrace> \<in> set evs3; \<not> expiredK Tka evs3; Ka \<notin> range shrK\<rbrakk> \<Longrightarrow> Ba \<in> bad \<longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs3 \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evs3) 3. \<And>evso Aa Tka Ba Ka. \<lbrakk>A \<notin> bad; B \<notin> bad; evso \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evso \<longrightarrow> Key K \<in> analz (knows Spy evso) \<longrightarrow> expiredK Tk evso; Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) \<in> set evso; expiredK Tka evso; shrK Aa = shrK Aa \<and> Ka \<notin> range shrK \<and> Key Ka \<notin> used before Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) on evso \<and> Tka = CT before Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) on evso\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evso \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evso) [PROOF STEP] txt\<open>BK2\<close> [PROOF STATE] proof (prove) goal (3 subgoals): 1. \<And>evs2 Ka Aa Ba. \<lbrakk>A \<notin> bad; B \<notin> bad; evs2 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs2 \<longrightarrow> Key K \<in> analz (knows Spy evs2) \<longrightarrow> expiredK Tk evs2; Key Ka \<notin> used evs2; Ka \<in> symKeys; Gets Server \<lbrace>Agent Aa, Agent Ba\<rbrace> \<in> set evs2\<rbrakk> \<Longrightarrow> (shrK Ba = Ka \<longrightarrow> (Aa \<in> bad \<longrightarrow> (A = Aa \<and> Tk = CT evs2 \<and> B = Ba \<and> K = Ka \<and> B = Ba \<and> Tk = CT evs2 \<and> A = Aa \<and> K = Ka \<longrightarrow> sesKlife = 0) \<and> (Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs2 \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evs2))) \<and> (Aa \<notin> bad \<longrightarrow> A = Aa \<and> Tk = CT evs2 \<and> B = Ba \<and> K = Ka \<and> B = Ba \<and> Tk = CT evs2 \<and> A = Aa \<and> K = Ka \<longrightarrow> Key Ka \<in> analz (knows Spy evs2) \<longrightarrow> sesKlife = 0)) \<and> (Ba \<in> bad \<longrightarrow> (Aa \<in> bad \<longrightarrow> (A = Aa \<and> Tk = CT evs2 \<and> B = Ba \<and> K = Ka \<and> B = Ba \<and> Tk = CT evs2 \<and> A = Aa \<and> K = Ka \<longrightarrow> sesKlife = 0) \<and> (Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs2 \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evs2))) \<and> (Aa \<notin> bad \<longrightarrow> A = Aa \<and> Tk = CT evs2 \<and> B = Ba \<and> K = Ka \<and> B = Ba \<and> Tk = CT evs2 \<and> A = Aa \<and> K = Ka \<longrightarrow> Key Ka \<in> analz (knows Spy evs2) \<longrightarrow> sesKlife = 0)) \<and> (shrK Ba \<noteq> Ka \<and> Ba \<notin> bad \<longrightarrow> (Aa \<in> bad \<longrightarrow> (A = Aa \<and> Tk = CT evs2 \<and> B = Ba \<and> K = Ka \<and> B = Ba \<and> Tk = CT evs2 \<and> A = Aa \<and> K = Ka \<longrightarrow> sesKlife = 0) \<and> (Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs2 \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evs2))) \<and> (Aa \<notin> bad \<longrightarrow> A = Aa \<and> Tk = CT evs2 \<and> B = Ba \<and> K = Ka \<and> B = Ba \<and> Tk = CT evs2 \<and> A = Aa \<and> K = Ka \<longrightarrow> Key Ka \<in> analz (knows Spy evs2) \<longrightarrow> sesKlife = 0)) 2. \<And>evs3 Aa Tka Ba Ka. \<lbrakk>A \<notin> bad; B \<notin> bad; evs3 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs3 \<longrightarrow> Key K \<in> analz (knows Spy evs3) \<longrightarrow> expiredK Tk evs3; Gets Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) \<in> set evs3; Says Aa Server \<lbrace>Agent Aa, Agent Ba\<rbrace> \<in> set evs3; \<not> expiredK Tka evs3; Ka \<notin> range shrK\<rbrakk> \<Longrightarrow> Ba \<in> bad \<longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs3 \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evs3) 3. \<And>evso Aa Tka Ba Ka. \<lbrakk>A \<notin> bad; B \<notin> bad; evso \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evso \<longrightarrow> Key K \<in> analz (knows Spy evso) \<longrightarrow> expiredK Tk evso; Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) \<in> set evso; expiredK Tka evso; shrK Aa = shrK Aa \<and> Ka \<notin> range shrK \<and> Key Ka \<notin> used before Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) on evso \<and> Tka = CT before Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) on evso\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evso \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evso) [PROOF STEP] apply (blast intro: parts_insertI less_SucI) [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>evs3 Aa Tka Ba Ka. \<lbrakk>A \<notin> bad; B \<notin> bad; evs3 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs3 \<longrightarrow> Key K \<in> analz (knows Spy evs3) \<longrightarrow> expiredK Tk evs3; Gets Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) \<in> set evs3; Says Aa Server \<lbrace>Agent Aa, Agent Ba\<rbrace> \<in> set evs3; \<not> expiredK Tka evs3; Ka \<notin> range shrK\<rbrakk> \<Longrightarrow> Ba \<in> bad \<longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs3 \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evs3) 2. \<And>evso Aa Tka Ba Ka. \<lbrakk>A \<notin> bad; B \<notin> bad; evso \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evso \<longrightarrow> Key K \<in> analz (knows Spy evso) \<longrightarrow> expiredK Tk evso; Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) \<in> set evso; expiredK Tka evso; shrK Aa = shrK Aa \<and> Ka \<notin> range shrK \<and> Key Ka \<notin> used before Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) on evso \<and> Tka = CT before Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) on evso\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evso \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evso) [PROOF STEP] txt\<open>BK3\<close> [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>evs3 Aa Tka Ba Ka. \<lbrakk>A \<notin> bad; B \<notin> bad; evs3 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs3 \<longrightarrow> Key K \<in> analz (knows Spy evs3) \<longrightarrow> expiredK Tk evs3; Gets Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) \<in> set evs3; Says Aa Server \<lbrace>Agent Aa, Agent Ba\<rbrace> \<in> set evs3; \<not> expiredK Tka evs3; Ka \<notin> range shrK\<rbrakk> \<Longrightarrow> Ba \<in> bad \<longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs3 \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evs3) 2. \<And>evso Aa Tka Ba Ka. \<lbrakk>A \<notin> bad; B \<notin> bad; evso \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evso \<longrightarrow> Key K \<in> analz (knows Spy evso) \<longrightarrow> expiredK Tk evso; Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) \<in> set evso; expiredK Tka evso; shrK Aa = shrK Aa \<and> Ka \<notin> range shrK \<and> Key Ka \<notin> used before Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) on evso \<and> Tka = CT before Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) on evso\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evso \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evso) [PROOF STEP] apply (case_tac "Aa \<in> bad") [PROOF STATE] proof (prove) goal (3 subgoals): 1. \<And>evs3 Aa Tka Ba Ka. \<lbrakk>A \<notin> bad; B \<notin> bad; evs3 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs3 \<longrightarrow> Key K \<in> analz (knows Spy evs3) \<longrightarrow> expiredK Tk evs3; Gets Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) \<in> set evs3; Says Aa Server \<lbrace>Agent Aa, Agent Ba\<rbrace> \<in> set evs3; \<not> expiredK Tka evs3; Ka \<notin> range shrK; Aa \<in> bad\<rbrakk> \<Longrightarrow> Ba \<in> bad \<longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs3 \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evs3) 2. \<And>evs3 Aa Tka Ba Ka. \<lbrakk>A \<notin> bad; B \<notin> bad; evs3 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs3 \<longrightarrow> Key K \<in> analz (knows Spy evs3) \<longrightarrow> expiredK Tk evs3; Gets Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) \<in> set evs3; Says Aa Server \<lbrace>Agent Aa, Agent Ba\<rbrace> \<in> set evs3; \<not> expiredK Tka evs3; Ka \<notin> range shrK; Aa \<notin> bad\<rbrakk> \<Longrightarrow> Ba \<in> bad \<longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs3 \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evs3) 3. \<And>evso Aa Tka Ba Ka. \<lbrakk>A \<notin> bad; B \<notin> bad; evso \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evso \<longrightarrow> Key K \<in> analz (knows Spy evso) \<longrightarrow> expiredK Tk evso; Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) \<in> set evso; expiredK Tka evso; shrK Aa = shrK Aa \<and> Ka \<notin> range shrK \<and> Key Ka \<notin> used before Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) on evso \<and> Tka = CT before Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) on evso\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evso \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evso) [PROOF STEP] prefer 2 [PROOF STATE] proof (prove) goal (3 subgoals): 1. \<And>evs3 Aa Tka Ba Ka. \<lbrakk>A \<notin> bad; B \<notin> bad; evs3 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs3 \<longrightarrow> Key K \<in> analz (knows Spy evs3) \<longrightarrow> expiredK Tk evs3; Gets Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) \<in> set evs3; Says Aa Server \<lbrace>Agent Aa, Agent Ba\<rbrace> \<in> set evs3; \<not> expiredK Tka evs3; Ka \<notin> range shrK; Aa \<notin> bad\<rbrakk> \<Longrightarrow> Ba \<in> bad \<longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs3 \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evs3) 2. \<And>evs3 Aa Tka Ba Ka. \<lbrakk>A \<notin> bad; B \<notin> bad; evs3 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs3 \<longrightarrow> Key K \<in> analz (knows Spy evs3) \<longrightarrow> expiredK Tk evs3; Gets Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) \<in> set evs3; Says Aa Server \<lbrace>Agent Aa, Agent Ba\<rbrace> \<in> set evs3; \<not> expiredK Tka evs3; Ka \<notin> range shrK; Aa \<in> bad\<rbrakk> \<Longrightarrow> Ba \<in> bad \<longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs3 \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evs3) 3. \<And>evso Aa Tka Ba Ka. \<lbrakk>A \<notin> bad; B \<notin> bad; evso \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evso \<longrightarrow> Key K \<in> analz (knows Spy evso) \<longrightarrow> expiredK Tk evso; Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) \<in> set evso; expiredK Tka evso; shrK Aa = shrK Aa \<and> Ka \<notin> range shrK \<and> Key Ka \<notin> used before Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) on evso \<and> Tka = CT before Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) on evso\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evso \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evso) [PROOF STEP] apply (blast dest: Kab_authentic unique_session_keys) [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>evs3 Aa Tka Ba Ka. \<lbrakk>A \<notin> bad; B \<notin> bad; evs3 \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs3 \<longrightarrow> Key K \<in> analz (knows Spy evs3) \<longrightarrow> expiredK Tk evs3; Gets Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) \<in> set evs3; Says Aa Server \<lbrace>Agent Aa, Agent Ba\<rbrace> \<in> set evs3; \<not> expiredK Tka evs3; Ka \<notin> range shrK; Aa \<in> bad\<rbrakk> \<Longrightarrow> Ba \<in> bad \<longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evs3 \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evs3) 2. \<And>evso Aa Tka Ba Ka. \<lbrakk>A \<notin> bad; B \<notin> bad; evso \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evso \<longrightarrow> Key K \<in> analz (knows Spy evso) \<longrightarrow> expiredK Tk evso; Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) \<in> set evso; expiredK Tka evso; shrK Aa = shrK Aa \<and> Ka \<notin> range shrK \<and> Key Ka \<notin> used before Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) on evso \<and> Tka = CT before Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) on evso\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evso \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evso) [PROOF STEP] apply (blast dest: Gets_imp_knows_Spy [THEN analz.Inj] Crypt_Spy_analz_bad elim!: MPair_analz intro: less_SucI) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>evso Aa Tka Ba Ka. \<lbrakk>A \<notin> bad; B \<notin> bad; evso \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evso \<longrightarrow> Key K \<in> analz (knows Spy evso) \<longrightarrow> expiredK Tk evso; Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) \<in> set evso; expiredK Tka evso; shrK Aa = shrK Aa \<and> Ka \<notin> range shrK \<and> Key Ka \<notin> used before Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) on evso \<and> Tka = CT before Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) on evso\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evso \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evso) [PROOF STEP] txt\<open>Oops: PROOF FAILS if unsafe intro below\<close> [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>evso Aa Tka Ba Ka. \<lbrakk>A \<notin> bad; B \<notin> bad; evso \<in> bankerb_gets; Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evso \<longrightarrow> Key K \<in> analz (knows Spy evso) \<longrightarrow> expiredK Tk evso; Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) \<in> set evso; expiredK Tka evso; shrK Aa = shrK Aa \<and> Ka \<notin> range shrK \<and> Key Ka \<notin> used before Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) on evso \<and> Tka = CT before Says Server Aa (Crypt (shrK Aa) \<lbrace>Number Tka, Agent Ba, Key Ka, Crypt (shrK Ba) \<lbrace>Number Tka, Agent Aa, Key Ka\<rbrace>\<rbrace>) on evso\<rbrakk> \<Longrightarrow> Says Server A (Crypt (shrK A) \<lbrace>Number Tk, Agent B, Key K, Crypt (shrK B) \<lbrace>Number Tk, Agent A, Key K\<rbrace>\<rbrace>) \<in> set evso \<longrightarrow> K = Ka \<longrightarrow> sesKlife + Tk < Suc (CT evso) [PROOF STEP] apply (blast dest: unique_session_keys intro!: less_SucI) [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done
[GOAL] Ξ± : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝¹ : PseudoMetricSpace Ξ± inst✝ : PseudoMetricSpace Ξ² K : ℝβ‰₯0 f : Ξ± β†’ Ξ² ⊒ AntilipschitzWith K f ↔ βˆ€ (x y : Ξ±), nndist x y ≀ K * nndist (f x) (f y) [PROOFSTEP] simp only [AntilipschitzWith, edist_nndist] [GOAL] Ξ± : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝¹ : PseudoMetricSpace Ξ± inst✝ : PseudoMetricSpace Ξ² K : ℝβ‰₯0 f : Ξ± β†’ Ξ² ⊒ (βˆ€ (x y : Ξ±), ↑(nndist x y) ≀ ↑K * ↑(nndist (f x) (f y))) ↔ βˆ€ (x y : Ξ±), nndist x y ≀ K * nndist (f x) (f y) [PROOFSTEP] norm_cast [GOAL] Ξ± : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝¹ : PseudoMetricSpace Ξ± inst✝ : PseudoMetricSpace Ξ² K : ℝβ‰₯0 f : Ξ± β†’ Ξ² ⊒ AntilipschitzWith K f ↔ βˆ€ (x y : Ξ±), dist x y ≀ ↑K * dist (f x) (f y) [PROOFSTEP] simp only [antilipschitzWith_iff_le_mul_nndist, dist_nndist] [GOAL] Ξ± : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝¹ : PseudoMetricSpace Ξ± inst✝ : PseudoMetricSpace Ξ² K : ℝβ‰₯0 f : Ξ± β†’ Ξ² ⊒ (βˆ€ (x y : Ξ±), nndist x y ≀ K * nndist (f x) (f y)) ↔ βˆ€ (x y : Ξ±), ↑(nndist x y) ≀ ↑K * ↑(nndist (f x) (f y)) [PROOFSTEP] norm_cast [GOAL] Ξ± : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝¹ : PseudoMetricSpace Ξ± inst✝ : PseudoMetricSpace Ξ² K : ℝβ‰₯0 f : Ξ± β†’ Ξ² hf : AntilipschitzWith K f x y : Ξ± ⊒ K⁻¹ * nndist x y ≀ nndist (f x) (f y) [PROOFSTEP] simpa only [div_eq_inv_mul] using NNReal.div_le_of_le_mul' (hf.le_mul_nndist x y) [GOAL] Ξ± : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝¹ : PseudoMetricSpace Ξ± inst✝ : PseudoMetricSpace Ξ² K : ℝβ‰₯0 f : Ξ± β†’ Ξ² hf : AntilipschitzWith K f x y : Ξ± ⊒ ↑K⁻¹ * dist x y ≀ dist (f x) (f y) [PROOFSTEP] exact_mod_cast hf.mul_le_nndist x y [GOAL] α✝ : Type u_1 β✝ : Type u_2 Ξ³ : Type u_3 inst✝⁴ : PseudoEMetricSpace α✝ inst✝³ : PseudoEMetricSpace β✝ inst✝² : PseudoEMetricSpace Ξ³ K✝ : ℝβ‰₯0 f✝ : α✝ β†’ β✝ Ξ± : Type u_4 Ξ² : Type u_5 inst✝¹ : EMetricSpace Ξ± inst✝ : PseudoEMetricSpace Ξ² K : ℝβ‰₯0 f : Ξ± β†’ Ξ² hf : AntilipschitzWith K f x y : Ξ± h : f x = f y ⊒ x = y [PROOFSTEP] simpa only [h, edist_self, mul_zero, edist_le_zero] using hf x y [GOAL] Ξ± : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝² : PseudoEMetricSpace Ξ± inst✝¹ : PseudoEMetricSpace Ξ² inst✝ : PseudoEMetricSpace Ξ³ K : ℝβ‰₯0 f : Ξ± β†’ Ξ² hf : AntilipschitzWith K f x y : Ξ± ⊒ (↑K)⁻¹ * edist x y ≀ edist (f x) (f y) [PROOFSTEP] rw [mul_comm, ← div_eq_mul_inv] [GOAL] Ξ± : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝² : PseudoEMetricSpace Ξ± inst✝¹ : PseudoEMetricSpace Ξ² inst✝ : PseudoEMetricSpace Ξ³ K : ℝβ‰₯0 f : Ξ± β†’ Ξ² hf : AntilipschitzWith K f x y : Ξ± ⊒ edist x y / ↑K ≀ edist (f x) (f y) [PROOFSTEP] exact ENNReal.div_le_of_le_mul' (hf x y) [GOAL] Ξ± : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝² : PseudoEMetricSpace Ξ± inst✝¹ : PseudoEMetricSpace Ξ² inst✝ : PseudoEMetricSpace Ξ³ K : ℝβ‰₯0 f : Ξ± β†’ Ξ² x y : Ξ± ⊒ edist x y ≀ ↑1 * edist (id x) (id y) [PROOFSTEP] simp only [ENNReal.coe_one, one_mul, id, le_refl] [GOAL] Ξ± : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝² : PseudoEMetricSpace Ξ± inst✝¹ : PseudoEMetricSpace Ξ² inst✝ : PseudoEMetricSpace Ξ³ K : ℝβ‰₯0 f✝ : Ξ± β†’ Ξ² Kg : ℝβ‰₯0 g : Ξ² β†’ Ξ³ hg : AntilipschitzWith Kg g Kf : ℝβ‰₯0 f : Ξ± β†’ Ξ² hf : AntilipschitzWith Kf f x y : Ξ± ⊒ ↑Kf * (↑Kg * edist (g (f x)) (g (f y))) = ↑(Kf * Kg) * edist ((g ∘ f) x) ((g ∘ f) y) [PROOFSTEP] rw [ENNReal.coe_mul, mul_assoc] [GOAL] Ξ± : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝² : PseudoEMetricSpace Ξ± inst✝¹ : PseudoEMetricSpace Ξ² inst✝ : PseudoEMetricSpace Ξ³ K : ℝβ‰₯0 f✝ : Ξ± β†’ Ξ² Kg : ℝβ‰₯0 g : Ξ² β†’ Ξ³ hg : AntilipschitzWith Kg g Kf : ℝβ‰₯0 f : Ξ± β†’ Ξ² hf : AntilipschitzWith Kf f x y : Ξ± ⊒ ↑Kf * (↑Kg * edist (g (f x)) (g (f y))) = ↑Kf * (↑Kg * edist ((g ∘ f) x) ((g ∘ f) y)) [PROOFSTEP] rfl [GOAL] Ξ± : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝² : PseudoEMetricSpace Ξ± inst✝¹ : PseudoEMetricSpace Ξ² inst✝ : PseudoEMetricSpace Ξ³ K : ℝβ‰₯0 f : Ξ± β†’ Ξ² s : Set Ξ± hf : AntilipschitzWith K (Set.restrict s f) g : Ξ² β†’ Ξ± t : Set Ξ² g_maps : MapsTo g t s g_inv : RightInvOn g f t x y : ↑t ⊒ edist (Set.restrict t g x) (Set.restrict t g y) ≀ ↑K * edist x y [PROOFSTEP] simpa only [restrict_apply, g_inv x.mem, g_inv y.mem, Subtype.edist_eq, Subtype.coe_mk] using hf ⟨g x, g_maps x.mem⟩ ⟨g y, g_maps y.mem⟩ [GOAL] Ξ± : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝² : PseudoEMetricSpace Ξ± inst✝¹ : PseudoEMetricSpace Ξ² inst✝ : PseudoEMetricSpace Ξ³ K : ℝβ‰₯0 f : Ξ± β†’ Ξ² hf : AntilipschitzWith K f g : Ξ² β†’ Ξ± hg : Function.RightInverse g f ⊒ LipschitzWith K g [PROOFSTEP] intro x y [GOAL] Ξ± : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝² : PseudoEMetricSpace Ξ± inst✝¹ : PseudoEMetricSpace Ξ² inst✝ : PseudoEMetricSpace Ξ³ K : ℝβ‰₯0 f : Ξ± β†’ Ξ² hf : AntilipschitzWith K f g : Ξ² β†’ Ξ± hg : Function.RightInverse g f x y : Ξ² ⊒ edist (g x) (g y) ≀ ↑K * edist x y [PROOFSTEP] have := hf (g x) (g y) [GOAL] Ξ± : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝² : PseudoEMetricSpace Ξ± inst✝¹ : PseudoEMetricSpace Ξ² inst✝ : PseudoEMetricSpace Ξ³ K : ℝβ‰₯0 f : Ξ± β†’ Ξ² hf : AntilipschitzWith K f g : Ξ² β†’ Ξ± hg : Function.RightInverse g f x y : Ξ² this : edist (g x) (g y) ≀ ↑K * edist (f (g x)) (f (g y)) ⊒ edist (g x) (g y) ≀ ↑K * edist x y [PROOFSTEP] rwa [hg x, hg y] at this [GOAL] Ξ± : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝² : PseudoEMetricSpace Ξ± inst✝¹ : PseudoEMetricSpace Ξ² inst✝ : PseudoEMetricSpace Ξ³ K : ℝβ‰₯0 f : Ξ± β†’ Ξ² hf : AntilipschitzWith K f ⊒ comap (Prod.map f f) (𝓀 Ξ²) ≀ 𝓀 Ξ± [PROOFSTEP] refine ((uniformity_basis_edist.comap _).le_basis_iff uniformity_basis_edist).2 fun Ξ΅ hβ‚€ => ?_ [GOAL] Ξ± : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝² : PseudoEMetricSpace Ξ± inst✝¹ : PseudoEMetricSpace Ξ² inst✝ : PseudoEMetricSpace Ξ³ K : ℝβ‰₯0 f : Ξ± β†’ Ξ² hf : AntilipschitzWith K f Ξ΅ : ℝβ‰₯0∞ hβ‚€ : 0 < Ξ΅ ⊒ βˆƒ i, 0 < i ∧ Prod.map f f ⁻¹' {p | edist p.fst p.snd < i} βŠ† {p | edist p.fst p.snd < Ξ΅} [PROOFSTEP] refine ⟨(↑K)⁻¹ * Ξ΅, ENNReal.mul_pos (ENNReal.inv_ne_zero.2 ENNReal.coe_ne_top) hβ‚€.ne', ?_⟩ [GOAL] Ξ± : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝² : PseudoEMetricSpace Ξ± inst✝¹ : PseudoEMetricSpace Ξ² inst✝ : PseudoEMetricSpace Ξ³ K : ℝβ‰₯0 f : Ξ± β†’ Ξ² hf : AntilipschitzWith K f Ξ΅ : ℝβ‰₯0∞ hβ‚€ : 0 < Ξ΅ ⊒ Prod.map f f ⁻¹' {p | edist p.fst p.snd < (↑K)⁻¹ * Ξ΅} βŠ† {p | edist p.fst p.snd < Ξ΅} [PROOFSTEP] refine' fun x hx => (hf x.1 x.2).trans_lt _ [GOAL] Ξ± : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝² : PseudoEMetricSpace Ξ± inst✝¹ : PseudoEMetricSpace Ξ² inst✝ : PseudoEMetricSpace Ξ³ K : ℝβ‰₯0 f : Ξ± β†’ Ξ² hf : AntilipschitzWith K f Ξ΅ : ℝβ‰₯0∞ hβ‚€ : 0 < Ξ΅ x : Ξ± Γ— Ξ± hx : x ∈ Prod.map f f ⁻¹' {p | edist p.fst p.snd < (↑K)⁻¹ * Ξ΅} ⊒ ↑K * edist (f x.fst) (f x.snd) < Ξ΅ [PROOFSTEP] rw [mul_comm, ← div_eq_mul_inv] at hx [GOAL] Ξ± : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝² : PseudoEMetricSpace Ξ± inst✝¹ : PseudoEMetricSpace Ξ² inst✝ : PseudoEMetricSpace Ξ³ K : ℝβ‰₯0 f : Ξ± β†’ Ξ² hf : AntilipschitzWith K f Ξ΅ : ℝβ‰₯0∞ hβ‚€ : 0 < Ξ΅ x : Ξ± Γ— Ξ± hx : x ∈ Prod.map f f ⁻¹' {p | edist p.fst p.snd < Ξ΅ / ↑K} ⊒ ↑K * edist (f x.fst) (f x.snd) < Ξ΅ [PROOFSTEP] rw [mul_comm] [GOAL] Ξ± : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝² : PseudoEMetricSpace Ξ± inst✝¹ : PseudoEMetricSpace Ξ² inst✝ : PseudoEMetricSpace Ξ³ K : ℝβ‰₯0 f : Ξ± β†’ Ξ² hf : AntilipschitzWith K f Ξ΅ : ℝβ‰₯0∞ hβ‚€ : 0 < Ξ΅ x : Ξ± Γ— Ξ± hx : x ∈ Prod.map f f ⁻¹' {p | edist p.fst p.snd < Ξ΅ / ↑K} ⊒ edist (f x.fst) (f x.snd) * ↑K < Ξ΅ [PROOFSTEP] exact ENNReal.mul_lt_of_lt_div hx [GOAL] Ξ± : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝³ : PseudoEMetricSpace Ξ± inst✝² : PseudoEMetricSpace Ξ² inst✝¹ : PseudoEMetricSpace Ξ³ K✝ : ℝβ‰₯0 f : Ξ± β†’ Ξ² inst✝ : Subsingleton Ξ± K : ℝβ‰₯0 x y : Ξ± ⊒ edist x y ≀ ↑K * edist (f x) (f y) [PROOFSTEP] simp only [Subsingleton.elim x y, edist_self, zero_le] [GOAL] Ξ± : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝¹ : PseudoMetricSpace Ξ± inst✝ : PseudoMetricSpace Ξ² K : ℝβ‰₯0 f : Ξ± β†’ Ξ² hf : AntilipschitzWith K f s : Set Ξ² hs : Metric.Bounded s x : Ξ± hx : x ∈ f ⁻¹' s y : Ξ± hy : y ∈ f ⁻¹' s ⊒ ↑K * dist (f x) (f y) ≀ ↑K * diam s [PROOFSTEP] gcongr [GOAL] case h Ξ± : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝¹ : PseudoMetricSpace Ξ± inst✝ : PseudoMetricSpace Ξ² K : ℝβ‰₯0 f : Ξ± β†’ Ξ² hf : AntilipschitzWith K f s : Set Ξ² hs : Metric.Bounded s x : Ξ± hx : x ∈ f ⁻¹' s y : Ξ± hy : y ∈ f ⁻¹' s ⊒ dist (f x) (f y) ≀ diam s [PROOFSTEP] exact dist_le_diam_of_mem hs hx hy [GOAL] α✝ : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝³ : PseudoMetricSpace α✝ inst✝² : PseudoMetricSpace Ξ² K✝ : ℝβ‰₯0 f✝ : α✝ β†’ Ξ² Ξ± : Type u_4 inst✝¹ : MetricSpace Ξ± K : ℝβ‰₯0 f : Ξ± β†’ Ξ² inst✝ : ProperSpace Ξ± hK : AntilipschitzWith K f f_cont : Continuous f hf : Function.Surjective f ⊒ ProperSpace Ξ² [PROOFSTEP] refine ⟨fun xβ‚€ r => ?_⟩ [GOAL] α✝ : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝³ : PseudoMetricSpace α✝ inst✝² : PseudoMetricSpace Ξ² K✝ : ℝβ‰₯0 f✝ : α✝ β†’ Ξ² Ξ± : Type u_4 inst✝¹ : MetricSpace Ξ± K : ℝβ‰₯0 f : Ξ± β†’ Ξ² inst✝ : ProperSpace Ξ± hK : AntilipschitzWith K f f_cont : Continuous f hf : Function.Surjective f xβ‚€ : Ξ² r : ℝ ⊒ IsCompact (closedBall xβ‚€ r) [PROOFSTEP] let K := f ⁻¹' closedBall xβ‚€ r [GOAL] α✝ : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝³ : PseudoMetricSpace α✝ inst✝² : PseudoMetricSpace Ξ² K✝¹ : ℝβ‰₯0 f✝ : α✝ β†’ Ξ² Ξ± : Type u_4 inst✝¹ : MetricSpace Ξ± K✝ : ℝβ‰₯0 f : Ξ± β†’ Ξ² inst✝ : ProperSpace Ξ± hK : AntilipschitzWith K✝ f f_cont : Continuous f hf : Function.Surjective f xβ‚€ : Ξ² r : ℝ K : Set Ξ± := f ⁻¹' closedBall xβ‚€ r ⊒ IsCompact (closedBall xβ‚€ r) [PROOFSTEP] have A : IsClosed K := isClosed_ball.preimage f_cont [GOAL] α✝ : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝³ : PseudoMetricSpace α✝ inst✝² : PseudoMetricSpace Ξ² K✝¹ : ℝβ‰₯0 f✝ : α✝ β†’ Ξ² Ξ± : Type u_4 inst✝¹ : MetricSpace Ξ± K✝ : ℝβ‰₯0 f : Ξ± β†’ Ξ² inst✝ : ProperSpace Ξ± hK : AntilipschitzWith K✝ f f_cont : Continuous f hf : Function.Surjective f xβ‚€ : Ξ² r : ℝ K : Set Ξ± := f ⁻¹' closedBall xβ‚€ r A : IsClosed K ⊒ IsCompact (closedBall xβ‚€ r) [PROOFSTEP] have B : Bounded K := hK.bounded_preimage bounded_closedBall [GOAL] α✝ : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝³ : PseudoMetricSpace α✝ inst✝² : PseudoMetricSpace Ξ² K✝¹ : ℝβ‰₯0 f✝ : α✝ β†’ Ξ² Ξ± : Type u_4 inst✝¹ : MetricSpace Ξ± K✝ : ℝβ‰₯0 f : Ξ± β†’ Ξ² inst✝ : ProperSpace Ξ± hK : AntilipschitzWith K✝ f f_cont : Continuous f hf : Function.Surjective f xβ‚€ : Ξ² r : ℝ K : Set Ξ± := f ⁻¹' closedBall xβ‚€ r A : IsClosed K B : Metric.Bounded K ⊒ IsCompact (closedBall xβ‚€ r) [PROOFSTEP] have : IsCompact K := isCompact_iff_isClosed_bounded.2 ⟨A, B⟩ [GOAL] α✝ : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝³ : PseudoMetricSpace α✝ inst✝² : PseudoMetricSpace Ξ² K✝¹ : ℝβ‰₯0 f✝ : α✝ β†’ Ξ² Ξ± : Type u_4 inst✝¹ : MetricSpace Ξ± K✝ : ℝβ‰₯0 f : Ξ± β†’ Ξ² inst✝ : ProperSpace Ξ± hK : AntilipschitzWith K✝ f f_cont : Continuous f hf : Function.Surjective f xβ‚€ : Ξ² r : ℝ K : Set Ξ± := f ⁻¹' closedBall xβ‚€ r A : IsClosed K B : Metric.Bounded K this : IsCompact K ⊒ IsCompact (closedBall xβ‚€ r) [PROOFSTEP] convert this.image f_cont [GOAL] case h.e'_3 α✝ : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝³ : PseudoMetricSpace α✝ inst✝² : PseudoMetricSpace Ξ² K✝¹ : ℝβ‰₯0 f✝ : α✝ β†’ Ξ² Ξ± : Type u_4 inst✝¹ : MetricSpace Ξ± K✝ : ℝβ‰₯0 f : Ξ± β†’ Ξ² inst✝ : ProperSpace Ξ± hK : AntilipschitzWith K✝ f f_cont : Continuous f hf : Function.Surjective f xβ‚€ : Ξ² r : ℝ K : Set Ξ± := f ⁻¹' closedBall xβ‚€ r A : IsClosed K B : Metric.Bounded K this : IsCompact K ⊒ closedBall xβ‚€ r = f '' K [PROOFSTEP] exact (hf.image_preimage _).symm [GOAL] Ξ± : Type u_1 Ξ² : Type u_2 Ξ³ : Type u_3 inst✝¹ : PseudoEMetricSpace Ξ± inst✝ : PseudoEMetricSpace Ξ² K : ℝβ‰₯0 f : Ξ± β†’ Ξ² hf : LipschitzWith K f g : Ξ² β†’ Ξ± hg : Function.RightInverse g f x y : Ξ² ⊒ edist x y ≀ ↑K * edist (g x) (g y) [PROOFSTEP] simpa only [hg _] using hf (g x) (g y)
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2016 Daniel Estevez <[email protected]>. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import numpy from gnuradio import gr import collections import pmt import array import os import base64 import datetime from gr_kiss import * class save_frame(gr.basic_block): """ docstring for block save_frame """ def __init__(self, filename, direction): gr.basic_block.__init__(self, name="save_frame", in_sig=None, out_sig=None) self.file = open(filename, "w") self.direction = {"Uplink": "U", "Downlink": "D"}[direction] self.message_port_register_in(pmt.intern('in')) self.set_msg_handler(pmt.intern('in'), self.handle_msg) def handle_msg(self, msg_pmt): msg = pmt.cdr(msg_pmt) if not pmt.is_u8vector(msg): print "[ERROR] Received invalid message type. Expected u8vector" return array = bytearray(pmt.u8vector_elements(msg)) packet = base64.b64encode(array) time = datetime.datetime.utcnow().strftime("%Y-%m-%d_%H:%M:%S:%f") self.file.write(time + "," + str(self.direction) + "," + packet + "\n") self.file.flush()
/- Copyright (c) 2022 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import analysis.inner_product_space.projection import linear_algebra.orientation /-! # Orientations of real inner product spaces. This file provides definitions and proves lemmas about orientations of real inner product spaces. ## Main definitions * `orientation.fin_orthonormal_basis` is an orthonormal basis, indexed by `fin n`, with the given orientation. -/ noncomputable theory variables {E : Type*} [inner_product_space ℝ E] variables {ΞΉ : Type*} [fintype ΞΉ] [decidable_eq ΞΉ] open finite_dimensional /-- `basis.adjust_to_orientation`, applied to an orthonormal basis, produces an orthonormal basis. -/ lemma orthonormal.orthonormal_adjust_to_orientation [nonempty ΞΉ] {e : basis ΞΉ ℝ E} (h : orthonormal ℝ e) (x : orientation ℝ E ΞΉ) : orthonormal ℝ (e.adjust_to_orientation x) := h.orthonormal_of_forall_eq_or_eq_neg (e.adjust_to_orientation_apply_eq_or_eq_neg x) /-- An orthonormal basis, indexed by `fin n`, with the given orientation. -/ protected def orientation.fin_orthonormal_basis {n : β„•} (hn : 0 < n) (h : finrank ℝ E = n) (x : orientation ℝ E (fin n)) : basis (fin n) ℝ E := begin haveI := fin.pos_iff_nonempty.1 hn, haveI := finite_dimensional_of_finrank (h.symm β–Έ hn : 0 < finrank ℝ E), exact (fin_std_orthonormal_basis h).adjust_to_orientation x end /-- `orientation.fin_orthonormal_basis` is orthonormal. -/ protected lemma orientation.fin_orthonormal_basis_orthonormal {n : β„•} (hn : 0 < n) (h : finrank ℝ E = n) (x : orientation ℝ E (fin n)) : orthonormal ℝ (x.fin_orthonormal_basis hn h) := begin haveI := fin.pos_iff_nonempty.1 hn, haveI := finite_dimensional_of_finrank (h.symm β–Έ hn : 0 < finrank ℝ E), exact (fin_std_orthonormal_basis_orthonormal h).orthonormal_adjust_to_orientation _ end /-- `orientation.fin_orthonormal_basis` gives a basis with the required orientation. -/ @[simp] lemma orientation.fin_orthonormal_basis_orientation {n : β„•} (hn : 0 < n) (h : finrank ℝ E = n) (x : orientation ℝ E (fin n)) : (x.fin_orthonormal_basis hn h).orientation = x := begin haveI := fin.pos_iff_nonempty.1 hn, exact basis.orientation_adjust_to_orientation _ _ end
(* MacBook-Air:~ billw$ /Applications/CoqIDE_8.4pl5.app/Contents/Resources/bin/coqtop Welcome to Coq 8.4pl5 (October 2014) Coq < Section Conjunction_A. Coq < Goal forall e g:Prop, ((~e) /\ (~g)) -> (~e /\ ~g). 1 subgoal ============================ forall e g : Prop, ~ e /\ ~ g -> ~ e /\ ~ g Unnamed_thm < intros. 1 subgoal e : Prop g : Prop H : ~ e /\ ~ g ============================ ~ e /\ ~ g Unnamed_thm < exact H. No more subgoals. Unnamed_thm < Qed. intros. exact H. Unnamed_thm is defined Coq < *) Section Conjunction_A. Goal forall e g:Prop, ((~e) /\ (~g)) -> (~e /\ ~g). intros. exact H. Qed.
#install.packages("rmarkdown", repos = "http://cran.us.r-project.org") install.packages("ggplot2", repos = "http://cran.us.r-project.org") install.packages("tidyverse", repos = "http://cran.us.r-project.org") install.packages("devtools", repos = "http://cran.us.r-project.org") library(devtools) devtools::install_github("dgrtwo/drlib")
! { dg-options "-O3 -floop-block" } MODULE util INTEGER, PARAMETER :: int_4=4 INTERFACE sort MODULE PROCEDURE sort_int_4v END INTERFACE CONTAINS SUBROUTINE sort_int_4v ( arr, n, index ) INTEGER(KIND=int_4), INTENT(INOUT) :: arr(1:n) INTEGER, INTENT(OUT) :: INDEX(1:n) DO i = 1, n INDEX(i) = i END DO 1 IF (ir-l<m) THEN DO j = l + 1, ir DO i = j - 1, 1, -1 IF (arr(i)<=a) GO TO 2 arr(i+1) = arr(i) INDEX(i+1) = INDEX(i) END DO 2 arr(i+1) = a END DO END IF END SUBROUTINE sort_int_4v SUBROUTINE create_destination_list(list) INTEGER, DIMENSION(:, :, :), POINTER :: list INTEGER :: icpu, ncpu, stat, ultimate_max INTEGER, ALLOCATABLE, DIMENSION(:) :: index, sublist ultimate_max=7 ALLOCATE(INDEX(ultimate_max),STAT=stat) CALL t(stat==0) ALLOCATE(sublist(ultimate_max),STAT=stat) DO icpu=0,ncpu-1 CALL sort(sublist,ultimate_max,index) list(1,:,icpu)=sublist list(2,:,icpu)=0 ENDDO END SUBROUTINE create_destination_list END MODULE
[STATEMENT] lemma vi_policy_opt: assumes "0 < eps" shows "dist (\<nu>\<^sub>b (mk_stationary_det (vi_policy eps v))) \<nu>\<^sub>b_opt < eps" [PROOF STATE] proof (prove) goal (1 subgoal): 1. dist (\<nu>\<^sub>b (mk_stationary_det (vi_policy eps v))) \<nu>\<^sub>b_opt < eps [PROOF STEP] unfolding vi_policy_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. dist (\<nu>\<^sub>b (mk_stationary_det (find_policy (value_iteration eps v)))) \<nu>\<^sub>b_opt < eps [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: 0 < eps goal (1 subgoal): 1. dist (\<nu>\<^sub>b (mk_stationary_det (find_policy (value_iteration eps v)))) \<nu>\<^sub>b_opt < eps [PROOF STEP] proof (induction eps v rule: value_iteration.induct) [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>eps v. \<lbrakk>\<lbrakk>\<not> (2 * l * dist v (\<L>\<^sub>b v) < eps * (1 - l) \<or> eps \<le> 0); 0 < eps\<rbrakk> \<Longrightarrow> dist (\<nu>\<^sub>b (mk_stationary_det (find_policy (value_iteration eps (\<L>\<^sub>b v))))) \<nu>\<^sub>b_opt < eps; 0 < eps\<rbrakk> \<Longrightarrow> dist (\<nu>\<^sub>b (mk_stationary_det (find_policy (value_iteration eps v)))) \<nu>\<^sub>b_opt < eps [PROOF STEP] case (1 v) [PROOF STATE] proof (state) this: \<lbrakk>\<not> (2 * l * dist v_ (\<L>\<^sub>b v_) < v * (1 - l) \<or> v \<le> 0); 0 < v\<rbrakk> \<Longrightarrow> dist (\<nu>\<^sub>b (mk_stationary_det (find_policy (value_iteration v (\<L>\<^sub>b v_))))) \<nu>\<^sub>b_opt < v 0 < v goal (1 subgoal): 1. \<And>eps v. \<lbrakk>\<lbrakk>\<not> (2 * l * dist v (\<L>\<^sub>b v) < eps * (1 - l) \<or> eps \<le> 0); 0 < eps\<rbrakk> \<Longrightarrow> dist (\<nu>\<^sub>b (mk_stationary_det (find_policy (value_iteration eps (\<L>\<^sub>b v))))) \<nu>\<^sub>b_opt < eps; 0 < eps\<rbrakk> \<Longrightarrow> dist (\<nu>\<^sub>b (mk_stationary_det (find_policy (value_iteration eps v)))) \<nu>\<^sub>b_opt < eps [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<lbrakk>\<not> (2 * l * dist v_ (\<L>\<^sub>b v_) < v * (1 - l) \<or> v \<le> 0); 0 < v\<rbrakk> \<Longrightarrow> dist (\<nu>\<^sub>b (mk_stationary_det (find_policy (value_iteration v (\<L>\<^sub>b v_))))) \<nu>\<^sub>b_opt < v 0 < v [PROOF STEP] show ?case [PROOF STATE] proof (prove) using this: \<lbrakk>\<not> (2 * l * dist v_ (\<L>\<^sub>b v_) < v * (1 - l) \<or> v \<le> 0); 0 < v\<rbrakk> \<Longrightarrow> dist (\<nu>\<^sub>b (mk_stationary_det (find_policy (value_iteration v (\<L>\<^sub>b v_))))) \<nu>\<^sub>b_opt < v 0 < v goal (1 subgoal): 1. dist (\<nu>\<^sub>b (mk_stationary_det (find_policy (value_iteration v v_)))) \<nu>\<^sub>b_opt < v [PROOF STEP] using find_policy_error_bound [PROOF STATE] proof (prove) using this: \<lbrakk>\<not> (2 * l * dist v_ (\<L>\<^sub>b v_) < v * (1 - l) \<or> v \<le> 0); 0 < v\<rbrakk> \<Longrightarrow> dist (\<nu>\<^sub>b (mk_stationary_det (find_policy (value_iteration v (\<L>\<^sub>b v_))))) \<nu>\<^sub>b_opt < v 0 < v \<lbrakk>0 < ?eps; 2 * l * dist ?v (\<L>\<^sub>b ?v) < ?eps * (1 - l)\<rbrakk> \<Longrightarrow> dist (\<nu>\<^sub>b (mk_stationary_det (find_policy (\<L>\<^sub>b ?v)))) \<nu>\<^sub>b_opt < ?eps goal (1 subgoal): 1. dist (\<nu>\<^sub>b (mk_stationary_det (find_policy (value_iteration v v_)))) \<nu>\<^sub>b_opt < v [PROOF STEP] by (subst value_iteration.simps) auto [PROOF STATE] proof (state) this: dist (\<nu>\<^sub>b (mk_stationary_det (find_policy (value_iteration v v_)))) \<nu>\<^sub>b_opt < v goal: No subgoals! [PROOF STEP] qed
(* * Copyright 2014, NICTA * * This software may be distributed and modified according to the terms of * the BSD 2-Clause license. Note that NO WARRANTY is provided. * See "LICENSE_BSD2.txt" for details. * * @TAG(NICTA_BSD) *) theory breakcontinue imports "CParser.CTranslation" begin declare sep_conj_ac [simp add] external_file "breakcontinue.c" install_C_file "breakcontinue.c" context breakcontinue_global_addresses begin thm f_body_def thm g_body_def thm h_body_def thm i_body_def thm dotest_body_def lemma h: "\<Gamma> \<turnstile> \<lbrace> -10 <=s \<acute>e & \<acute>e <s 0 \<rbrace> \<acute>ret__int :== PROC h(\<acute>e) \<lbrace> \<acute>ret__int = \<acute>e \<rbrace>" apply (hoare_rule HoarePartial.ProcNoRec1) apply (hoare_rule HoarePartial.Catch [where R = "\<lbrace> \<acute>ret__int = \<acute>e \<rbrace>"]) defer apply vcg apply (hoare_rule HoarePartial.conseq [where P' = "\<lambda>e. \<lbrace> \<acute>e = e & e <s 0 & -10 <=s e \<rbrace>" and Q' = "\<lambda>e. \<lbrace> \<acute>e = e & \<acute>ret__int = e \<rbrace>" and A' = "\<lambda>e. \<lbrace> \<acute>e = e & \<acute>ret__int = e \<rbrace>"]) defer apply (simp add: subset_iff) apply clarsimp apply (rule_tac R="{}" in HoarePartial.Seq) defer apply vcg apply (rule_tac R="\<lbrace> \<acute>e = Z \<rbrace>" in HoarePartial.Seq) defer apply vcg apply (rule_tac R = "\<lbrace> \<acute>e = Z & \<acute>global_exn_var = Break \<rbrace>" in HoarePartial.Catch) defer apply vcg apply simp apply (rule_tac P' = "\<lbrace> \<acute>e = Z & Z <s 0 & -10 <=s Z \<rbrace>" and Q' = "\<lbrace> \<acute>e = Z & Z <s 0 & -10 <=s Z \<rbrace> \<inter> - \<lbrace> \<acute>e <s 10 \<rbrace>" and A' = "\<lbrace> \<acute>e = Z & \<acute>global_exn_var = Break \<rbrace>" in HoarePartial.conseq_no_aux) defer apply simp apply (simp add: whileAnno_def) apply (rule HoarePartialDef.While) apply vcg apply (simp add: subset_iff) done (* another example where vcg fails, generating impossible sub-goals *) lemma dotest: "\<Gamma> \<turnstile> \<lbrace> \<acute>x = 4 \<rbrace> \<acute>ret__int :== PROC dotest(\<acute>x) \<lbrace> \<acute>ret__int = 4 \<rbrace>" apply (hoare_rule HoarePartial.ProcNoRec1) apply (hoare_rule HoarePartial.Catch [where R="\<lbrace> \<acute>ret__int = 4 \<rbrace>"]) apply (hoare_rule HoarePartial.Seq [where R="{}"]) apply (hoare_rule HoarePartial.Seq [where R="\<lbrace> \<acute>x = 4 \<rbrace>"]) apply (hoare_rule HoarePartial.Catch [where R="\<lbrace> \<acute>x = 4 & \<acute>global_exn_var = Break \<rbrace>"]) apply (hoare_rule HoarePartial.Seq [where R="\<lbrace> False \<rbrace>"]) apply (vcg, simp) apply (hoare_rule HoarePartial.conseq_exploit_pre, simp) apply (vcg, simp) apply vcg apply vcg apply vcg done end end
------------------------------------------------------------------------------ -- Totality of natural numbers addition ------------------------------------------------------------------------------ {-# OPTIONS --exact-split #-} {-# OPTIONS --no-sized-types #-} {-# OPTIONS --no-universe-polymorphism #-} {-# OPTIONS --without-K #-} module FOT.FOTC.Data.Nat.AddTotality where open import FOTC.Base open import FOTC.Data.Nat ------------------------------------------------------------------------------ module InductionPrinciple where -- Interactive proof using the induction principle for natural numbers. +-N : βˆ€ {m n} β†’ N m β†’ N n β†’ N (m + n) +-N {m} {n} Nm Nn = N-ind A A0 is Nm where A : D β†’ Set A i = N (i + n) A0 : A zero A0 = subst N (sym (+-0x n)) Nn is : βˆ€ {i} β†’ A i β†’ A (succ₁ i) is {i} Ai = subst N (sym (+-Sx i n)) (nsucc Ai) -- Combined proof using the induction principle. -- -- The translation is -- βˆ€ p. app₁(p,zero) β†’ -- (βˆ€ x. app₁(n,x) β†’ app₁(p,x) β†’ app₁(p,appFn(succ,x))) β†’ -- N-ind -- (βˆ€ x. app₁(n,x) β†’ app₁(p,x)) ---------------------------------------------------------------- -- βˆ€ x y. app₁(n,x) β†’ app₁(n,y) β†’ app₁(n,appFn(appFn(+,x),y)) -- +-N -- Because the ATPs don't handle induction, them cannot prove this -- postulate. postulate +-N' : βˆ€ {m n} β†’ N m β†’ N n β†’ N (m + n) -- {-# ATP prove +-N' N-ind #-} module Instance where -- Interactive proof using an instance of the induction principle. +-N-ind : βˆ€ {n} β†’ N (zero + n) β†’ (βˆ€ {m} β†’ N (m + n) β†’ N (succ₁ m + n)) β†’ βˆ€ {m} β†’ N m β†’ N (m + n) +-N-ind {n} = N-ind (Ξ» i β†’ N (i + n)) +-N : βˆ€ {m n} β†’ N m β†’ N n β†’ N (m + n) +-N {n = n} Nm Nn = +-N-ind A0 is Nm where A0 : N (zero + n) A0 = subst N (sym (+-0x n)) Nn is : βˆ€ {m} β†’ N (m + n) β†’ N (succ₁ m + n) is {m} Ai = subst N (sym (+-Sx m n)) (nsucc Ai) -- Combined proof using an instance of the induction principle. postulate +-N' : βˆ€ {m n} β†’ N m β†’ N n β†’ N (m + n) {-# ATP prove +-N' +-N-ind #-}
myTestRule { # Examples are in irods/server/config/reConfigs # Input parameters are: # Rule file without the .re extension # Session variable file name mapping file without the .dvm extension # Application microservice mapping file without the .fnm extension # Output from running the example is: # List of the rules in the In-memory Rule Base msiAdmAddAppRuleStruct("*File","",""); msiAdmShowIRB(); } INPUT *File="core3" OUTPUT ruleExecOut
[GOAL] Ξ± : Type u_1 inst✝ : DecidableEq Ξ± s t : Finset Ξ± P : Finpartition s ⊒ IsEquipartition P ↔ βˆ€ (a : Finset Ξ±), a ∈ P.parts β†’ Finset.card a = Finset.card s / Finset.card P.parts ∨ Finset.card a = Finset.card s / Finset.card P.parts + 1 [PROOFSTEP] simp_rw [IsEquipartition, Finset.equitableOn_iff, P.sum_card_parts] [GOAL] Ξ± : Type u_1 inst✝ : DecidableEq Ξ± s t : Finset Ξ± P : Finpartition s hP : IsEquipartition P ht : t ∈ P.parts ⊒ Finset.card s / Finset.card P.parts ≀ Finset.card t [PROOFSTEP] rw [← P.sum_card_parts] [GOAL] Ξ± : Type u_1 inst✝ : DecidableEq Ξ± s t : Finset Ξ± P : Finpartition s hP : IsEquipartition P ht : t ∈ P.parts ⊒ (Finset.sum P.parts fun i => Finset.card i) / Finset.card P.parts ≀ Finset.card t [PROOFSTEP] exact Finset.EquitableOn.le hP ht [GOAL] Ξ± : Type u_1 inst✝ : DecidableEq Ξ± s t : Finset Ξ± P : Finpartition s hP : IsEquipartition P ht : t ∈ P.parts ⊒ Finset.card t ≀ Finset.card s / Finset.card P.parts + 1 [PROOFSTEP] rw [← P.sum_card_parts] [GOAL] Ξ± : Type u_1 inst✝ : DecidableEq Ξ± s t : Finset Ξ± P : Finpartition s hP : IsEquipartition P ht : t ∈ P.parts ⊒ Finset.card t ≀ (Finset.sum P.parts fun i => Finset.card i) / Finset.card P.parts + 1 [PROOFSTEP] exact Finset.EquitableOn.le_add_one hP ht [GOAL] Ξ± : Type u_1 inst✝ : DecidableEq Ξ± s t : Finset Ξ± P : Finpartition s ⊒ βˆ€ (a : Finset Ξ±), a ∈ ↑βŠ₯.parts β†’ Finset.card a = 1 ∨ Finset.card a = 1 + 1 [PROOFSTEP] simp [GOAL] Ξ± : Type u_1 inst✝ : DecidableEq Ξ± s t : Finset Ξ± P : Finpartition s hs : s β‰  βˆ… ⊒ IsEquipartition (indiscrete hs) [PROOFSTEP] rw [IsEquipartition, indiscrete_parts, coe_singleton] [GOAL] Ξ± : Type u_1 inst✝ : DecidableEq Ξ± s t : Finset Ξ± P : Finpartition s hs : s β‰  βˆ… ⊒ Set.EquitableOn {s} Finset.card [PROOFSTEP] exact Set.equitableOn_singleton s _
lemma eucl_rel_poly_mult: assumes "eucl_rel_poly x y (q, r)" "eucl_rel_poly q z (q', r')" shows "eucl_rel_poly x (y * z) (q', y * r' + r)"
% DOC % % Files % afemdoc - Adaptive Finite Element Method % amgdoc - ALGEBRAIC MULTIGRID METHOD % amgdoctest1 - AMG TEST I: DIFFERENT MESHES % amgdoctest2 - AMG TEST II: Different boundary conditions % amgdoctest3 - AMG TEST III: Robustness to time discretization % amgtest - test algebraic mutligrid solver % amgtest2 - AMG TEST II: Different boundary conditions % auxstructuredoc - Auxiliary Mesh Data Structure % bddoc - Data Structure: Boundary Conditions % bisectdoc - Bisection in Two Dimensions % coarsenAMGdoc - Coarsening for Algebraic Multigrid % coarsendoc - COARSENING in TWO DIMENSIONS % coloringdoc - Coloring Vertices of a Graph % dof3edgedoc - Data Structure: Lowest Order Edge Element % dofdoc - Data Sturcture for Degree of Freedom (DOF) % dofedgedoc - Dofedge in Two Dimensions % dofP2doc - Data Structure: P2 Quadratic Element % fastcoding - Vectorization % femcontent - Finite Element Methods % femdoc - Finite Element Methods % ifem - Display HTML documentation in the MATLAB web browser. % introduction - Introduction of iFEM % Maxwell1doc - Equation: Maxwell Equation Discretized by Edge Element % Maxwell1testdoc - Edge Element Discretization of Maxwell Equations: Linear Element % Maxwell2doc - Equation: Maxwell equation Quadratic Element in 3D % Maxwell2testdoc - Edge Element Discretization of Maxwell Equations % Maxwelldoc - Equation: Maxwell Equation Discretized by Edge Element % MaxwellNeumanBCdoc - Local Labeling of DOFs % Maxwelltestdoc - Edge Element Discretization of Maxwell Equations % meshamrdoc - Adaptive Mesh Refinement/Coarsening % meshbasicdoc - Basic Data Structure representing a Mesh % meshdoc - Mesh % meshoptdoc - Mesh Smoothing and Optimization % mgdoc - MULTIGRID on BISECTION GRIDS % mixFEMsolverdoc - Mixed FEM solver % Poisson3BDM1doc - Equation: Poisson Equation Discretized by $BDM_1$ Element in 3D % Poisson3RT0doc - Equation: Poisson Equation Discretized by $RT_0$ Element in 3D % PoissonBDM1doc - Equation: Poisson Equation Discretized by $BDM_1$ Element in 2D % PoissonRT0doc - Equation: Poisson Equation Discretized by $RT_0$ Element in 2D % sc3doc - Simplicial Complex in Three Dimensions % scdoc - Simplicial Complex in Three Dimensions % simplicialcomplexdoc - Simplicial Complex in 3D % solverdoc - Multigrid Method % sparsematrixdoc - Vectorization using Sparse Matrices % uniformrefine3doc - 3-D Red Refinement
{ \begin{doublespacing} \begin{flushleft} \section{Contributions to knowledge} This is a section of your contribution to knowledge. This is a section of your contribution to knowledge. This is a section of your contribution to knowledge. This is a section of your contribution to knowledge. This is a section of your contribution to knowledge. This is a section of your contribution to knowledge. This is a section of your contribution to knowledge. This is a section of your contribution to knowledge. This is a section of your contribution to knowledge. This is a section of your contribution to knowledge. This is a section of your contribution to knowledge. This is a section of your contribution to knowledge. This is a section of your contribution to knowledge. This is a section of your contribution to knowledge. This is a section of your contribution to knowledge. This is a section of your contribution to knowledge. This is a section of your contribution to knowledge. This is a section of your contribution to knowledge. This is a section of your contribution to knowledge. This is a section of your contribution to knowledge. This is a section of your contribution to knowledge. \end{flushleft} \end{doublespacing} }
theory ExF006 imports Main begin lemma "(\<exists>x. \<forall>y. P x y) \<longrightarrow> (\<forall>y. \<exists>x. P x y)" proof - { assume "\<exists>x. \<forall>y. P x y" { fix b { fix a assume "\<forall>y .P a y" hence "P a b" by (rule allE) hence "\<exists>x. P x b" by (rule exI) } with \<open>\<exists>x. \<forall>y. P x y\<close> have "\<exists>x. P x b" by (rule exE) } hence "\<forall>y. \<exists>x. P x y" by (rule allI) } thus ?thesis by (rule impI) qed
export DFlow, RawDFlowPDSource struct DFlow; end struct RawDFlow; end struct RawDFlowPD; end const DFlowSource = Source{DFlow} const RawDFlowPDSource = Source{RawDFlowPD} function DatasetManager.readsource(s::DFlowSource; kwargs...) CSV.read(sourcepath(s), DataFrame; header=2, kwargs...) end function DatasetManager.readsource(s::Source{RawDFlow}; kwargs...) CSV.read(sourcepath(s), DataFrame; header=1, kwargs...) end function DatasetManager.readsource(s::Source{RawDFlowPD}; kwargs...) CSV.read(sourcepath(s), DataFrame; header=7, kwargs...) end function DatasetManager.readsegment( seg::Segment{O}; kwargs... ) where O <: Union{Source{DFlow},Source{RawDFlow}} timecol = (O isa DFlowSource) ? 1 : 2 columns, colnames = readsource(seg.source; kwargs...) firsttime = first(columns[timecol]) lasttime = last(columns[timecol]) if isnothing(seg.finish) _finish = lasttime else _finish = seg.finish end firsttime ≀ seg.start ≀ lasttime || throw(error("$s start time $(seg.start) is not within"* "the source time range of $firsttime:$lasttime")) firsttime ≀ _finish ≀ lasttime || throw(error("$s finish time $(seg.finish) is not within "* "the source time range of $firsttime:$lasttime")) startidx = searchsortedfirst(columns[timecol], firsttime) if isnothing(seg.finish) finidx = lastindex(columns[timecol]) else finidx = searchsortedlast(columns[timecol], seg.finish) end segcolumns = ntuple(i -> columns[i][startidx:finidx], length(columns)) return segcolumns, colnames end
/- Copyright (c) 2021 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta ! This file was ported from Lean 3 source module category_theory.limits.constructions.epi_mono ! leanprover-community/mathlib commit f7baecbb54bd0f24f228576f97b1752fc3c9b318 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathlib.CategoryTheory.Limits.Shapes.Pullbacks import Mathlib.CategoryTheory.Limits.Shapes.BinaryProducts import Mathlib.CategoryTheory.Limits.Preserves.Shapes.Pullbacks /-! # Relating monomorphisms and epimorphisms to limits and colimits If `F` preserves (resp. reflects) pullbacks, then it preserves (resp. reflects) monomorphisms. We also provide the dual version for epimorphisms. -/ universe v₁ vβ‚‚ u₁ uβ‚‚ namespace CategoryTheory open Category Limits variable {C : Type u₁} {D : Type uβ‚‚} [Category.{v₁} C] [Category.{vβ‚‚} D] variable (F : C β₯€ D) /-- If `F` preserves pullbacks, then it preserves monomorphisms. -/ theorem preserves_mono_of_preservesLimit {X Y : C} (f : X ⟢ Y) [PreservesLimit (cospan f f) F] [Mono f] : Mono (F.map f) := by have := isLimitPullbackConeMapOfIsLimit F _ (PullbackCone.isLimitMkIdId f) simp_rw [F.map_id] at this apply PullbackCone.mono_of_isLimitMkIdId _ this #align category_theory.preserves_mono_of_preserves_limit CategoryTheory.preserves_mono_of_preservesLimit instance (priority := 100) preservesMonomorphisms_of_preservesLimitsOfShape [PreservesLimitsOfShape WalkingCospan F] : F.PreservesMonomorphisms where preserves f _ := preserves_mono_of_preservesLimit F f #align category_theory.preserves_monomorphisms_of_preserves_limits_of_shape CategoryTheory.preservesMonomorphisms_of_preservesLimitsOfShape /-- If `F` reflects pullbacks, then it reflects monomorphisms. -/ theorem reflects_mono_of_reflectsLimit {X Y : C} (f : X ⟢ Y) [ReflectsLimit (cospan f f) F] [Mono (F.map f)] : Mono f := by have := PullbackCone.isLimitMkIdId (F.map f) simp_rw [← F.map_id] at this apply PullbackCone.mono_of_isLimitMkIdId _ (isLimitOfIsLimitPullbackConeMap F _ this) #align category_theory.reflects_mono_of_reflects_limit CategoryTheory.reflects_mono_of_reflectsLimit instance (priority := 100) reflectsMonomorphisms_of_reflectsLimitsOfShape [ReflectsLimitsOfShape WalkingCospan F] : F.ReflectsMonomorphisms where reflects f _ := reflects_mono_of_reflectsLimit F f #align category_theory.reflects_monomorphisms_of_reflects_limits_of_shape CategoryTheory.reflectsMonomorphisms_of_reflectsLimitsOfShape /-- If `F` preserves pushouts, then it preserves epimorphisms. -/ theorem preserves_epi_of_preservesColimit {X Y : C} (f : X ⟢ Y) [PreservesColimit (span f f) F] [Epi f] : Epi (F.map f) := by have := isColimitPushoutCoconeMapOfIsColimit F _ (PushoutCocone.isColimitMkIdId f) simp_rw [F.map_id] at this apply PushoutCocone.epi_of_isColimitMkIdId _ this #align category_theory.preserves_epi_of_preserves_colimit CategoryTheory.preserves_epi_of_preservesColimit instance (priority := 100) preservesEpimorphisms_of_preservesColimitsOfShape [PreservesColimitsOfShape WalkingSpan F] : F.PreservesEpimorphisms where preserves f _ := preserves_epi_of_preservesColimit F f #align category_theory.preserves_epimorphisms_of_preserves_colimits_of_shape CategoryTheory.preservesEpimorphisms_of_preservesColimitsOfShape /-- If `F` reflects pushouts, then it reflects epimorphisms. -/ theorem reflects_epi_of_reflectsColimit {X Y : C} (f : X ⟢ Y) [ReflectsColimit (span f f) F] [Epi (F.map f)] : Epi f := by have := PushoutCocone.isColimitMkIdId (F.map f) simp_rw [← F.map_id] at this apply PushoutCocone.epi_of_isColimitMkIdId _ (isColimitOfIsColimitPushoutCoconeMap F _ this) #align category_theory.reflects_epi_of_reflects_colimit CategoryTheory.reflects_epi_of_reflectsColimit instance (priority := 100) reflectsEpimorphisms_of_reflectsColimitsOfShape [ReflectsColimitsOfShape WalkingSpan F] : F.ReflectsEpimorphisms where reflects f _ := reflects_epi_of_reflectsColimit F f #align category_theory.reflects_epimorphisms_of_reflects_colimits_of_shape CategoryTheory.reflectsEpimorphisms_of_reflectsColimitsOfShape end CategoryTheory
! Written by Ulf Saalmann MODULE spaic IMPLICIT NONE ! Global parameters double precision, parameter :: pi = 3.141592653589793238462 integer :: npara, jr, nr double precision :: rclus = 14.478 double precision :: drclus = 0.9 double precision :: vclus = 0.226 double precision :: fluc = 0.3 integer :: lin = 0 ! s integer :: kin = 1 ! 1 integer :: dl = 1 ! l -> l+1 integer :: nw = 100 ! num frequencies double precision :: wmin = 0.2 double precision :: wmax = 2.2 double precision, dimension(:), allocatable :: para ! hard-wired parameter integer :: jpot=1 double precision :: dr = 0.05, rmax = 200 ! Internal parameters double precision, allocatable :: knots(:), pots(:,:), pot0(:), pot1(:), pot(:), bpot(:), cpot(:) double precision, allocatable :: rr(:), bpsi(:), cpsi(:), frequencies(:), spectrum(:) ! Function and Subroutines public :: set_params public :: bspline public :: cnumerov public :: bnumerov public :: integ public :: wkbratio public :: compute_crosssection public :: initialize public :: deinitialize public :: free_all_memory CONTAINS ! SUBROUTINE deallocate_dv(mem) ! double precision, dimension(:), allocatable, intent(inout) :: mem ! if(allocated(mem)) then ! deallocate(mem) ! endif ! END SUBROUTINE deallocate_dv SUBROUTINE set_params(params, n) integer, intent(in) :: n double precision, dimension(n), intent(in) :: params double precision, allocatable :: para(:) if(allocated(para)) then deallocate(para) endif allocate(para(1:n)) para(:) = params(:) if(npara .NE. n) then npara = n call initialize() endif END SUBROUTINE set_params SUBROUTINE compute_crosssection() call crossection(nr) END SUBROUTINE compute_crosssection subroutine crossection(nr) implicit none integer, intent(in) :: nr integer :: i double precision :: w, eb if (lin+dl<0) then write (*, *) "negative angular momentum: lin+dl" stop end if ! potential pot(:) = pot0(:) do i=1,npara pot(:) = pot(:) + (2*para(i)-1)*pots(:,i) end do bpot(:) = pot(:) + lin*(lin+1)*pot1(:) cpot(:) = pot(:) + (lin+dl)*(lin+dl+1)*pot1(:) ! bound state call bnumerov(lin,kin,bpot(:),eb,bpsi, nr) ! continuum states do i=1,nr if (abs(pot(i)+(lin+dl)*(lin+dl+1)*pot1(i))>1d-3) jr=i end do if (nr-jr<10) then write (*, *) "too few asymptotic points: ", nr-jr stop end if if (eb+wmin<0) then write (*, *) "freqeuncy too small: ", nr-jr, eb+wmin stop end if do i=0,nw w = wmin + i*((wmax-wmin)/nw) call cnumerov(lin+dl, eb+w,cpot(0:), cpsi, nr) frequencies(i) = w spectrum(i) = (sum(bpsi(:)*rr(:)*cpsi(:)))**2 end do end subroutine crossection SUBROUTINE deinitialize() IMPLICIT NONE if(allocated(knots)) then deallocate(knots) endif if(allocated(pots)) then deallocate(pots) endif if(allocated(rr)) then deallocate(rr) endif if(allocated(bpot)) then deallocate(bpot) endif if(allocated(cpot)) then deallocate(cpot) endif if(allocated(bpsi)) then deallocate(bpsi) endif if(allocated(cpsi)) then deallocate(cpsi) endif if(allocated(pot)) then deallocate(pot) endif if(allocated(pot0)) then deallocate(pot0) endif if(allocated(pot1)) then deallocate(pot1) endif if(allocated(frequencies)) then deallocate(frequencies) endif if(allocated(spectrum)) then deallocate(spectrum) endif END SUBROUTINE deinitialize SUBROUTINE free_all_memory() IMPLICIT NONE call deinitialize() if(allocated(para)) then deallocate(para) endif END SUBROUTINE free_all_memory subroutine initialize() implicit none integer :: i,ii double precision :: r nr = nint(rmax/dr) call deinitialize() allocate(knots(1:npara+1)) allocate(pots(0:nr,1:npara)) allocate(rr(0:nr),bpot(0:nr),cpot(0:nr),bpsi(0:nr),cpsi(0:nr)) allocate(pot(0:nr),pot0(0:nr),pot1(0:nr)) allocate(frequencies(0:nw)) allocate(spectrum(0:nw)) ! define the knots for b-splines select case(jpot) case(1) do i=1,npara+1 knots(i) = (i-1)*((rclus+2*drclus)/npara) end do end select ! calculate all potentials do ii=0,nr r = ii*dr rr(ii) = r pot0(ii) = -vclus/(1+exp((r-rclus)/drclus)) if (ii>0) & pot1(ii) = 1/(2*r**2) do i=1,npara pots(ii,i) = fluc*vclus*bspline(i,r,npara+2,knots(:)) end do end do pot1(0) = pot1(1) end subroutine initialize ! ========= ! B-splines ! ========= function bspline(j, x, n, xx) implicit none integer, intent(in) :: j,n double precision, intent(in) :: x,xx(1:n-1) double precision :: bspline bspline = 0 if (j==1) then if (xx(1)<=x .and. x<xx(2)) & bspline = ((x-xx(2))/(xx(1)-xx(2)))**2 end if if (j==2) then if (xx(1)<=x .and. x<xx(2)) & bspline = -(((x - xx(1))*(x*(2*xx(1) - xx(2) - xx(3)) & + 2*xx(2)*xx(3) - xx(1)*(xx(2) + xx(3)))) & / ((xx(1) - xx(2))**2*(xx(1) - xx(3)))) if (xx(2)<=x .and. x<=xx(3)) & bspline = (x - xx(3))**2 & / ((-xx(1) + xx(3))*(-xx(2) + xx(3))) end if if (2<j .and. j<n-1) then if (xx(j-2)<=x .and. x<xx(j-1)) & bspline = (x - xx(j-2))**2/((xx(j-2) - xx(j-1))*(xx(j-2) - xx(j))) if (xx(j-1)<=x .and. x<xx(j)) & bspline = (((x - xx(j-2))*(x - xx(j)))/(xx(j-2) - xx(j)) & + ((x - xx(j-1))*(x - xx(j+1)))/(xx(j-1) - xx(j+1)))/(-xx(j-1) + xx(j)) if (xx(j)<=x .and. x<xx(j+1)) & bspline = (x - xx(j+1))**2/((-xx(j-1) + xx(j+1))*(-xx(j) + xx(j+1))) end if if (j==n-1) then if (xx(n-3)<=x .and. x<xx(n-2)) & bspline = (x - xx(n-3))**2/((xx(n-3) - xx(n-1))*(xx(n-3) - xx(n-2))) if (xx(n-2)<=x .and. x<xx(n-1)) & bspline = -(((x - xx(n-1))*(xx(n-3)*(xx(n-1) - 2*xx(n-2)) & + xx(n-1)*xx(n-2) + x*(xx(n-3) - 2*xx(n-1) + xx(n-2)))) & / ((xx(n-3) - xx(n-1))*(xx(n-1) - xx(n-2))**2)) end if if (j==n) then if (xx(n-2)<=x .and. x<=xx(n-1)) & bspline = (x - xx(n-2))**2/(xx(n-1) - xx(n-2))**2 end if end function bspline ! ============== ! numerov method ! ============== subroutine cnumerov(l,e,pot,psi, nr) implicit none integer, intent(in) :: l, nr double precision, intent(in) :: e,pot(0:nr) double precision, intent(out) :: psi(0:nr) integer :: j double precision :: norm call integ(l,e,pot,j,psi, nr) norm = maxval(abs(psi(jr:nr))) psi(:) = psi(:)/norm if (psi(1)<0) psi(:) = -psi(:) end subroutine cnumerov subroutine bnumerov(l,k,pot,e,psi, nr) implicit none integer, intent(in) :: l,k, nr double precision, intent(in) :: pot(0:nr) double precision, intent(out) :: e,psi(0:nr) integer :: j1,j2,j,i,nzeros double precision :: e1,e2 nzeros = k-1 if (nzeros<0) then write (*, *) "bnumerov: nzeros<0" stop end if ! lower limit for bracketing e1 = -0.1 j1 = nzeros+1 do while(j1>nzeros) e1 = 2*e1 call integ(l,e1,pot(0:nr),j1,psi, nr) end do ! upper limit for bracketing e2 = 1 j2 = nzeros do while(j2.le.nzeros) e2 = 2*e2 call integ(l,e2,pot,j2,psi, nr) end do ! naive bracketing do i=1,33 ! could be improved e = (e1+e2)/2 call integ(l,e,pot,j,psi, nr) if (j>nzeros) then e2 = e else e1 = e end if end do if (e>0 .and. sqrt(2*e)*dr>0.5) then write (*, *) "bnumerov: too large grid spacing? momentum:", sqrt(2*e) end if end subroutine bnumerov subroutine integ(l,e,pot,nzeros,psi,nr) implicit none integer, intent(in) :: l, nr double precision, intent(in) :: e double precision, intent(in) :: pot(0:nr) integer, intent(out) :: nzeros double precision, intent(out) :: psi(0:nr) integer :: i,j0,flag,j double precision :: r,rtp,drq double precision :: raux(0:2) flag = 1 nzeros = 0 drq = dr**2 psi(:) = 0 ! outer classical turning point j = nr do while (e<pot(j) .and. j>0) j = j-1 end do rtp = j*dr if (pot(1)<e) then ! no inner classical forbidden region j0 = 1 r = dr psi(1) = r**(l+1)*(1-r/(l+1)) raux(2) = drq * (pot(1)-e) r = 2*dr psi(2) = r**(l+1)*(1-r/(l+1)) raux(1) = drq * (pot(2)-e) else ! with inner classical forbidden region ! j0*dr is the radius where propagation should be possible j0 = max(1,nint(sqrt(l*(l+1)/(2*e+1/drq))/dr)) r = j0*dr psi(j0) = 1d-10 raux(2) = drq * (pot(j0)-e) r = (j0+1)*dr ! use WKB psi(j0+1) = psi(j0) * wkbratio(pot(j0),pot(j0+1),dr,e) raux(1) = drq * (pot(j0+1)-e) do i=j0-1,1,-1 psi(i) = psi(i+1)/wkbratio(pot(i),pot(i+1),dr,e) end do end if do i=j0+2,nr r = i*dr raux(0) = drq * (pot(i)-e) psi(i) = ( (12+10*raux(1))*psi(i-1) - (6-raux(2))*psi(i-2) ) / (6-raux(0)) raux(2) = raux(1) raux(1) = raux(0) if (flag>0 .and. psi(i)<0) then flag = -flag nzeros = nzeros+1 end if if (flag<0 .and. psi(i)>0) then flag = -flag nzeros = nzeros+1 end if if (e<0 .and. r>rtp+1 .and. abs(psi(i))>abs(psi(i-1))) then psi(i) = psi(i-1)/2 exit end if end do ! normalize wave-functions psi(:) = psi(:)/sqrt(sum(psi(:)**2)) end subroutine integ function wkbratio(pot1,pot2,dr,e) implicit none double precision, intent(in) :: pot1,pot2,dr,e double precision :: wkbratio double precision :: raux1,raux2,raux3 raux1 = sqrt(2*(pot1-e)) raux2 = sqrt(2*((pot1+pot2)/2-e)) raux3 = sqrt(2*(pot2-e)) wkbratio = exp((dr/6)*(raux1+4*raux2+raux3)) end function wkbratio END MODULE spaic
\chapter{EVL} Taken from the Epsilon Book \begin{evl} context Singleton { guard : self .stereotype->exists(s | s.name = "singleton") constraint DefinesGetInstance { check : self .getGetInstanceOperation().isDefined() message : "Singleton " + self .name + " must define a getInstance() operation" fix { title : "Add a getInstance() operation to " + self .name do { // Create the getInstance operation var op : new Operation; op.name = "getInstance"; op.owner = self; op.ownerScope = ScopeKind#sk_classifier; // Create the return parameter var returnParameter : new Parameter; returnParameter.type = self; op.parameter = Sequence{returnParameter}; returnParameter.kind = ParameterDirectionKind#pdk_return; } } } } \end{evl}
example : if x = 0 then y + x = y else x β‰  0 := by simp (config := { contextual := true }) example : if x = 0 then y + x = y else x β‰  0 := by split simp_all simp_all example : if x = 0 then y + x = y else x β‰  0 := by simp (config := { contextual := true }) split -- Error: no goals to be solved
/- This is a section. It contains 00DZ, 00E0, 00E1 and 00E2 and 00E3 and 00E4 and 00E5 and 00E6 and 00E7 and 00E8 and 04PM It also contains the following useful claim, just under Lemma 10.16.2 (tag 00E0): The sets D(f) are open and form a basis for this topology (on Spec(R)) -/ --import Kenny_comm_alg.temp import Kenny_comm_alg.Zariski universe u local attribute [instance] classical.prop_decidable definition standard_basis (R : Type u) [comm_ring R] := {U : set (X R) | βˆƒ f : R, U = Spec.D'(f)} lemma D_f_form_basis (R : Type u) [comm_ring R] : topological_space.is_topological_basis (standard_basis R) := begin refine topological_space.is_topological_basis_of_open_of_nhds _ _, { intros U H, cases H with f Hf, existsi ({f} : set R), rw Hf, unfold Spec.D', unfold Spec.V, unfold Spec.V', rw set.compl_compl, simp }, { intros x U H1 H, cases H with U1 H, have H2 : U = -Spec.V U1, { rw [H, set.compl_compl] }, rw set.ext_iff at H2, have H3 := H2 x, rw iff_true_left H1 at H3, simp [Spec.V, has_subset.subset, set.subset] at H3, rw not_forall at H3, cases H3 with f H3, rw not_imp at H3, cases H3 with H3 H4, existsi Spec.D' f, split, { existsi f, refl }, split, { exact H4 }, { intros y H5, rw H2, intro H6, apply H5, exact H6 H3 } } end
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn Basic properties of lists. -/ import logic tools.helper_tactics data.nat.order data.nat.sub open eq.ops nat prod function option inductive list (T : Type) : Type := | nil {} : list T | cons : T β†’ list T β†’ list T protected definition list.is_inhabited [instance] (A : Type) : inhabited (list A) := inhabited.mk list.nil namespace list notation h :: t := cons h t notation `[` l:(foldr `, ` (h t, cons h t) nil `]`) := l variable {T : Type} lemma cons_ne_nil [simp] (a : T) (l : list T) : a::l β‰  [] := by contradiction lemma head_eq_of_cons_eq {A : Type} {h₁ hβ‚‚ : A} {t₁ tβ‚‚ : list A} : (h₁::t₁) = (hβ‚‚::tβ‚‚) β†’ h₁ = hβ‚‚ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pheq) lemma tail_eq_of_cons_eq {A : Type} {h₁ hβ‚‚ : A} {t₁ tβ‚‚ : list A} : (h₁::t₁) = (hβ‚‚::tβ‚‚) β†’ t₁ = tβ‚‚ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pteq) lemma cons_inj {A : Type} {a : A} : injective (cons a) := take l₁ lβ‚‚, assume Pe, tail_eq_of_cons_eq Pe /- append -/ definition append : list T β†’ list T β†’ list T | [] l := l | (h :: s) t := h :: (append s t) notation l₁ ++ lβ‚‚ := append l₁ lβ‚‚ theorem append_nil_left [simp] (t : list T) : [] ++ t = t := rfl theorem append_cons [simp] (x : T) (s t : list T) : (x::s) ++ t = x::(s ++ t) := rfl theorem append_nil_right [simp] : βˆ€ (t : list T), t ++ [] = t := by rec_inst_simp theorem append.assoc [simp] : βˆ€ (s t u : list T), s ++ t ++ u = s ++ (t ++ u) := by rec_inst_simp /- length -/ definition length : list T β†’ nat | [] := 0 | (a :: l) := length l + 1 theorem length_nil [simp] : length (@nil T) = 0 := rfl theorem length_cons [simp] (x : T) (t : list T) : length (x::t) = length t + 1 := rfl theorem length_append [simp] : βˆ€ (s t : list T), length (s ++ t) = length s + length t := by rec_inst_simp theorem eq_nil_of_length_eq_zero : βˆ€ {l : list T}, length l = 0 β†’ l = [] | [] H := rfl | (a::s) H := by contradiction theorem length_cons_pos (h : T) (tt : list T) : 0 < length (h::tt) := begin apply lt_of_not_ge, intro H, let H' := list.eq_nil_of_length_eq_zero (eq_zero_of_le_zero H), apply !list.cons_ne_nil H' end theorem ne_nil_of_length_eq_succ : βˆ€ {l : list T} {n : nat}, length l = succ n β†’ l β‰  [] | [] n h := by contradiction | (a::l) n h := by contradiction /- concat -/ definition concat : Ξ  (x : T), list T β†’ list T | a [] := [a] | a (b :: l) := b :: concat a l theorem concat_nil [simp] (x : T) : concat x [] = [x] := rfl theorem concat_cons [simp] (x y : T) (l : list T) : concat x (y::l) = y::(concat x l) := rfl theorem concat_eq_append [simp] (a : T) : βˆ€ (l : list T), concat a l = l ++ [a] := by rec_inst_simp theorem concat_ne_nil [simp] (a : T) : βˆ€ (l : list T), concat a l β‰  [] := by intro l; induction l; repeat contradiction theorem length_concat [simp] (a : T) : βˆ€ (l : list T), length (concat a l) = length l + 1 := by rec_inst_simp theorem concat_append [simp] (a : T) : βˆ€ (l₁ lβ‚‚ : list T), concat a l₁ ++ lβ‚‚ = l₁ ++ a :: lβ‚‚ := by rec_inst_simp theorem append_concat (a : T) : βˆ€(l₁ lβ‚‚ : list T), l₁ ++ concat a lβ‚‚ = concat a (l₁ ++ lβ‚‚) := by rec_inst_simp /- last -/ definition last : Ξ  l : list T, l β‰  [] β†’ T | [] h := absurd rfl h | [a] h := a | (a₁::aβ‚‚::l) h := last (aβ‚‚::l) !cons_ne_nil lemma last_singleton [simp] (a : T) (h : [a] β‰  []) : last [a] h = a := rfl lemma last_cons_cons [simp] (a₁ aβ‚‚ : T) (l : list T) (h : a₁::aβ‚‚::l β‰  []) : last (a₁::aβ‚‚::l) h = last (aβ‚‚::l) !cons_ne_nil := rfl theorem last_congr {l₁ lβ‚‚ : list T} (h₁ : l₁ β‰  []) (hβ‚‚ : lβ‚‚ β‰  []) (h₃ : l₁ = lβ‚‚) : last l₁ h₁ = last lβ‚‚ hβ‚‚ := by subst l₁ theorem last_concat [simp] {x : T} : βˆ€ {l : list T} (h : concat x l β‰  []), last (concat x l) h = x := by rec_simp -- add_rewrite append_nil append_cons /- reverse -/ definition reverse : list T β†’ list T | [] := [] | (a :: l) := concat a (reverse l) theorem reverse_nil [simp] : reverse (@nil T) = [] := rfl theorem reverse_cons [simp] (x : T) (l : list T) : reverse (x::l) = concat x (reverse l) := rfl theorem reverse_singleton [simp] (x : T) : reverse [x] = [x] := rfl theorem reverse_append [simp] : βˆ€ (s t : list T), reverse (s ++ t) = (reverse t) ++ (reverse s) := by rec_inst_simp theorem reverse_reverse [simp] : βˆ€ (l : list T), reverse (reverse l) = l := by rec_inst_simp theorem concat_eq_reverse_cons (x : T) (l : list T) : concat x l = reverse (x :: reverse l) := by inst_simp theorem length_reverse : βˆ€ (l : list T), length (reverse l) = length l := by rec_inst_simp /- head and tail -/ definition head [h : inhabited T] : list T β†’ T | [] := arbitrary T | (a :: l) := a theorem head_cons [simp] [h : inhabited T] (a : T) (l : list T) : head (a::l) = a := rfl theorem head_append [simp] [h : inhabited T] (t : list T) : βˆ€ {s : list T}, s β‰  [] β†’ head (s ++ t) = head s := by rec_inst_simp definition tail : list T β†’ list T | [] := [] | (a :: l) := l theorem tail_nil [simp] : tail (@nil T) = [] := rfl theorem tail_cons [simp] (a : T) (l : list T) : tail (a::l) = l := rfl theorem cons_head_tail [h : inhabited T] {l : list T} : l β‰  [] β†’ (head l)::(tail l) = l := by rec_inst_simp /- list membership -/ definition mem : T β†’ list T β†’ Prop | a [] := false | a (b :: l) := a = b ∨ mem a l notation e ∈ s := mem e s notation e βˆ‰ s := Β¬ e ∈ s theorem mem_nil_iff (x : T) : x ∈ [] ↔ false := iff.rfl theorem not_mem_nil (x : T) : x βˆ‰ [] := iff.mp !mem_nil_iff theorem mem_cons [simp] (x : T) (l : list T) : x ∈ x :: l := or.inl rfl theorem mem_cons_of_mem (y : T) {x : T} {l : list T} : x ∈ l β†’ x ∈ y :: l := assume H, or.inr H theorem mem_cons_iff (x y : T) (l : list T) : x ∈ y::l ↔ (x = y ∨ x ∈ l) := iff.rfl theorem eq_or_mem_of_mem_cons {x y : T} {l : list T} : x ∈ y::l β†’ x = y ∨ x ∈ l := assume h, h theorem mem_singleton {x a : T} : x ∈ [a] β†’ x = a := suppose x ∈ [a], or.elim (eq_or_mem_of_mem_cons this) (suppose x = a, this) (suppose x ∈ [], absurd this !not_mem_nil) theorem mem_of_mem_cons_of_mem {a b : T} {l : list T} : a ∈ b::l β†’ b ∈ l β†’ a ∈ l := assume ainbl binl, or.elim (eq_or_mem_of_mem_cons ainbl) (suppose a = b, by substvars; exact binl) (suppose a ∈ l, this) theorem mem_or_mem_of_mem_append {x : T} {s t : list T} : x ∈ s ++ t β†’ x ∈ s ∨ x ∈ t := list.induction_on s or.inr (take y s, assume IH : x ∈ s ++ t β†’ x ∈ s ∨ x ∈ t, suppose x ∈ y::s ++ t, have x = y ∨ x ∈ s ++ t, from this, have x = y ∨ x ∈ s ∨ x ∈ t, from or_of_or_of_imp_right this IH, iff.elim_right or.assoc this) theorem mem_append_of_mem_or_mem {x : T} {s t : list T} : x ∈ s ∨ x ∈ t β†’ x ∈ s ++ t := list.induction_on s (take H, or.elim H false.elim (assume H, H)) (take y s, assume IH : x ∈ s ∨ x ∈ t β†’ x ∈ s ++ t, suppose x ∈ y::s ∨ x ∈ t, or.elim this (suppose x ∈ y::s, or.elim (eq_or_mem_of_mem_cons this) (suppose x = y, or.inl this) (suppose x ∈ s, or.inr (IH (or.inl this)))) (suppose x ∈ t, or.inr (IH (or.inr this)))) theorem mem_append_iff (x : T) (s t : list T) : x ∈ s ++ t ↔ x ∈ s ∨ x ∈ t := iff.intro mem_or_mem_of_mem_append mem_append_of_mem_or_mem theorem not_mem_of_not_mem_append_left {x : T} {s t : list T} : x βˆ‰ s++t β†’ x βˆ‰ s := Ξ» nxinst xins, absurd (mem_append_of_mem_or_mem (or.inl xins)) nxinst theorem not_mem_of_not_mem_append_right {x : T} {s t : list T} : x βˆ‰ s++t β†’ x βˆ‰ t := Ξ» nxinst xint, absurd (mem_append_of_mem_or_mem (or.inr xint)) nxinst theorem not_mem_append {x : T} {s t : list T} : x βˆ‰ s β†’ x βˆ‰ t β†’ x βˆ‰ s++t := Ξ» nxins nxint xinst, or.elim (mem_or_mem_of_mem_append xinst) (Ξ» xins, by contradiction) (Ξ» xint, by contradiction) lemma length_pos_of_mem {a : T} : βˆ€ {l : list T}, a ∈ l β†’ 0 < length l | [] := assume Pinnil, by contradiction | (b::l) := assume Pin, !zero_lt_succ section local attribute mem [reducible] local attribute append [reducible] theorem mem_split {x : T} {l : list T} : x ∈ l β†’ βˆƒs t : list T, l = s ++ (x::t) := list.induction_on l (suppose x ∈ [], false.elim (iff.elim_left !mem_nil_iff this)) (take y l, assume IH : x ∈ l β†’ βˆƒs t : list T, l = s ++ (x::t), suppose x ∈ y::l, or.elim (eq_or_mem_of_mem_cons this) (suppose x = y, exists.intro [] (!exists.intro (this β–Έ rfl))) (suppose x ∈ l, obtain s (H2 : βˆƒt : list T, l = s ++ (x::t)), from IH this, obtain t (H3 : l = s ++ (x::t)), from H2, have y :: l = (y::s) ++ (x::t), from H3 β–Έ rfl, !exists.intro (!exists.intro this))) end theorem mem_append_left {a : T} {l₁ : list T} (lβ‚‚ : list T) : a ∈ l₁ β†’ a ∈ l₁ ++ lβ‚‚ := assume ainl₁, mem_append_of_mem_or_mem (or.inl ainl₁) theorem mem_append_right {a : T} (l₁ : list T) {lβ‚‚ : list T} : a ∈ lβ‚‚ β†’ a ∈ l₁ ++ lβ‚‚ := assume ainlβ‚‚, mem_append_of_mem_or_mem (or.inr ainlβ‚‚) definition decidable_mem [instance] [H : decidable_eq T] (x : T) (l : list T) : decidable (x ∈ l) := list.rec_on l (decidable.inr (not_of_iff_false !mem_nil_iff)) (take (h : T) (l : list T) (iH : decidable (x ∈ l)), show decidable (x ∈ h::l), from decidable.rec_on iH (assume Hp : x ∈ l, decidable.rec_on (H x h) (suppose x = h, decidable.inl (or.inl this)) (suppose x β‰  h, decidable.inl (or.inr Hp))) (suppose Β¬x ∈ l, decidable.rec_on (H x h) (suppose x = h, decidable.inl (or.inl this)) (suppose x β‰  h, have Β¬(x = h ∨ x ∈ l), from suppose x = h ∨ x ∈ l, or.elim this (suppose x = h, by contradiction) (suppose x ∈ l, by contradiction), have Β¬x ∈ h::l, from iff.elim_right (not_iff_not_of_iff !mem_cons_iff) this, decidable.inr this))) theorem mem_of_ne_of_mem {x y : T} {l : list T} (H₁ : x β‰  y) (Hβ‚‚ : x ∈ y :: l) : x ∈ l := or.elim (eq_or_mem_of_mem_cons Hβ‚‚) (Ξ»e, absurd e H₁) (Ξ»r, r) theorem ne_of_not_mem_cons {a b : T} {l : list T} : a βˆ‰ b::l β†’ a β‰  b := assume nin aeqb, absurd (or.inl aeqb) nin theorem not_mem_of_not_mem_cons {a b : T} {l : list T} : a βˆ‰ b::l β†’ a βˆ‰ l := assume nin nainl, absurd (or.inr nainl) nin lemma not_mem_cons_of_ne_of_not_mem {x y : T} {l : list T} : x β‰  y β†’ x βˆ‰ l β†’ x βˆ‰ y::l := assume P1 P2, not.intro (assume Pxin, absurd (eq_or_mem_of_mem_cons Pxin) (not_or P1 P2)) lemma ne_and_not_mem_of_not_mem_cons {x y : T} {l : list T} : x βˆ‰ y::l β†’ x β‰  y ∧ x βˆ‰ l := assume P, and.intro (ne_of_not_mem_cons P) (not_mem_of_not_mem_cons P) definition sublist (l₁ lβ‚‚ : list T) := βˆ€ ⦃a : T⦄, a ∈ l₁ β†’ a ∈ lβ‚‚ infix βŠ† := sublist theorem nil_sub [simp] (l : list T) : [] βŠ† l := Ξ» b i, false.elim (iff.mp (mem_nil_iff b) i) theorem sub.refl [simp] (l : list T) : l βŠ† l := Ξ» b i, i theorem sub.trans {l₁ lβ‚‚ l₃ : list T} (H₁ : l₁ βŠ† lβ‚‚) (Hβ‚‚ : lβ‚‚ βŠ† l₃) : l₁ βŠ† l₃ := Ξ» b i, Hβ‚‚ (H₁ i) theorem sub_cons [simp] (a : T) (l : list T) : l βŠ† a::l := Ξ» b i, or.inr i theorem sub_of_cons_sub {a : T} {l₁ lβ‚‚ : list T} : a::l₁ βŠ† lβ‚‚ β†’ l₁ βŠ† lβ‚‚ := Ξ» s b i, s b (mem_cons_of_mem _ i) theorem cons_sub_cons {l₁ lβ‚‚ : list T} (a : T) (s : l₁ βŠ† lβ‚‚) : (a::l₁) βŠ† (a::lβ‚‚) := Ξ» b Hin, or.elim (eq_or_mem_of_mem_cons Hin) (Ξ» e : b = a, or.inl e) (Ξ» i : b ∈ l₁, or.inr (s i)) theorem sub_append_left [simp] (l₁ lβ‚‚ : list T) : l₁ βŠ† l₁++lβ‚‚ := Ξ» b i, iff.mpr (mem_append_iff b l₁ lβ‚‚) (or.inl i) theorem sub_append_right [simp] (l₁ lβ‚‚ : list T) : lβ‚‚ βŠ† l₁++lβ‚‚ := Ξ» b i, iff.mpr (mem_append_iff b l₁ lβ‚‚) (or.inr i) theorem sub_cons_of_sub (a : T) {l₁ lβ‚‚ : list T} : l₁ βŠ† lβ‚‚ β†’ l₁ βŠ† (a::lβ‚‚) := Ξ» (s : l₁ βŠ† lβ‚‚) (x : T) (i : x ∈ l₁), or.inr (s i) theorem sub_app_of_sub_left (l l₁ lβ‚‚ : list T) : l βŠ† l₁ β†’ l βŠ† l₁++lβ‚‚ := Ξ» (s : l βŠ† l₁) (x : T) (xinl : x ∈ l), have x ∈ l₁, from s xinl, mem_append_of_mem_or_mem (or.inl this) theorem sub_app_of_sub_right (l l₁ lβ‚‚ : list T) : l βŠ† lβ‚‚ β†’ l βŠ† l₁++lβ‚‚ := Ξ» (s : l βŠ† lβ‚‚) (x : T) (xinl : x ∈ l), have x ∈ lβ‚‚, from s xinl, mem_append_of_mem_or_mem (or.inr this) theorem cons_sub_of_sub_of_mem {a : T} {l m : list T} : a ∈ m β†’ l βŠ† m β†’ a::l βŠ† m := Ξ» (ainm : a ∈ m) (lsubm : l βŠ† m) (x : T) (xinal : x ∈ a::l), or.elim (eq_or_mem_of_mem_cons xinal) (suppose x = a, by substvars; exact ainm) (suppose x ∈ l, lsubm this) theorem app_sub_of_sub_of_sub {l₁ lβ‚‚ l : list T} : l₁ βŠ† l β†’ lβ‚‚ βŠ† l β†’ l₁++lβ‚‚ βŠ† l := Ξ» (l₁subl : l₁ βŠ† l) (lβ‚‚subl : lβ‚‚ βŠ† l) (x : T) (xinl₁lβ‚‚ : x ∈ l₁++lβ‚‚), or.elim (mem_or_mem_of_mem_append xinl₁lβ‚‚) (suppose x ∈ l₁, l₁subl this) (suppose x ∈ lβ‚‚, lβ‚‚subl this) /- find -/ section variable [H : decidable_eq T] include H definition find : T β†’ list T β†’ nat | a [] := 0 | a (b :: l) := if a = b then 0 else succ (find a l) theorem find_nil [simp] (x : T) : find x [] = 0 := rfl theorem find_cons (x y : T) (l : list T) : find x (y::l) = if x = y then 0 else succ (find x l) := rfl theorem find_cons_of_eq {x y : T} (l : list T) : x = y β†’ find x (y::l) = 0 := assume e, if_pos e theorem find_cons_of_ne {x y : T} (l : list T) : x β‰  y β†’ find x (y::l) = succ (find x l) := assume n, if_neg n theorem find_of_not_mem {l : list T} {x : T} : Β¬x ∈ l β†’ find x l = length l := list.rec_on l (suppose Β¬x ∈ [], rfl) (take y l, assume iH : Β¬x ∈ l β†’ find x l = length l, suppose Β¬x ∈ y::l, have Β¬(x = y ∨ x ∈ l), from iff.elim_right (not_iff_not_of_iff !mem_cons_iff) this, have Β¬x = y ∧ Β¬x ∈ l, from (iff.elim_left !not_or_iff_not_and_not this), calc find x (y::l) = if x = y then 0 else succ (find x l) : !find_cons ... = succ (find x l) : if_neg (and.elim_left this) ... = succ (length l) : {iH (and.elim_right this)} ... = length (y::l) : !length_cons⁻¹) lemma find_le_length : βˆ€ {a} {l : list T}, find a l ≀ length l | a [] := !le.refl | a (b::l) := decidable.rec_on (H a b) (assume Peq, by rewrite [find_cons_of_eq l Peq]; exact !zero_le) (assume Pne, begin rewrite [find_cons_of_ne l Pne, length_cons], apply succ_le_succ, apply find_le_length end) lemma not_mem_of_find_eq_length : βˆ€ {a} {l : list T}, find a l = length l β†’ a βˆ‰ l | a [] := assume Peq, !not_mem_nil | a (b::l) := decidable.rec_on (H a b) (assume Peq, by rewrite [find_cons_of_eq l Peq, length_cons]; contradiction) (assume Pne, begin rewrite [find_cons_of_ne l Pne, length_cons, mem_cons_iff], intro Plen, apply (not_or Pne), exact not_mem_of_find_eq_length (succ.inj Plen) end) lemma find_lt_length {a} {l : list T} (Pin : a ∈ l) : find a l < length l := begin apply nat.lt_of_le_and_ne, apply find_le_length, apply not.intro, intro Peq, exact absurd Pin (not_mem_of_find_eq_length Peq) end end /- nth element -/ section nth definition nth : list T β†’ nat β†’ option T | [] n := none | (a :: l) 0 := some a | (a :: l) (n+1) := nth l n theorem nth_zero [simp] (a : T) (l : list T) : nth (a :: l) 0 = some a := rfl theorem nth_succ [simp] (a : T) (l : list T) (n : nat) : nth (a::l) (succ n) = nth l n := rfl theorem nth_eq_some : βˆ€ {l : list T} {n : nat}, n < length l β†’ Ξ£ a : T, nth l n = some a | [] n h := absurd h !not_lt_zero | (a::l) 0 h := ⟨a, rfl⟩ | (a::l) (succ n) h := have n < length l, from lt_of_succ_lt_succ h, obtain (r : T) (req : nth l n = some r), from nth_eq_some this, ⟨r, by rewrite [nth_succ, req]⟩ open decidable theorem find_nth [decidable_eq T] {a : T} : βˆ€ {l}, a ∈ l β†’ nth l (find a l) = some a | [] ain := absurd ain !not_mem_nil | (b::l) ainbl := by_cases (Ξ» aeqb : a = b, by rewrite [find_cons_of_eq _ aeqb, nth_zero, aeqb]) (Ξ» aneb : a β‰  b, or.elim (eq_or_mem_of_mem_cons ainbl) (Ξ» aeqb : a = b, absurd aeqb aneb) (Ξ» ainl : a ∈ l, by rewrite [find_cons_of_ne _ aneb, nth_succ, find_nth ainl])) definition inth [h : inhabited T] (l : list T) (n : nat) : T := match nth l n with | some a := a | none := arbitrary T end theorem inth_zero [inhabited T] (a : T) (l : list T) : inth (a :: l) 0 = a := rfl theorem inth_succ [inhabited T] (a : T) (l : list T) (n : nat) : inth (a::l) (n+1) = inth l n := rfl end nth section ith definition ith : Ξ  (l : list T) (i : nat), i < length l β†’ T | nil i h := absurd h !not_lt_zero | (x::xs) 0 h := x | (x::xs) (succ i) h := ith xs i (lt_of_succ_lt_succ h) lemma ith_zero [simp] (a : T) (l : list T) (h : 0 < length (a::l)) : ith (a::l) 0 h = a := rfl lemma ith_succ [simp] (a : T) (l : list T) (i : nat) (h : succ i < length (a::l)) : ith (a::l) (succ i) h = ith l i (lt_of_succ_lt_succ h) := rfl end ith open decidable definition has_decidable_eq {A : Type} [H : decidable_eq A] : βˆ€ l₁ lβ‚‚ : list A, decidable (l₁ = lβ‚‚) | [] [] := inl rfl | [] (b::lβ‚‚) := inr (by contradiction) | (a::l₁) [] := inr (by contradiction) | (a::l₁) (b::lβ‚‚) := match H a b with | inl Hab := match has_decidable_eq l₁ lβ‚‚ with | inl He := inl (by congruence; repeat assumption) | inr Hn := inr (by intro H; injection H; contradiction) end | inr Hnab := inr (by intro H; injection H; contradiction) end /- quasiequal a l l' means that l' is exactly l, with a added once somewhere -/ section qeq variable {A : Type} inductive qeq (a : A) : list A β†’ list A β†’ Prop := | qhead : βˆ€ l, qeq a l (a::l) | qcons : βˆ€ (b : A) {l l' : list A}, qeq a l l' β†’ qeq a (b::l) (b::l') open qeq notation l' `β‰ˆ`:50 a `|` l:50 := qeq a l l' theorem qeq_app : βˆ€ (l₁ : list A) (a : A) (lβ‚‚ : list A), l₁++(a::lβ‚‚) β‰ˆ a|l₁++lβ‚‚ | [] a lβ‚‚ := qhead a lβ‚‚ | (x::xs) a lβ‚‚ := qcons x (qeq_app xs a lβ‚‚) theorem mem_head_of_qeq {a : A} {l₁ lβ‚‚ : list A} : lβ‚β‰ˆa|lβ‚‚ β†’ a ∈ l₁ := take q, qeq.induction_on q (Ξ» l, !mem_cons) (Ξ» b l l' q r, or.inr r) theorem mem_tail_of_qeq {a : A} {l₁ lβ‚‚ : list A} : lβ‚β‰ˆa|lβ‚‚ β†’ βˆ€ x, x ∈ lβ‚‚ β†’ x ∈ l₁ := take q, qeq.induction_on q (Ξ» l x i, or.inr i) (Ξ» b l l' q r x xinbl, or.elim (eq_or_mem_of_mem_cons xinbl) (Ξ» xeqb : x = b, xeqb β–Έ mem_cons x l') (Ξ» xinl : x ∈ l, or.inr (r x xinl))) theorem mem_cons_of_qeq {a : A} {l₁ lβ‚‚ : list A} : lβ‚β‰ˆa|lβ‚‚ β†’ βˆ€ x, x ∈ l₁ β†’ x ∈ a::lβ‚‚ := take q, qeq.induction_on q (Ξ» l x i, i) (Ξ» b l l' q r x xinbl', or.elim (eq_or_mem_of_mem_cons xinbl') (Ξ» xeqb : x = b, xeqb β–Έ or.inr (mem_cons x l)) (Ξ» xinl' : x ∈ l', or.elim (eq_or_mem_of_mem_cons (r x xinl')) (Ξ» xeqa : x = a, xeqa β–Έ mem_cons x (b::l)) (Ξ» xinl : x ∈ l, or.inr (or.inr xinl)))) theorem length_eq_of_qeq {a : A} {l₁ lβ‚‚ : list A} : lβ‚β‰ˆa|lβ‚‚ β†’ length l₁ = succ (length lβ‚‚) := take q, qeq.induction_on q (Ξ» l, rfl) (Ξ» b l l' q r, by rewrite [*length_cons, r]) theorem qeq_of_mem {a : A} {l : list A} : a ∈ l β†’ (βˆƒl', lβ‰ˆa|l') := list.induction_on l (Ξ» h : a ∈ nil, absurd h (not_mem_nil a)) (Ξ» x xs r ainxxs, or.elim (eq_or_mem_of_mem_cons ainxxs) (Ξ» aeqx : a = x, have aux : βˆƒ l, x::xsβ‰ˆx|l, from exists.intro xs (qhead x xs), by rewrite aeqx; exact aux) (Ξ» ainxs : a ∈ xs, have βˆƒl', xs β‰ˆ a|l', from r ainxs, obtain (l' : list A) (q : xs β‰ˆ a|l'), from this, have x::xs β‰ˆ a | x::l', from qcons x q, exists.intro (x::l') this)) theorem qeq_split {a : A} {l l' : list A} : l'β‰ˆa|l β†’ βˆƒl₁ lβ‚‚, l = l₁++lβ‚‚ ∧ l' = l₁++(a::lβ‚‚) := take q, qeq.induction_on q (Ξ» t, have t = []++t ∧ a::t = []++(a::t), from and.intro rfl rfl, exists.intro [] (exists.intro t this)) (Ξ» b t t' q r, obtain (l₁ lβ‚‚ : list A) (h : t = l₁++lβ‚‚ ∧ t' = l₁++(a::lβ‚‚)), from r, have b::t = (b::l₁)++lβ‚‚ ∧ b::t' = (b::l₁)++(a::lβ‚‚), begin rewrite [and.elim_right h, and.elim_left h], constructor, repeat reflexivity end, exists.intro (b::l₁) (exists.intro lβ‚‚ this)) theorem sub_of_mem_of_sub_of_qeq {a : A} {l : list A} {u v : list A} : a βˆ‰ l β†’ a::l βŠ† v β†’ vβ‰ˆa|u β†’ l βŠ† u := Ξ» (nainl : a βˆ‰ l) (s : a::l βŠ† v) (q : vβ‰ˆa|u) (x : A) (xinl : x ∈ l), have x ∈ v, from s (or.inr xinl), have x ∈ a::u, from mem_cons_of_qeq q x this, or.elim (eq_or_mem_of_mem_cons this) (suppose x = a, by substvars; contradiction) (suppose x ∈ u, this) end qeq section firstn variable {A : Type} definition firstn : nat β†’ list A β†’ list A | 0 l := [] | (n+1) [] := [] | (n+1) (a::l) := a :: firstn n l lemma firstn_zero [simp] : βˆ€ (l : list A), firstn 0 l = [] := by intros; reflexivity lemma firstn_nil [simp] : βˆ€ n, firstn n [] = ([] : list A) | 0 := rfl | (n+1) := rfl lemma firstn_cons : βˆ€ n (a : A) (l : list A), firstn (succ n) (a::l) = a :: firstn n l := by intros; reflexivity lemma firstn_all : βˆ€ (l : list A), firstn (length l) l = l | [] := rfl | (a::l) := begin unfold [length, firstn], rewrite firstn_all end lemma firstn_all_of_ge : βˆ€ {n} {l : list A}, n β‰₯ length l β†’ firstn n l = l | 0 [] h := rfl | 0 (a::l) h := absurd h (not_le_of_gt !succ_pos) | (n+1) [] h := rfl | (n+1) (a::l) h := begin unfold firstn, rewrite [firstn_all_of_ge (le_of_succ_le_succ h)] end lemma firstn_firstn : βˆ€ (n m) (l : list A), firstn n (firstn m l) = firstn (min n m) l | n 0 l := by rewrite [min_zero, firstn_zero, firstn_nil] | 0 m l := by rewrite [zero_min] | (succ n) (succ m) nil := by rewrite [*firstn_nil] | (succ n) (succ m) (a::l) := by rewrite [*firstn_cons, firstn_firstn, min_succ_succ] lemma length_firstn_le : βˆ€ (n) (l : list A), length (firstn n l) ≀ n | 0 l := by rewrite [firstn_zero] | (succ n) (a::l) := by rewrite [firstn_cons, length_cons, add_one]; apply succ_le_succ; apply length_firstn_le | (succ n) [] := by rewrite [firstn_nil, length_nil]; apply zero_le lemma length_firstn_eq : βˆ€ (n) (l : list A), length (firstn n l) = min n (length l) | 0 l := by rewrite [firstn_zero, zero_min] | (succ n) (a::l) := by rewrite [firstn_cons, *length_cons, *add_one, min_succ_succ, length_firstn_eq] | (succ n) [] := by rewrite [firstn_nil] end firstn section dropn variables {A : Type} -- 'dropn n l' drops the first 'n' elements of 'l' definition dropn : β„• β†’ list A β†’ list A | 0 a := a | (succ n) [] := [] | (succ n) (x::r) := dropn n r theorem length_dropn : βˆ€ (i : β„•) (l : list A), length (dropn i l) = length l - i | 0 l := rfl | (succ i) [] := calc length (dropn (succ i) []) = 0 - succ i : nat.zero_sub (succ i) | (succ i) (x::l) := calc length (dropn (succ i) (x::l)) = length (dropn i l) : rfl ... = length l - i : length_dropn i l ... = succ (length l) - succ i : succ_sub_succ (length l) i end dropn section count variable {A : Type} variable [decA : decidable_eq A] include decA definition count (a : A) : list A β†’ nat | [] := 0 | (x::xs) := if a = x then succ (count xs) else count xs lemma count_nil (a : A) : count a [] = 0 := rfl lemma count_cons (a b : A) (l : list A) : count a (b::l) = if a = b then succ (count a l) else count a l := rfl lemma count_cons_eq (a : A) (l : list A) : count a (a::l) = succ (count a l) := if_pos rfl lemma count_cons_of_ne {a b : A} (h : a β‰  b) (l : list A) : count a (b::l) = count a l := if_neg h lemma count_cons_ge_count (a b : A) (l : list A) : count a (b::l) β‰₯ count a l := by_cases (suppose a = b, begin subst b, rewrite count_cons_eq, apply le_succ end) (suppose a β‰  b, begin rewrite (count_cons_of_ne this), apply le.refl end) lemma count_singleton (a : A) : count a [a] = 1 := by rewrite count_cons_eq lemma count_append (a : A) : βˆ€ l₁ lβ‚‚, count a (l₁++lβ‚‚) = count a l₁ + count a lβ‚‚ | [] lβ‚‚ := by rewrite [append_nil_left, count_nil, zero_add] | (b::l₁) lβ‚‚ := by_cases (suppose a = b, by rewrite [-this, append_cons, *count_cons_eq, succ_add, count_append]) (suppose a β‰  b, by rewrite [append_cons, *count_cons_of_ne this, count_append]) lemma count_concat (a : A) (l : list A) : count a (concat a l) = succ (count a l) := by rewrite [concat_eq_append, count_append, count_singleton] lemma mem_of_count_gt_zero : βˆ€ {a : A} {l : list A}, count a l > 0 β†’ a ∈ l | a [] h := absurd h !lt.irrefl | a (b::l) h := by_cases (suppose a = b, begin subst b, apply mem_cons end) (suppose a β‰  b, have count a l > 0, by rewrite [count_cons_of_ne this at h]; exact h, have a ∈ l, from mem_of_count_gt_zero this, show a ∈ b::l, from mem_cons_of_mem _ this) lemma count_gt_zero_of_mem : βˆ€ {a : A} {l : list A}, a ∈ l β†’ count a l > 0 | a [] h := absurd h !not_mem_nil | a (b::l) h := or.elim h (suppose a = b, begin subst b, rewrite count_cons_eq, apply zero_lt_succ end) (suppose a ∈ l, calc count a (b::l) β‰₯ count a l : count_cons_ge_count ... > 0 : count_gt_zero_of_mem this) lemma count_eq_zero_of_not_mem {a : A} {l : list A} (h : a βˆ‰ l) : count a l = 0 := match count a l with | zero := suppose count a l = zero, this | (succ n) := suppose count a l = succ n, absurd (mem_of_count_gt_zero (begin rewrite this, exact dec_trivial end)) h end rfl end count end list attribute list.has_decidable_eq [instance] attribute list.decidable_mem [instance]
lemma connected_iff_eq_connected_component_set: "connected S \<longleftrightarrow> (\<forall>x \<in> S. connected_component_set S x = S)"
-- The "intro" command manages to refine goals of type ∞ A with the -- term β™―Β ?. module IntroSharp where postulate ∞ : βˆ€ {a} (A : Set a) β†’ Set a β™―_ : βˆ€ {a} {A : Set a} β†’ A β†’ ∞ A β™­ : βˆ€ {a} {A : Set a} β†’ ∞ A β†’ A {-# BUILTIN INFINITY ∞ #-} {-# BUILTIN SHARP β™―_ #-} {-# BUILTIN FLAT β™­ #-} Foo : ∞ Set Foo = ?
import number_theory.padics.padic_integers --OUTPUT 1 theorem p_adic_units (p : β„•) (h : prime p) (x : β„•) : coprime x p β†’ is_unit (x : β„•) := begin -- let us prove the contrapositive, that is, is $x$ is not a unit of $\mathbb{Z}_p$, then $x$ is not coprime to $p$. have h1 : Β¬ is_unit (x : β„•) β†’ Β¬ coprime x p, { assume h1 : Β¬ is_unit (x : β„•), assume h2 : coprime x p, have h3 : p ∣ x, from by auto [h1, is_unit_iff_dvd], show false, from by auto [h2, nat.gcd_dvd_left, dvd.refl], }, show is_unit (x : β„•) ∨ Β¬ coprime x p, from by auto [h1] end --OUTPUT 2 theorem p_adic_units_coprime {p n} : p.prime β†’ (p ∣ n) β†’ Β¬ (βˆƒ k, n = p ^ k) := begin assume hp : p.prime, assume hx : p ∣ n, assume hn : βˆƒ k, n = p ^ k, have hn1 : (βˆƒ k, n = p ^ k) β†’ n β‰  0, from by auto [hp.pos, pow_zero], have hn2 : n β‰  0, from hn1 hn, exfalso, from hn2 hx, end --OUTPUT 3 theorem padic_units (p : β„•) (h : prime p) (x : β„•) (h1 : coprime p x) : is_unit (x : β„€_[p]) := begin -- We know that any element of $\mathbb{Z}_p$ is a unit if and only if it has norm 1, thus $\Vert x \Vert \neq 1$. have h2 : is_unit (x : β„€_[p]) ↔ (βˆ₯xβˆ₯ : β„€_[p]) = 1, from by auto [norm_one_iff_is_unit], have h3 : is_unit (x : β„€_[p]) ↔ (βˆ₯xβˆ₯ : β„€_[p]) β‰  0, from by auto [norm_eq_zero_iff], have h4 : (βˆ₯xβˆ₯ : β„€_[p]) = 0 ↔ p ∣ x, from by auto [padic_norm_eq_zero_iff], have h5 : (βˆ₯xβˆ₯ : β„€_[p]) β‰  0 ↔ p ∀ x, from by auto [h4, not_not_intro, exists_eq_mul_right_of_dvd], have h6 : (βˆ₯xβˆ₯ : β„€_[p]) = 1 ↔ p ∀ x, from by auto [h5, h2], have h7 : (βˆ₯xβˆ₯ : β„€_[p]) = 1 ↔ p ∣ x, from by auto [h6, not_not_intro, exists_eq_mul_right_of_dvd], have h8 : (βˆ₯xβˆ₯ : β„€_[p]) = 1, from by auto [h7, h1], have h9 : is_unit (x : β„€_[p]), from by auto [h2, h8], show is_unit (x : β„€_[p]), from h9, end --OUTPUT 4 theorem p_adic_units (p : β„•) [prime p] (x : β„•) (h : x.coprime p) : x.is_unit [Z p] := begin -- Prove the contrapositive have h1 : Β¬ (x.is_unit [Z p]), from by auto [not_not], -- Show that $p$ divides $x$. have h2 : p ∣ x, from by auto [h1, h, p_adic_integers.is_unit_iff_norm_eq_one, p_adic_integers.norm_eq_one_iff_is_unit, p_adic_integers.norm_le_one, p_adic_integers.norm_lt_one_iff_dvd_prime, Zp.setoid, Zp.coe_eq_of_val_eq, Zp.coe_val, Zp.coe_one], -- Show that $x$ is not coprime to $p$. have h3 : Β¬ (x.coprime p), from by auto [h2, dvd_prime], -- Show the contrapositive show x.is_unit [Z p], from by auto [not_not, h1, h3], end --OUTPUT 5 theorem p_adic_units (p : β„•) (x : β„•) (h1 : p.prime) (h2 : nat.coprime x p): nat.units (p_adic_int.padic_norm p x) := begin -- Proving contrapositive: have h3 : Β¬ (p_adic_int.padic_norm p x = 1) β†’ p ∣ x, from by auto [p_adic_int.padic_norm_eq_one_iff], have h4 : Β¬ (p_adic_int.padic_norm p x = 1) β†’ Β¬ nat.coprime x p, from by auto [h3, nat.coprime_dvd_left], have h5 : Β¬ (p_adic_int.padic_norm p x = 1) β†’ Β¬ nat.units (p_adic_int.padic_norm p x), from by auto [h4, nat.units_iff_coprime], have h6 : Β¬ (p_adic_int.padic_norm p x = 1) β†’ Β¬ nat.units (p_adic_int.padic_norm p x), from by auto [h4, nat.units_iff_coprime], show nat.units (p_adic_int.padic_norm p x), from by auto [h6] using [h2], end --OUTPUT 6 theorem p_adic_units {p : β„•} (hp : prime p) (x : β„•) (hx : gcd x p = 1) : is_unit (⟨x, hx⟩ : β„€_[p]) := begin -- Assume that $x$ is not a unit of $\mathbb{Z}_p$ assume h1 : Β¬ is_unit (⟨x, hx⟩ : β„€_[p]), have h2 : Β¬ (norm (⟨x, hx⟩ : β„€_[p]) = 1), from h1, have h3 : norm (⟨x, hx⟩ : β„€_[p]) < 1, from show norm (⟨x, hx⟩ : β„€_[p]) < 1, from by auto [norm_lt_one, h2], have h4 : p ∣ x, from show p ∣ x, from by auto [norm_lt_one, h3], -- But this must imply that $x$ is not coprime to $p$. have h5 : Β¬ gcd x p = 1, from show Β¬ gcd x p = 1, from by auto [h4], show false, from h5 hx, end --OUTPUT 7 theorem p_adic_units (p : β„•) (hp : prime p) (x : β„•) (hx : coprime x p) : βˆƒ y : β„•, x * y = 1 := begin -- prove the contrapositive, that is, is $x$ is not a unit of $\mathbb{Z}_p$, then $x$ is not coprime to $p$. have h1 : Β¬βˆƒ y : β„•, x * y = 1 β†’ Β¬coprime x p, from by auto [nat.not_coprime_iff_dvd], have h2 : Β¬βˆƒ y : β„•, x * y = 1, from by auto [h1, hx], have h3 : βˆ€ y : β„•, x * y β‰  1, from by auto [h2], have h4 : βˆ€ y : β„•, Β¬(x * y = 1), from by auto [h3], have h5 : Β¬βˆƒ y : β„•, x * y = 1, from by auto [h4], -- We know that any element of $\mathbb{Z}_p$ is a unit if and only if it has norm 1, thus $\Vert x \Vert \neq 1$. have h6 : βˆƒ y : β„•, x * y = 1 ↔ βˆƒ y : β„•, x * y = 1, from by auto [exists_congr], have h7 : Β¬βˆƒ y : β„•, x * y = 1 ↔ Β¬(βˆƒ y : β„•, x * y = 1), from by auto [h6], have h8 : Β¬(βˆƒ y : β„•, x * y = 1), from by auto [h7, h5], have h9 : βˆƒ y : β„•, x * y = 1 β†’ false, from by auto [h8], have h10 : Β¬βˆƒ y : β„•, x * y = 1, from by auto [h9], have h11 : Β¬(βˆƒ y : β„•, x * y = 1), from by auto [h10], have h12 : βˆƒ y : β„•, x * y = 1 β†’ false, from by auto [h11], have h13 : βˆ€ y : β„•, Β¬(x * y = 1), from by auto [h12], have h14 : βˆ€ y : β„•, x * y β‰  1, from by auto [h13], have h15 : Β¬βˆƒ y : β„•, x * y = 1, from by auto [h14], have h16 : Β¬(βˆƒ y : β„•, x * y = 1), from by auto [h15], have h17 : βˆƒ y : β„•, x * y = 1 β†’ false, from by auto [h16], have h18 : βˆ€ y : β„•, Β¬(x * y = 1), from by auto [h17], have h19 : βˆ€ y : β„•, x * y β‰  1, from by auto [h18], have h20 : Β¬βˆƒ y : β„•, x * y = 1, from by auto [h19], have h21 : Β¬(βˆƒ y : β„•, x * y = 1), from by auto [h20], have h22 : βˆƒ y : β„•, x * y = 1 β†’ false, from by auto [h21], have h23 : βˆ€ y : β„•, Β¬(x * y = 1), from by auto [h22], have h24 : βˆ€ y : β„•, x * y β‰  1, from by auto [h23], have h25 : Β¬βˆƒ y : β„•, x * y = 1, from by auto [h24], have h26 : Β¬(βˆƒ y : β„•, x * y = 1), from by auto [h25], have h27 : βˆƒ y : β„•, x * y = 1 β†’ false, from by auto [h26], have h28 : βˆ€ y : β„•, Β¬(x * y = 1), from by auto [h27], have h29 : βˆ€ y : β„•, x * y β‰  1, from by auto [h28], have h30 : Β¬βˆƒ y : β„•, x * y = 1, from by auto [h29], have h31 : Β¬(βˆƒ y : β„•, x * y = 1), from by auto [h30], have h32 : βˆƒ y : β„•, x * y = 1 β†’ false, from by auto [h31], have h33 : βˆ€ y : β„•, Β¬(x * y = 1), from by auto [h32], have h34 : βˆ€ y : β„•, x * y β‰  1, from by auto [h33], have h35 : Β¬βˆƒ y : β„•, x * y = 1, from by auto [h34], have h36 : Β¬(βˆƒ y : β„•, x * y = 1), from by auto [h35], have h37 : βˆƒ y : β„•, x * y = 1 β†’ false, from by auto [h36], have h38 : βˆ€ y : β„•, Β¬(x * y = 1), from by auto [h37], have h39 : βˆ€ y : β„•, x * y β‰  1, from by auto [h38], have h40 : Β¬βˆƒ y : β„•, x * y = 1, from by auto [h39], have h41 : Β¬(βˆƒ y : β„•, x * y = 1), from by auto [h40], have h42 : βˆƒ y : β„•, x * y = 1 β†’ false, from by auto [h41], have h43 : βˆ€ y : β„•, Β¬(x * y = 1), from by auto [h42], have h44 : βˆ€ y : β„•, x * y β‰  1, from by auto [h43], have h45 : Β¬βˆƒ y : β„•, x * y = 1, from by auto [h44], have h46 : Β¬(βˆƒ y : β„•, x * y = 1), from by auto [h45], have h47 : βˆƒ y : β„•, x * y = 1 β†’ false, from by auto [h46], have h48 : βˆ€ y : β„•, Β¬(x * y = 1), from by auto [h47], have h49 : βˆ€ y : β„•, x * y β‰  1, from by auto [h48], have h50 : Β¬βˆƒ y : β„•, x * y = 1, from by auto [h49], have h51 : Β¬(βˆƒ y : β„•, x * y = 1), from by auto [h50], have h52 : βˆƒ y : β„•, x * y = 1 β†’ false, from by auto [h51], have h53 : βˆ€ y : β„•, Β¬(x * y = 1), from by auto [h52], have h54 : βˆ€ y : β„•, x * y β‰  1, from by auto [h53], have h55 : Β¬βˆƒ y : β„•, x * y = 1, from by auto [h54], have h56 : Β¬(βˆƒ y : β„•, x * y = 1), from by auto [h55], have h57 : βˆƒ y : β„•, x * y = 1 β†’ false, from by auto [h56], have h58 : βˆ€ y : β„•, Β¬(x * y = 1), from by auto [h57], have h59 : βˆ€ y : β„•, x * y β‰  1, from by auto [h58], have h60 : Β¬βˆƒ y : β„•, x * y = 1, from by auto [h59], have h61 : Β¬(βˆƒ y : β„•, x * y = 1), from by auto [h60], have h62 : βˆƒ y : β„•, x * y = 1 β†’ false, from by auto end --Needs more than 2000 tokens! --OUTPUT 8 theorem p_adic_units (p : β„•) (x : β„•) : gcd x p = 1 β†’ x ∈ units (p_adic_int p) := begin intro h1, have h2 : x ∈ units (p_adic_int p), from by auto [p_adic_int.units], show x ∈ units (p_adic_int p), from by auto [h1, h2], end /- FEW SHOT PROMPTS TO CODEX(START) /--`theorem` Power Set is Closed under Intersection Let $S$ be a set. Let $\powerset S$ be the power set of $S$. Then: :$\forall A, B \in \powerset S: A \cap B \in \powerset S$ `proof` Let $A, B \in \powerset S$. Then by the definition of power set, $A \subseteq S$ and $B \subseteq S$. From Intersection is Subset we have that $A \cap B \subseteq A$. It follows from Subset Relation is Transitive that $A \cap B \subseteq S$. Thus $A \cap B \in \powerset S$ and closure is proved. {{qed}} -/ theorem power_set_intersection_closed {Ξ± : Type*} (S : set Ξ±) : βˆ€ A B ∈ 𝒫 S, (A ∩ B) ∈ 𝒫 S := begin -- $A$ and $B$ are sets. $A$ and $B$ belong to power set of $S$ assume (A : set Ξ±) (hA : A ∈ 𝒫 S) (B : set Ξ±) (hB : B ∈ 𝒫 S), -- Then $A βŠ† S$ and $B βŠ† S$, by power set definition have h1 : (A βŠ† S) ∧ (B βŠ† S), from by auto [set.subset_of_mem_powerset, set.subset_of_mem_powerset], -- Then $(A ∩ B) βŠ† A$, by intersection of set is a subset have h2 : (A ∩ B) βŠ† A, from by auto [set.inter_subset_left], -- Then $(A ∩ B) βŠ† S$, by subset relation is transitive have h3 : (A ∩ B) βŠ† S, from by auto [set.subset.trans], -- Hence $(A ∩ B) ∈ 𝒫 S$, by power set definition show (A ∩ B) ∈ 𝒫 S, from by auto [set.mem_powerset], end /--`theorem` Square of Sum :$\forall x, y \in \R: \paren {x + y}^2 = x^2 + 2 x y + y^2$ `proof` Follows from the distribution of multiplication over addition: {{begin-eqn}} {{eqn | l = \left({x + y}\right)^2 | r = \left({x + y}\right) \cdot \left({x + y}\right) }} {{eqn | r = x \cdot \left({x + y}\right) + y \cdot \left({x + y}\right) | c = Real Multiplication Distributes over Addition }} {{eqn | r = x \cdot x + x \cdot y + y \cdot x + y \cdot y | c = Real Multiplication Distributes over Addition }} {{eqn | r = x^2 + 2xy + y^2 | c = }} {{end-eqn}} {{qed}} -/ theorem square_of_sum (x y : ℝ) : (x + y)^2 = (x^2 + 2*x*y + y^2) := begin -- expand the power calc (x + y)^2 = (x+y)*(x+y) : by auto [sq] -- distributive property of multiplication over addition gives: ... = x*(x+y) + y*(x+y) : by auto [add_mul] -- applying the above property further gives: ... = x*x + x*y + y*x + y*y : by auto [mul_comm, add_mul] using [ring] -- rearranging the terms using commutativity and adding gives: ... = x^2 + 2*x*y + y^2 : by auto [sq, mul_comm] using [ring] end /--`theorem` Identity of Group is Unique Let $\struct {G, \circ}$ be a group. Then there is a unique identity element $e \in G$. `proof` From Group has Latin Square Property, there exists a unique $x \in G$ such that: :$a x = b$ and there exists a unique $y \in G$ such that: :$y a = b$ Setting $b = a$, this becomes: There exists a unique $x \in G$ such that: :$a x = a$ and there exists a unique $y \in G$ such that: :$y a = a$ These $x$ and $y$ are both $e$, by definition of identity element. {{qed}} -/ theorem group_identity_unique {G : Type*} [group G] : βˆƒ! e : G, βˆ€ a : G, e * a = a ∧ a * e = a := begin -- Group has Latin Square Property have h1 : βˆ€ a b : G, βˆƒ! x : G, a * x = b, from by auto using [use (a⁻¹ * b)], have h2 : βˆ€ a b : G, βˆƒ! y : G, y * a = b, from by auto using [use b * a⁻¹], -- Setting $b = a$, this becomes: have h3 : βˆ€ a : G, βˆƒ! x : G, a * x = a, from by auto [h1], have h4 : βˆ€ a : G, βˆƒ! y : G, y * a = a, from by auto [h2], -- These $x$ and $y$ are both $(1 : G)$, by definition of identity element have h5 : βˆ€ a : G, classical.some (h3 a).exists = (1 : G), from by auto [exists_unique.unique, h3, classical.some_spec, exists_unique.exists, mul_one], have h6 : βˆ€ a : G, classical.some (h4 a).exists = (1 : G), from by auto [exists_unique.unique, h4, classical.some_spec, exists_unique.exists, one_mul], show βˆƒ! e : G, βˆ€ a : G, e * a = a ∧ a * e = a, from by auto [h3, h4, exists_unique.unique, classical.some_spec, exists_unique.exists] using [use (1 : G)], end /--`theorem` p-adic units Given a prime number $p$ and a natural number $x$, if $x$ is coprime to $p$, then $x$ is a unit in the $p$-adic integers. `proof` Let us prove the contrapositive, that is, is $x$ is not a unit of $\mathbb{Z}_p$, then $x$ is not coprime to $p$. We know that any element of $\mathbb{Z}_p$ is a unit if and only if it has norm 1, thus $\Vert x \Vert \neq 1$. Also, since every element of $\mathbb{Z}_p$ must have norm less than or equal to 1, we conclude that $\Vert x \Vert < 1$. But this must imply that $p | x$. This completes our proof. QED -/ theorem FEW SHOT PROMPTS TO CODEX(END)-/
-- modular arithmetic module nat-mod where open import eq open import nat infix 8 _≑_mod_ data _≑_mod_ : β„• β†’ β„• β†’ β„• β†’ Set where mod-refl : βˆ€ {n k} β†’ n ≑ n mod k mod-add : βˆ€ {n m k} β†’ n ≑ m mod k β†’ n + k ≑ m mod k mod-symm : βˆ€ {n m k} β†’ n ≑ m mod k β†’ m ≑ n mod k {- mod-trans : βˆ€ {n m o k} β†’ n ≑ m mod k β†’ m ≑ o mod k β†’ n ≑ o mod k mod-trans{n}{.n}{o}{k} mod-refl p2 = {!!} mod-trans}{m}{o}{k} (mod-add p1) p2 = {!!} mod-trans{n}{m}{o}{k} (mod-symm p1) p2 = {!!} -}
module StringLiterals hello : FromString a => a hello = "Hello" helloName : String -> String helloName name = "\{hello {a = String}} \{name}" welcomeName : String -> String welcomeName name = """ \{helloName name} and welcome! """ scareQuotes : String scareQuotes = #""hello""# test : StringLiterals.scareQuotes = "\"hello\"" test = Refl
During World War I , ZrΓ­nyi saw action in the Adriatic Sea . She served with the Second Division of the Austro @-@ Hungarian Navy 's battleships and shelled Senigallia as part of the bombardment of the key seaport of Ancona , Italy , during May 1915 . However , Allied control of the Strait of Otranto meant that the Austro @-@ Hungarian Navy was , for all intents and purposes , effectively bottled up in the Adriatic . Nonetheless , the presence of the ZrΓ­nyi and other battleships tied down a substantial force of Allied ships .
# Copyright (c) 2018-2021, Carnegie Mellon University # See LICENSE for details ######################################################################## # vector constructs ######################################################################## IsSIMD_ISA := s -> IsRec(s) and IsBound(s.isSIMD_ISA) and s.isSIMD_ISA; IsISA := x -> IsRec(x) and IsBound(x.isISA) and x.isISA; Class(AVecReg, AGenericTag, rec( isReg := true, isRegCx := false, isVec := true, updateParams := meth(self) Checked(IsSIMD_ISA(self.params[1])); Checked(Length(self.params)=1); self.v := self.params[1].v; self.isa := self.params[1]; end, container := (self, spl) >> paradigms.vector.sigmaspl.VContainer(spl, self.isa) )); Class(AVecRegCx, AVecReg, rec( updateParams := meth(self) Checked(IsSIMD_ISA(self.params[1])); Checked(Length(self.params)=1); self.v := self.params[1].v/2; self.isa := self.params[1]; end, container := (self, spl) >> paradigms.vector.sigmaspl.VContainer(spl, self.isa.cplx()), isRegCx := true )); # AMultiVec - list of ISAs, must be list of AVecReg tags in the future # Class(AMultiVec, AGenericTag, rec( isVec := true, updateParams := meth(self) Checked(ForAll(self.params, IsSIMD_ISA)); Checked(Length(self.params)>=1); end, )); Class(AISA, AGenericTag, rec( updateParams := meth(self) Checked(IsISA(self.params[1])); Checked(Length(self.params)=1); self.isa := self.params[1]; end, # it's not a vectorized code, maybe defferent kind of containers? # containers do not go along well with OL though container := (self, spl) >> paradigms.vector.sigmaspl.VContainer(spl, self.isa) ));
Formal statement is: lemma in_bigomega_zero [simp]: "f \<in> \<Omega>[F](\<lambda>x. 0)" Informal statement is: If $f$ is a function, then $f \in \Omega[F](0)$.
Lemma impl_and_iff {A B C} : (A -> (B /\ C)) <-> ((A -> B) /\ (A -> C)). Proof. tauto. Qed.
rebol [title: "test dragbar"] ;- . ;----------------------------------------------------------------------------------------------------------- ; ;- LIBS ; ;----------------------------------------------------------------------------------------------------------- glass-root-path: clean-path %../ ;---- ; start the slim library manager, if it's not setup in your user.r file ; ; the following loading setup allows us to get slim and various packages in a variety of places easily ; and with no discreet setup. ; ; they can be: ; - Installed within the glass project ; - Installed at the same level as glass itself ; - Installed anywhere else, in this case just create a file called slim-path-setup.r within ; the root of the glass project and fill it with a single Rebol formatted path which points to ; the location of your slim.r script. ; ; if you have GIT installed, you can use a script called get-git-slim-libs.r script to retrieve the latest versions ; of the various slim library packages. Find the steel project (rebol dev tools) on github to get this script. ; ; if you go to github.com, you can get slim and all libs without GIT using a manual download link ; for each slim package which gives you a .zip of all the files its repository contains. ;---- unless value? 'slim [ do any [ all [ exists? glass-root-path/slim-path-setup.r do read glass-root-path/slim-path-setup.r ] all [ exists? glass-root-path/../slim-libs/slim/slim.r glass-root-path/../slim-libs/slim/slim.r ] all [ exists? glass-root-path/slim-libs/slim/slim.r glass-root-path/slim-libs/slim/slim.r ] ] ] slim/vexpose ;- . ;----------------------------------------------------------------------------------------------------------- ; ;- LIBS ; ;----------------------------------------------------------------------------------------------------------- gl: slim/open/expose 'glass none [ screen-size request-string request-inform discard ] liquid-lib: slim/open/expose 'liquid none [ fill liquify content dirty !plug link unlink processor detach attach insubordinate] slim/open/expose 'bulk none [ make-bulk clear-bulk ] barlib: slim/open 'style-dragbar none barlib/von von ;- . ;----------------------------------------------------------------------------------------------------------- ; ;- GUI ; ;----------------------------------------------------------------------------------------------------------- gl/layout compose/deep [ row [ column stiff tight adjust 300x0 [ lst: scrolled-list [] (make-bulk 3) stiff-x 120x200 ] dragbar column [ fld: field "enter value" row tight [ label "Color" 40 fld-clr: field "255.0.0" button stiff 20x20 (200.0.255) (200.0.255) "" [fill fld-clr/aspects/label "200.0.255"] button stiff 20x20 (blue) (blue) "" [fill fld-clr/aspects/label "0.0.255"] button stiff 20x20 (0.180.200) (0.180.200) "" [fill fld-clr/aspects/label "0.180.200"] button stiff 20x20 (green) (green) "" [fill fld-clr/aspects/label "0.255.0"] button stiff 20x20 (yellow) (yellow) "" [fill fld-clr/aspects/label "255.255.0"] button stiff 20x20 (orange) (orange) "" [fill fld-clr/aspects/label "255.150.10"] button stiff 20x20 (red) (red) "" [fill fld-clr/aspects/label "255.0.0"] ] button "add" [ append content lst/aspects/items reduce [ data: copy content fld/aspects/label reduce [ any [attempt [to-tuple content fld-clr/aspects/label] black ] ] data ] dirty lst/aspects/items probe head content lst/aspects/items ] button "remove" [ lst/list-marble/valve/delete-chosen lst/list-marble ] ] ] ] do-events
classdef FWModes enumeration FAT32_ZIP, DISK_IMAGE end end
section {* ICTAC 2016 tutorial. Taipei, 24/10/2016 *} theory ictac16_tutorial imports "../theories/utp_designs" begin subsection {* Laws of programming *} theorem cond_shadow: "(P \<triangleleft> b \<triangleright> (Q \<triangleleft> b \<triangleright> R)) = (P \<triangleleft> b \<triangleright> R)" oops theorem seqr_assoc: "(P ;; (Q ;; R)) = ((P ;; Q) ;; R)" oops theorem seqr_left_unit: "(II ;; P) = P" oops theorem seqr_left_zero: "(false ;; P) = false" oops theorem cond_seq_left_distr: assumes "out\<alpha> \<sharp> b" shows "((P \<triangleleft> b \<triangleright> Q) ;; R) = ((P ;; R) \<triangleleft> b \<triangleright> (Q ;; R))" using assms by (rel_simp, blast+) theorem assign_twice: assumes "vwb_lens x" "x \<sharp> f" shows "(x := e ;; x := f) = (x := f)" using assms by rel_auto theorem assign_commute: assumes "x \<bowtie> y" "x \<sharp> f" "y \<sharp> e" shows "(x := e ;; y := f) = (y := f ;; x := e)" using assms by (rel_auto, simp_all add: lens_indep_comm) subsection {* Design laws *} theorem design_false_pre: "(false \<turnstile> P) = true" by rel_auto theorem design_true_left_zero: "(true ;; (P \<turnstile> Q)) = true" proof - have "(true ;; (P \<turnstile> Q)) = (\<^bold>\<exists> ok\<^sub>0 \<bullet> true\<lbrakk>\<guillemotleft>ok\<^sub>0\<guillemotright>/$ok\<acute>\<rbrakk> ;; (P \<turnstile> Q)\<lbrakk>\<guillemotleft>ok\<^sub>0\<guillemotright>/$ok\<rbrakk>)" by (subst seqr_middle[of ok], simp_all) also have "... = ((true\<lbrakk>false/$ok\<acute>\<rbrakk> ;; (P \<turnstile> Q)\<lbrakk>false/$ok\<rbrakk>) \<or> (true\<lbrakk>true/$ok\<acute>\<rbrakk> ;; (P \<turnstile> Q)\<lbrakk>true/$ok\<rbrakk>))" by (simp add: disj_comm false_alt_def true_alt_def) also have "... = ((true\<lbrakk>false/$ok\<acute>\<rbrakk> ;; true\<^sub>h) \<or> (true ;; ((P \<turnstile> Q)\<lbrakk>true/$ok\<rbrakk>)))" by (subst_tac, rel_auto) also have "... = true" by (subst_tac, simp add: precond_right_unit unrest) finally show ?thesis . qed theorem rdesign_left_unit: fixes P Q :: "'\<alpha> hrel_des" shows "II\<^sub>D ;; (P \<turnstile>\<^sub>r Q) = (P \<turnstile>\<^sub>r Q)" proof - -- {* We first expand out the definition of the design identity *} have "II\<^sub>D ;; (P \<turnstile>\<^sub>r Q) = (true \<turnstile>\<^sub>r II) ;; (P \<turnstile>\<^sub>r Q)" by (simp add: skip_d_def) -- {* Next, we apply the design composition law above in a subproof *} also have "... = (true \<and> \<not> (II ;; (\<not> P))) \<turnstile>\<^sub>r (II ;; Q)" proof - -- {* The assumption of identity is $\true$ so it is easy to discharge the proviso *} have "out\<alpha> \<sharp> true" by unrest_tac -- {* From this we can apply the composition law *} thus ?thesis using rdesign_composition_cond by blast qed -- {* Simplification then allows us to remove extraneous terms *} also have "... = (\<not> (\<not> P)) \<turnstile>\<^sub>r Q" by simp -- {* Finally, we can show the thesis *} finally show ?thesis by simp qed subsection {* Program example *} alphabet my_state = x :: int y :: int z :: int lemma "(x := 1 ;; x := (&x + 1)) = (x := 2)" oops lemma "($x\<acute> >\<^sub>u $x \<and> $y\<acute> <\<^sub>u $y) \<sqsubseteq> x, y := &x + 1, &y" oops lemma "(x := 1 ;; (y := 7 \<triangleleft> $x >\<^sub>u 0 \<triangleright> y := 8)) = ((x,y) := (1,7))" oops (* Need following law: *) theorem ndesign_composition_wp: "((p1 \<turnstile>\<^sub>n Q1) ;; (p2 \<turnstile>\<^sub>n Q2)) = ((p1 \<and> Q1 wp p2) \<turnstile>\<^sub>n (Q1 ;; Q2))" oops lemma violate_precond: "(true \<turnstile>\<^sub>n x := 1) ;; ((&x >\<^sub>u 1) \<turnstile>\<^sub>n y := 2) = \<bottom>\<^sub>D" apply (subst ndesign_composition_wp) apply (simp) apply (wp_tac) apply (subst_tac) apply (rel_auto) done end
From iris.base_logic.lib Require Import invariants. From BurrowLang Require Import lang simp adequacy primitive_laws. From Tpcms Require Import rwlock. Require Import Burrow.tpcms. Require Import Burrow.ra. Require Import Burrow.trees. Require Import cpdt.CpdtTactics. Require Import Burrow.tactics. Require Import Tpcms.auth_frag. From iris.base_logic Require Export base_logic. From iris.program_logic Require Export weakestpre. From iris.proofmode Require Import tactics. From iris.program_logic Require Import ectx_lifting. From BurrowLang Require Import notation tactics class_instances. From BurrowLang Require Import heap_ra. From BurrowLang Require Import lang. From iris Require Import options. (* really crummy sequence library *) Definition seq_idx : lang.val := (rec: "seq_idx" "i" "array" := if: (BinOp EqOp "i" #0) then Fst "array" else "seq_idx" ("i" + #(-1)) (Snd "array") ). Fixpoint has_elem (v: lang.val) (i: nat) : Prop := match i, v with | O, (PairV l _ ) => True | S i, (PairV _ r ) => has_elem r i | _, _ => False end. Definition has_length (v: lang.val) (len: nat) : Prop := match len with | O => True | S j => has_elem v j end. Lemma has_elem_of_has_elem : βˆ€ (j: nat) (i: nat) (v: lang.val) (lt: i ≀ j) , has_elem v j -> has_elem v i. Proof. induction j. - intros. assert (@eq nat i%nat 0%nat) by lia. subst i. trivial. - intros. destruct v. + cbn [has_elem] in H. contradiction. + cbn [has_elem] in H. contradiction. + cbn [has_elem] in H. destruct i. * unfold has_elem. trivial. * cbn [has_elem]. apply IHj; trivial. lia. Qed. Lemma has_elem_of_has_length : βˆ€ (len: nat) (v: lang.val) (i: nat) (lt: i < len) , has_length v len -> has_elem v i. Proof. intros. unfold has_length in H. destruct len. - lia. - apply has_elem_of_has_elem with (j := len); trivial. lia. Qed. Fixpoint elem (v: lang.val) (i: nat) := match i, v with | O, (PairV l _ ) => l | S i, (PairV _ r ) => elem r i | _, _ => #() end. Section SeqProof. Context `{heap_hastpcm: !HasTPCM πœ‡ (AuthFrag (gmap loc (option lang.val)))}. Context `{!simpGS πœ‡ Ξ£}. Lemma wp_seq_idx (seq: lang.val) (i: nat) (he: has_elem seq i) : {{{ True }}} seq_idx #i seq {{{ RET (elem seq i); True }}}. Proof. iIntros (P) "_ P". unfold seq_idx. wp_pures. generalize he. generalize i. clear he. clear i. induction seq; intros i he. - cbn [has_elem] in he. destruct i; contradiction. - cbn [has_elem] in he. destruct i; contradiction. - cbn [has_elem] in he. destruct i. + wp_pures. unfold elem. iModIntro. iApply "P". trivial. + wp_pures. replace ((Z.add (S i) (Zneg xH))) with (i : Z) by lia. cbn [elem]. apply IHseq2; trivial. Qed. End SeqProof.
import data.matrix.block namespace matrix open_locale matrix variables {l m Ξ± R : Type*} variables [decidable_eq l] [decidable_eq m] section has_zero variables [has_zero Ξ±] lemma to_block_diagonal_self (d : m β†’ Ξ±) (p : m β†’ Prop) : matrix.to_block (diagonal d) p p = diagonal (Ξ» i : subtype p, d ↑i) := begin ext i j, by_cases i = j, { simp [h] }, { simp [has_one.one, h, Ξ» h', h $ subtype.ext h'], } end lemma to_block_diagonal_disjoint (d : m β†’ Ξ±) {p q : m β†’ Prop} (hpq : disjoint p q) : matrix.to_block (diagonal d) p q = 0 := begin ext ⟨i, hi⟩ ⟨j, hj⟩, have : i β‰  j, from Ξ» heq, hpq i ⟨hi, heq.symm β–Έ hj⟩, simp [diagonal_apply_ne d this] end end has_zero section has_zero_has_one variables [has_zero Ξ±] [has_one Ξ±] lemma to_block_one_self (p : m β†’ Prop) : matrix.to_block (1 : matrix m m Ξ±) p p = 1 := to_block_diagonal_self _ p lemma to_block_one_disjoint {p q : m β†’ Prop} (hpq : disjoint p q) : matrix.to_block (1 : matrix m m Ξ±) p q = 0 := to_block_diagonal_disjoint _ hpq end has_zero_has_one section variables [comm_ring R] lemma to_block_mul_eq_mul {m n k : Type*} [fintype n] (p : m β†’ Prop) (q : k β†’ Prop) (A : matrix m n R) (B : matrix n k R) : (A ⬝ B).to_block p q = A.to_block p ⊀ ⬝ B.to_block ⊀ q := begin ext i k, simp only [to_block_apply, mul_apply], rw finset.sum_subtype, simp [has_top.top, complete_lattice.top, bounded_order.top], end lemma to_block_mul_eq_add {m n k : Type*} [fintype n] (p : m β†’ Prop) (q : n β†’ Prop) [decidable_pred q] (r : k β†’ Prop) (A : matrix m n R) (B : matrix n k R) : (A ⬝ B).to_block p r = A.to_block p q ⬝ B.to_block q r + A.to_block p (Ξ» i, Β¬ q i) ⬝ B.to_block (Ξ» i, Β¬ q i) r := begin classical, ext i k, simp only [to_block_apply, mul_apply, pi.add_apply], convert (fintype.sum_subtype_add_sum_subtype q (Ξ» x, A ↑i x * B x ↑k)).symm end end end matrix
Check 0. Check nat. Check Set. Check Type. Check forall T : Set, T. Check forall T : Type, T. Definition id (T : Type) (x : T) : T := x. Set Printing Universes. Inductive exp : Type -> Type := | Const : forall T, T -> exp T | Pair : forall T1 T2, exp T1 -> exp T2 -> exp (T1 * T2) | Eq : forall T, exp T -> exp T -> exp bool. Print exp. Check (nat, (Type, Set)). Inductive prod' : Type -> Type -> Type := | pair' : forall A B : Type, A -> B -> prod' A B. Inductive foo (A : Type) : Type := | Foo : A -> foo A. Check foo nat. Check foo Set. Check foo Type. Check foo True. Inductive bar : Type := Bar : bar. Check Bar. Check bar. Print sig. Print ex. Definition projS A (P : A -> Prop) (x : sig P) : A := match x with | exist _ v _ => v end. Definition churchnat := forall X : Prop, (X -> X) -> X -> X. Definition two : churchnat := fun (X : Prop) (f : X -> X) (x : X) => f (f x). Definition three : churchnat := fun (X : Prop) (f : X -> X) (x : X) => f (f (f x)). Definition succ (n : churchnat) : churchnat := fun (X : Prop) (f : X -> X) (x : X) => f (n X f x). Example succ_2 : succ two = three. Proof. reflexivity. Qed. Definition plus (n m : churchnat) : churchnat := n _ succ m. Example plus_2 : plus two three = plus three two. Proof. reflexivity. Qed. Definition projE A (P : A -> Prop) (x : ex P) : A := match x with | ex_intro _ v _ => v end.
Require Import Frap Setoid Classes.Morphisms SepCancel. Set Implicit Arguments. Set Asymmetric Patterns. (** * Shared notations and definitions; main material starts afterward. *) Notation heap := (fmap nat nat). Notation locks := (set nat). Local Hint Extern 1 (_ <= _) => linear_arithmetic : core. Local Hint Extern 1 (@eq nat _ _) => linear_arithmetic : core. Ltac simp := repeat (simplify; subst; propositional; try match goal with | [ H : ex _ |- _ ] => invert H end); try linear_arithmetic. (** * A shared-memory concurrent language with loops *) Inductive loop_outcome acc := | Done (a : acc) | Again (a : acc). Definition valueOf {A} (o : loop_outcome A) := match o with | Done v => v | Again v => v end. Inductive cmd : Set -> Type := | Return {result : Set} (r : result) : cmd result | Fail {result} : cmd result | Bind {result result'} (c1 : cmd result') (c2 : result' -> cmd result) : cmd result | Loop {acc : Set} (init : acc) (body : acc -> cmd (loop_outcome acc)) : cmd acc | Read (a : nat) : cmd nat | Write (a v : nat) : cmd unit | Lock (a : nat) : cmd unit | Unlock (a : nat) : cmd unit | Alloc (numWords : nat) : cmd nat | Free (base numWords : nat) : cmd unit | Par (c1 c2 : cmd unit) : cmd unit. Notation "x <- c1 ; c2" := (Bind c1 (fun x => c2)) (right associativity, at level 80). Notation "'for' x := i 'loop' c1 'done'" := (Loop i (fun x => c1)) (right associativity, at level 80). Infix "||" := Par. Fixpoint initialize (h : heap) (base numWords : nat) : heap := match numWords with | O => h | S numWords' => initialize h base numWords' $+ (base + numWords', 0) end. Fixpoint deallocate (h : heap) (base numWords : nat) : heap := match numWords with | O => h | S numWords' => deallocate (h $- base) (base+1) numWords' end. Inductive step : forall A, heap * locks * cmd A -> heap * locks * cmd A -> Prop := | StepBindRecur : forall result result' (c1 c1' : cmd result') (c2 : result' -> cmd result) h l h' l', step (h, l, c1) (h', l', c1') -> step (h, l, Bind c1 c2) (h', l', Bind c1' c2) | StepBindProceed : forall (result result' : Set) (v : result') (c2 : result' -> cmd result) h l, step (h, l, Bind (Return v) c2) (h, l, c2 v) | StepLoop : forall (acc : Set) (init : acc) (body : acc -> cmd (loop_outcome acc)) h l, step (h, l, Loop init body) (h, l, o <- body init; match o with | Done a => Return a | Again a => Loop a body end) | StepRead : forall h l a v, h $? a = Some v -> step (h, l, Read a) (h, l, Return v) | StepWrite : forall h l a v v', h $? a = Some v -> step (h, l, Write a v') (h $+ (a, v'), l, Return tt) | StepAlloc : forall h l numWords a, a <> 0 -> (forall i, i < numWords -> h $? (a + i) = None) -> step (h, l, Alloc numWords) (initialize h a numWords, l, Return a) | StepFree : forall h l a numWords, step (h, l, Free a numWords) (deallocate h a numWords, l, Return tt) | StepLock : forall h l a, ~a \in l -> step (h, l, Lock a) (h, l \cup {a}, Return tt) | StepUnlock : forall h l a, a \in l -> step (h, l, Unlock a) (h, l \setminus {a}, Return tt) | StepPar1 : forall h l c1 c2 h' l' c1', step (h, l, c1) (h', l', c1') -> step (h, l, Par c1 c2) (h', l', Par c1' c2) | StepPar2 : forall h l c1 c2 h' l' c2', step (h, l, c2) (h', l', c2') -> step (h, l, Par c1 c2) (h', l', Par c1 c2'). Definition trsys_of (h : heap) (l : locks) {result} (c : cmd result) := {| Initial := {(h, l, c)}; Step := step (A := result) |}. Module Import S <: SEP. Definition hprop := heap -> Prop. (* We add the locks to the mix. *) Definition himp (p q : hprop) := forall h, p h -> q h. Definition heq (p q : hprop) := forall h, p h <-> q h. (* Lifting a pure proposition: it must hold, and the heap must be empty. *) Definition lift (P : Prop) : hprop := fun h => P /\ h = $0. (* Separating conjunction, one of the two big ideas of separation logic. * When does [star p q] apply to [h]? When [h] can be partitioned into two * subheaps [h1] and [h2], respectively compatible with [p] and [q]. See book * module [Map] for definitions of [split] and [disjoint]. *) Definition star (p q : hprop) : hprop := fun h => exists h1 h2, split h h1 h2 /\ disjoint h1 h2 /\ p h1 /\ q h2. (* Existential quantification *) Definition exis A (p : A -> hprop) : hprop := fun h => exists x, p x h. (* Convenient notations *) Notation "[| P |]" := (lift P) : sep_scope. Infix "*" := star : sep_scope. Notation "'exists' x .. y , p" := (exis (fun x => .. (exis (fun y => p)) ..)) : sep_scope. Delimit Scope sep_scope with sep. Notation "p === q" := (heq p%sep q%sep) (no associativity, at level 70). Notation "p ===> q" := (himp p%sep q%sep) (no associativity, at level 70). Local Open Scope sep_scope. (* And now we prove some key algebraic properties, whose details aren't so * important. The library automation uses these properties. *) Lemma iff_two : forall A (P Q : A -> Prop), (forall x, P x <-> Q x) -> (forall x, P x -> Q x) /\ (forall x, Q x -> P x). Proof. firstorder. Qed. Local Ltac t := (unfold himp, heq, lift, star, exis; propositional; subst); repeat (match goal with | [ H : forall x, _ <-> _ |- _ ] => apply iff_two in H | [ H : ex _ |- _ ] => destruct H | [ H : split _ _ $0 |- _ ] => apply split_empty_fwd in H end; propositional; subst); eauto 15. Theorem himp_heq : forall p q, p === q <-> (p ===> q /\ q ===> p). Proof. t. Qed. Theorem himp_refl : forall p, p ===> p. Proof. t. Qed. Theorem himp_trans : forall p q r, p ===> q -> q ===> r -> p ===> r. Proof. t. Qed. Theorem lift_left : forall p (Q : Prop) r, (Q -> p ===> r) -> p * [| Q |] ===> r. Proof. t. Qed. Theorem lift_right : forall p q (R : Prop), p ===> q -> R -> p ===> q * [| R |]. Proof. t. Qed. Local Hint Resolve split_empty_bwd' : core. Theorem extra_lift : forall (P : Prop) p, P -> p === [| P |] * p. Proof. t. apply split_empty_fwd' in H1; subst; auto. Qed. Theorem star_comm : forall p q, p * q === q * p. Proof. t. Qed. Theorem star_assoc : forall p q r, p * (q * r) === (p * q) * r. Proof. t. Qed. Theorem star_cancel : forall p1 p2 q1 q2, p1 ===> p2 -> q1 ===> q2 -> p1 * q1 ===> p2 * q2. Proof. t. Qed. Theorem exis_gulp : forall A p (q : A -> _), p * exis q === exis (fun x => p * q x). Proof. t. Qed. Theorem exis_left : forall A (p : A -> _) q, (forall x, p x ===> q) -> exis p ===> q. Proof. t. Qed. Theorem exis_right : forall A p (q : A -> _) x, p ===> q x -> p ===> exis q. Proof. t. Qed. End S. Export S. (* Instantiate our big automation engine to these definitions. *) Module Import Se := SepCancel.Make(S). (* ** Some extra predicates outside the set that the engine knows about *) (* Capturing single-mapping heaps *) Definition heap1 (a v : nat) : heap := $0 $+ (a, v). Definition ptsto (a v : nat) : hprop := fun h => h = heap1 a v. (* Helpful notations, some the same as above *) Notation "[| P |]" := (lift P) : sep_scope. Notation emp := (lift True). Infix "*" := star : sep_scope. Notation "'exists' x .. y , p" := (exis (fun x => .. (exis (fun y => p)) ..)) : sep_scope. Delimit Scope sep_scope with sep. Notation "p === q" := (heq p%sep q%sep) (no associativity, at level 70). Notation "p ===> q" := (himp p%sep q%sep) (no associativity, at level 70). Infix "|->" := ptsto (at level 30) : sep_scope. Fixpoint multi_ptsto (a : nat) (vs : list nat) : hprop := match vs with | nil => emp | v :: vs' => a |-> v * multi_ptsto (a + 1) vs' end%sep. Infix "|-->" := multi_ptsto (at level 30) : sep_scope. Fixpoint zeroes (n : nat) : list nat := match n with | O => nil | S n' => zeroes n' ++ 0 :: nil end. Fixpoint allocated (a n : nat) : hprop := match n with | O => emp | S n' => (exists v, a |-> v) * allocated (a+1) n' end%sep. Infix "|->?" := allocated (at level 30) : sep_scope. (** * Finally, the Hoare logic *) (* The whole thing is parameterized on a map from locks to invariants on their * owned state. The map is a list, with lock [i] getting the [i]th invariant in * the list. Lock numbers at or beyond the list length are forbidden. Beyond * this new wrinkle, the type signature of the predicate is the same. *) Inductive hoare_triple (linvs : list hprop) : forall {result}, hprop -> cmd result -> (result -> hprop) -> Prop := (* First, we have the basic separation-logic rules from before. The only change * is in the threading-through of parameter [linvs]. *) | HtReturn : forall P {result : Set} (v : result), hoare_triple linvs P (Return v) (fun r => P * [| r = v |])%sep | HtBind : forall P {result' result} (c1 : cmd result') (c2 : result' -> cmd result) Q R, hoare_triple linvs P c1 Q -> (forall r, hoare_triple linvs (Q r) (c2 r) R) -> hoare_triple linvs P (Bind c1 c2) R | HtLoop : forall {acc : Set} (init : acc) (body : acc -> cmd (loop_outcome acc)) I, (forall acc, hoare_triple linvs (I (Again acc)) (body acc) I) -> hoare_triple linvs (I (Again init)) (Loop init body) (fun r => I (Done r)) | HtFail : forall {result}, hoare_triple linvs [| False |]%sep (Fail (result := result)) (fun _ => [| False |])%sep | HtRead : forall a R, hoare_triple linvs (exists v, a |-> v * R v)%sep (Read a) (fun r => a |-> r * R r)%sep | HtWrite : forall a v', hoare_triple linvs (exists v, a |-> v)%sep (Write a v') (fun _ => a |-> v')%sep | HtAlloc : forall numWords, hoare_triple linvs emp%sep (Alloc numWords) (fun r => r |--> zeroes numWords * [| r <> 0 |])%sep | HtFree : forall a numWords, hoare_triple linvs (a |->? numWords)%sep (Free a numWords) (fun _ => emp)%sep (* Next, how to handle locking: the thread takes ownership of a memory chunk * satisfying the lock's invariant. *) | HtLock : forall a I, nth_error linvs a = Some I -> hoare_triple linvs emp%sep (Lock a) (fun _ => I) (* When unlocking, the thread relinquishes ownership of a memory chunk * satisfying the lock's invariant. *) | HtUnlock : forall a I, nth_error linvs a = Some I -> hoare_triple linvs I (Unlock a) (fun _ => emp)%sep (* When forking into two threads, divide the (local) heap among them. * For simplicity, we never let parallel compositions terminate, * so it is appropriate to assign a contradictory overall postcondition. *) | HtPar : forall P1 c1 Q1 P2 c2 Q2, hoare_triple linvs P1 c1 Q1 -> hoare_triple linvs P2 c2 Q2 -> hoare_triple linvs (P1 * P2)%sep (Par c1 c2) (fun _ => [| False |])%sep (* Now we repeat these two structural rules from before. *) | HtConsequence : forall {result} (c : cmd result) P Q (P' : hprop) (Q' : _ -> hprop), hoare_triple linvs P c Q -> P' ===> P -> (forall r, Q r ===> Q' r) -> hoare_triple linvs P' c Q' | HtFrame : forall {result} (c : cmd result) P Q R, hoare_triple linvs P c Q -> hoare_triple linvs (P * R)%sep c (fun r => Q r * R)%sep. Notation "linvs ||- {{ P }} c {{ r ~> Q }}" := (hoare_triple linvs P%sep c (fun r => Q%sep)) (at level 90, c at next level). Lemma HtStrengthen : forall linvs {result} (c : cmd result) P Q (Q' : _ -> hprop), hoare_triple linvs P c Q -> (forall r, Q r ===> Q' r) -> hoare_triple linvs P c Q'. Proof. simplify. eapply HtConsequence; eauto. reflexivity. Qed. Lemma HtStrengthenFalse : forall linvs {result} (c : cmd result) P (Q' : _ -> hprop), hoare_triple linvs P c (fun _ => [| False |])%sep -> hoare_triple linvs P c Q'. Proof. simplify. eapply HtStrengthen; eauto. simplify. unfold himp; simplify. cases H0. tauto. Qed. Lemma HtWeaken : forall linvs {result} (c : cmd result) P Q (P' : hprop), hoare_triple linvs P c Q -> P' ===> P -> hoare_triple linvs P' c Q. Proof. simplify. eapply HtConsequence; eauto. reflexivity. Qed. (** * Examples *) Opaque heq himp lift star exis ptsto. (* Here comes some automation that we won't explain in detail, instead opting to * use examples. Search for "nonzero" to skip ahead to the first one. *) Theorem use_lemma : forall linvs result P' (c : cmd result) (Q : result -> hprop) P R, hoare_triple linvs P' c Q -> P ===> P' * R -> hoare_triple linvs P c (fun r => Q r * R)%sep. Proof. simp. eapply HtWeaken. eapply HtFrame. eassumption. eauto. Qed. Theorem HtRead' : forall linvs a v, hoare_triple linvs (a |-> v)%sep (Read a) (fun r => a |-> v * [| r = v |])%sep. Proof. simp. apply HtWeaken with (exists r, a |-> r * [| r = v |])%sep. eapply HtStrengthen. apply HtRead. simp. cancel; auto. subst; cancel. Qed. Theorem HtRead'' : forall linvs p P R, P ===> (exists v, p |-> v * R v) -> hoare_triple linvs P (Read p) (fun r => p |-> r * R r)%sep. Proof. simp. eapply HtWeaken. apply HtRead. assumption. Qed. Lemma HtReturn' : forall linvs P {result : Set} (v : result) Q, P ===> Q v -> hoare_triple linvs P (Return v) Q. Proof. simp. eapply HtStrengthen. constructor. simp. cancel. subst. assumption. Qed. Ltac basic := apply HtReturn' || eapply HtWrite || eapply HtAlloc || eapply HtFree || (eapply HtLock; simplify; solve [ eauto ]) || (eapply HtUnlock; simplify; solve [ eauto ]). Ltac step0 := basic || eapply HtBind || (eapply use_lemma; [ basic | cancel ]) || (eapply use_lemma; [ eapply HtRead' | solve [ cancel ] ]) || (eapply HtRead''; solve [ cancel ]) || (eapply HtStrengthen; [ eapply use_lemma; [ basic | cancel ] | ]) || (eapply HtConsequence; [ apply HtFail | .. ]). Ltac step := step0; simp. Ltac ht := simp; repeat step. Ltac conseq := simplify; eapply HtConsequence. Ltac use_IH H := conseq; [ apply H | .. ]; ht. Ltac loop_inv0 Inv := (eapply HtWeaken; [ apply HtLoop with (I := Inv) | .. ]) || (eapply HtConsequence; [ apply HtLoop with (I := Inv) | .. ]). Ltac loop_inv Inv := loop_inv0 Inv; ht. Ltac fork0 P1 P2 := apply HtWeaken with (P := (P1 * P2)%sep); [ eapply HtPar | ]. Ltac fork P1 P2 := fork0 P1 P2 || (eapply HtStrengthenFalse; fork0 P1 P2). Ltac use H := (eapply use_lemma; [ eapply H | cancel ]) || (eapply HtStrengthen; [ eapply use_lemma; [ eapply H | cancel ] | ]). Ltac heq := intros; apply himp_heq; split. (* Fancy theorem to help us rewrite within preconditions and postconditions *) Local Instance hoare_triple_morphism : forall linvs A, Proper (heq ==> eq ==> (eq ==> heq) ==> iff) (@hoare_triple linvs A). Proof. Transparent himp. repeat (hnf; intros). unfold pointwise_relation in *; intuition subst. eapply HtConsequence; eauto. rewrite H; reflexivity. intros. hnf in H1. specialize (H1 r _ eq_refl). rewrite H1; reflexivity. eapply HtConsequence; eauto. rewrite H; reflexivity. intros. hnf in H1. specialize (H1 r _ eq_refl). rewrite H1; reflexivity. Opaque himp. Qed. Theorem try_ptsto_first : forall a v, try_me_first (ptsto a v). Proof. simplify. apply try_me_first_easy. Qed. Local Hint Resolve try_ptsto_first : core. (** ** The nonzero shared counter *) (* This program has two threads sharing a numeric counter, which starts out as * nonzero and remains that way, since each thread only increments the counter, * with the lock held to avoid race conditions. *) Example incrementer := for i := tt loop _ <- Lock 0; n <- Read 0; _ <- Write 0 (n + 1); _ <- Unlock 0; if n ==n 0 then Fail else Return (Again tt) done. Definition incrementer_inv := emp%sep. Theorem incrementers_ok : [incrementer_inv] ||- {{emp}} incrementer || incrementer {{_ ~> emp}}. Proof. unfold incrementer, incrementer_inv. Admitted. Fixpoint incrementers (n : nat) := match n with | O => incrementer | S n' => incrementers n' || incrementers n' end. Theorem any_incrementers_ok : forall n, [incrementer_inv] ||- {{emp}} incrementers n {{_ ~> emp}}. Proof. Admitted. (** ** Producer-consumer with a linked list *) (* First, here's a literal repetition of the definition of linked lists from * SeparationLogic.v. *) Fixpoint linkedList (p : nat) (ls : list nat) := match ls with | nil => [| p = 0 |] | x :: ls' => [| p <> 0 |] * exists p', p |--> [x; p'] * linkedList p' ls' end%sep. Theorem linkedList_null : forall ls, linkedList 0 ls === [| ls = nil |]. Proof. heq; cases ls; cancel. Qed. Theorem linkedList_nonnull : forall p ls, p <> 0 -> linkedList p ls === exists x ls' p', [| ls = x :: ls' |] * p |--> [x; p'] * linkedList p' ls'. Proof. heq; cases ls; cancel; match goal with | [ H : _ = _ :: _ |- _ ] => invert H end; cancel. Qed. (* Now let's use linked lists as shared stacks for communication between * threads, with a lock protecting each stack. To start out with, here's a * producer-consumer example with just one stack. The producer is looping * pushing the consecutive even numbers to the stack, and the consumer is * looping popping numbers and failing if they're odd. *) Example producer := _ <- for i := 0 loop cell <- Alloc 2; _ <- Write cell i; _ <- Lock 0; head <- Read 0; _ <- Write (cell+1) head; _ <- Write 0 cell; _ <- Unlock 0; Return (Again (2 + i)) done; Return tt. Fixpoint isEven (n : nat) : bool := match n with | O => true | S (S n) => isEven n | _ => false end. Example consumer := for i := tt loop _ <- Lock 0; head <- Read 0; if head ==n 0 then _ <- Unlock 0; Return (Again tt) else tail <- Read (head+1); _ <- Write 0 tail; _ <- Unlock 0; data <- Read head; _ <- Free head 2; if isEven data then Return (Again tt) else Fail done. Definition producer_consumer_inv := emp%sep. Theorem producer_consumer_ok : [producer_consumer_inv] ||- {{emp}} producer || consumer {{_ ~> emp}}. Proof. unfold producer_consumer_inv, producer, consumer. Admitted. (** ** A length-3 producer-consumer chain *) (* Here's a variant on the last example. Now we have three stages. * Stage 1: push consecutive even numbers to stack 1. * Stage 2: pop from stack 1 and push to stack 1, reusing the memory for the * list node. * Stage 3: pop from stack 2 and fail if odd. *) Example stage1 := _ <- for i := 0 loop cell <- Alloc 2; _ <- Write cell i; _ <- Lock 0; head <- Read 0; _ <- Write (cell+1) head; _ <- Write 0 cell; _ <- Unlock 0; Return (Again (2 + i)) done; Return tt. Example stage2 := for i := tt loop _ <- Lock 0; head <- Read 0; if head ==n 0 then _ <- Unlock 0; Return (Again tt) else tail <- Read (head+1); _ <- Write 0 tail; _ <- Unlock 0; _ <- Lock 1; head' <- Read 1; _ <- Write (head+1) head'; _ <- Write 1 head; _ <- Unlock 1; Return (Again tt) done. Example stage3 := for i := tt loop _ <- Lock 1; head <- Read 1; if head ==n 0 then _ <- Unlock 1; Return (Again tt) else tail <- Read (head+1); _ <- Write 1 tail; _ <- Unlock 1; data <- Read head; _ <- Free head 2; if isEven data then Return (Again tt) else Fail done. (* Same invariant as before, for each of the two stacks. *) Definition stages_inv root := (exists ls p, root |-> p * linkedList p ls * [| forallb isEven ls = true |])%sep. Theorem stages_ok : [stages_inv 0; stages_inv 1] ||- {{emp}} stage1 || stage2 || stage3 {{_ ~> emp}}. Proof. unfold stages_inv, stage1, stage2, stage3. fork (emp%sep) (emp%sep); ht. fork (emp%sep) (emp%sep); ht. loop_inv (fun o => [| isEven (valueOf o) = true |]%sep). match goal with | [ H : r = 0 -> False |- _ ] => erewrite (linkedList_nonnull _ H) end. cancel. simp. apply andb_true_iff; propositional. cancel. cancel. cancel. loop_inv (fun _ : loop_outcome unit => emp%sep). simp. cases (r0 ==n 0). ht. cancel. setoid_rewrite (linkedList_nonnull _ n). ht. apply andb_true_iff in H. simp. erewrite (linkedList_nonnull _ n). cancel. simp. apply andb_true_iff in H1. apply andb_true_iff. simp. cancel. cancel. cancel. loop_inv (fun _ : loop_outcome unit => emp%sep). simp. cases (r0 ==n 0). ht. cancel. setoid_rewrite (linkedList_nonnull _ n). ht. apply andb_true_iff in H. simp. simp. cases (isEven r4); ht. cancel. cancel. simp. rewrite Heq in H0. simp. try equality. cancel. cancel. cancel. Qed. (** * Soundness proof *) Local Hint Resolve himp_refl : core. Lemma invert_Return : forall linvs {result : Set} (r : result) P Q, hoare_triple linvs P (Return r) Q -> P ===> Q r. Proof. induct 1; propositional; eauto. cancel. eauto using himp_trans. rewrite IHhoare_triple; eauto. Qed. Local Hint Constructors hoare_triple : core. Lemma invert_Bind : forall linvs {result' result} (c1 : cmd result') (c2 : result' -> cmd result) P Q, hoare_triple linvs P (Bind c1 c2) Q -> exists R, hoare_triple linvs P c1 R /\ forall r, hoare_triple linvs (R r) (c2 r) Q. Proof. induct 1; propositional; eauto. invert IHhoare_triple; propositional. eexists; propositional. eapply HtWeaken. eassumption. auto. eapply HtStrengthen. apply H4. auto. simp. exists (fun r => x r * R)%sep. propositional. eapply HtFrame; eauto. eapply HtFrame; eauto. Qed. Transparent heq himp lift star exis ptsto. Lemma invert_Loop : forall linvs {acc : Set} (init : acc) (body : acc -> cmd (loop_outcome acc)) P Q, hoare_triple linvs P (Loop init body) Q -> exists I, (forall acc, hoare_triple linvs (I (Again acc)) (body acc) I) /\ P ===> I (Again init) /\ (forall r, I (Done r) ===> Q r). Proof. induct 1; propositional; eauto. invert IHhoare_triple; propositional. exists x; propositional; eauto. unfold himp in *; eauto. eauto using himp_trans. simp. exists (fun o => x o * R)%sep; propositional; eauto. rewrite H0; eauto. rewrite H3; eauto. Qed. Opaque heq himp lift star exis ptsto. Lemma unit_not_nat : unit = nat -> False. Proof. simplify. assert (exists x : unit, forall y : unit, x = y). exists tt; simplify. cases y; reflexivity. rewrite H in H0. invert H0. specialize (H1 (S x)). linear_arithmetic. Qed. Lemma invert_Read : forall linvs a P Q, hoare_triple linvs P (Read a) Q -> exists R, (P ===> exists v, a |-> v * R v)%sep /\ forall r, a |-> r * R r ===> Q r. Proof. induct 1; simp; eauto. apply unit_not_nat in x0; simp. apply unit_not_nat in x0; simp. apply unit_not_nat in x0; simp. apply unit_not_nat in x0; simp. apply unit_not_nat in x0; simp. eauto 7 using himp_trans. exists (fun n => x n * R)%sep; simp. rewrite H1. cancel. rewrite <- H2. cancel. Qed. Lemma invert_Write : forall linvs a v' P Q, hoare_triple linvs P (Write a v') Q -> exists R, (P ===> (exists v, a |-> v) * R)%sep /\ a |-> v' * R ===> Q tt. Proof. induct 1; simp; eauto. symmetry in x0. apply unit_not_nat in x0; simp. exists emp; simp. cancel; auto. cancel; auto. symmetry in x0. apply unit_not_nat in x0; simp. eauto 7 using himp_trans. exists (x * R)%sep; simp. rewrite H1. cancel. cancel. rewrite <- H2. cancel. Qed. Lemma invert_Alloc : forall linvs numWords P Q, hoare_triple linvs P (Alloc numWords) Q -> forall r, P * r |--> zeroes numWords * [| r <> 0 |] ===> Q r. Proof. induct 1; simp; eauto. apply unit_not_nat in x0; simp. cancel. apply unit_not_nat in x0; simp. apply unit_not_nat in x0; simp. apply unit_not_nat in x0; simp. apply unit_not_nat in x0; simp. rewrite H0; eauto. eauto 7 using himp_trans. rewrite <- IHhoare_triple. cancel. Qed. Transparent heq himp lift star exis ptsto. Lemma zeroes_initialize' : forall h a v, h $? a = None -> (fun h' : heap => h' = h $+ (a, v)) ===> (fun h' => h' = h) * a |-> v. Proof. unfold himp, star, split, ptsto, disjoint; simp. exists h, (heap1 a v). propositional. maps_equal. unfold heap1. rewrite lookup_join2. simp. simp. apply lookup_None_dom in H. propositional. cases (h $? k). rewrite lookup_join1; auto. eauto using lookup_Some_dom. rewrite lookup_join2; auto. unfold heap1; simp. eauto using lookup_None_dom. unfold heap1 in *. cases (a ==n a0); simp. Qed. Opaque heq himp lift star exis ptsto. Lemma multi_ptsto_app : forall ls2 ls1 a, a |--> ls1 * (a + length ls1) |--> ls2 ===> a |--> (ls1 ++ ls2). Proof. induct ls1; simp; cancel; auto. replace (a + 0) with a by linear_arithmetic. cancel. rewrite <- IHls1. cancel. replace (a0 + 1 + length ls1) with (a0 + S (length ls1)) by linear_arithmetic. cancel. Qed. Lemma length_zeroes : forall n, length (zeroes n) = n. Proof. induct n; simplify; auto. rewrite app_length; simplify. linear_arithmetic. Qed. Lemma initialize_fresh : forall a' h a numWords, a' >= a + numWords -> initialize h a numWords $? a' = h $? a'. Proof. induct numWords; simp; auto. Qed. Lemma zeroes_initialize : forall numWords a h, (forall i, i < numWords -> h $? (a + i) = None) -> (fun h' => h' = initialize h a numWords) ===> (fun h' => h' = h) * a |--> zeroes numWords. Proof. induct numWords; simp. cancel; auto. rewrite <- multi_ptsto_app. rewrite zeroes_initialize'. erewrite IHnumWords. simp. rewrite length_zeroes. cancel; auto. auto. rewrite initialize_fresh; auto. Qed. Lemma invert_Free : forall linvs a numWords P Q, hoare_triple linvs P (Free a numWords) Q -> P ===> a |->? numWords * Q tt. Proof. induct 1; simp; eauto. symmetry in x0. apply unit_not_nat in x0; simp. symmetry in x0. apply unit_not_nat in x0; simp. cancel; auto. rewrite H0. rewrite IHhoare_triple. cancel; auto. rewrite IHhoare_triple. cancel; auto. Qed. Transparent heq himp lift star exis ptsto. Lemma do_deallocate' : forall a Q h, ((exists v, a |-> v) * Q)%sep h -> Q (h $- a). Proof. unfold ptsto, star, split, heap1; simp. invert H1. replace ($0 $+ (a, x1) $++ x0 $- a) with x0; auto. maps_equal. cases (k ==n a); simp. specialize (H a). simp. cases (x0 $? a); auto. exfalso; apply H; equality. rewrite lookup_join2; auto. apply lookup_None_dom. simp. Qed. Lemma do_deallocate : forall Q numWords a h, (a |->? numWords * Q)%sep h -> Q (deallocate h a numWords). Proof. induct numWords; simp. unfold star, exis, lift in H; simp. apply split_empty_fwd' in H0; simp. apply IHnumWords. clear IHnumWords. apply do_deallocate'. Opaque heq himp lift star exis ptsto. match goal with | [ H : ?P h |- ?Q h ] => assert (P ===> Q) by cancel end. Transparent himp. apply H0; auto. Opaque himp. Qed. Opaque heq himp lift star exis ptsto. Lemma invert_Lock : forall linvs a P Q, hoare_triple linvs P (Lock a) Q -> exists I, nth_error linvs a = Some I /\ P * I ===> Q tt. Proof. induct 1; simp; eauto 10. symmetry in x0. apply unit_not_nat in x0; simp. symmetry in x0. apply unit_not_nat in x0; simp. eexists; simp. eauto. cancel. eexists; simp. eauto. rewrite H0; eauto using himp_trans. eexists; simp. eauto. rewrite <- H2. cancel. Qed. Lemma invert_Unlock : forall linvs a P Q, hoare_triple linvs P (Unlock a) Q -> exists I, nth_error linvs a = Some I /\ P ===> Q tt * I. Proof. induct 1; simp; eauto 10. symmetry in x0. apply unit_not_nat in x0; simp. symmetry in x0. apply unit_not_nat in x0; simp. eexists; simp. eauto. cancel. eexists; simp. eauto. rewrite <- H1; eauto using himp_trans. eexists; simp. eauto. rewrite H2. cancel. Qed. Lemma invert_Par : forall linvs c1 c2 P Q, hoare_triple linvs P (Par c1 c2) Q -> exists P1 P2 Q1 Q2, hoare_triple linvs P1 c1 Q1 /\ hoare_triple linvs P2 c2 Q2 /\ P ===> P1 * P2. Proof. induct 1; simp; eauto 7. symmetry in x0. apply unit_not_nat in x0; simp. symmetry in x0. apply unit_not_nat in x0; simp. eauto 8 using himp_trans. exists (x * R)%sep, x0, (fun r => x1 r * R)%sep, x2; simp; eauto. rewrite H3; cancel. Qed. Transparent heq himp lift star exis ptsto. Definition guarded (P : Prop) (p : hprop) : hprop := fun h => IFF P then p h else emp%sep h. Infix "===>" := guarded : sep_scope. Theorem guarded_true : forall (P : Prop) p, P -> (P ===> p) === p. Proof. unfold heq, guarded, IF_then_else; simp. Qed. Theorem guarded_false : forall (P : Prop) p, ~P -> (P ===> p) === emp. Proof. unfold heq, guarded, IF_then_else; simp. Qed. Fixpoint bigstar A (P : nat -> A -> hprop) (ls : list A) : hprop := match ls with | nil => emp | x :: ls' => P 0 x * bigstar (fun n => P (S n)) ls' end%sep. Definition lockChunks (l : locks) (ls : list hprop) := bigstar (fun i I => (~i \in l) ===> I)%sep ls. Lemma use_himp : forall P Q, P ===> Q -> forall h, P h -> Q h. Proof. auto. Qed. Lemma ptsto_out : forall h a v p, h $? a = Some v -> (exists v', a |-> v' * p v')%sep h -> (a |-> v * p v)%sep h /\ forall v', (a |-> v' * p v)%sep (h $+ (a, v')). Proof. invert 2. invert H1. simp. invert H2. unfold split in H0; subst. rewrite lookup_join1 in H. unfold heap1 in H. simplify. invert H. exists (heap1 a v), x1; simp. eauto. unfold ptsto. eauto. unfold heap1; simplify. sets. invert H2. unfold split in H0; subst. rewrite lookup_join1 in H. unfold heap1 in H. simplify. invert H. exists (heap1 a v'), x1; simp. unfold split. maps_equal. rewrite lookup_join1. unfold heap1; simplify; auto. unfold heap1; simplify; sets. repeat rewrite lookup_join2; auto. unfold heap1; simplify; sets. unfold heap1; simplify; sets. unfold disjoint in *; simp. apply (H1 a0); eauto. cases (a ==n a0); simp. unfold heap1 in *; simplify; equality. unfold heap1 in *; simplify; equality. unfold ptsto. eauto. unfold heap1; simplify; sets. Qed. Lemma specialize_hprop : forall (p : hprop) h, p h -> (fun h' => h' = h) ===> p. Proof. unfold himp; equality. Qed. Opaque heq himp lift star exis ptsto. Lemma bigstar_impl : forall A ls (p q : nat -> A -> hprop), (forall i x, p i x ===> q i x) -> bigstar p ls ===> bigstar q ls. Proof. induct ls; simplify; auto. rewrite H. rewrite IHls. cancel. simp. eauto. Qed. Lemma guarded_impl : forall P Q p, (P <-> Q) -> (P ===> p) ===> (Q ===> p). Proof. simp. excluded_middle P. repeat rewrite guarded_true by propositional. auto. repeat rewrite guarded_false by propositional. auto. Qed. Lemma lockChunks_lock' : forall l I linvs (f : nat -> nat) a, ~f a \in l -> nth_error linvs a = Some I -> (forall x y, f x = f y -> x = y) -> bigstar (fun i I => (~f i \in l) ===> I)%sep linvs ===> I * bigstar (fun i I => (~(f i \in {f a} \cup l)) ===> I)%sep linvs. Proof. induct linvs; simplify. cases a; simplify; try unfold error in *; equality. cases a0; simplify. invert H0. rewrite guarded_true by sets. rewrite guarded_false by sets. cancel. apply bigstar_impl. simp. apply guarded_impl. sets. apply H1 in H2. equality. apply (IHlinvs (fun n => f (S n))) in H0; auto. rewrite H0. cancel. apply guarded_impl. sets. apply H1 in H3. equality. simp. apply H1 in H2. equality. Qed. Lemma lockChunks_lock : forall a l I linvs, ~a \in l -> nth_error linvs a = Some I -> lockChunks l linvs ===> I * lockChunks ({a} \cup l) linvs. Proof. simp. apply lockChunks_lock' with (f := fun n => n); auto. Qed. Lemma lockChunks_unlock' : forall l I linvs (f : nat -> nat) a, f a \in l -> nth_error linvs a = Some I -> (forall x y, f x = f y -> x = y) -> I * bigstar (fun i I => (~f i \in l) ===> I)%sep linvs ===> bigstar (fun i I => (~(f i \in l \setminus {f a})) ===> I)%sep linvs. Proof. induct linvs; simplify. cases a; simplify; try unfold error in *; equality. cases a0; simplify. invert H0. rewrite guarded_false by sets. rewrite guarded_true by sets. cancel. apply bigstar_impl. simp. apply guarded_impl. sets. apply H0; propositional. apply H1 in H4. equality. apply (IHlinvs (fun n => f (S n))) in H0; auto. rewrite <- H0. cancel. apply guarded_impl. sets. apply H2; propositional. apply H1 in H5. equality. simp. apply H1 in H2. equality. Qed. Lemma lockChunks_unlock : forall a l I linvs, a \in l -> nth_error linvs a = Some I -> I * lockChunks l linvs ===> lockChunks (l \setminus {a}) linvs. Proof. simp. apply lockChunks_unlock' with (f := fun n => n); auto. Qed. Lemma preservation : forall linvs {result} (c : cmd result) h l c' h' l', step (h, l, c) (h', l', c') -> forall P Q R, hoare_triple linvs P c Q -> (P * R * lockChunks l linvs)%sep h -> exists P', hoare_triple linvs P' c' Q /\ (P' * R * lockChunks l' linvs)%sep h'. Proof. induct 1; simplify. apply invert_Bind in H0; simp. eapply IHstep in H0; eauto. simp. eauto. apply invert_Bind in H; simp. specialize (invert_Return H); eauto using HtWeaken. apply invert_Loop in H; simp. eexists; simp. econstructor. eauto. simp. cases r. apply HtReturn'. auto. eapply HtStrengthen. eauto. eauto. eapply use_himp; try eassumption. rewrite H1. eauto. apply invert_Read in H0; simp. assert ((exists v, a |-> v * (x v * R * lockChunks l' linvs))%sep h'). eapply use_himp; try eassumption. rewrite H0. cancel. eapply ptsto_out in H2; eauto. eexists; simp. apply HtReturn'. eauto. eapply use_himp; try eassumption. cancel. apply invert_Write in H0; simp. assert ((exists v, a |-> v * (x * R * lockChunks l' linvs))%sep h). eapply use_himp; try eassumption. rewrite H0. cancel. eapply ptsto_out in H2; eauto. propositional. eexists; simp. apply HtReturn'. eauto. eapply use_himp; try apply H5. cancel. apply invert_Alloc with (r := a) in H1. eexists; propositional. apply HtReturn'. eassumption. apply use_himp with ((P * R * lockChunks l' linvs) * a |--> zeroes numWords)%sep. cancel. apply use_himp with ((fun h' => h' = h) * a |--> zeroes numWords)%sep. cancel. eauto using specialize_hprop. eapply use_himp. apply zeroes_initialize; auto. simp. apply invert_Free in H. eexists; propositional. instantiate (1 := Q tt). apply HtReturn'. auto. apply do_deallocate; simplify. change (fun f => (Q tt * lockChunks l' linvs) f)%sep with (Q tt * lockChunks l' linvs)%sep. eapply use_himp; try eassumption. rewrite H. cancel. apply invert_Lock in H0. simp. eexists; propositional. apply HtReturn'; auto. eapply use_himp; try eassumption. rewrite <- H3. cancel. apply lockChunks_lock; auto. apply invert_Unlock in H0. simp. eexists; propositional. apply HtReturn'; auto. eapply use_himp; try eassumption. rewrite H3. cancel. rewrite <- lockChunks_unlock; eauto. cancel. apply invert_Par in H0. simp. eapply IHstep in H2. simp. eexists; propositional. apply HtStrengthenFalse. econstructor. eassumption. eassumption. eapply use_himp; try eassumption. cancel. eapply use_himp; try eassumption. cancel. apply invert_Par in H0. simp. eapply IHstep in H0. simp. eexists; propositional. apply HtStrengthenFalse. econstructor. eassumption. eassumption. eapply use_himp; try eassumption. cancel. eapply use_himp; try eassumption. rewrite H4. cancel. Qed. Definition allLockChunks (linvs : list hprop) := bigstar (fun _ I => I) linvs. Lemma allLockChunks_lockChunks' : forall linvs (f : nat -> nat), bigstar (fun _ I => I) linvs ===> bigstar (fun i I => (~f i \in {}) ===> I) linvs. Proof. induct linvs; simp; auto. rewrite guarded_true by sets. rewrite IHlinvs. cancel. Qed. Lemma allLockChunks_lockChunks : forall linvs, allLockChunks linvs ===> lockChunks {} linvs. Proof. simp. apply allLockChunks_lockChunks' with (f := fun n => n). Qed. Lemma hoare_triple_sound' : forall linvs P {result} (c : cmd result) Q, hoare_triple linvs P c Q -> forall h, (P * allLockChunks linvs)%sep h -> invariantFor (trsys_of h {} c) (fun p => let '(h, l, c) := p in exists P', hoare_triple linvs P' c Q /\ (P' * lockChunks l linvs)%sep h). Proof. simplify. apply invariant_induction; simplify. propositional; subst; simplify. eexists; propositional. eauto. eapply use_himp; try eassumption. rewrite allLockChunks_lockChunks. auto. cases s. cases p. cases s'. cases p. simp. eapply preservation with (R := emp%sep) in H1; eauto. simp. eexists; propositional; eauto. eapply use_himp; try eassumption. cancel. eapply use_himp; try eassumption. cancel. Qed. Fixpoint notAboutToFail {result} (c : cmd result) := match c with | Fail _ => false | Bind _ _ c1 _ => notAboutToFail c1 | Par c1 c2 => notAboutToFail c1 && notAboutToFail c2 | _ => true end. Lemma hoare_triple_notAboutToFail : forall linvs P result (c : cmd result) Q, hoare_triple linvs P c Q -> notAboutToFail c = false -> P ===> [| False |]. Proof. induct 1; simp; try equality; eauto using himp_trans. apply andb_false_iff in H1; propositional. rewrite H1; cancel. rewrite H1; cancel. rewrite H1; cancel. Qed. Lemma False_star : forall p, [| False |] * p ===> [| False |]. Proof. cancel. Qed. Theorem hoare_triple_sound : forall linvs P {result} (c : cmd result) Q, hoare_triple linvs P c Q -> forall h, (P * allLockChunks linvs)%sep h -> invariantFor (trsys_of h {} c) (fun p => let '(_, _, c) := p in notAboutToFail c = true). Proof. simplify. eapply invariant_weaken. eapply hoare_triple_sound'; eauto. simp. cases s. cases p. simp. cases (notAboutToFail c0); auto. eapply hoare_triple_notAboutToFail in Heq; eauto. assert ([| False |]%sep f). apply use_himp with (x * lockChunks s linvs)%sep. rewrite Heq. apply False_star. assumption. invert H2; propositional. Qed.
> module Math > import Data.Vect > import Data.HVect > import Data.List > import Data.Fin We take some tricks from https://boxbase.org/entries/2019/sep/16/grabbag-of-idris-tricks/ and http://firsov.ee/finset/finset.pdf. Use Pauli group as small example: > data PauliGroup : Type where > X : PauliGroup > Y : PauliGroup > Zp : PauliGroup > I : PauliGroup We provide a complete list of PauliGroup elements: > listPauli : List PauliGroup > listPauli = [X,Y,Zp,I] > allPauli : (x: PauliGroup) -> Data.List.Elem x Math.listPauli > allPauli X = Here > allPauli Y = There Here > allPauli Zp = There (There Here) > allPauli I = There (There (There Here)) > xIsNotY : (X = Y) -> Void > xIsNotY Refl impossible > xIsNotZ : (X = Zp) -> Void > xIsNotZ Refl impossible > xIsNotI : (X = I) -> Void > xIsNotI Refl impossible > yIsNotZ : (Y = Zp) -> Void > yIsNotZ Refl impossible > yIsNotI : (Y = I) -> Void > yIsNotI Refl impossible > zIsNotI : (Zp = I) -> Void > zIsNotI Refl impossible > DecEq PauliGroup where > decEq X X = Yes Refl > decEq X Y = No xIsNotY > decEq X Zp = No xIsNotZ > decEq X I = No xIsNotI > decEq Y X = No (\c => xIsNotY (sym c)) > decEq Y Y = Yes Refl > decEq Y Zp = No yIsNotZ > decEq Y I = No yIsNotI > decEq Zp X = No (\c => xIsNotZ (sym c)) > decEq Zp Y = No (\c => yIsNotZ (sym c)) > decEq Zp Zp = Yes Refl > decEq Zp I = No zIsNotI > decEq I X = No (\c => xIsNotI (sym c)) > decEq I Y = No (\c => yIsNotI (sym c)) > decEq I Zp = No (\c => zIsNotI (sym c)) > decEq I I = Yes Refl And we give the group structure: > multPauli : PauliGroup -> PauliGroup -> PauliGroup > multPauli X X = I > multPauli X Y = Zp > multPauli X Zp = Y > multPauli X I = X > multPauli Y X = Zp > multPauli Y Y = I > multPauli Y Zp = X > multPauli Y I = Y > multPauli Zp X = Y > multPauli Zp Y = X > multPauli Zp Zp = I > multPauli Zp I = Zp > multPauli I X = X > multPauli I Y = Y > multPauli I Zp = Zp > multPauli I I = I > commPauli : (x:PauliGroup) -> (y:PauliGroup) -> (multPauli x y = multPauli y x) > commPauli X X = Refl > commPauli X Y = Refl > commPauli X Zp = Refl > commPauli X I = Refl > commPauli Y X = Refl > commPauli Y Y = Refl > commPauli Y Zp = Refl > commPauli Y I = Refl > commPauli Zp X = Refl > commPauli Zp Y = Refl > commPauli Zp Zp = Refl > commPauli Zp I = Refl > commPauli I X = Refl > commPauli I Y = Refl > commPauli I Zp = Refl > commPauli I I = Refl Obviously there are a number of shortcomings with this approach.... and associativity would take 64 lines to prove... > Injective : {t,u:Type} -> (t -> u) -> Type > Injective f {t} = (x,y:t) -> (f x = f y) -> (x = y) > Surjective : {t,u:Type} -> (t -> u) -> Type > Surjective f {t} {u} = (y:u) -> (x:t ** f x = y) > getInverse : {t,u:Type} -> {func: t -> u} -> (Injective func) -> (Surjective func) -> (u -> t) > getInverse {t} {u} {func} inj surj = \y => fst (surj y) > Bijective : {t,u : Type} -> (t -> u) -> Type > Bijective f {t} {u} = ?bij Proofs that a list contain all possible elements of a type: > All : {t : Type} -> List t -> Type > All xs {t} = (x:t) -> Elem x xs Given a type t and a proof of t, it is a contradiction to have a proof that the empty list contains all elements of t. > allNotEmpty : All {t} [] -> t -> Void > allNotEmpty f x = absurd (f x) > voidEmptyAll : Uninhabited t => All {t} [] > voidEmptyAll = \c => absurd c Decidable list membership: > DecIn : (t: Type) -> Type > DecIn t = (x:t) -> (xs : List t) -> Dec (Elem x xs) Decidable equality and decidable list membership are equivalent: > decInToDeqEq : DecIn t -> (x:t) -> (y:t) -> Dec (x = y) > decInToDeqEq f x y = case (f x [y]) of > Yes Here => Yes Refl > No contra => No (\eq => contra (rewrite eq in Here)) Little helper lemmas: > matchingSingleton : Data.List.Elem x [y] -> (x = y) > matchingSingleton Here = Refl > matchingSingleton (There later) impossible > deqEqToDeqIn : DecEq t => DecIn t > deqEqToDeqIn x [] = No absurd > deqEqToDeqIn x (y::ys) with (deqEqToDeqIn x ys) > deqEqToDeqIn x (y::ys) | No notLater = case decEq x y of > Yes Refl => Yes Here > No contra => No (\later => > case later of > Here => contra (matchingSingleton Here) > (There t) => notLater t) > deqEqToDeqIn x (y::ys) | Yes later = Yes (There later) Proof that a given type is a "mere proposition" (i.e. it only has one element) > Prop : (t:Type) -> Type > Prop t = (p1:t) -> (p2:t) -> (p1=p2) We also have a notion of a List with no duplicates: > NoDupes : {t:Type} -> List t -> Type > NoDupes {t} xs = (x:t) -> Prop (Elem x xs) Some trivial helper lemmas: > noDupesInHeadLemma : Elem x xs -> NoDupes (x :: xs) -> Void > noDupesInHeadLemma {x = x} {xs = []} _ _ impossible > noDupesInHeadLemma {x} a b = hereIsNotThere (b x Here (There a)) If a type has decidable equality, then All and NoDupes are decidable. We need a (somewhat metamathematical) lemma to start stating that any two void values of the same type are equal (there are in fact zero of them - this is just a wrapper for "void can prove anything") > voidsAreEquivalent : {t: Type} -> (t -> Void) -> (a:t) -> (b:t) -> (a=b) > voidsAreEquivalent f a b = void (f a) > sameTheresLemma : {a: Data.List.Elem x xs} -> (There a = There a) > sameTheresLemma = Refl To avoid an awkward workaround with Void types, we force the caller to prove that the type isn't void by providing some item. This might need some work... > deqEqToAllIncomplete : DecEq t => (xs:List t) -> t -> Dec (All xs) > deqEqToAllIncomplete [] someItem = No (\c => allNotEmpty c someItem) > deqEqToAllIncomplete (x :: xs) someitem = Yes (\c => > case (decEq x c) of > Yes pf => rewrite pf in Here > No contra => ?newh2) After some reflection, I don't think this will work. We need to know *ahead of time* that All {t} [xs] exists. This method will always fail to converge for Nats. > thereLemma1 : {a: Data.List.Elem x xs} -> {b : Data.List.Elem x xs} -> (a = b) -> There a = There b > thereLemma1 {a = Here} {b = Here} Refl = Refl > thereLemma1 {a = Here} {b = (There _)} Refl impossible > thereLemma1 {a = (There _)} {b = Here} Refl impossible > thereLemma1 {a = (There x)} {b = (There x)} Refl = Refl > thereLemma2 : {a: Data.List.Elem x xs} -> {b : Data.List.Elem x xs} -> (There a = There b) -> a = b > thereLemma2 {a = Here} {b = Here} pf = Refl > thereLemma2 {a = Here} {b = (There _)} Refl impossible > thereLemma2 {a = (There _)} {b = Here} Refl impossible > thereLemma2 {a = (There x)} {b = (There x)} Refl = Refl > consNoDupes : DecEq t => {x : t} -> NoDupes {t} xs -> (Not (Elem x xs)) -> NoDupes (x :: xs) > consNoDupes {x = x} noDupesSublist notIn y pf1 pf2 with (decEq x y) > consNoDupes {x = y} noDupesSublist notIn y Here Here | Yes pf = Refl > consNoDupes {x = y} noDupesSublist notIn y Here (There later) | Yes pf = absurd (notIn later) > consNoDupes {x = y} noDupesSublist notIn y (There later) Here | Yes pf = absurd (notIn later) > consNoDupes {x = x} noDupesSublist notIn y (There later) (There z) | Yes pf = absurd (notIn (rewrite pf in later)) --rewrite (noDupesSublist y later z) in Refl > consNoDupes {x = y} noDupesSublist notIn y Here Here | No contra = Refl > consNoDupes {x = y} noDupesSublist notIn y Here (There later) | No contra = absurd (notIn later) > consNoDupes {x = y} noDupesSublist notIn y (There later) Here | No contra = absurd (notIn later) > consNoDupes {x = x} noDupesSublist notIn y (There later) (There z) | No contra = let ndupes = (noDupesSublist y later z) in thereLemma1 ndupes > dupeCons : NoDupes (x :: xs) -> NoDupes xs > dupeCons dupeBiglist item pf1 pf2 = thereLemma2 (dupeBiglist item (There pf1) (There pf2)) > deqEqToDupe : DecEq t => (xs:List t) -> Dec (NoDupes xs) > deqEqToDupe [] = Yes (\a => (\b => (\c => (voidsAreEquivalent uninhabited b c)))) > deqEqToDupe (x :: xs) with (isElem x xs) > deqEqToDupe (x :: xs) | Yes pf = No (noDupesInHeadLemma pf) > deqEqToDupe (x :: xs) | No contra = case deqEqToDupe xs of > Yes noDupes => Yes (consNoDupes noDupes contra) > No areDupes => No (\c => areDupes (dupeCons c)) If P is a decidable proposition, we can quotient P by the total equivalence relation and get a "squashed" type {what is this relation?} > squash : {p:Type} -> Dec p -> Type > squash (Yes _) = Unit > squash (No _) = Void An example: Elem x [x,y,x] is decidable: > exSquash1 : Dec (Data.List.Elem X [X,Y,X]) > exSquash1 = Yes Here > exSquash2 : Dec (Data.List.Elem X [X,Y,X]) > exSquash2 = Yes (There (There Here)) Both "squash" to Unit. Note that any two squashed values are trivially equal: > propSquash : {p: Type} -> (d : Dec p) -> Prop (squash d) > propSquash (Yes prf) () () = Refl > propSquash (No contra) v1 _ = absurd v1 > fromSquash : {p:Type} -> (d : Dec p) -> squash d -> p > fromSquash (Yes prf) () = prf makeAllFin : (k:Nat) -> (xs:(List (Fin (S k))) ** All (Fin (S k)) xs) makeAllFin Z = ([FZ] ** (IsAll (\x => Here))) Kuratowski finiteness: > Listable : (t : Type) -> Type > Listable t = (xs ** (All {t} xs)) An alternative idea is to require a surjection Fin n to t for some Nat n: > FinSurjective : (t: Type) -> Type > FinSurjective ty = (n:Nat ** (fromFin : (Fin n -> ty) ** (Surjective fromFin))) These notions are equivalent. We need some helper lemmas... it is quite likely that these can be cleaned up considerably... > getIndexOfElem : Data.List.Elem x xs -> Fin (length xs) > getIndexOfElem Here = FZ > getIndexOfElem (There later) = FS (getIndexOfElem later) > getIndexFromAll : All {t} xs -> t -> Fin (length xs) > getIndexFromAll {xs = []} pf x = absurd (pf x) > getIndexFromAll {xs = (y :: xs)} pf x = getIndexOfElem (pf x) > finIndexList : (l:List t) -> Fin (length l) -> t > finIndexList [] _ impossible > finIndexList (x :: _) FZ = x > finIndexList (_ :: xs) (FS y) = finIndexList xs y > getIndexOfElemLemma : (pf : Data.List.Elem x xs) -> finIndexList xs (getIndexOfElem pf) = x > getIndexOfElemLemma {xs = (x :: ys)} Here = Refl > getIndexOfElemLemma {xs = (y :: ys)} (There later) = getIndexOfElemLemma later > getIndexOfAllLemma : (pf : All {t} xs) -> (x : t) -> finIndexList xs (getIndexFromAll pf x) = x > getIndexOfAllLemma {xs} pf x with (pf x) > getIndexOfAllLemma {xs= x :: ys} pf x | Here = getIndexOfElemLemma (pf x) > getIndexOfAllLemma {xs= y :: ys} pf x | (There later) = getIndexOfElemLemma (pf x) > finIndexListSurjectiveIfAll : All {t} xs -> Surjective (finIndexList xs) > finIndexListSurjectiveIfAll {xs} pf = \y => ((getIndexFromAll pf y) ** (getIndexOfAllLemma pf y)) > indexIntoAll : All {t} xs -> (f : (Fin (length xs) -> t) ** Surjective f) > indexIntoAll {xs} pf = ((finIndexList xs) ** (finIndexListSurjectiveIfAll pf)) > natToListFin : (n : Nat) -> List (Fin n) > natToListFin Z = [] > natToListFin (S n) = (the (Fin (S n)) last) :: (map weaken (natToListFin n)) > lastFinLemma : {n: Nat} -> (((FS k) = last {n=n}) -> Void) -> ((k = last {n=n}) -> Void) > lastFinLemma {n = Z} {k=_} _ impossible > lastFinLemma {n = (S Z)} {k = FZ} contra = absurd (contra Refl) > lastFinLemma {n = (S (S k))} {k = FZ} contra = ?lastFinLemma_rhs_4 > lastFinLemma {n = (S j)} {k = (FS x)} contra = ?lastFinLemma_rhs_3 lastFinLemma {n = Z} {k = FZ} _ impossible lastFinLemma {n = Z} {k = (FS _)} _ impossible > safeStrengthen : (f : Fin (S n)) -> (contra : (f = last {n=n}) -> Void) -> Fin n > safeStrengthen {n=Z} FZ contra = absurd (contra Refl) > safeStrengthen {n=(S k)} FZ contra = FZ > safeStrengthen {n=(S k)} (FS x) contra = ?ssh_2 > natToListFinIsAll : (n : Nat) -> (All (natToListFin n)) > natToListFinIsAll Z = voidEmptyAll > natToListFinIsAll (S n) = \f => > case (decEq (the (Fin (S n)) last) f) of > Yes pf => rewrite pf in Here > No _ => ?newhole -- There (natToListFinIsAll n (safeStrengthen f)) natToListFinIsAll (S Z) = (\FZ => Here) > getAllFins : (n : Nat) -> (xs : (List (Fin n)) ** All xs) > getAllFins n = ((natToListFin n) ** (natToListFinIsAll n)) getAllFins (S k) = ((getAllFinsInner (S k)) ** ) > listableIsFinSurjective : Listable t -> FinSurjective t > listableIsFinSurjective (xs ** pf) = ((length xs) ** (indexIntoAll pf)) > finSurjectiveToList : FinSurjective t -> List t > finSurjectiveToList (bd ** (surj ** pf)) = map surj (fst (getAllFins bd)) > finSurjectiveIsListable : FinSurjective t -> Listable t > finSurjectiveIsListable (bound ** (surj ** pf)) = ?finSurjectiveIsListable_rhs_2 > contrapositive : (a -> b) -> Not b -> Not a > contrapositive f nb a = nb (f a) makeAllFin (S k) = ?makeAllFin_rhs_2 > interface Countable t where > FromNat : Nat -> t > ToNat : t -> Nat > Countable Nat where > FromNat = id > ToNat = id An $n$-place relation on a collection of sets $S_1, S_2,\dots,S_n$ is a set $R\subset S_1 \times S_2 \times \dots \times S_n$. We say $s_1\in S_1,s_2\in S_2,\dots, s_n\in S_n$ are related by $R$ if $(s_1,s_2,\dots,s_n)\in R$. > NaryRelation : Vect n Type -> Type > NaryRelation xs = List (HVect xs) -- for our purposes it is fine to use lists instead of sets > BinaryRelation : Vect 2 Type -> Type > BinaryRelation = NaryRelation > domain : BinaryRelation [xt,yt] -> List yt > domain [] = [] > domain ([x,y] :: xs) = y :: (domain xs) > codomain : BinaryRelation [xt,yt] -> List xt > codomain [] = [] > codomain ([x,y] :: xs) = x :: (codomain xs) > data PartialFunction : BinaryRelation [xy,yt] -> Type where >
(* Lemma cons_inj : forall x1 x2 :Type, forall l1 l2 : list Type, cons x1 l1 = cons x2 l2 -> x1=x2 /\ l1=l2. Proof. intros. injection H. split. apply H1. apply H0. Qed. *) Parameter A:Type. Definition tl (l: list A) : list A := match l with nil => nil |cons _ t => t end . Definition hd (v:A) (l: list A) : A := match l with nil => v |cons h t => h end . Lemma cons_inj : forall x1 x2 :A, forall l1 l2 : list A, cons x1 l1 = cons x2 l2 -> x1=x2 /\ l1=l2. Proof. intros. split. apply f_equal with (f:= hd x1) in H. simpl in H. apply H. apply f_equal with (f:= tl) in H. simpl in H. apply H. Qed. Definition Nil (l: list A) := match l with nil => True |_ => False end . Lemma cons_discr : forall x : A, forall l : list A, nil <> cons x l. Proof. intros. unfold not. intro. apply f_equal with (f:=Nil) in H. unfold Nil in H. rewrite <- H. exact I.
\ mouse \ \ Copyright (C) 2016 David J Goehrig <[email protected]> \ \ This software is provided 'as-is' \ warranty. In no event will the authors be held liable for any damages \ arising from the use of this software. \ \ Permission is granted to anyone to use this software for any purpose \ including commercial applications \ freely \ \ 1. The origin of this software must not be misrepresented; you must not \ claim that you wrote the original software. If you use this software \ in a product \ appreciated but is not required. \ 2. Altered source versions must be plainly marked as such \ misrepresented as being the original software. \ 3. This notice may not be removed or altered from any source distribution. \ 0 enum SDL_SYSTEM_CURSOR_ARROW enum SDL_SYSTEM_CURSOR_IBEAM enum SDL_SYSTEM_CURSOR_WAIT enum SDL_SYSTEM_CURSOR_CROSSHAIR enum SDL_SYSTEM_CURSOR_WAITARROW enum SDL_SYSTEM_CURSOR_SIZENWSE enum SDL_SYSTEM_CURSOR_SIZENESW enum SDL_SYSTEM_CURSOR_SIZEWE enum SDL_SYSTEM_CURSOR_SIZENS enum SDL_SYSTEM_CURSOR_SIZEALL enum SDL_SYSTEM_CURSOR_NO enum SDL_SYSTEM_CURSOR_HAND enum SDL_NUM_SYSTEM_CURSORS drop : SDL_BUTTON 1- 1 swap lshift ; 1 constant SDL_BUTTON_LEFT 2 constant SDL_BUTTON_MIDDLE 3 constant SDL_BUTTON_RIGHT 4 constant SDL_BUTTON_X1 5 constant SDL_BUTTON_X2 SDL_BUTTON_LEFT SDL_BUTTON constant SDL_BUTTON_LMASK SDL_BUTTON_MIDDLE SDL_BUTTON constant SDL_BUTTON_MMASK SDL_BUTTON_RIGHT SDL_BUTTON constant SDL_BUTTON_RMASK SDL_BUTTON_X1 SDL_BUTTON constant SDL_BUTTON_X1MASK SDL_BUTTON_X2 SDL_BUTTON constant SDL_BUTTON_X2MASK FUNCTION: SDL_GetMouseFocus ( -- win ) FUNCTION: SDL_GetMouseState ( x* y* -- buttons ) FUNCTION: SDL_GetRelativeMouseState ( x* y* -- buttons ) FUNCTION: SDL_WarpMouseInWindow ( win x y -- ) FUNCTION: SDL_SetRelativeMouseMode ( flag -- flag ) FUNCTION: SDL_GetRelativeMouseMode ( -- flag ) FUNCTION: SDL_CreateCursor ( data mask w h x y -- cursor ) FUNCTION: SDL_CreateColorCursor ( surface x y -- cursor ) FUNCTION: SDL_CreateSystemCursor ( id -- cursor ) FUNCTION: SDL_SetCursor ( cursor -- ) FUNCTION: SDL_GetCursor ( -- cursor ) FUNCTION: SDL_GetDefaultCursor ( -- cursor ) FUNCTION: SDL_FreeCursor ( cursor -- ) FUNCTION: SDL_ShowCursor ( flag -- flag )
# Source all the plotting scripts # The user has to input a vector/list of numbers associated with the lecture notes they would like to reproduce run_plots <- function(list_lecture_nr, data_vintage) { list_lecture_nr <- as.character(list_lecture_nr) for (lecture_nr in list_lecture_nr) { str <- sprintf("lectures/lec%s/code/plot_all.r", lecture_nr) path_to_script <- here(str) source(path_to_script) do.call(plot_all, list(lecture_nr, data_vintage)) } }
Global Set Primitive Projections. Global Unset Printing Primitive Projection Parameters. Global Set Universe Polymorphism. Global Set Default Goal Selector "!". From Ltac2 Require Import Ltac2. Set Default Proof Mode "Classic". Require Import Coq.Unicode.Utf8. Require Import Coq.Lists.List. Require Import Coq.Setoids.Setoid. Require Import Coq.Classes.SetoidClass. Module Import Bundle. #[universes(cumulative)] Record bundle A := suprema { s: Type ; Ο€: s β†’ A ; }. Arguments suprema [A s]. Arguments s [A]. Arguments Ο€ [A]. Coercion s: bundle >-> Sortclass. Coercion Ο€: bundle >-> Funclass. Notation "'sup' x .. y , P" := {| Ο€ x := .. {| Ο€ y := P |} .. |} (at level 200, x binder, y binder, right associativity, format "'[ ' '[ ' 'sup' x .. y ']' , '/' P ']'"). End Bundle. Module Import Span. #[universes(cumulative)] Record span A B := { s: Type ; Ο€1: s β†’ A ; Ο€2: s β†’ B ; }. Arguments s [A B]. Arguments Ο€1 [A B]. Arguments Ο€2 [A B]. Coercion s: span >-> Sortclass. Module Export SpanNotations. Reserved Notation "'SPAN' x , P β€”β€”β€”β€” Q" (x ident, at level 90, format "'SPAN' x , '//' P '//' β€”β€”β€”β€” '//' Q"). Reserved Notation "'SPAN' x : A , P β€”β€”β€”β€” Q" (x ident, at level 90, format "'SPAN' x : A , '//' P '//' β€”β€”β€”β€” '//' Q"). Reserved Notation "'SPAN' ( x : A ) , P β€”β€”β€”β€” Q" (x ident, at level 90, format "'SPAN' ( x : A ) , '//' P '//' β€”β€”β€”β€” '//' Q"). Notation "'SPAN' x , P β€”β€”β€”β€” Q" := {| Ο€1 x := P ; Ο€2 x := Q |} . Notation "'SPAN' x : A , P β€”β€”β€”β€” Q" := {| Ο€1 (x : A) := P ; Ο€2 (x : A) := Q |} . Notation "'SPAN' ( x : A ) , P β€”β€”β€”β€” Q" := {| Ο€1 (x : A) := P ; Ο€2 (x : A) := Q |} . End SpanNotations. End Span. Module Import Logic. Import List.ListNotations. (* FIXME have an or for results as well ? *) Definition axiom C := span C C. Definition axiom_scheme C := bundle (axiom C). Definition theory C := bundle (axiom_scheme C). (* FIXME make category *) Inductive syn {K} {th: theory K}: K β†’ K β†’ Type := | syn_id {A}: syn A A | syn_compose {A B C}: syn B C β†’ syn A B β†’ syn A C | syn_axiom rule args C D: (βˆ€ ix, syn C (Ο€1 (th rule args) ix)) β†’ (βˆ€ ix, syn (Ο€2 (th rule args) ix) D) β†’ syn C D . End Logic. Module Import Sanity. #[universes(cumulative)] Class Propositional := { P: Type ; true: P ; and: P β†’ P β†’ P ; false: P ; or: P β†’ P β†’ P ; }. Infix "∧" := and. Infix "∨" := or. Variant idx := | bang | absurd | inl | inr | fanin | fst | snd | fanout. Definition propositional `{Propositional}: theory P := sup ix, match ix with | bang => sup A, SPAN (_: True), A β€”β€”β€”β€” true | absurd => sup A, SPAN (_: True), false β€”β€”β€”β€” A | fanin => sup '(A, B), SPAN b:bool, A ∨ B β€”β€”β€”β€” if b then A else B | inl => sup '(A, B), SPAN _:True, A β€”β€”β€”β€” A ∨ B | inr => sup '(A, B), SPAN _:True, B β€”β€”β€”β€” A ∨ B | fanout => sup '(A, B), SPAN b:bool, (if b then A else B) β€”β€”β€”β€” A ∧ B | fst => sup '(A, B), SPAN _:True, A ∧ B β€”β€”β€”β€” A | snd => sup '(A, B), SPAN _:True, A ∧ B β€”β€”β€”β€” B end . Section sanity. Context `{Propositional}. Definition free := @syn _ propositional. Definition bang' C: free C true := @syn_axiom _ propositional bang C C true (Ξ» _, syn_id) (Ξ» _, syn_id). Definition inl' A B: free A (A ∨ B) := @syn_axiom _ propositional inl (A, B) A (A ∨ B) (Ξ» _, syn_id) (Ξ» _, syn_id). Definition inr' A B: free B (A ∨ B) := @syn_axiom _ propositional inr (A, B) B (A ∨ B) (Ξ» _, syn_id) (Ξ» _, syn_id). #[program] Definition fanin' C A B (f: free A C) (g: free B C) := @syn_axiom _ propositional fanin (A, B) (A ∨ B) C (Ξ» _, syn_id) _. Next Obligation. destruct ix. - apply f. - apply g. Defined. #[program] Definition fanout' C A B (f: free C A) (g: free C B): free C (A ∧ B) := @syn_axiom _ propositional fanout (A, B) C (A ∧ B) _ (Ξ» _, syn_id). Next Obligation. destruct ix. - apply f. - apply g. Defined. Definition fst' A B: free (A ∧ B) A := @syn_axiom _ propositional fst (A, B) (A ∧ B) A (Ξ» _, syn_id) (Ξ» _, syn_id). Definition snd' A B: free (A ∧ B) B := @syn_axiom _ propositional snd (A, B) (A ∧ B) B (Ξ» _, syn_id) (Ξ» _, syn_id). End sanity. Instance as_Prop: Propositional := { P := Prop ; true := True ; and := Logic.and ; false := False ; or := Logic.or ; }. Definition eval_Prop [A B: @P as_Prop]: free A B β†’ A β†’ B. intros f. induction f. - intro x. apply x. - intro x. apply (IHf1 (IHf2 x)). - destruct rule. all: cbn in *. + intro x. apply H0. all: auto. + intro x. set (H' := H I x). contradiction. + intro x. destruct args as [P Q]. cbn in *. apply (H0 I). left. apply (H I x). + intro x. destruct args as [P Q]. cbn in *. apply (H0 I). right. apply (H I x). + destruct args as [P Q]. cbn in *. intro x. refine (_ (H Datatypes.false x)). * intro x'. destruct x'. -- apply (H0 Datatypes.true H1). -- apply (H0 Datatypes.false H1). + destruct args as [P Q]. cbn in *. intro x. apply (H0 I). apply (H I x). + destruct args as [P Q]. cbn in *. intro x. apply (H0 I). apply (H I x). + destruct args as [P Q]. cbn in *. intro x. apply (H0 Datatypes.false). split. * apply (H Datatypes.true x). * apply (H Datatypes.false x). Defined. Instance as_Set: Propositional := { P := Set ; true := unit ; and := prod ; false := Empty_set ; or := sum ; }. Definition eval_Set [A B: @P as_Set]: free A B β†’ A β†’ B. intros f. induction f. - intro x. apply x. - intro x. apply (IHf1 (IHf2 x)). - destruct rule. all: cbn in *. + intro x. apply (H0 I tt). + intro x. set (H' := H I x). contradiction. + intro x. destruct args as [P Q]. cbn in *. apply (H0 I). left. apply (H I x). + intro x. destruct args as [P Q]. cbn in *. apply (H0 I). right. apply (H I x). + destruct args as [P Q]. cbn in *. intro x. refine (_ (H Datatypes.false x)). * intro x'. destruct x' as [p|q]. -- apply (H0 Datatypes.true p). -- apply (H0 Datatypes.false q). + destruct args as [P Q]. cbn in *. intro x. apply (H0 I). apply (H I x). + destruct args as [P Q]. cbn in *. intro x. apply (H0 I). apply (H I x). + destruct args as [P Q]. cbn in *. intro x. apply (H0 Datatypes.false). split. * apply (H Datatypes.true x). * apply (H Datatypes.false x). Defined. Example foo `{Propositional}: free true (true ∧ true) := fanout' _ _ _ (bang' _) (bang' _). Definition foo' := eval_Set foo. End Sanity. (* FIXME do the same thing but with bundles ? *) Module Import Hoas. #[universes(cumulative)] Class Lam := { tm: Type ; ty: Type ; pt: ty ; exp: ty β†’ ty β†’ ty ; lam: ty β†’ (tm β†’ tm) β†’ tm ; app: tm β†’ tm β†’ tm ; }. End Hoas. Module Import Spec. Import List.ListNotations. Variant type_query `{Lam} := ofty (_:tm) (_: ty). Module Export SpecNotations. Infix "∈" := ofty (at level 40). End SpecNotations. Open Scope logic_scope. Variant index := app_rule | lam_rule. Definition stlc `{Lam}: theory type_query := {| dom := index ; proj x := match x with | app_rule => FREE (A, B, f, x) , app f x ∈ B ⊒ [ f ∈ exp A B ; x ∈ A ] (* Not sure how I'm going to handle variables, not correct at all here, Also not sure how I'm going to handle evaluating expressions *) | lam_rule => FREE (A, B, f, x) , lam A f ∈ exp A B ⊒ [ x ∈ A ; f x ∈ B] end |}. End Spec. Module Import Sanity. Import List.ListNotations. Section sanity. Context `{Lam}. Definition free := @syn _ stlc. Definition foo x A: free [ x ∈ A ; x ∈ A ] []. apply (syn_weaken nil). Defined. End sanity. End Sanity. Module Import Lattice. #[universes(cumulative)] Class Lattice := { S: Type ; top: S ; bot: S ; meet: S β†’ S β†’ S ; join: S β†’ S β†’ S ; }. Definition meet_all `{Lattice}: list S β†’ S := List.fold_right meet top. Definition join_all `{Lattice}: list S β†’ S := List.fold_right join bot. Module Export LatticeNotations. Declare Scope lattice_scope. Delimit Scope lattice_scope with lattice. Bind Scope lattice_scope with S. Notation "⊀" := top : lattice_scope. Notation "βŠ₯" := bot : lattice_scope. Infix "∧" := meet : lattice_scope. Notation "β‹€" := meet_all : lattice_scope. Notation "⋁" := join_all : lattice_scope. Coercion S: Lattice >-> Sortclass. End LatticeNotations. End Lattice. (* FIXME implement a Lattice algebra using bundles and interpret everything categorically *) Module Import Pred. #[program] Definition predicate_logic A: Lattice := {| S := A β†’ Prop ; top _ := True ; bot _ := False ; meet P Q x := P x ∧ Q x ; join P Q x := P x ∨ Q x ; |}. End Pred. Module Import Sanity. Local Set Implicit Arguments. Definition ofty `{Lam} A B f x := check stlc app_rule (A, B, f, x). Check ofty. Definition ofty `{Lam} i v x A := let (H, T) := chk (predicate_logic _) (simplify pred_stlc) {| ix := i ; val := v |} in H (x ∈ A) β†’ T (x ∈ A). Definition foo `{Lam} A: ofty (lam A (Ξ» x, x)) (exp A A). exists lam_rule. intro. cbn in *. destruct . Definition bar `{Lam} := foo 0 I. #[program] Definition bar `{Lam} := foo 1 _. Next Obligation. cbn. (* Definition foo `{Lam}: oftype (Ξ» x, x = P ∈ T) (Ξ» x, x = P ∈ T) *) cbn. eexists. Unshelve. 2: { cbn. left. exists. } cbn. reflexivity. Qed. End Sanity. Module Import Foo. Definition type_Lattice := {| S := Set ; top := True ; bot := False ; meet P Q := P * Q ; join P Q := P + Q ; |}. Definition oftype `{Lam} (p: any_head rules) := let (H, T) := chk type_Lattice (Ξ» q, {x: type_query | q = x}) rules p in T β†’ H. Definition bar `{Lam} : any_head rules. cbn. left. exists. Defined. Definition foo `{Lam}: oftype bar. cbn. intros. exists (P ∈ T). reflexivity. Defined. End Foo.
[STATEMENT] lemma OTNoTN[rule_format]: " OnlyTwoNets p \<longrightarrow> x \<noteq> DenyAll \<longrightarrow> x \<in> set p \<longrightarrow> onlyTwoNets x" [PROOF STATE] proof (prove) goal (1 subgoal): 1. OnlyTwoNets p \<longrightarrow> x \<noteq> DenyAll \<longrightarrow> x \<in> set p \<longrightarrow> onlyTwoNets x [PROOF STEP] apply (induct p, simp_all, rename_tac a p) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>a p. OnlyTwoNets p \<longrightarrow> x \<noteq> DenyAll \<longrightarrow> x \<in> set p \<longrightarrow> onlyTwoNets x \<Longrightarrow> OnlyTwoNets (a # p) \<longrightarrow> x \<noteq> DenyAll \<longrightarrow> (x = a \<longrightarrow> onlyTwoNets a) \<and> (x \<in> set p \<longrightarrow> onlyTwoNets x) [PROOF STEP] apply (intro impI conjI, simp) [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>a p. \<lbrakk>OnlyTwoNets p \<longrightarrow> a \<in> set p \<longrightarrow> onlyTwoNets a; OnlyTwoNets (a # p); a \<noteq> DenyAll; x = a\<rbrakk> \<Longrightarrow> onlyTwoNets a 2. \<And>a p. \<lbrakk>OnlyTwoNets p \<longrightarrow> x \<noteq> DenyAll \<longrightarrow> x \<in> set p \<longrightarrow> onlyTwoNets x; OnlyTwoNets (a # p); x \<noteq> DenyAll; x \<in> set p\<rbrakk> \<Longrightarrow> onlyTwoNets x [PROOF STEP] subgoal for a p [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>OnlyTwoNets p \<longrightarrow> a \<in> set p \<longrightarrow> onlyTwoNets a; OnlyTwoNets (a # p); a \<noteq> DenyAll; x = a\<rbrakk> \<Longrightarrow> onlyTwoNets a [PROOF STEP] apply(case_tac a, simp_all) [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>a p. \<lbrakk>OnlyTwoNets p \<longrightarrow> x \<noteq> DenyAll \<longrightarrow> x \<in> set p \<longrightarrow> onlyTwoNets x; OnlyTwoNets (a # p); x \<noteq> DenyAll; x \<in> set p\<rbrakk> \<Longrightarrow> onlyTwoNets x [PROOF STEP] subgoal for a p [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>OnlyTwoNets p \<longrightarrow> x \<noteq> DenyAll \<longrightarrow> x \<in> set p \<longrightarrow> onlyTwoNets x; OnlyTwoNets (a # p); x \<noteq> DenyAll; x \<in> set p\<rbrakk> \<Longrightarrow> onlyTwoNets x [PROOF STEP] apply(case_tac a, simp_all) [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done
ResultDir <- "/gpfs/data/stranger-lab/askol/TCGA2/DiffExpression/Results/" SurvResultDir <- "/gpfs/data/stranger-lab/askol/TCGA2/DE_Surv/Results/" DataDir <- "/gpfs/data/stranger-lab/askol/TCGA2/Data/Expression/" ## READ IN DE RESULTS ## projects = read.table(file = "/gpfs/data/stranger-lab/askol/TCGA/TCGA_Target_projects.txt", header=TRUE, as.is=TRUE, sep="\t") projects = projects[grep("TCGA",projects[,1]),1] skip.cancers <- c("TCGA-BRCA","TCGA-OV", "TCGA-CESC", "TCGA-PRAD", "TCGA-TGCT", "TCGA-UCS", "TCGA-UCEC") projects <- projects[!projects %in% skip.cancers] tmp <- collect.de.results(projects, ResultDir) logFC.tcga <- tmp$logFC logPs.tcga <- tmp$logPs Qs.tcga <- tmp$Qs ## READ IN GSEA RESULTS ## file <- paste0(ResultDir,"GSEA_Cluster_Genes_NoX_gt6shared.txt") ## LEADING EDGE GENES FROM GENE SETS ASSOCIATED WITH HIGH-LEVEL CLUSTER ASSIGNMENTS ## ONLY INCLUDES GENES THAT WERE PRESENT IN 25% OR MORE OF THE GENESETS BELONGING TO ## THE HL CLUSTER cl.genes.25 <- read.table(file = file, header=T, as.is=T) ## CLUSTER DEFINITIONS cluster.labs <- rbind(c(0,"Mitochondria/Phosphorylation/TCA"), c(2,"Transcription/Translation/RNA Metabolism"), c(3,"Cancer Gene Neighborhood (MORF)"), c(4,"DNA packaging"), c(5,"Mitosis/Cell cycle/Cancer/Chromosome Segregation"), c(6,"Immunity"), c(7,"Cytokines/Inflammation"), c(8,"Cell adhesion and Immunity"), c(9,"Monocytes"), c(10, "Immune Response"), c(11, "Cancer Modules"), c(12, "mRNA processing/splicing"), c(13, "Mircroglia"), c(15, "Extracellular Matrix"), c(16, "Cancer/Immunity/Inflammation"), c(17, "Rapamycin"), c(18, "Cancer Modules2")) ## READ IN SURVIVAL RESULTS ## sdata <- collect.surv.data(SurvResultDir) sdata <- mutate(sdata, DEPop = ifelse(grepl("TCGA",tissue), "TCGA" , "GTEx")) ## survival results used are thos with suffix: _lcpm.invnorm.covs_<sex>_COEF.txt ## ## PLOT SIGNED LOG P-VALUES VERSUS DE ## COLOR CODE FOR CANCER, SHAPE FOR ALL, FEMALE, MALE ## AND SIZE FOR SURVIVAL P-VALUE ## FOR EACH CANCER AND EACH HIGH LEVEL FUNCTION, USE A FISHER'S LOG SUM P-VALUE TO ## ASSESS HOW MUCH A HIGH LEVEL FUNCTION IS AFFECTING SURVIVAL
Formal statement is: lemma fract_poly_0 [simp]: "fract_poly 0 = 0" Informal statement is: The fractional polynomial of degree 0 is 0.
N Street is the highest lettered Navigating Davis street in Davis. It is a short and entirely residential street, only connected to the rest of the world by Lehigh St. and Colgate Dr. Stuff on N Street: N Street Park N Street Cohousing
! This is a test program that CMake uses to check that the Fortran compiler is ! working. PROGRAM TESTFortran PRINT *, 'Hello' END
/- Copyright (c) 2021 OpenAI. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kunhao Zheng, Stanislas Polu, David Renshaw, OpenAI GPT-f -/ import mathzoo.imports.miniF2F open_locale nat rat real big_operators topological_space theorem mathd_algebra_432 (x : ℝ) : (x + 3) * (2 * x - 6) = 2 * x^2 - 18 := begin linarith, end
% THIS IS SIGPROC-SP.TEX - VERSION 3.1 % WORKS WITH V3.2SP OF ACM_PROC_ARTICLE-SP.CLS % APRIL 2009 % % It is an example file showing how to use the 'acm_proc_article-sp.cls' V3.2SP % LaTeX2e document class file for Conference Proceedings submissions. % ---------------------------------------------------------------------------------------------------------------- % This .tex file (and associated .cls V3.2SP) *DOES NOT* produce: % 1) The Permission Statement % 2) The Conference (location) Info information % 3) The Copyright Line with ACM data % 4) Page numbering % --------------------------------------------------------------------------------------------------------------- % It is an example which *does* use the .bib file (from which the .bbl file % is produced). % REMEMBER HOWEVER: After having produced the .bbl file, % and prior to final submission, % you need to 'insert' your .bbl file into your source .tex file so as to provide % ONE 'self-contained' source file. % % Questions regarding SIGS should be sent to % Adrienne Griscti ---> [email protected] % % Questions/suggestions regarding the guidelines, .tex and .cls files, etc. to % Gerald Murray ---> [email protected] % % For tracking purposes - this is V3.1SP - APRIL 2009 \documentclass{acm_proc_article-sp} \begin{document} \title{Hello World} % % You need the command \numberofauthors to handle the 'placement % and alignment' of the authors beneath the title. % % For aesthetic reasons, we recommend 'three authors at a time' % i.e. three 'name/affiliation blocks' be placed beneath the title. % % NOTE: You are NOT restricted in how many 'rows' of % "name/affiliations" may appear. We just ask that you restrict % the number of 'columns' to three. % % Because of the available 'opening page real-estate' % we ask you to refrain from putting more than six authors % (two rows with three columns) beneath the article title. % More than six makes the first-page appear very cluttered indeed. % % Use the \alignauthor commands to handle the names % and affiliations for an 'aesthetic maximum' of six authors. % Add names, affiliations, addresses for % the seventh etc. author(s) as the argument for the % \additionalauthors command. % These 'additional authors' will be output/set for you % without further effort on your part as the last section in % the body of your article BEFORE References or any Appendices. \newcommand{\AUTHORS}{1,2,3} \numberofauthors{2} % in this sample file, there are a *total* % of EIGHT authors. SIX appear on the 'first-page' (for formatting % reasons) and the remaining two appear in the \additionalauthors section. % \author{ % You can go ahead and credit any number of authors here, % e.g. one 'row of three' or two rows (consisting of one row of three % and a second row of one, two or three). % % The command \alignauthor (no curly braces needed) should % precede each author name, affiliation/snail-mail address and % e-mail address. Additionally, tag each line of % affiliation/address with \affaddr, and tag the % e-mail address with \email. % % 1st. author \alignauthor Ben Trovato\\ \affaddr{Institute for Clarity in Documentation}\\ \affaddr{1932 Wallamaloo Lane}\\ \affaddr{Wallamaloo, New Zealand}\\ \email{[email protected]} % 2nd. author \alignauthor G.K.M. Tobin\\ \affaddr{Institute for Clarity in Documentation}\\ \affaddr{P.O. Box 1212}\\ \affaddr{Dublin, Ohio 43017-6221}\\ \email{[email protected]} } % There's nothing stopping you putting the seventh, eighth, etc. % author on the opening page (as the 'third row') but we ask, % for aesthetic reasons that you place these 'additional authors' % in the \additional authors block, viz. \date{30 July 1999} % Just remember to make sure that the TOTAL number of authors % is the number that will appear on the first page PLUS the % number that will appear in the \additionalauthors section. \maketitle \begin{abstract} Abstract goes here \end{abstract} % A category with the (minimum) three required fields \category{H.4}{Information Systems Applications}{Miscellaneous} %A category including the fourth, optional field follows... \category{D.2.8}{Software Engineering}{Metrics}[complexity measures, performance measures] \terms{Theory} \keywords{ACM proceedings, \LaTeX, text tagging} % NOT required for Proceedings \input{1.introduction} \input{2.related} \section{Conclusions} conclusions go here %\end{document} % This is where a 'short' article might terminate %ACKNOWLEDGMENTS are optional \section{Acknowledgments} I would like to thank... % % The following two commands are all you need in the % initial runs of your .tex file to % produce the bibliography for the citations in your paper. \bibliographystyle{abbrv} \bibliography{sigproc} % sigproc.bib is the name of the Bibliography in this case \balancecolumns % That's all folks! \end{document}
function predict(net::Vector{Layer},input) net[1].rβ‚’=input for idx=1:length(net)-1 forward!(net[idx]) end ~,index=findmax(net[end-1].rβ‚’,1) #regression=>net[end-1].rβ‚’ return map(x->mod1(x,size(net[end-1].rβ‚’,1)),index) end
lemma bounded_Un[simp]: "bounded (S \<union> T) \<longleftrightarrow> bounded S \<and> bounded T"
module TestConnectance using Test using EcologicalNetworks using LinearAlgebra # Generate some data N = BipartiteProbabilisticNetwork([0.0 0.1 0.0; 0.2 0.0 0.2; 0.4 0.5 0.0]) @test links(N) β‰ˆ 1.4 @test links_var(N) β‰ˆ 0.9 @test connectance(N) β‰ˆ 1.4 / 9.0 @test connectance_var(N) β‰ˆ 0.011111111111111111111 # Once more with a deterministic network N = BipartiteNetwork([false true false; false false true; true true true]) @test links(N) β‰ˆ 5 @test connectance(N) β‰ˆ 5/9 @test linkage_density(N) β‰ˆ 5/6 # Once more with a deterministic unipartite network N = UnipartiteNetwork([false true false; false false true; true true true]) @test links(N) β‰ˆ 5 @test connectance(N) β‰ˆ 5/9 @test linkage_density(N) β‰ˆ 5/3 # Links with quantitative networks K = BipartiteQuantitativeNetwork(rand(Float64, (3,3))) @test links(K) == 9 # Convert to adjacency @test connectance(UnipartiteNetwork(Matrix(I, (10,10)))) β‰ˆ connectance(UnipartiteQuantitativeNetwork(Matrix{Int64}(I, (10,10)).*2)) end
{- Byzantine Fault Tolerant Consensus Verification in Agda, version 0.9. Copyright (c) 2020 Oracle and/or its affiliates. Licensed under the Universal Permissive License v 1.0 as shown at https://opensource.oracle.com/licenses/upl -} open import Optics.All open import LibraBFT.Prelude open import LibraBFT.Hash open import LibraBFT.Lemmas open import LibraBFT.Base.KVMap open import LibraBFT.Base.PKCS open import LibraBFT.Abstract.Types open EpochConfig open import LibraBFT.Impl.NetworkMsg open import LibraBFT.Impl.Consensus.Types open import LibraBFT.Impl.Util.Crypto open import LibraBFT.Impl.Handle sha256 sha256-cr open import LibraBFT.Concrete.System.Parameters open import LibraBFT.Yasm.Base open import LibraBFT.Yasm.AvailableEpochs using (AvailableEpochs ; lookup'; lookup'') open import LibraBFT.Yasm.System ConcSysParms open import LibraBFT.Yasm.Properties ConcSysParms -- This module contains placeholders for the future analog of the -- corresponding VotesOnce property. Defining the implementation -- obligation and proving that it is an invariant of an implementation -- is a substantial undertaking. We are working first on proving the -- simpler VotesOnce property to settle down the structural aspects -- before tackling the harder semantic issues. module LibraBFT.Concrete.Properties.LockedRound where -- TODO-3: define the implementation obligation ImplObligation₁ : Set ImplObligation₁ = Unit -- Next, we prove that given the necessary obligations, module Proof (sps-corr : StepPeerState-AllValidParts) (Impl-LR1 : ImplObligation₁) where -- Any reachable state satisfies the LR rule for any epoch in the system. module _ {e}(st : SystemState e)(r : ReachableSystemState st)(eid : Fin e) where -- Bring in 'unwind', 'ext-unforgeability' and friends open Structural sps-corr -- Bring in ConcSystemState open import LibraBFT.Concrete.System sps-corr open PerState st r open PerEpoch eid open import LibraBFT.Abstract.Obligations.LockedRound 𝓔 Hash _β‰ŸHash_ (ConcreteVoteEvidence 𝓔) as LR postulate -- TODO-3: prove it lrr : LR.Type ConcSystemState
/- Copyright (c) 2021 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author : Kevin Buzzard -/ import tactic -- imports all the Lean tactics /-! # Sets in Lean, example sheet 2 : the empty set and the "universal set". We know what the empty subset of `X` is, and the Lean notation for it is `βˆ…`, or, if you want to say which type we're the empty subset of, it's `βˆ… : set X`. At the other extreme, the subset of `X` containing all the terms of type `X` is...well...mathematicians would just call it `X`, but `X` is a type, and so if we want a set it's called `set.univ : set X`, or just `univ : set X` if we have opened the `set` namespace. Let's do that now. -/ open set /- ## Important `x ∈ βˆ…` is *by definition* equal to `false` and `x ∈ univ` is *by definition* equal to `true`. You can use the `change` tactic to make these changes if you like. But you don't have to. ## Tactics you will need You've seen them already. `trivial` proves `⊒ true` and `exfalso` changes `⊒ P` to `⊒ false`. -/ -- set up variables variables (X : Type) -- Everything will be a subset of `X` (A B C D E : set X) -- A,B,C,D,E are subsets of `X` (x y z : X) -- x,y,z are elements of `X` or, more precisely, terms of type `X` /- If `x : X` then `x ∈ βˆ…` is *by definition* `false`, and `x ∈ univ` is *by definition* `true`. So you can use the `change` tactic to change between these things, for example if your goal is ``` ⊒ x ∈ univ ``` then `change true` will change the goal to ``` ⊒ true ``` and you can now prove this goal with `trivial`. However you can prove it with `trivial` even without `change`ing it. -/ open set example : x ∈ (univ : set X) := begin trivial, end example : x ∈ (βˆ… : set X) β†’ false := begin intro h, exact h, end example : βˆ€ x : X, x ∈ A β†’ x ∈ (univ : set X) := begin intros x h, trivial, end example : βˆ€ x : X, x ∈ (βˆ… : set X) β†’ x ∈ A := begin intros x h, exfalso, exact h, end
State Before: o : Ordinal ho : ord (card o) = o ho' : Ο‰ ≀ o ⊒ βˆƒ a, ord (aleph a) = o State After: case intro o : Ordinal ho : ord (card o) = o ho' : Ο‰ ≀ o a : Ordinal ha : ord (aleph' a) = o ⊒ βˆƒ a, ord (aleph a) = o Tactic: cases' eq_aleph'_of_eq_card_ord ho with a ha State Before: case intro o : Ordinal ho : ord (card o) = o ho' : Ο‰ ≀ o a : Ordinal ha : ord (aleph' a) = o ⊒ βˆƒ a, ord (aleph a) = o State After: case intro o : Ordinal ho : ord (card o) = o ho' : Ο‰ ≀ o a : Ordinal ha : ord (aleph' a) = o ⊒ ord (aleph (a - Ο‰)) = o Tactic: use a - Ο‰ State Before: case intro o : Ordinal ho : ord (card o) = o ho' : Ο‰ ≀ o a : Ordinal ha : ord (aleph' a) = o ⊒ ord (aleph (a - Ο‰)) = o State After: case intro o : Ordinal ho : ord (card o) = o ho' : Ο‰ ≀ o a : Ordinal ha : ord (aleph' a) = o ⊒ ord (aleph' (Ο‰ + (a - Ο‰))) = o Tactic: unfold aleph State Before: case intro o : Ordinal ho : ord (card o) = o ho' : Ο‰ ≀ o a : Ordinal ha : ord (aleph' a) = o ⊒ ord (aleph' (Ο‰ + (a - Ο‰))) = o State After: case intro o : Ordinal ho : ord (card o) = o ho' : Ο‰ ≀ o a : Ordinal ha : ord (aleph' a) = o ⊒ Ο‰ ≀ a Tactic: rwa [Ordinal.add_sub_cancel_of_le] State Before: case intro o : Ordinal ho : ord (card o) = o ho' : Ο‰ ≀ o a : Ordinal ha : ord (aleph' a) = o ⊒ Ο‰ ≀ a State After: no goals Tactic: rwa [← aleph0_le_aleph', ← ord_le_ord, ha, ord_aleph0]
\documentclass{memoir} \usepackage{notestemplate} %\logo{~/School-Work/Auxiliary-Files/resources/png/logo.png} %\institute{Rice University} %\faculty{Faculty of Whatever Sciences} %\department{Department of Mathematics} %\title{Class Notes} %\subtitle{Based on MATH xxx} %\author{\textit{Author}\\Gabriel \textsc{Gress}} %\supervisor{Linus \textsc{Torvalds}} %\context{Well, I was bored...} %\date{\today} \begin{document} % \maketitle % Notes taken on 05/10/21 We can summarize our characterization thus far by a set of equivalences. The following are equivalent: \begin{itemize} \item A finite field extension \(K / F\) is Galois \item \(\left| \textrm{Aut}(K / F) \right| = [K:F]\) \item \(K / F\) is the splitting field of a separable polynomial over \(F\) \item \(K / F\) is normal and separable \item \(F = K^{\textrm{Aut}(K / F)}\) \end{itemize} \section{Fundamental Theorem of Galois Theory} \label{sec:fundamental_theorem_of_galois_theory} \begin{thm}[Fundamental Theorem of Galois Theory] Let \(K / F\) be Galois and set \(G:= \textrm{Gal}(K / F)\). Then there exists a bijection between the subfields \(E\subset K\) with \(F\subset E\) and the subgroups \(H \leq G\) given by \begin{align*} E \mapsto \textrm{Aut}(K / E)\\ H \mapsto K^{H} \end{align*} and these maps are inverses of each other. Furthermore, this bijection has some additonal properties: \begin{itemize} \item If \(E_1 \leftrightarrow H_1\) and \(E_2 \leftrightarrow H_2\), then \(E_1 \subset E_2 \iff H_2 \leq H_1\). \item If \(E \leftrightarrow H\), then \([K:E] = \left| H \right| \) and \([E:F] = [G:H]\). \item \(K / E\) is always Galois for \(F \subset E \subset K\). \item \(E / F\) is Galois if and only if \(H \triangleleft G\). In this case, \(\textrm{Gal}(E / F) \cong G / H\). \item If \(E_1 \leftrightarrow H_1\) and \(E_2 \leftrightarrow H_2\), then \(E_1 \cap E_2 \leftrightarrow \langle H_1,H_2 \rangle \) and \(E_1E_2 \leftrightarrow H_1 \cap H_2\). \end{itemize} \end{thm} Remember that \(H \triangleleft G\) is equivalent to \(\textrm{Aut}(K / E) \triangleleft \textrm{Aut}(K / F)\). Also recaall that \(\langle H_1,H_2 \rangle \) is the smallest subgroup of \(G\) that contains \(H_1,H_2\), and \(E_1E_2\) is the smallest subfield of \(K\) containing \(E_1,E_2\). They are not necessarily equivalent! % Examples here % Proof here \vspace{5mm} \end{document}
If you want to use a hand cursor (like web browsers use when the mouse is over a link) you either have to have Windows 2000 or above, or use a resource. [Yes, this is an old article, but it is kept in to demonstrate the technique] The trouble with resources is that you need to know the Resource ID and for the little classes offered on this site, that is not known. So this little class steals the Hand Cursor from a standard Win32 file and uses CopyCursor (and DeleteCursor) to create a local copy. You can see it in use in the Web Link Button and MSN Message Window in this section.
Require Import Logic.Logic. Require Import Logic.BasicProofRules. Require Import Logic.Tactics. Require Import Coq.Classes.Morphisms. Local Open Scope HP_scope. Definition Preserves (P : StateFormula) (A : ActionFormula) : Formula := A -->> (P -->> next P). Global Instance Proper_Preserves_lequiv : Proper (eq ==> lequiv ==> lequiv) Preserves. Proof. morphism_intro. unfold Preserves. subst. rewrite H0. reflexivity. Qed. Global Instance Proper_Preserves_lentails : Proper (eq ==> lentails --> lentails) Preserves. Proof. morphism_intro. unfold Preserves. subst. rewrite H0. reflexivity. Qed. Theorem Preserves_Or : forall (P Q : StateFormula) (S1 S2 : ActionFormula), Preserves P S1 //\\ Preserves Q S2 |-- Preserves (P \\// Q) (P //\\ S1 \\// Q //\\ S2). Proof. unfold Preserves. simpl; restoreAbstraction. intros. charge_intro. charge_assert (next P \\// next Q); [ | charge_intros; charge_assumption ]. charge_cases; solve [ charge_left; charge_use; charge_tauto | charge_right; charge_use; charge_tauto ]. Qed. Lemma Preserves_Inv_simple : forall (P : StateFormula) (A : ActionFormula), is_st_formula P -> |-- Preserves P A -> P //\\ []A |-- []P. Proof. intros. eapply discr_indX. - assumption. - charge_assumption. - charge_assumption. - unfold Preserves in *. charge_tauto. Qed. Lemma Preserves_Inv : forall (P X : StateFormula) (A : ActionFormula) (G : Formula), is_st_formula P -> G |-- [] X -> X |-- Preserves P A -> G |-- P //\\ []A -->> []P. Proof. intros. rewrite landC. rewrite curry. charge_intros. eapply discr_indX. - assumption. - rewrite H0. rewrite Always_and. charge_assumption. - charge_assumption. - unfold Preserves in *. charge_tauto. Qed. Lemma Preserves_And_simple : forall P Q A B, Preserves P A //\\ Preserves Q B |-- Preserves (P //\\ Q) (A //\\ B). Proof. unfold Preserves. intros. rewrite next_And. charge_tauto. Qed. Lemma Preserves_And : forall (P Q : StateFormula) (A B : ActionFormula), Preserves P (Q //\\ A) //\\ Preserves Q (P //\\ B) |-- Preserves (P //\\ Q) (A //\\ B). Proof. unfold Preserves. intros. rewrite next_And. charge_tauto. Qed. Lemma Preserves_intro : forall (I P G : Formula) (A : ActionFormula), G //\\ P |-- Preserves I A -> G |-- Preserves I (P //\\ A). Proof. unfold Preserves. intros. charge_intros. charge_apply H. charge_tauto. Qed. Lemma Preserves_equiv : forall a b : StateFormula, is_st_formula a -> is_st_formula b -> a -|- b -> forall c d : Formula, c -|- d -> Preserves a c -|- Preserves b d. Proof. unfold Preserves. intros. rewrite H2; clear H2. eapply limpl_lequiv_m. { reflexivity. } { split; [ rewrite H1 at 1; rewrite (next_st_formula_entails a b) | rewrite <- H1 at 1; rewrite (next_st_formula_entails b a) ]; try reflexivity; auto; eapply H1. } Qed. Lemma Preserves_entails : forall a b : Formula, is_st_formula a -> is_st_formula b -> b -|- a -> forall c d : Formula, d |-- c -> Preserves a c |-- Preserves b d. Proof. unfold Preserves. intros. rewrite H2; clear H2. eapply limpl_lentails_m. { red. reflexivity. } { rewrite H1 at 1. rewrite (next_st_formula_entails a b); eauto. eapply H1. } Qed. Definition Inductively (P : StateFormula) (A : ActionFormula) : Formula := []Preserves P A. Lemma Inductively_Inv : forall P A, is_st_formula P -> P //\\ []A //\\ Inductively P A |-- []P. Proof. unfold Inductively, Preserves. intros. rewrite Always_and. eapply discr_indX. - auto. - charge_assumption. - charge_assumption. - charge_tauto. Qed. Lemma Inductively_And : forall P Q E, Inductively P (Q //\\ E) //\\ Inductively Q (P //\\ E) |-- Inductively (P //\\ Q) E. Proof. unfold Inductively, Preserves. intros. rewrite Always_and. always_imp_tac. rewrite next_And. charge_tauto. Qed. Lemma Inductively_Or : forall P Q S1 S2, Inductively P S1 //\\ Inductively Q S2 |-- Inductively (P \\// Q) ((P //\\ S1) \\// (Q //\\ S2)). Proof. unfold Inductively, Preserves. intros. tlaRevert. tlaRevert. rewrite <- curry. rewrite Always_and. apply Always_imp. simpl. restoreAbstraction. charge_intro. charge_intro. charge_cases; charge_tauto. Qed. Lemma Proper_Inductively : Proper (eq ==> lequiv ==> lequiv)%signature Inductively. Proof. red. do 2 red. unfold Inductively, Preserves. intros. apply Proper_Always_lequiv. eapply limpl_lequiv_m. { assumption. } { subst. reflexivity. } Qed. Lemma Proper_Inductively_entails : Proper (eq ==> lentails --> lentails)%signature Inductively. Proof. red. do 2 red. unfold Inductively, Preserves. intros. eapply Proper_Always_entails. subst. red in H0. rewrite H0. reflexivity. Qed. Lemma Inductively_equiv : forall a b : StateFormula, is_st_formula a -> is_st_formula b -> a -|- b -> forall c d : Formula, c -|- d -> Inductively a c -|- Inductively b d. Proof. unfold Inductively, Preserves. intros. apply Proper_Always_lequiv. rewrite H2; clear H2. eapply limpl_lequiv_m. { reflexivity. } { split; [ rewrite H1 at 1; rewrite (next_st_formula_entails a b) | rewrite <- H1 at 1; rewrite (next_st_formula_entails b a) ]; try reflexivity; auto; eapply H1. } Qed. Lemma Inductively_entails : forall a b : Formula, is_st_formula a -> is_st_formula b -> b -|- a -> forall c d : Formula, d |-- c -> Inductively a c |-- Inductively b d. Proof. unfold Inductively, Preserves. intros. eapply Proper_Always_entails. rewrite H2; clear H2. eapply limpl_lentails_m. { red. reflexivity. } { rewrite H1 at 1. rewrite (next_st_formula_entails a b); eauto. eapply H1. } Qed. Lemma Inductively_Or' : forall G P Q S1 S2, G |-- Inductively P S1 -> G |-- Inductively Q S2 -> G |-- Inductively (P \\// Q) ((P //\\ S1) \\// (Q //\\ S2)). Proof. intros. charge_apply (Inductively_Or P Q S1 S2). charge_tauto. Qed.
module CFT.Containers record SCont (n : Nat) where constructor MkSCont shapes : Type seq : (x, y : shapes) -> Dec (x = y) positions : shapes -> Type -- SExt : {n : Nat} -> SCont n -> Vect n Type -> Type -- SExt (MkSCont shapes seq pos) x = -- DPair shapes (\s => ((i : Fin n) -> (Vect (pos i s) (index i x)))) -- ex : {n : Nat} -> String -- ex {n} = "hello" ++ show n -- -- -- main : IO () -- main = putStrLn ex
From Coq Require Import ZArith Reals Psatz. From Flocq Require Import Binary. From mathcomp Require Import all_ssreflect ssralg all_algebra seq matrix. Import List ListNotations. From vcfloat Require Import FPLang FPLangOpt RAux Rounding Reify Float_notations Automate. Set Bullet Behavior "Strict Subproofs". Require Import floatlib. Section WITHNANS. Context {NANS: Nans}. Definition sum ty (a b : ftype ty) : ftype ty := BPLUS a b. Definition list_to_vec_float {ty} {n:nat} (l : list (ftype ty)): 'cV[ftype ty]_n := \col_(i < n) (List.nth (nat_of_ord i) l (Zconst ty 0)). (** Define matrix_addition **) Definition addmx_float {ty} {m n:nat} (A B: 'M[ftype ty]_(m,n)) : 'M[ftype ty]_(m,n) := \matrix_(i, j) (sum ty (A i j) (B i j)). Fixpoint vec_to_list_float {ty} {n:nat} (m:nat) (v :'cV[ftype ty]_n.+1) : list (ftype ty) := match m with | O => [] | S p => [v (@inord n p) ord0] ++ vec_to_list_float p v end. Definition vec_to_list_float_1 {ty} {n:nat} (m:nat) (v :'cV[ftype ty]_n.+1) := rev (vec_to_list_float m v). Lemma nth_vec_to_list_float {ty} {n:nat} i m (v :'cV[ftype ty]_n.+1) d: (i < m)%nat -> nth (m.-1 -i) (@vec_to_list_float _ n m v) d = v (@inord n i) ord0. Proof. intros. elim: m i H => [ | m IHm] i H. + by []. + simpl. rewrite leq_eqVlt in H. assert ((i == m) \/ (i < m)%nat). { by apply /orP. } destruct H0. - assert (i = m). { by apply /eqP. } rewrite H1. simpl. assert ((m - m)%nat = 0%N). { apply /eqP. rewrite subn_eq0. by []. } by rewrite H2 /=. - assert (nth (m.-1 - i) (vec_to_list_float m v) d = v (inord i) ord0). { by apply IHm. } rewrite -H1. rewrite -[in RHS]predn_sub. rewrite -subn_gt0 in H0. rewrite -predn_sub in H1. by destruct (m - i)%nat. Qed. Definition dotprod_r {t: type} (v1 v2: list (ftype t)) : ftype t := fold_right (fun x12 s => BFMA (fst x12) (snd x12) s) (Zconst t 0) (List.combine v1 v2) . Lemma combine_rev {ty}: forall (v1 v2: vector ty), length v1 = length v2 -> (combine (rev v1) (rev v2)) = rev (combine v1 v2). Proof. intros. elim: v1 v2 H => [ |s v1 IHv1] v2 H. + simpl;auto. + destruct v2. - by simpl in H. - specialize (IHv1 v2). assert (length v1 = length v2). { simpl in H. lia. } specialize (IHv1 H0). simpl. rewrite -IHv1. assert (length (rev v1) = length (rev v2)). { by rewrite !rev_length. } clear IHv1 H H0. elim: (rev v1) (rev v2) H1 => [ |a1 v3 IHv3] v4 H. * destruct v4. ++ simpl;auto. ++ by simpl in H. * destruct v4. ++ by simpl in H. ++ simpl. rewrite IHv3; try by []. simpl in H. lia. Qed. Lemma dotprod_rev_equiv {ty} (v1 v2: vector ty): length v1 = length v2 -> dotprod (rev v1) (rev v2) = dotprod_r v1 v2. Proof. intros. unfold dotprod, dotprod_r. assert (combine (rev v1) (rev v2) = rev (combine v1 v2)). { by rewrite combine_rev. } rewrite H0. rewrite <-fold_left_rev_right. rewrite rev_involutive. reflexivity. Qed. (** The issue is that b could appear more than once in the list. So the current version of lemma is not correct ***) (* Lemma fold_right_except_zero {A B} (f: B -> A -> A) (a : A) (L: list B) (b : B) : In b L -> (forall s d, In s L -> s <> b -> f s d = d) -> fold_right f a L = f b a. Admitted. *) Definition mulmx_float {ty} {m n p : nat} (A: 'M[ftype ty]_(m.+1,n.+1)) (B: 'M[ftype ty]_(n.+1,p.+1)) : 'M[ftype ty]_(m.+1,p.+1):= \matrix_(i, k) let l1 := vec_to_list_float n.+1 (\row_(j < n.+1) A i j)^T in let l2 := vec_to_list_float n.+1 (\col_(j < n.+1) B j k) in @dotprod_r ty l1 l2. Definition opp_mat {ty} {m n: nat} (A : 'M[ftype ty]_(m.+1, n.+1)) : 'M[ftype ty]_(m.+1, n.+1) := \matrix_(i,j) (BOPP (A i j)). Definition sub_mat {ty} {m n: nat} (A B : 'M[ftype ty]_(m.+1, n.+1)) : 'M[ftype ty]_(m.+1, n.+1) := \matrix_(i,j) (BMINUS (A i j) (B i j)). Notation "A +f B" := (addmx_float A B) (at level 80). Notation "-f A" := (opp_mat A) (at level 50). Notation "A *f B" := (mulmx_float A B) (at level 70). Notation "A -f B" := (sub_mat A B) (at level 80). Definition A1_inv_J {ty} {n:nat} (A: 'M[ftype ty]_n.+1) : 'cV[ftype ty]_n.+1 := \col_i (BDIV (Zconst ty 1) (A i i)). Definition A2_J {ty} {n:nat} (A: 'M[ftype ty]_n.+1): 'M[ftype ty]_n.+1 := \matrix_(i,j) if (i==j :> nat) then (Zconst ty 0) else A i j. Definition diag_vector_mult {ty} {n:nat} (v1 v2: 'cV[ftype ty]_n.+1) : 'cV[ftype ty]_n.+1 := \col_i (BMULT (nth (n.+1.-1 -i) (vec_to_list_float n.+1 v1) (Zconst ty 0)) (nth (n.+1.-1 - i) (vec_to_list_float n.+1 v2) (Zconst ty 0))). Definition jacobi_iter {ty} {n:nat} x0 b (A: 'M[ftype ty]_n.+1) : 'cV[ftype ty]_n.+1 := let r := b -f ((A2_J A) *f x0) in diag_vector_mult (A1_inv_J A) r. Definition X_m_jacobi {ty} {n:nat} m x0 b (A: 'M[ftype ty]_n.+1) : 'cV[ftype ty]_n.+1 := Nat.iter m (fun x0 => jacobi_iter x0 b A) x0. Definition matrix_inj' {t} (A: matrix t) m n d d': 'M[ftype t]_(m,n):= \matrix_(i < m, j < n) nth j (nth i A d) d'. Definition matrix_inj {t} (A: matrix t) m n : 'M[ftype t]_(m,n):= matrix_inj' A m n [::] (Zconst t 0). Definition vector_inj' {t} (v: vector t) n d : 'cV[ftype t]_n := \col_(i < n) nth i v d. Definition vector_inj {t} (v: vector t) n : 'cV[ftype t]_n := vector_inj' v n (Zconst t 0). Lemma length_veclist {ty} {n m:nat} (v: 'cV[ftype ty]_n.+1): length (@vec_to_list_float _ n m v) = m. Proof. induction m. + simpl. auto. + simpl. by rewrite IHm. Qed. Definition FT2R_mat {m n: nat} {ty} (A : 'M[ftype ty]_(m.+1, n.+1)) : 'M[R]_(m.+1, n.+1):= \matrix_(i, j) FT2R (A i j). End WITHNANS.
(* ************************************************************** *) Section pred1. Variable Terms : Set. Variable M : Terms. (* predicates *) Variable A : Prop. Variable P : Terms -> Prop. Variable Q : Terms -> Prop. Variable R : Terms -> Terms -> Prop. (* example *) Theorem example0 : (forall x:Terms, (P x)) -> (P M). Proof. intro u. apply u. Qed. Print example0. (* \u: Pi x:Terms. Px. (u M) *) (* example *) Theorem example1 : forall x:Terms, (P x) -> (forall y:Terms, (P y) -> A) -> A. Proof. intro x. intro h. intro i. apply i with x. assumption. Qed. Print example1. (* \x:Terms. \h:(P x). \i:(Pi y:Terms. Py -> A). (i x h) *) (* example, see slide 35 of week 6 *) Theorem example2 : (forall x : Terms , P x -> Q x) -> (forall x : Terms , P x) -> forall y : Terms , Q y. Proof. intro h. intro i. intro y. apply h. apply i. Qed. Print example2. (* \h: (Pi x:Terms. Px -> Qx). \i: (Pi x:Terms Px). \y: Terms. h y (i y) *) (* exercise 1: prove the lemma and inspect the proof term *) Lemma one : (forall x : Terms, P x) -> P M. Proof. intro u. apply u. Qed. Print one. (* exercise 2: prove the lemma and inspect the proof term *) Lemma two : (A -> forall x : Terms, P x) -> (forall y : Terms, A -> P y). Proof. intro H. intro y. intro x. apply H. exact x. Qed. Print two. (* exercise 3: prove the lemma and inspect the proof term *) Lemma three : A -> forall x : Terms, A. Proof. intro x. intro y. exact x. Qed. Print three. (* example, see slides 13-14-15 of week 7 *) Definition AS := forall x y : Terms, (R x y) -> ~(R y x). Definition IR := forall x:Terms, ~(R x x). Theorem AS_implies_IR : AS -> IR. Proof. unfold AS. unfold IR. unfold not. intro h. intro x. intro i. apply h with x x. (* alternative: apply (h x x ) *) exact i. exact i. Qed. Print AS_implies_IR. (* given *) Definition reflif := forall x : Terms, (exists y : Terms, R x y) -> R x x. (* exercise 4: define sym as the proposition stating that R is symmetric, that is, if x and y are related via R, then y and x are related via R *) Definition sym := forall x y : Terms, R x y -> R y x. (* exercise 5: define trans as the proposition stating that R is transitive, that is, if x and y are related via R, and y and z are related via R, then x and z are related via R *) Definition trans := forall x y z : Terms, (R x y /\ R y z) -> R x z. (* exercise 6: prove the following Lemma *) Lemma str : sym -> trans -> reflif. Proof. unfold sym, trans, reflif. intro sym. intro trans. intro. intro. elim H. intro. intro. apply trans with x0. split. exact H0. apply sym. apply H0. Qed. End pred1. (* ************************************************************** *) Section logical_framework. (* we encode propositional logic source: webpage Herman Geuvers handbook article Henk Barendregt *) (* prop representing the propositions is declared as a Set *) Parameter prop : Set. (* implication on prop is a binary operator *) Parameter imp : prop -> prop -> prop. (* we can use infix notation => for imp *) Infix "=>" := imp (right associativity, at level 85). (* T expresses if a proposion in prop is valid if (T p) is inhabited then p is valid if (T p) is not inhabited then p is not valid *) Parameter T : prop -> Prop. (* the variable imp_introduction models the introduction rule for imp *) Parameter imp_introduction : forall p q : prop, (T p -> T q) -> T (p => q). (* the variable imp_elimination models the elimination rule for imp *) Parameter imp_elimination : forall p q : prop, T (p => q) -> T p -> T q. (* exercise 7 : prove the following lemma *) Lemma I : forall p : prop, T (p => p). Proof. intro p. apply imp_introduction. intro Tp. apply Tp. Qed. (* exercise 8 : prove the following lemma *) Lemma transitivity : forall p q r : prop, T (p => q) -> T (q => r) -> T (p => r). Proof. intros p q r. intros p_implies_q q_implies_r. apply imp_introduction. intro Tp. apply imp_elimination with q. assumption. apply imp_elimination with p. assumption. assumption. Qed. Parameter conjunction : prop -> prop -> prop. Infix "X" := conjunction (no associativity, at level 90). (* exercise 9 : define variables that model the introduction rule for conjuction on prop, and both elimination rules *) Parameter conjunction_introduction : forall p q : prop, T p -> T q -> T (p X q). Parameter conjunction_elimination_l : forall p q : prop, T (p X q) -> T p. Parameter conjunction_elimination_r : forall p q : prop, T (p X q) -> T q. (* exercise 10: prove the following lemma *) Lemma weak : forall a b c : prop, T (a => c) -> T ((a X b) => c). Proof. intros a b c a_implies_c. apply imp_introduction. intro a_conj_b. apply imp_elimination with a. assumption. apply conjunction_elimination_l with b. assumption. Qed. (* the remainder is not obligatory *) (* bot represents falsum in prop *) Parameter bot : prop. (* not represents negation in prop *) Definition not (p : prop) := p => bot. (* not obligatory *) (* exercise 11 : prove the following lemma *) Lemma contrapositive : forall p q : prop, T (p => q) -> T (not q => not p). Proof. intros p q p_implies_q. apply imp_introduction. unfold not. intro not_q. apply imp_introduction. intro Tp. apply imp_elimination with q. apply not_q. apply imp_elimination with p. assumption. assumption. Qed. End logical_framework. (* vim: filetype=coq *)
State Before: R : Type u inst✝ : CommRing R f₁ fβ‚‚ g₁ gβ‚‚ : R U : Opens ↑(PrimeSpectrum.Top R) hu₁ : βˆ€ (x : ↑(PrimeSpectrum.Top R)), x ∈ U β†’ g₁ ∈ Ideal.primeCompl x.asIdeal huβ‚‚ : βˆ€ (x : ↑(PrimeSpectrum.Top R)), x ∈ U β†’ gβ‚‚ ∈ Ideal.primeCompl x.asIdeal x : { x // x ∈ U.op.unop } ⊒ ↑(const R (f₁ * fβ‚‚) (g₁ * gβ‚‚) U (_ : βˆ€ (x : ↑(PrimeSpectrum.Top R)), x ∈ U β†’ g₁ * gβ‚‚ ∈ Ideal.primeCompl x.asIdeal)) x = ↑(const R f₁ g₁ U hu₁ * const R fβ‚‚ gβ‚‚ U huβ‚‚) x State After: no goals Tactic: convert IsLocalization.mk'_mul _ f₁ fβ‚‚ ⟨g₁, hu₁ x x.2⟩ ⟨gβ‚‚, huβ‚‚ x x.2⟩
module Web.Internal.VisibilityTypes import JS -------------------------------------------------------------------------------- -- Enums -------------------------------------------------------------------------------- namespace VisibilityState public export data VisibilityState = Hidden | Visible public export Show VisibilityState where show Hidden = "hidden" show Visible = "visible" public export Eq VisibilityState where (==) = (==) `on` show public export Ord VisibilityState where compare = compare `on` show public export read : String -> Maybe VisibilityState read "hidden" = Just Hidden read "visible" = Just Visible read _ = Nothing public export fromString : (s : String) -> {auto 0 _ : IsJust (VisibilityState.read s)} -> VisibilityState fromString s = fromJust $ read s export ToFFI VisibilityState String where toFFI = show export FromFFI VisibilityState String where fromFFI = read
MODULE info_module implicit none PRIVATE PUBLIC :: open_info, write_info, close_info integer,parameter :: unit_info = 100, unit_stdout = 6 character(30) :: file_name = "RSDFT_INFO" integer :: myrank character(8) :: date_start, date_end character(10) :: time_start, time_end CONTAINS SUBROUTINE open_info(rank) implicit none integer,intent(IN) :: rank myrank = rank ! if ( rank == 0 ) then ! open(unit_info,file=file_name) ! end if if ( myrank == 0 ) call header_info( unit_stdout ) END SUBROUTINE open_info SUBROUTINE write_info(info) implicit none character(*),intent(IN) :: info if ( info == "" ) return if ( myrank == 0 ) then write(*,*) "INFO: ",info write(unit_info,*) "INFO: ",info end if END SUBROUTINE write_info SUBROUTINE close_info if ( myrank == 0 ) call footer_info( unit_stdout ) ! if ( myrank == 0 ) close(unit_info) END SUBROUTINE close_info SUBROUTINE header_info( unit ) implicit none integer,intent(IN) :: unit ! character(8) :: date ! character(10) :: time write(unit,'(a70)') repeat("-",70) write(unit,*) "RSDFT ver.1.0.0" include 'git_info.inc' write(unit,'(a60," header_info")') repeat("-",60) call date_and_time(DATE=date_start,TIME=time_start) call write_date_and_time( unit, "Start time ", date_start, time_start ) write(unit,*) "preprocessor option list ( -cpp -Dxxxx )" #ifdef _DRSDFT_ write(unit,*) "_DRSDFT_"," (wave functions are REAL8)" #else write(unit,*) " "," (wave functions are COMPLEX16)" #endif #ifdef _SPLINE_ write(unit,*) "_SPLINE_"," (spline interpolation is use in ps_nloc2)" #endif #ifdef _FFTW_ write(unit,*) "_FFTW_"," (FFTW is available)" #endif #ifdef _LAPACK_ write(unit,*) "_LAPACK_"," (LAPACK is used instead of ScaLAPACK" #endif END SUBROUTINE header_info SUBROUTINE write_date_and_time( unit, indx, date, time ) implicit none integer,intent(IN) :: unit character(*),intent(IN) :: indx, date, time write(unit,*) indx//date(1:4)//"/"//date(5:6)//"/"//date(7:8) & //" "//time(1:2)//":"//time(3:4)//":"//time(5:10) END SUBROUTINE write_date_and_time SUBROUTINE footer_info( unit ) implicit none integer,intent(IN) :: unit call date_and_time(DATE=date_end,TIME=time_end) call write_date_and_time( unit, "Start time ", date_start, time_start ) call write_date_and_time( unit, "End time ", date_end, time_end ) END SUBROUTINE footer_info END MODULE info_module
(* * Copyright 2014, NICTA * * This software may be distributed and modified according to the terms of * the BSD 2-Clause license. Note that NO WARRANTY is provided. * See "LICENSE_BSD2.txt" for details. * * @TAG(NICTA_BSD) *) theory many_local_vars imports "../CTranslation" begin (* Avoid memory explosion caused by the C parser generating a huge record * containing local variables. *) declare [[record_codegen = false]] install_C_file "many_local_vars.c" context "many_local_vars_global_addresses" begin lemma "\<forall>\<sigma>. \<Gamma> \<turnstile>\<^bsub>/UNIV\<^esub> {\<sigma>} Call test_'proc {t. t may_not_modify_globals \<sigma>}" apply (tactic {* HoarePackage.vcg_tac "_modifies" "false" [] @{context} 1 *}) done end end
/- Lemmas for basic logic -/ lemma contrapos {p q : Prop} (h : p β†’ q) (g : Β¬ q) : Β¬ p := g ∘ h lemma ite_iff {P Q : Prop} [decP : decidable P] [decQ : decidable Q] (H : P ↔ Q) {A} : @ite P _ A = ite Q := begin apply funext, intros x, apply funext, intros y, have decP' := decP, cases decP' with HP HP, rw (if_neg HP), rw if_neg, rw ← H, assumption, rw (if_pos HP), rw if_pos, rw ← H, assumption, end
[STATEMENT] lemma tuple_ABC_in_hom: shows "Maps.in_hom tuple_ABC (Maps.MkIde (src TTfgh.p\<^sub>0)) (Maps.MkIde (src TfTgh.p\<^sub>0))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Maps.in_hom tuple_ABC (Maps.MkIde (src TTfgh.p\<^sub>0)) (Maps.MkIde (src TfTgh.p\<^sub>0)) [PROOF STEP] proof [PROOF STATE] proof (state) goal (3 subgoals): 1. Maps.arr tuple_ABC 2. Maps.dom tuple_ABC = Maps.MkIde (src TTfgh.p\<^sub>0) 3. Maps.cod tuple_ABC = Maps.MkIde (src TfTgh.p\<^sub>0) [PROOF STEP] show 1: "Maps.arr tuple_ABC" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Maps.arr tuple_ABC [PROOF STEP] using SPN_fgh.chine_assoc_def SPN_fgh.chine_assoc_in_hom [PROOF STATE] proof (prove) using this: SPN_fgh.chine_assoc \<equiv> tuple_ABC Maps.in_hom SPN_fgh.chine_assoc (Chn ((SPN f \<circ> SPN g) \<circ> SPN h)) (Chn (SPN f \<circ> SPN g \<circ> SPN h)) goal (1 subgoal): 1. Maps.arr tuple_ABC [PROOF STEP] by auto [PROOF STATE] proof (state) this: Maps.arr tuple_ABC goal (2 subgoals): 1. Maps.dom tuple_ABC = Maps.MkIde (src TTfgh.p\<^sub>0) 2. Maps.cod tuple_ABC = Maps.MkIde (src TfTgh.p\<^sub>0) [PROOF STEP] show "Maps.dom tuple_ABC = Maps.MkIde (src TTfgh.p\<^sub>0)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Maps.dom tuple_ABC = Maps.MkIde (src TTfgh.p\<^sub>0) [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. Maps.dom tuple_ABC = Maps.MkIde (src TTfgh.p\<^sub>0) [PROOF STEP] have "Maps.dom tuple_ABC = Maps.dom SPN_fgh.chine_assoc" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Maps.dom tuple_ABC = Maps.dom SPN_fgh.chine_assoc [PROOF STEP] by (simp add: SPN_fgh.chine_assoc_def) [PROOF STATE] proof (state) this: Maps.dom tuple_ABC = Maps.dom SPN_fgh.chine_assoc goal (1 subgoal): 1. Maps.dom tuple_ABC = Maps.MkIde (src TTfgh.p\<^sub>0) [PROOF STEP] also [PROOF STATE] proof (state) this: Maps.dom tuple_ABC = Maps.dom SPN_fgh.chine_assoc goal (1 subgoal): 1. Maps.dom tuple_ABC = Maps.MkIde (src TTfgh.p\<^sub>0) [PROOF STEP] have "... = Chn ((SPN f \<circ> SPN g) \<circ> SPN h)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Maps.dom SPN_fgh.chine_assoc = Chn ((SPN f \<circ> SPN g) \<circ> SPN h) [PROOF STEP] using SPN_fgh.chine_assoc_in_hom [PROOF STATE] proof (prove) using this: Maps.in_hom SPN_fgh.chine_assoc (Chn ((SPN f \<circ> SPN g) \<circ> SPN h)) (Chn (SPN f \<circ> SPN g \<circ> SPN h)) goal (1 subgoal): 1. Maps.dom SPN_fgh.chine_assoc = Chn ((SPN f \<circ> SPN g) \<circ> SPN h) [PROOF STEP] by blast [PROOF STATE] proof (state) this: Maps.dom SPN_fgh.chine_assoc = Chn ((SPN f \<circ> SPN g) \<circ> SPN h) goal (1 subgoal): 1. Maps.dom tuple_ABC = Maps.MkIde (src TTfgh.p\<^sub>0) [PROOF STEP] also [PROOF STATE] proof (state) this: Maps.dom SPN_fgh.chine_assoc = Chn ((SPN f \<circ> SPN g) \<circ> SPN h) goal (1 subgoal): 1. Maps.dom tuple_ABC = Maps.MkIde (src TTfgh.p\<^sub>0) [PROOF STEP] have "... = Maps.MkIde (src TTfgh.p\<^sub>0)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Chn ((SPN f \<circ> SPN g) \<circ> SPN h) = Maps.MkIde (src TTfgh.p\<^sub>0) [PROOF STEP] by (metis (lifting) Maps.Dom.simps(1) Maps.dom_char SPN_fgh.prj_simps(3) SPN_fgh.prj_simps(6) prj_char(3)) [PROOF STATE] proof (state) this: Chn ((SPN f \<circ> SPN g) \<circ> SPN h) = Maps.MkIde (src TTfgh.p\<^sub>0) goal (1 subgoal): 1. Maps.dom tuple_ABC = Maps.MkIde (src TTfgh.p\<^sub>0) [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: Maps.dom tuple_ABC = Maps.MkIde (src TTfgh.p\<^sub>0) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: Maps.dom tuple_ABC = Maps.MkIde (src TTfgh.p\<^sub>0) goal (1 subgoal): 1. Maps.dom tuple_ABC = Maps.MkIde (src TTfgh.p\<^sub>0) [PROOF STEP] by blast [PROOF STATE] proof (state) this: Maps.dom tuple_ABC = Maps.MkIde (src TTfgh.p\<^sub>0) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: Maps.dom tuple_ABC = Maps.MkIde (src TTfgh.p\<^sub>0) goal (1 subgoal): 1. Maps.cod tuple_ABC = Maps.MkIde (src TfTgh.p\<^sub>0) [PROOF STEP] show "Maps.cod tuple_ABC = Maps.MkIde (src TfTgh.p\<^sub>0)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Maps.cod tuple_ABC = Maps.MkIde (src TfTgh.p\<^sub>0) [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. Maps.cod tuple_ABC = Maps.MkIde (src TfTgh.p\<^sub>0) [PROOF STEP] have "Maps.cod tuple_ABC = Maps.cod SPN_fgh.chine_assoc" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Maps.cod tuple_ABC = Maps.cod SPN_fgh.chine_assoc [PROOF STEP] by (simp add: SPN_fgh.chine_assoc_def) [PROOF STATE] proof (state) this: Maps.cod tuple_ABC = Maps.cod SPN_fgh.chine_assoc goal (1 subgoal): 1. Maps.cod tuple_ABC = Maps.MkIde (src TfTgh.p\<^sub>0) [PROOF STEP] also [PROOF STATE] proof (state) this: Maps.cod tuple_ABC = Maps.cod SPN_fgh.chine_assoc goal (1 subgoal): 1. Maps.cod tuple_ABC = Maps.MkIde (src TfTgh.p\<^sub>0) [PROOF STEP] have 1: "... = Chn (SPN f \<circ> SPN g \<circ> SPN h)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Maps.cod SPN_fgh.chine_assoc = Chn (SPN f \<circ> SPN g \<circ> SPN h) [PROOF STEP] using SPN_fgh.chine_assoc_in_hom [PROOF STATE] proof (prove) using this: Maps.in_hom SPN_fgh.chine_assoc (Chn ((SPN f \<circ> SPN g) \<circ> SPN h)) (Chn (SPN f \<circ> SPN g \<circ> SPN h)) goal (1 subgoal): 1. Maps.cod SPN_fgh.chine_assoc = Chn (SPN f \<circ> SPN g \<circ> SPN h) [PROOF STEP] by blast [PROOF STATE] proof (state) this: Maps.cod SPN_fgh.chine_assoc = Chn (SPN f \<circ> SPN g \<circ> SPN h) goal (1 subgoal): 1. Maps.cod tuple_ABC = Maps.MkIde (src TfTgh.p\<^sub>0) [PROOF STEP] also [PROOF STATE] proof (state) this: Maps.cod SPN_fgh.chine_assoc = Chn (SPN f \<circ> SPN g \<circ> SPN h) goal (1 subgoal): 1. Maps.cod tuple_ABC = Maps.MkIde (src TfTgh.p\<^sub>0) [PROOF STEP] have "... = Maps.MkIde (src TfTgh.p\<^sub>0)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Chn (SPN f \<circ> SPN g \<circ> SPN h) = Maps.MkIde (src TfTgh.p\<^sub>0) [PROOF STEP] by (metis (lifting) Maps.Dom.simps(1) Maps.cod_char Maps.seq_char SPN_fgh.prj_chine_assoc(1) SPN_fgh.prj_simps(1) TfTgh.leg1_in_hom(1) TfTgh_TfTgh.u_in_hom 1 in_hhomE prj_char(4) src_hcomp) [PROOF STATE] proof (state) this: Chn (SPN f \<circ> SPN g \<circ> SPN h) = Maps.MkIde (src TfTgh.p\<^sub>0) goal (1 subgoal): 1. Maps.cod tuple_ABC = Maps.MkIde (src TfTgh.p\<^sub>0) [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: Maps.cod tuple_ABC = Maps.MkIde (src TfTgh.p\<^sub>0) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: Maps.cod tuple_ABC = Maps.MkIde (src TfTgh.p\<^sub>0) goal (1 subgoal): 1. Maps.cod tuple_ABC = Maps.MkIde (src TfTgh.p\<^sub>0) [PROOF STEP] by argo [PROOF STATE] proof (state) this: Maps.cod tuple_ABC = Maps.MkIde (src TfTgh.p\<^sub>0) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: Maps.cod tuple_ABC = Maps.MkIde (src TfTgh.p\<^sub>0) goal: No subgoals! [PROOF STEP] qed
With 83 percent of adults using smartphones or tablets to look up restaurant locations, directions, and hours, quick-serve and casual dining restaurant chains need effective local marketing to drive business and build relationships within their communities. Leading restaurant chains look to BrandMuscle to empower their franchisees with the right tools to think globally and market locally. Whether it’s launching new locations or effectively running in-store marketing campaigns, BrandMuscle's experience ensures that your local franchisees will be able to quickly and effectively execute traditional, digital, and print media that will not only generate sales, but also loyal customers. From digital tactics like paid social media and location data management, to traditional tactics like direct mail and couponing, BrandMuscle supplies your franchisees with everything they need to stay top of mind when hunger hits. As a relatively unknown fast casual restaurant opening new locations in competitive markets, this client needed to ramp up its online marketing efforts to generate awareness and motivate action through in-store purchases by capturing the attention of its target audience.
lemma bigtheta_refl [simp]: "f \<in> \<Theta>[F](f)"
! ################################################################################################################################## ! Begin MIT license text. ! _______________________________________________________________________________________________________ ! Copyright 2019 Dr William R Case, Jr ([email protected]) ! Permission is hereby granted, free of charge, to any person obtaining a copy of this software and ! associated documentation files (the "Software"), to deal in the Software without restriction, including ! without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ! copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to ! the following conditions: ! The above copyright notice and this permission notice shall be included in all copies or substantial ! portions of the Software and documentation. ! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ! OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN ! THE SOFTWARE. ! _______________________________________________________________________________________________________ ! End MIT license text. MODULE SCRATCH_MATRICES ! Arrays for scratch matrices. CRSi are matrices in sparse CRS format. CCSi are matrices in sparse CCS format USE PENTIUM_II_KIND, ONLY : BYTE, LONG, DOUBLE IMPLICIT NONE SAVE INTEGER(LONG), ALLOCATABLE :: I_CCS1(:) ! Row indicators for nonzero terms in scratch matrix CCS1 INTEGER(LONG), ALLOCATABLE :: I_CCS2(:) ! Row indicators for nonzero terms in scratch matrix CCS2 INTEGER(LONG), ALLOCATABLE :: I_CCS3(:) ! Row indicators for nonzero terms in scratch matrix CCS3 INTEGER(LONG), ALLOCATABLE :: I_CRS1(:) ! Row indicators for nonzero terms in scratch matrix CRS1 INTEGER(LONG), ALLOCATABLE :: I_CRS2(:) ! Row indicators for nonzero terms in scratch matrix CRS2 INTEGER(LONG), ALLOCATABLE :: I_CRS3(:) ! Row indicators for nonzero terms in scratch matrix CRS3 INTEGER(LONG), ALLOCATABLE :: J_CCS1(:) ! Col numbers for nonzero terms in scratch matrix CCS1 INTEGER(LONG), ALLOCATABLE :: J_CCS2(:) ! Col numbers for nonzero terms in scratch matrix CCS2 INTEGER(LONG), ALLOCATABLE :: J_CCS3(:) ! Col numbers for nonzero terms in scratch matrix CCS3 INTEGER(LONG), ALLOCATABLE :: J_CRS1(:) ! Col numbers for nonzero terms in scratch matrix CRS1 INTEGER(LONG), ALLOCATABLE :: J_CRS2(:) ! Col numbers for nonzero terms in scratch matrix CRS2 INTEGER(LONG), ALLOCATABLE :: J_CRS3(:) ! Col numbers for nonzero terms in scratch matrix CRS3 REAL(DOUBLE) , ALLOCATABLE :: CCS1(:) ! Compressed col storage scratch matrix REAL(DOUBLE) , ALLOCATABLE :: CCS2(:) ! Compressed col storage scratch matrix REAL(DOUBLE) , ALLOCATABLE :: CCS3(:) ! Compressed col storage scratch matrix REAL(DOUBLE) , ALLOCATABLE :: CRS1(:) ! Compressed row storage scratch matrix REAL(DOUBLE) , ALLOCATABLE :: CRS2(:) ! Compressed row storage scratch matrix REAL(DOUBLE) , ALLOCATABLE :: CRS3(:) ! Compressed row storage scratch matrix END MODULE SCRATCH_MATRICES
program types_12 use iso_c_binding, only: c_int, c_double implicit none interface integer(c_int) function f(a, b) result(r) import :: c_int, c_double integer(c_int), value, intent(in) :: a real(c_double), value, intent(in) :: b end function end interface end program
import number_theory.padics.padic_integers --OUTPUT 1 theorem p_adic_units (p : β„•) (x : β„•) (h : coprime p x) : is_unit (x : β„€_p) := begin -- prove the contrapositive have h1 : Β¬ is_unit (x : β„€_p) β†’ Β¬ coprime p x, from sorry, -- we know that any element of $\mathbb{Z}_p$ is a unit if and only if it has norm 1 have h2 : is_unit (x : β„€_p) ↔ (x : β„€_p).norm = 1, from sorry, -- thus $\Vert x \Vert \neq 1$ have h3 : Β¬ is_unit (x : β„€_p) β†’ (x : β„€_p).norm β‰  1, from sorry, -- Also, since every element of $\mathbb{Z}_p$ must have norm less than or equal to 1 have h4 : (x : β„€_p).norm ≀ 1, from sorry, -- we conclude that $\Vert x \Vert < 1$ have h5 : Β¬ is_unit (x : β„€_p) β†’ (x : β„€_p).norm < 1, from sorry, -- But this must imply that $p | x$ have h6 : Β¬ is_unit (x : β„€_p) β†’ p ∣ x, from sorry, -- This completes our proof. show is_unit (x : β„€_p), from sorry, end --OUTPUT 2 theorem p_adic_units (p : β„•) (x : β„•) (h : nat.coprime p x) : (x : β„€_[p]) ∈ units β„€_[p] := begin -- prove the contrapositive have h1 : Β¬ (x : β„€_[p]) ∈ units β„€_[p] β†’ Β¬ nat.coprime p x, from sorry, have h2 : Β¬ (x : β„€_[p]) ∈ units β„€_[p] β†’ p ∣ x, from sorry, have h3 : Β¬ nat.coprime p x β†’ p ∣ x, from sorry, show (x : β„€_[p]) ∈ units β„€_[p], from sorry, end --OUTPUT 3 theorem p_adic_units (p : β„•) (x : β„•) (h : coprime p x) : is_unit (x : β„€_[p]) := begin -- prove the contrapositive have h1 : Β¬ is_unit (x : β„€_[p]) β†’ Β¬ coprime p x, from sorry, have h2 : Β¬ is_unit (x : β„€_[p]) β†’ p ∣ x, from sorry, show is_unit (x : β„€_[p]), from sorry, end /- FEW SHOT PROMPTS TO CODEX(START) /--`theorem` Power Set is Closed under Intersection Let $S$ be a set. Let $\powerset S$ be the power set of $S$. Then: :$\forall A, B \in \powerset S: A \cap B \in \powerset S$ `proof` Let $A, B \in \powerset S$. Then by the definition of power set, $A \subseteq S$ and $B \subseteq S$. From Intersection is Subset we have that $A \cap B \subseteq A$. It follows from Subset Relation is Transitive that $A \cap B \subseteq S$. Thus $A \cap B \in \powerset S$ and closure is proved. {{qed}} -/ theorem power_set_intersection_closed {Ξ± : Type*} (S : set Ξ±) : βˆ€ A B ∈ 𝒫 S, (A ∩ B) ∈ 𝒫 S := begin -- $A$ and $B$ are sets. $A$ and $B$ belong to power set of $S$ assume (A : set Ξ±) (hA : A ∈ 𝒫 S) (B : set Ξ±) (hB : B ∈ 𝒫 S), -- Then $A βŠ† S$ and $B βŠ† S$, by power set definition have h1 : (A βŠ† S) ∧ (B βŠ† S), from sorry, -- Then $(A ∩ B) βŠ† A$, by intersection of set is a subset have h2 : (A ∩ B) βŠ† A, from sorry, -- Then $(A ∩ B) βŠ† S$, by subset relation is transitive have h3 : (A ∩ B) βŠ† S, from sorry, -- Hence $(A ∩ B) ∈ 𝒫 S$, by power set definition show (A ∩ B) ∈ 𝒫 S, from sorry, end /--`theorem` Square of Sum :$\forall x, y \in \R: \paren {x + y}^2 = x^2 + 2 x y + y^2$ `proof` Follows from the distribution of multiplication over addition: {{begin-eqn}} {{eqn | l = \left({x + y}\right)^2 | r = \left({x + y}\right) \cdot \left({x + y}\right) }} {{eqn | r = x \cdot \left({x + y}\right) + y \cdot \left({x + y}\right) | c = Real Multiplication Distributes over Addition }} {{eqn | r = x \cdot x + x \cdot y + y \cdot x + y \cdot y | c = Real Multiplication Distributes over Addition }} {{eqn | r = x^2 + 2xy + y^2 | c = }} {{end-eqn}} {{qed}} -/ theorem square_of_sum (x y : ℝ) : (x + y)^2 = (x^2 + 2*x*y + y^2) := begin -- expand the power calc (x + y)^2 = (x+y)*(x+y) : by sorry -- distributive property of multiplication over addition gives: ... = x*(x+y) + y*(x+y) : by sorry -- applying the above property further gives: ... = x*x + x*y + y*x + y*y : by sorry -- rearranging the terms using commutativity and adding gives: ... = x^2 + 2*x*y + y^2 : by sorry, end /--`theorem` Identity of Group is Unique Let $\struct {G, \circ}$ be a group. Then there is a unique identity element $e \in G$. `proof` From Group has Latin Square Property, there exists a unique $x \in G$ such that: :$a x = b$ and there exists a unique $y \in G$ such that: :$y a = b$ Setting $b = a$, this becomes: There exists a unique $x \in G$ such that: :$a x = a$ and there exists a unique $y \in G$ such that: :$y a = a$ These $x$ and $y$ are both $e$, by definition of identity element. {{qed}} -/ theorem group_identity_unique {G : Type*} [group G] : βˆƒ! e : G, βˆ€ a : G, e * a = a ∧ a * e = a := begin -- Group has Latin Square Property have h1 : βˆ€ a b : G, βˆƒ! x : G, a * x = b, from sorry, have h2 : βˆ€ a b : G, βˆƒ! y : G, y * a = b, from sorry, -- Setting $b = a$, this becomes: have h3 : βˆ€ a : G, βˆƒ! x : G, a * x = a, from sorry, have h4 : βˆ€ a : G, βˆƒ! y : G, y * a = a, from sorry, -- These $x$ and $y$ are both $(1 : G)$, by definition of identity element have h5 : βˆ€ a : G, classical.some (h3 a) = (1 : G), from sorry, have h6 : βˆ€ a : G, classical.some (h4 a) = (1 : G), from sorry, show βˆƒ! e : G, βˆ€ a : G, e * a = a ∧ a * e = a, from by { use (1 : G), have h7 : βˆ€ e : G, (βˆ€ a : G, e * a = a ∧ a * e = a) β†’ e = 1, from by { assume (e : G) (h7 : βˆ€ a : G, e * a = a ∧ a * e = a), have h8 : βˆ€ a : G, e = classical.some (h3 a), from sorry, have h9 : βˆ€ a : G, e = classical.some (h4 a), from sorry, show e = (1 : G), from sorry, }, sorry, } end /--`theorem` p-adic units Given a prime number $p$ and a natural number $x$, if $x$ is coprime to $p$, then $x$ is a unit in the $p$-adic integers. `proof` Let us prove the contrapositive, that is, is $x$ is not a unit of $\mathbb{Z}_p$, then $x$ is not coprime to $p$. We know that any element of $\mathbb{Z}_p$ is a unit if and only if it has norm 1, thus $\Vert x \Vert \neq 1$. Also, since every element of $\mathbb{Z}_p$ must have norm less than or equal to 1, we conclude that $\Vert x \Vert < 1$. But this must imply that $p | x$. This completes our proof. QED -/ theorem FEW SHOT PROMPTS TO CODEX(END)-/
import minimal_sub_pq import sub_pq_normal universe u section pq_like_normal variables {Q : Type u} [power_quandle Q] theorem pq_like_normal : sub_pq_normal (gen_group_sub_pq (@of_gen_group_sub_pq Q _)) := begin intros x y, cases y with y hy, simp only [subtype.coe_mk], cases hy with z hz, rw hz, rw set.mem_def, unfold gen_group_sub_pq, simp only, unfold of_gen_group_sub_pq, simp only, unfold of_gen, sorry, --use ((counit x) β–· z : Q), end end pq_like_normal
{-# OPTIONS --cubical --safe --no-sized-types --no-guardedness #-} module Agda.Builtin.Cubical.Path where open import Agda.Primitive.Cubical postulate PathP : βˆ€ {β„“} (A : I β†’ Set β„“) β†’ A i0 β†’ A i1 β†’ Set β„“ {-# BUILTIN PATHP PathP #-} infix 4 _≑_ _≑_ : βˆ€ {β„“} {A : Set β„“} β†’ A β†’ A β†’ Set β„“ _≑_ {A = A} = PathP (Ξ» _ β†’ A) {-# BUILTIN PATH _≑_ #-}
[STATEMENT] lemma PO_m2_step3_refines_m1_step3: "{R12 \<inter> UNIV \<times> (m2_inv4_inon_secret \<inter> m2_inv3_msg2)} (m1_step3 Ra A B Na Nb), (m2_step3 Ra A B Na Nb) {> R12}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. {R12 \<inter> UNIV \<times> (m2_inv4_inon_secret \<inter> m2_inv3_msg2)} m1_step3 Ra A B Na Nb, m2_step3 Ra A B Na Nb {> R12} [PROOF STEP] by (auto simp add: PO_rhoare_defs R12_def m1_defs m2_defs) (blast)
lemma in_upd_image: "A \<subseteq> {..< n} \<Longrightarrow> i < n \<Longrightarrow> upd i \<in> upd ` A \<longleftrightarrow> i \<in> A"
import json import numpy as np from sklearn.utils import shuffle import matplotlib.pyplot as plt HYPERPARAMETERS = { 'num_features': 7, 'features': ('lokacija2', 'kvadratura', 'sprat', 'broj_soba', 'parking', 'lift', 'terasa'), 'learning_rate': [0.001, 0.003, 0.01, 0.03], # 0.001, 0.003, 0.01, 0.03, 0.1, 0.3, 1 'mini_batch_size': [16, 32, 64, 128], 'random_seed': 1, 'outer_cv_fold': 10, 'inner_cv_fold': 10, 'iterations': 50 } def plotting(it, J_train, J_val): epochs = list(range(it)) plt.plot(epochs, J_train, '-b+', label='J train') plt.plot(epochs, J_val, '-r', label='J val') plt.legend() plt.show() def train_main(): # ------------------------------------------PREPROCESSING DATA---------------------------------------------------------- # I Create and import data and output with open("../data/data_flats_sale.json", 'r') as infile: json_data = json.load(infile) m = len(json_data) data = np.zeros([m, HYPERPARAMETERS['num_features']]) output = np.zeros([m, 1]) i = 0 for r in json_data: j = 0 for feature in HYPERPARAMETERS['features']: data[i, j] = r[feature] j += 1 output[i, 0] = r['cena'] i += 1 # II Normalization (Standardization) mean = np.mean(data, axis=0) data = data - mean std = np.std(data, axis=0) data = data / std # III Shuffling data data, output = shuffle(data, output, random_state=HYPERPARAMETERS['random_seed']) # IV Adding first column of ones for bias term data = np.hstack((np.ones((m, 1)), data)) # ------------------------------------------------------------------------------------------------------------------- # --------------------------Nested Cross Validation For Finding BEST HYPERPARAMETERS-------------------------------- # ------------------------------------------------------------------------------------------------------------------- # I Splitting data k-fold on train and test set k = HYPERPARAMETERS['outer_cv_fold'] l = HYPERPARAMETERS['inner_cv_fold'] J_total = np.array([], dtype=np.int64).reshape(0, len(HYPERPARAMETERS['learning_rate']) * len( HYPERPARAMETERS['mini_batch_size'])) for i in range(k): index = slice(int(i * m / k), int(i * m / k + m / k)) test_data, test_output = data[index, :], output[index, :] trainval_data, trainval_output = np.delete(data, index, axis=0), np.delete(output, index, axis=0) J_avg_val_list = np.array([], dtype=np.int64).reshape(0, len(HYPERPARAMETERS['learning_rate']) * len( HYPERPARAMETERS['mini_batch_size'])) # II Splitting data l-fold on train and validation set for j in range(l): index = slice(int(j * (m - m / k) / l), int(j * (m - m / k) / l + (m - m / k) / l)) val_data, val_output = trainval_data[index, :], trainval_output[index, :] train_data, train_output = np.delete(trainval_data, index, axis=0), np.delete(trainval_output, index, axis=0) # III Creating model parameters initialized with zeros params = np.zeros([1, HYPERPARAMETERS['num_features'] + 1]) # IV Splitting training data on mini-batches J_val_list = [] for lr in HYPERPARAMETERS['learning_rate']: for m_batch in HYPERPARAMETERS['mini_batch_size']: J_val = 0 # -----------------------------------One trained model---------------------------------------------- for it in range(HYPERPARAMETERS['iterations']): for b in range(0, train_data.shape[0], m_batch): X = train_data[b:b + m_batch] # 32x8 h = np.dot(X, params.transpose()) # 32x1 # V Loss funtion L = h - train_output[b:b + m_batch] # 32x1 J_train = np.sum(L ** 2) / (2 * X.shape[0]) # VI Updating model parameters dJ = np.dot(L.transpose(), X) # 1 x NUM_FEATURES + 1 params = params - (lr / X.shape[0]) * dJ # --------------------Validation------------------------------------------------------------ h_val = np.dot(val_data, params.transpose()) L_val = h_val - val_output J_val = np.sum(L_val ** 2) / (2 * val_data.shape[0]) # ------------------------------------------------------------------------------------------ J_val_list.append(J_val) J_avg_val_list = np.vstack([J_avg_val_list, J_val_list]) # print(str(J_avg_val_list.shape[0]) + "/10") temp = list(np.mean(J_avg_val_list, axis=0)) J_total = np.vstack([J_total, temp]) print("Hyperparameter index for iteration " + str(J_total.shape[0]) + "/10 is " + str(temp.index(min(temp)))) temp = list(np.mean(J_total, axis=0)) print("Hyperparameter index is " + str(temp.index(min(temp)))) # best_hparam_index = temp.index(min(temp)) best_hparam_index = 14 best_hyperparams = [HYPERPARAMETERS['learning_rate'][best_hparam_index // len(HYPERPARAMETERS['learning_rate'])], HYPERPARAMETERS['mini_batch_size'][best_hparam_index % len(HYPERPARAMETERS['mini_batch_size'])]] # ------------------------------------------------------------------------------------------------------------------- # ---------------------Cross Validation On Evaluation For Finding MEAN PERFORMANCE---------------------------------- # ------------------------------------------------------------------------------------------------------------------- RMSE = [] MAE = [] for i in range(k): index = slice(int(i * m / k), int(i * m / k + m / k)) test_data, test_output = data[index, :], output[index, :] trainval_data, trainval_output = np.delete(data, index, axis=0), np.delete(output, index, axis=0) params = np.zeros([1, HYPERPARAMETERS['num_features'] + 1]) lr, m_batch = best_hyperparams[0], best_hyperparams[1] # -----------------------------------One trained model---------------------------------------------- for it in range(HYPERPARAMETERS['iterations']): for b in range(0, trainval_data.shape[0], int(m_batch)): X = trainval_data[b:b + m_batch] # 32x8 h = np.dot(X, params.transpose()) # 32x1 # V Loss funtion L = h - trainval_output[b:b + m_batch] # 32x1 J_train = np.sum(L ** 2) / (2 * X.shape[0]) # VI Updating model parameters dJ = np.dot(L.transpose(), X) # 1 x NUM_FEATURES + 1 params = params - (lr / X.shape[0]) * dJ # --------------------Evaluation------------------------------------------------------------ h_test = np.dot(test_data, params.transpose()) L_test = h_test - test_output RMSE.append(np.sqrt(np.sum(L_test ** 2) / test_data.shape[0])) MAE.append(np.sum(np.absolute(L_test)) / test_data.shape[0]) # ------------------------------------------------------------------------------------------ print("Average root mean squared error: " + str(np.mean(RMSE))) print("Average mean absolute error: " + str(np.mean(MAE))) # ------------------------------------------------------------------------------------------------------------------- # ----------------------------Training on whole data set for BEST PARAMETERS---------------------------------------- # ------------------------------------------------------------------------------------------------------------------- params = np.zeros([1, HYPERPARAMETERS['num_features'] + 1]) lr, m_batch = best_hyperparams[0], best_hyperparams[1] # -----------------------------------One trained model---------------------------------------------- for it in range(HYPERPARAMETERS['iterations']): for b in range(0, data.shape[0], int(m_batch)): X = data[b:b + m_batch] # 32x8 h = np.dot(X, params.transpose()) # 32x1 # V Loss funtion L = h - output[b:b + m_batch] # 32x1 J_train = np.sum(L ** 2) / (2 * X.shape[0]) # VI Updating model parameters dJ = np.dot(L.transpose(), X) # 1 x NUM_FEATURES + 1 params = params - (lr / X.shape[0]) * dJ with open('model_parameters.json', 'w') as output_file: output_file.write(json.dumps({"parameters": params.tolist(), 'mean': mean.tolist(), 'std': std.tolist()}, indent=4)) train_main()
lemma measure_nonneg[simp]: "0 \<le> measure M A"
[GOAL] ⊒ SuccOrder (Fin 0) [PROOFSTEP] constructor [GOAL] case le_succ ⊒ βˆ€ (a : Fin 0), a ≀ ?succ a [PROOFSTEP] first | assumption | intro a; exact elim0 a [GOAL] case le_succ ⊒ βˆ€ (a : Fin 0), a ≀ ?succ a [PROOFSTEP] assumption [GOAL] case le_succ ⊒ βˆ€ (a : Fin 0), a ≀ ?succ a [PROOFSTEP] intro a [GOAL] case le_succ a : Fin 0 ⊒ a ≀ ?succ a [PROOFSTEP] exact elim0 a [GOAL] case max_of_succ_le ⊒ βˆ€ {a : Fin 0}, ?succ a ≀ a β†’ IsMax a [PROOFSTEP] first | assumption | intro a; exact elim0 a [GOAL] case max_of_succ_le ⊒ βˆ€ {a : Fin 0}, ?succ a ≀ a β†’ IsMax a [PROOFSTEP] assumption [GOAL] case max_of_succ_le ⊒ βˆ€ {a : Fin 0}, ?succ a ≀ a β†’ IsMax a [PROOFSTEP] intro a [GOAL] case max_of_succ_le a : Fin 0 ⊒ ?succ a ≀ a β†’ IsMax a [PROOFSTEP] exact elim0 a [GOAL] case succ_le_of_lt ⊒ βˆ€ {a b : Fin 0}, a < b β†’ ?succ a ≀ b [PROOFSTEP] first | assumption | intro a; exact elim0 a [GOAL] case succ_le_of_lt ⊒ βˆ€ {a b : Fin 0}, a < b β†’ ?succ a ≀ b [PROOFSTEP] assumption [GOAL] case succ_le_of_lt ⊒ βˆ€ {a b : Fin 0}, a < b β†’ ?succ a ≀ b [PROOFSTEP] intro a [GOAL] case succ_le_of_lt a : Fin 0 ⊒ βˆ€ {b : Fin 0}, a < b β†’ ?succ a ≀ b [PROOFSTEP] exact elim0 a [GOAL] case le_of_lt_succ ⊒ βˆ€ {a b : Fin 0}, a < ?succ b β†’ a ≀ b [PROOFSTEP] first | assumption | intro a; exact elim0 a [GOAL] case le_of_lt_succ ⊒ βˆ€ {a b : Fin 0}, a < ?succ b β†’ a ≀ b [PROOFSTEP] assumption [GOAL] case le_of_lt_succ ⊒ βˆ€ {a b : Fin 0}, a < ?succ b β†’ a ≀ b [PROOFSTEP] intro a [GOAL] case le_of_lt_succ a : Fin 0 ⊒ βˆ€ {b : Fin 0}, a < ?succ b β†’ a ≀ b [PROOFSTEP] exact elim0 a [GOAL] case succ ⊒ Fin 0 β†’ Fin 0 [PROOFSTEP] first | assumption | intro a; exact elim0 a [GOAL] case succ ⊒ Fin 0 β†’ Fin 0 [PROOFSTEP] assumption [GOAL] case succ ⊒ Fin 0 β†’ Fin 0 [PROOFSTEP] intro a [GOAL] case succ a : Fin 0 ⊒ Fin 0 [PROOFSTEP] exact elim0 a [GOAL] n : β„• ⊒ βˆ€ {a : Fin (n + 1)}, Β¬IsMax a β†’ βˆ€ (b : Fin (n + 1)), a < b ↔ (fun i => if i < last n then i + 1 else i) a ≀ b [PROOFSTEP] intro a ha b [GOAL] n : β„• a : Fin (n + 1) ha : Β¬IsMax a b : Fin (n + 1) ⊒ a < b ↔ (fun i => if i < last n then i + 1 else i) a ≀ b [PROOFSTEP] rw [isMax_iff_eq_top, eq_top_iff, not_le, top_eq_last] at ha [GOAL] n : β„• a : Fin (n + 1) ha✝ : Β¬IsMax a ha : a < last n b : Fin (n + 1) ⊒ a < b ↔ (fun i => if i < last n then i + 1 else i) a ≀ b [PROOFSTEP] dsimp [GOAL] n : β„• a : Fin (n + 1) ha✝ : Β¬IsMax a ha : a < last n b : Fin (n + 1) ⊒ a < b ↔ (if a < last n then a + 1 else a) ≀ b [PROOFSTEP] rw [if_pos ha, lt_iff_val_lt_val, le_iff_val_le_val, val_add_one_of_lt ha] [GOAL] n : β„• a : Fin (n + 1) ha✝ : Β¬IsMax a ha : a < last n b : Fin (n + 1) ⊒ ↑a < ↑b ↔ ↑a + 1 ≀ ↑b [PROOFSTEP] exact Nat.lt_iff_add_one_le [GOAL] n : β„• ⊒ βˆ€ (a : Fin (n + 1)), IsMax a β†’ (fun i => if i < last n then i + 1 else i) a = a [PROOFSTEP] intro a ha [GOAL] n : β„• a : Fin (n + 1) ha : IsMax a ⊒ (fun i => if i < last n then i + 1 else i) a = a [PROOFSTEP] rw [isMax_iff_eq_top, top_eq_last] at ha [GOAL] n : β„• a : Fin (n + 1) ha✝ : IsMax a ha : a = last n ⊒ (fun i => if i < last n then i + 1 else i) a = a [PROOFSTEP] dsimp [GOAL] n : β„• a : Fin (n + 1) ha✝ : IsMax a ha : a = last n ⊒ (if a < last n then a + 1 else a) = a [PROOFSTEP] rw [if_neg ha.not_lt] [GOAL] ⊒ PredOrder (Fin 0) [PROOFSTEP] constructor [GOAL] case pred_le ⊒ βˆ€ (a : Fin 0), ?pred a ≀ a [PROOFSTEP] first | assumption | intro a; exact elim0 a [GOAL] case pred_le ⊒ βˆ€ (a : Fin 0), ?pred a ≀ a [PROOFSTEP] assumption [GOAL] case pred_le ⊒ βˆ€ (a : Fin 0), ?pred a ≀ a [PROOFSTEP] intro a [GOAL] case pred_le a : Fin 0 ⊒ ?pred a ≀ a [PROOFSTEP] exact elim0 a [GOAL] case min_of_le_pred ⊒ βˆ€ {a : Fin 0}, a ≀ ?pred a β†’ IsMin a [PROOFSTEP] first | assumption | intro a; exact elim0 a [GOAL] case min_of_le_pred ⊒ βˆ€ {a : Fin 0}, a ≀ ?pred a β†’ IsMin a [PROOFSTEP] assumption [GOAL] case min_of_le_pred ⊒ βˆ€ {a : Fin 0}, a ≀ ?pred a β†’ IsMin a [PROOFSTEP] intro a [GOAL] case min_of_le_pred a : Fin 0 ⊒ a ≀ ?pred a β†’ IsMin a [PROOFSTEP] exact elim0 a [GOAL] case le_pred_of_lt ⊒ βˆ€ {a b : Fin 0}, a < b β†’ a ≀ ?pred b [PROOFSTEP] first | assumption | intro a; exact elim0 a [GOAL] case le_pred_of_lt ⊒ βˆ€ {a b : Fin 0}, a < b β†’ a ≀ ?pred b [PROOFSTEP] assumption [GOAL] case le_pred_of_lt ⊒ βˆ€ {a b : Fin 0}, a < b β†’ a ≀ ?pred b [PROOFSTEP] intro a [GOAL] case le_pred_of_lt a : Fin 0 ⊒ βˆ€ {b : Fin 0}, a < b β†’ a ≀ ?pred b [PROOFSTEP] exact elim0 a [GOAL] case le_of_pred_lt ⊒ βˆ€ {a b : Fin 0}, ?pred a < b β†’ a ≀ b [PROOFSTEP] first | assumption | intro a; exact elim0 a [GOAL] case le_of_pred_lt ⊒ βˆ€ {a b : Fin 0}, ?pred a < b β†’ a ≀ b [PROOFSTEP] assumption [GOAL] case le_of_pred_lt ⊒ βˆ€ {a b : Fin 0}, ?pred a < b β†’ a ≀ b [PROOFSTEP] intro a [GOAL] case le_of_pred_lt a : Fin 0 ⊒ βˆ€ {b : Fin 0}, ?pred a < b β†’ a ≀ b [PROOFSTEP] exact elim0 a [GOAL] case pred ⊒ Fin 0 β†’ Fin 0 [PROOFSTEP] first | assumption | intro a; exact elim0 a [GOAL] case pred ⊒ Fin 0 β†’ Fin 0 [PROOFSTEP] assumption [GOAL] case pred ⊒ Fin 0 β†’ Fin 0 [PROOFSTEP] intro a [GOAL] case pred a : Fin 0 ⊒ Fin 0 [PROOFSTEP] exact elim0 a [GOAL] n : β„• ⊒ βˆ€ {a : Fin (n + 1)}, Β¬IsMin a β†’ βˆ€ (b : Fin (n + 1)), b ≀ (fun x => if x = 0 then 0 else x - 1) a ↔ b < a [PROOFSTEP] intro a ha b [GOAL] n : β„• a : Fin (n + 1) ha : Β¬IsMin a b : Fin (n + 1) ⊒ b ≀ (fun x => if x = 0 then 0 else x - 1) a ↔ b < a [PROOFSTEP] rw [isMin_iff_eq_bot, eq_bot_iff, not_le, bot_eq_zero] at ha [GOAL] n : β„• a : Fin (n + 1) ha✝ : Β¬IsMin a ha : 0 < a b : Fin (n + 1) ⊒ b ≀ (fun x => if x = 0 then 0 else x - 1) a ↔ b < a [PROOFSTEP] dsimp [GOAL] n : β„• a : Fin (n + 1) ha✝ : Β¬IsMin a ha : 0 < a b : Fin (n + 1) ⊒ (b ≀ if a = 0 then 0 else a - 1) ↔ b < a [PROOFSTEP] rw [if_neg ha.ne', lt_iff_val_lt_val, le_iff_val_le_val, coe_sub_one, if_neg ha.ne', le_tsub_iff_right, Iff.comm] [GOAL] n : β„• a : Fin (n + 1) ha✝ : Β¬IsMin a ha : 0 < a b : Fin (n + 1) ⊒ ↑b < ↑a ↔ ↑b + 1 ≀ ↑a n : β„• a : Fin (n + 1) ha✝ : Β¬IsMin a ha : 0 < a b : Fin (n + 1) ⊒ 1 ≀ ↑a [PROOFSTEP] exact Nat.lt_iff_add_one_le [GOAL] n : β„• a : Fin (n + 1) ha✝ : Β¬IsMin a ha : 0 < a b : Fin (n + 1) ⊒ 1 ≀ ↑a [PROOFSTEP] exact ha [GOAL] n : β„• ⊒ βˆ€ (a : Fin (n + 1)), IsMin a β†’ (fun x => if x = 0 then 0 else x - 1) a = a [PROOFSTEP] intro a ha [GOAL] n : β„• a : Fin (n + 1) ha : IsMin a ⊒ (fun x => if x = 0 then 0 else x - 1) a = a [PROOFSTEP] rw [isMin_iff_eq_bot, bot_eq_zero] at ha [GOAL] n : β„• a : Fin (n + 1) ha✝ : IsMin a ha : a = 0 ⊒ (fun x => if x = 0 then 0 else x - 1) a = a [PROOFSTEP] dsimp [GOAL] n : β„• a : Fin (n + 1) ha✝ : IsMin a ha : a = 0 ⊒ (if a = 0 then 0 else a - 1) = a [PROOFSTEP] rwa [if_pos ha, eq_comm]
theory FreeLogic imports Main begin consts fExistence:: "'a\<Rightarrow>bool" ("E") (*Existence/definedness predicate in free logic*) abbreviation fForall ("\<^bold>\<forall>") (*Free universal quantification*) where "\<^bold>\<forall>\<Phi> \<equiv> \<forall>x. E x \<longrightarrow> \<Phi> x" abbreviation fForallBinder (binder "\<^bold>\<forall>" [8] 9) (*Binder notation*) where "\<^bold>\<forall>x. \<phi> x \<equiv> \<^bold>\<forall>\<phi>" abbreviation fExists ("\<^bold>\<exists>") where "\<^bold>\<exists>\<Phi> \<equiv> \<not>(\<^bold>\<forall>(\<lambda>y. \<not>(\<Phi> y)))" abbreviation fExistsBinder (binder "\<^bold>\<exists>" [8]9) where "\<^bold>\<exists>x. \<phi> x \<equiv> \<^bold>\<exists>\<phi>" abbreviation fExistsUnique ("\<^bold>\<exists>!") where "\<^bold>\<exists>!\<phi> \<equiv> \<^bold>\<exists>x. (\<phi> x \<and> (\<^bold>\<forall>y. \<phi> y \<longrightarrow> y = x))" abbreviation fExistsUniqueBinder (binder "\<^bold>\<exists>!" [8]9) where "\<^bold>\<exists>!x. \<phi> x \<equiv> \<^bold>\<exists>!\<phi>" abbreviation KlEq (infixr "\<cong>" 56) (* Kleene equality *) where "x \<cong> y \<equiv> (E x \<or> E y) \<longrightarrow> x = y" abbreviation ExId (infixr "\<simeq>" 56) (* Existing identity *) where "x \<simeq> y \<equiv> E x \<and> E y \<and> x = y" lemma fallI [intro]: "\<^bold>\<forall>x. \<phi> x" if "\<And>x. E x \<longrightarrow> \<phi> x" using that by simp lemma fexI [intro]: "E x \<and> \<phi> x \<Longrightarrow> \<^bold>\<exists>x::'a. \<phi> x" by auto lemma fexE [elim]: "(\<And>x. (E x \<and> \<phi> x) \<Longrightarrow> C) \<Longrightarrow> C" if "\<^bold>\<exists>x. \<phi> x" using that by auto lemma fall3I: "(\<And>x y z. E x \<and> E y \<and> E z \<Longrightarrow> \<phi> x y z) \<Longrightarrow> (\<^bold>\<forall>x y z. \<phi> x y z)" for \<phi>::"'a \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> bool" by simp lemma equE: assumes "A \<Longrightarrow> B" and "B \<Longrightarrow> A" shows "A \<longleftrightarrow> B" using assms(1) assms(2) by blast lemma contraposition: assumes "\<not>B \<longrightarrow> \<not>A" shows "A \<longrightarrow> B" using assms by blast end