Datasets:
AI4M
/

text
stringlengths
0
3.34M
lemma eventually_Lim_ident_at: "(\<forall>\<^sub>F y in at x within X. P (Lim (at x within X) (\<lambda>x. x)) y) \<longleftrightarrow> (\<forall>\<^sub>F y in at x within X. P x y)" for x::"'a::t2_space"
[STATEMENT] lemma not_fresh_nat_of: shows "\<not> a \<sharp> nat_of" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<not> a \<sharp> nat_of [PROOF STEP] unfolding fresh_def supp_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<not> a \<notin> {a. infinite {b. (a \<rightleftharpoons> b) \<bullet> nat_of \<noteq> nat_of}} [PROOF STEP] proof (clarsimp) [PROOF STATE] proof (state) goal (1 subgoal): 1. finite {b. (a \<rightleftharpoons> b) \<bullet> nat_of \<noteq> nat_of} \<Longrightarrow> False [PROOF STEP] assume "finite {b. (a \<rightleftharpoons> b) \<bullet> nat_of \<noteq> nat_of}" [PROOF STATE] proof (state) this: finite {b. (a \<rightleftharpoons> b) \<bullet> nat_of \<noteq> nat_of} goal (1 subgoal): 1. finite {b. (a \<rightleftharpoons> b) \<bullet> nat_of \<noteq> nat_of} \<Longrightarrow> False [PROOF STEP] hence "finite ({a} \<union> {b. (a \<rightleftharpoons> b) \<bullet> nat_of \<noteq> nat_of})" [PROOF STATE] proof (prove) using this: finite {b. (a \<rightleftharpoons> b) \<bullet> nat_of \<noteq> nat_of} goal (1 subgoal): 1. finite ({a} \<union> {b. (a \<rightleftharpoons> b) \<bullet> nat_of \<noteq> nat_of}) [PROOF STEP] by simp [PROOF STATE] proof (state) this: finite ({a} \<union> {b. (a \<rightleftharpoons> b) \<bullet> nat_of \<noteq> nat_of}) goal (1 subgoal): 1. finite {b. (a \<rightleftharpoons> b) \<bullet> nat_of \<noteq> nat_of} \<Longrightarrow> False [PROOF STEP] then [PROOF STATE] proof (chain) picking this: finite ({a} \<union> {b. (a \<rightleftharpoons> b) \<bullet> nat_of \<noteq> nat_of}) [PROOF STEP] obtain b where b1: "b \<noteq> a" and b2: "sort_of b = sort_of a" and b3: "(a \<rightleftharpoons> b) \<bullet> nat_of = nat_of" [PROOF STATE] proof (prove) using this: finite ({a} \<union> {b. (a \<rightleftharpoons> b) \<bullet> nat_of \<noteq> nat_of}) goal (1 subgoal): 1. (\<And>b. \<lbrakk>b \<noteq> a; sort_of b = sort_of a; (a \<rightleftharpoons> b) \<bullet> nat_of = nat_of\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by (rule obtain_atom) auto [PROOF STATE] proof (state) this: b \<noteq> a sort_of b = sort_of a (a \<rightleftharpoons> b) \<bullet> nat_of = nat_of goal (1 subgoal): 1. finite {b. (a \<rightleftharpoons> b) \<bullet> nat_of \<noteq> nat_of} \<Longrightarrow> False [PROOF STEP] have "nat_of a = (a \<rightleftharpoons> b) \<bullet> (nat_of a)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. nat_of a = (a \<rightleftharpoons> b) \<bullet> nat_of a [PROOF STEP] by (simp add: permute_nat_def) [PROOF STATE] proof (state) this: nat_of a = (a \<rightleftharpoons> b) \<bullet> nat_of a goal (1 subgoal): 1. finite {b. (a \<rightleftharpoons> b) \<bullet> nat_of \<noteq> nat_of} \<Longrightarrow> False [PROOF STEP] also [PROOF STATE] proof (state) this: nat_of a = (a \<rightleftharpoons> b) \<bullet> nat_of a goal (1 subgoal): 1. finite {b. (a \<rightleftharpoons> b) \<bullet> nat_of \<noteq> nat_of} \<Longrightarrow> False [PROOF STEP] have "\<dots> = ((a \<rightleftharpoons> b) \<bullet> nat_of) ((a \<rightleftharpoons> b) \<bullet> a)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (a \<rightleftharpoons> b) \<bullet> nat_of a = ((a \<rightleftharpoons> b) \<bullet> nat_of) ((a \<rightleftharpoons> b) \<bullet> a) [PROOF STEP] by (simp add: permute_fun_app_eq) [PROOF STATE] proof (state) this: (a \<rightleftharpoons> b) \<bullet> nat_of a = ((a \<rightleftharpoons> b) \<bullet> nat_of) ((a \<rightleftharpoons> b) \<bullet> a) goal (1 subgoal): 1. finite {b. (a \<rightleftharpoons> b) \<bullet> nat_of \<noteq> nat_of} \<Longrightarrow> False [PROOF STEP] also [PROOF STATE] proof (state) this: (a \<rightleftharpoons> b) \<bullet> nat_of a = ((a \<rightleftharpoons> b) \<bullet> nat_of) ((a \<rightleftharpoons> b) \<bullet> a) goal (1 subgoal): 1. finite {b. (a \<rightleftharpoons> b) \<bullet> nat_of \<noteq> nat_of} \<Longrightarrow> False [PROOF STEP] have "\<dots> = nat_of ((a \<rightleftharpoons> b) \<bullet> a)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ((a \<rightleftharpoons> b) \<bullet> nat_of) ((a \<rightleftharpoons> b) \<bullet> a) = nat_of ((a \<rightleftharpoons> b) \<bullet> a) [PROOF STEP] using b3 [PROOF STATE] proof (prove) using this: (a \<rightleftharpoons> b) \<bullet> nat_of = nat_of goal (1 subgoal): 1. ((a \<rightleftharpoons> b) \<bullet> nat_of) ((a \<rightleftharpoons> b) \<bullet> a) = nat_of ((a \<rightleftharpoons> b) \<bullet> a) [PROOF STEP] by simp [PROOF STATE] proof (state) this: ((a \<rightleftharpoons> b) \<bullet> nat_of) ((a \<rightleftharpoons> b) \<bullet> a) = nat_of ((a \<rightleftharpoons> b) \<bullet> a) goal (1 subgoal): 1. finite {b. (a \<rightleftharpoons> b) \<bullet> nat_of \<noteq> nat_of} \<Longrightarrow> False [PROOF STEP] also [PROOF STATE] proof (state) this: ((a \<rightleftharpoons> b) \<bullet> nat_of) ((a \<rightleftharpoons> b) \<bullet> a) = nat_of ((a \<rightleftharpoons> b) \<bullet> a) goal (1 subgoal): 1. finite {b. (a \<rightleftharpoons> b) \<bullet> nat_of \<noteq> nat_of} \<Longrightarrow> False [PROOF STEP] have "\<dots> = nat_of b" [PROOF STATE] proof (prove) goal (1 subgoal): 1. nat_of ((a \<rightleftharpoons> b) \<bullet> a) = nat_of b [PROOF STEP] using b2 [PROOF STATE] proof (prove) using this: sort_of b = sort_of a goal (1 subgoal): 1. nat_of ((a \<rightleftharpoons> b) \<bullet> a) = nat_of b [PROOF STEP] by simp [PROOF STATE] proof (state) this: nat_of ((a \<rightleftharpoons> b) \<bullet> a) = nat_of b goal (1 subgoal): 1. finite {b. (a \<rightleftharpoons> b) \<bullet> nat_of \<noteq> nat_of} \<Longrightarrow> False [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: nat_of a = nat_of b [PROOF STEP] have "nat_of a = nat_of b" [PROOF STATE] proof (prove) using this: nat_of a = nat_of b goal (1 subgoal): 1. nat_of a = nat_of b [PROOF STEP] by simp [PROOF STATE] proof (state) this: nat_of a = nat_of b goal (1 subgoal): 1. finite {b. (a \<rightleftharpoons> b) \<bullet> nat_of \<noteq> nat_of} \<Longrightarrow> False [PROOF STEP] with b2 [PROOF STATE] proof (chain) picking this: sort_of b = sort_of a nat_of a = nat_of b [PROOF STEP] have "a = b" [PROOF STATE] proof (prove) using this: sort_of b = sort_of a nat_of a = nat_of b goal (1 subgoal): 1. a = b [PROOF STEP] by (simp add: atom_components_eq_iff) [PROOF STATE] proof (state) this: a = b goal (1 subgoal): 1. finite {b. (a \<rightleftharpoons> b) \<bullet> nat_of \<noteq> nat_of} \<Longrightarrow> False [PROOF STEP] with b1 [PROOF STATE] proof (chain) picking this: b \<noteq> a a = b [PROOF STEP] show "False" [PROOF STATE] proof (prove) using this: b \<noteq> a a = b goal (1 subgoal): 1. False [PROOF STEP] by simp [PROOF STATE] proof (state) this: False goal: No subgoals! [PROOF STEP] qed
A Florida felon is back in jail after uploading photos to his Instagram page showing him posing with firearms. Police raided Depree Johnson’s Lake Worth home last week after investigators spotted the incriminating images of the 19-year-old on the photo-sharing web site. Johnson’s rap sheet includes convictions for grand theft, burglary, and felon in possession of a firearm. As seen above, one of the Instagram photos (click to enlarge) shows Johnson holding two handguns, while a friend points another weapon at his head. Detectives with the Palm Beach County Sheriff’s Office recently examined Johnson’s Instagram account as they were investigating his possible involvement in a series of burglaries. The search of Johnson’s home turned up numerous pieces of stolen jewelry and a pair of stolen firearms. As a result, Johnson was arrested and booked into the county jail on 142 criminal counts.
function interp (x, y, kfmin, kfmax, kfstep, kmax, xval) !----- GPL --------------------------------------------------------------------- ! ! Copyright (C) Stichting Deltares, 2011-2016. ! ! This program is free software: you can redistribute it and/or modify ! it under the terms of the GNU General Public License as published by ! the Free Software Foundation version 3. ! ! This program is distributed in the hope that it will be useful, ! but WITHOUT ANY WARRANTY; without even the implied warranty of ! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ! GNU General Public License for more details. ! ! You should have received a copy of the GNU General Public License ! along with this program. If not, see <http://www.gnu.org/licenses/>. ! ! contact: [email protected] ! Stichting Deltares ! P.O. Box 177 ! 2600 MH Delft, The Netherlands ! ! All indications and logos of, and references to, "Delft3D" and "Deltares" ! are registered trademarks of Stichting Deltares, and remain the property of ! Stichting Deltares. All rights reserved. ! !------------------------------------------------------------------------------- ! $Id: interp.f90 5717 2016-01-12 11:35:24Z mourits $ ! $HeadURL: https://svn.oss.deltares.nl/repos/delft3d/tags/6686/src/engines_gpl/flow2d3d/packages/kernel/src/compute/interp.f90 $ !!--description----------------------------------------------------------------- ! ! interpolate y values for xval in the range of x array ! !!--pseudo code and references-------------------------------------------------- ! NONE !!--declarations---------------------------------------------------------------- use precision ! implicit none ! ! Function result real(fp) :: interp ! ! ! Global variables ! integer , intent(in) :: kfmin integer , intent(in) :: kfmax integer , intent(in) :: kfstep integer , intent(in) :: kmax real(fp) , intent(in) :: xval real(fp), dimension (0:kmax+1), intent(in) :: x real(fp), dimension (kmax) , intent(in) :: y ! ! Local variables ! integer :: k ! !! executable statements ------------------------------------------------------- ! interp = -999.0_fp if (xval < x(0)) then ! ! outside extrapolation region lower side ! interp = 0.0_fp elseif (xval <= x(kfmin)) then ! ! inside extrapolation region lower side ! interp = y(kfmin) elseif (xval > x(kfmax+1)) then ! ! outside extrapolation region upper side ! interp = 0.0_fp elseif (xval >= x(kfmax)) then ! ! inside extrapolation region upper side ! interp = y(kfmax) else ! ! interpolation ! do k = kfmin+kfstep, kfmax, kfstep if (xval >= x(k-kfstep) .and. xval <= x(k)) then interp = y(k-kfstep) + ((xval - x(k-kfstep))/(x(k) - x(k-kfstep))) & & * (y(k) - y(k-kfstep)) exit endif enddo endif end function interp
# Copyright 2021 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """The functions for computing gradient updates.""" from typing import Callable, NamedTuple, Sequence import chex import haiku as hk import jax import optax from brave.datasets import datasets from brave.models import embedding_model class ModelUpdates(NamedTuple): params: hk.Params state: hk.State opt_state: optax.OptState scalars: embedding_model.Scalars UpdateFn = Callable[ [chex.PRNGKey, datasets.MiniBatch, hk.Params, hk.State, optax.OptState], ModelUpdates] def build_update_fn(optimizer: optax.GradientTransformation, loss_fn: embedding_model.LossFn) -> UpdateFn: """Returns a function for computing model updates. Args: optimizer: The optimizer to use e.g. the result of optax.sgd(...). loss_fn: An instance of the loss function, pmapped across all devices. Returns: A callable function that takes one step in the optimization problem using the gradients of the loss computed by the model loss function. """ def update_fn(rng: chex.PRNGKey, minibatch: datasets.MiniBatch, params: hk.Params, state: hk.State, opt_state: optax.OptState) -> ModelUpdates: grad_fn = jax.grad(loss_fn, has_aux=True) grad, (state, scalars) = grad_fn(params, state, rng, minibatch) grad = jax.lax.pmean(grad, axis_name='i') scalars = jax.lax.pmean(scalars, axis_name='i') updates, opt_state = optimizer.update(grad, opt_state, params) params = optax.apply_updates(params, updates) return ModelUpdates(params, state, opt_state, scalars) return update_fn def get_batch_dims(global_batch_size: int, device_count: int, local_device_count: int) -> Sequence[int]: """Compute the batch dims for this host. The global_batch_size is the number of data samples that are optimized over in one step of the optimization. This value must be split up so that each individual device gets some share of the batch. When running with multiple devices, there may be multiple hosts, each with multiple local devices. Each host has a local copy of the program, and runs a local copy of the code. Each host must therefore use a batch size so that when all of the hosts run together, the total number of batched elements matches the global batch size. We do this by splitting up the global batch size evenly amongst all devices, and setting the batch size per host to the number of host devices times the device batch size. Args: global_batch_size: The target total batch size per optimization step. device_count: The total number of devices sharing computation per step. local_device_count: The number of devices available on the current host. Returns: The batch dimensions to use on the currently running host. """ per_device_batch_size, remainder = divmod(global_batch_size, device_count) if remainder: raise ValueError( f'Cannot split batch of {global_batch_size} evenly across {local_device_count} devices.' ) host_batch_dims = (local_device_count, per_device_batch_size) return host_batch_dims
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Anne Baanen ! This file was ported from Lean 3 source module algebra.algebra.tower ! leanprover-community/mathlib commit 71150516f28d9826c7341f8815b31f7d8770c212 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathlib.Algebra.Algebra.Equiv import Mathlib.LinearAlgebra.Span /-! # Towers of algebras In this file we prove basic facts about towers of algebra. An algebra tower A/S/R is expressed by having instances of `Algebra A S`, `Algebra R S`, `Algebra R A` and `IsScalarTower R S A`, the later asserting the compatibility condition `(r • s) • a = r • (s • a)`. An important definition is `toAlgHom R S A`, the canonical `R`-algebra homomorphism `S →ₐ[R] A`. -/ open Pointwise universe u v w u₁ v₁ variable (R : Type u) (S : Type v) (A : Type w) (B : Type u₁) (M : Type v₁) namespace Algebra variable [CommSemiring R] [Semiring A] [Algebra R A] variable [AddCommMonoid M] [Module R M] [Module A M] [IsScalarTower R A M] variable {A} /-- The `R`-algebra morphism `A → End (M)` corresponding to the representation of the algebra `A` on the `R`-module `M`. This is a stronger version of `DistribMulAction.toLinearMap`, and could also have been called `Algebra.toModuleEnd`. -/ def lsmul : A →ₐ[R] Module.End R M where toFun := DistribMulAction.toLinearMap R M map_one' := LinearMap.ext fun _ => one_smul A _ map_mul' a b := LinearMap.ext <| smul_assoc a b map_zero' := LinearMap.ext fun _ => zero_smul A _ map_add' _a _b := LinearMap.ext fun _ => add_smul _ _ _ commutes' r := LinearMap.ext <| algebraMap_smul A r #align algebra.lsmul Algebra.lsmul @[simp] theorem lsmul_coe (a : A) : (lsmul R M a : M → M) = (· • ·) a := rfl #align algebra.lsmul_coe Algebra.lsmul_coe end Algebra namespace IsScalarTower section Module variable [CommSemiring R] [Semiring A] [Algebra R A] variable [SMul R M] [MulAction A M] [IsScalarTower R A M] variable {R} {M} theorem algebraMap_smul (r : R) (x : M) : algebraMap R A r • x = r • x := by rw [Algebra.algebraMap_eq_smul_one, smul_assoc, one_smul] #align is_scalar_tower.algebra_map_smul IsScalarTower.algebraMap_smul end Module section Semiring variable [CommSemiring R] [CommSemiring S] [Semiring A] [Semiring B] variable [Algebra R S] [Algebra S A] [Algebra S B] variable {R S A} theorem of_algebraMap_eq [Algebra R A] (h : ∀ x, algebraMap R A x = algebraMap S A (algebraMap R S x)) : IsScalarTower R S A := ⟨fun x y z => by simp_rw [Algebra.smul_def, RingHom.map_mul, mul_assoc, h]⟩ #align is_scalar_tower.of_algebra_map_eq IsScalarTower.of_algebraMap_eq /-- See note [partially-applied ext lemmas]. -/ theorem of_algebraMap_eq' [Algebra R A] (h : algebraMap R A = (algebraMap S A).comp (algebraMap R S)) : IsScalarTower R S A := of_algebraMap_eq <| RingHom.ext_iff.1 h #align is_scalar_tower.of_algebra_map_eq' IsScalarTower.of_algebraMap_eq' variable (R S A) variable [Algebra R A] [Algebra R B] variable [IsScalarTower R S A] [IsScalarTower R S B] theorem algebraMap_eq : algebraMap R A = (algebraMap S A).comp (algebraMap R S) := RingHom.ext fun x => by simp_rw [RingHom.comp_apply, Algebra.algebraMap_eq_smul_one, smul_assoc, one_smul] #align is_scalar_tower.algebra_map_eq IsScalarTower.algebraMap_eq theorem algebraMap_apply (x : R) : algebraMap R A x = algebraMap S A (algebraMap R S x) := by rw [algebraMap_eq R S A, RingHom.comp_apply] #align is_scalar_tower.algebra_map_apply IsScalarTower.algebraMap_apply @[ext] theorem Algebra.ext {S : Type u} {A : Type v} [CommSemiring S] [Semiring A] (h1 h2 : Algebra S A) (h : ∀ (r : S) (x : A), (by have I := h1; exact r • x) = r • x) : h1 = h2 := Algebra.algebra_ext _ _ fun r => by simpa only [@Algebra.smul_def _ _ _ _ h1, @Algebra.smul_def _ _ _ _ h2, mul_one] using h r 1 #align is_scalar_tower.algebra.ext IsScalarTower.Algebra.ext /-- In a tower, the canonical map from the middle element to the top element is an algebra homomorphism over the bottom element. -/ def toAlgHom : S →ₐ[R] A := { algebraMap S A with commutes' := fun _ => (algebraMap_apply _ _ _ _).symm } #align is_scalar_tower.to_alg_hom IsScalarTower.toAlgHom @[simp] theorem coe_toAlgHom : ↑(toAlgHom R S A) = algebraMap S A := RingHom.ext fun _ => rfl #align is_scalar_tower.coe_to_alg_hom IsScalarTower.coe_toAlgHom @[simp] theorem coe_to_alg_hom' : (toAlgHom R S A : S → A) = algebraMap S A := rfl #align is_scalar_tower.coe_to_alg_hom' IsScalarTower.coe_to_alg_hom' variable {R S A B} @[simp] theorem AlgHom.map_algebraMap (f : A →ₐ[S] B) (r : R) : f (algebraMap R A r) = algebraMap R B r := by rw [algebraMap_apply R S A r, f.commutes, ← algebraMap_apply R S B] #align alg_hom.map_algebra_map IsScalarTower.AlgHom.map_algebraMap variable (R) @[simp] theorem AlgHom.comp_algebraMap_of_tower (f : A →ₐ[S] B) : (f : A →+* B).comp (algebraMap R A) = algebraMap R B := RingHom.ext (map_algebraMap f) #align alg_hom.comp_algebra_map_of_tower IsScalarTower.AlgHom.comp_algebraMap_of_tower -- conflicts with IsScalarTower.Subalgebra instance (priority := 999) subsemiring (U : Subsemiring S) : IsScalarTower U S A := of_algebraMap_eq fun _x => rfl #align is_scalar_tower.subsemiring IsScalarTower.subsemiring -- Porting note: @[nolint instance_priority] instance of_ring_hom {R A B : Type _} [CommSemiring R] [CommSemiring A] [CommSemiring B] [Algebra R A] [Algebra R B] (f : A →ₐ[R] B) : @IsScalarTower R A B _ f.toRingHom.toAlgebra.toSMul _ := letI := (f : A →+* B).toAlgebra of_algebraMap_eq fun x => (f.commutes x).symm #align is_scalar_tower.of_ring_hom IsScalarTower.of_ring_hom end Semiring end IsScalarTower section Homs variable [CommSemiring R] [CommSemiring S] [Semiring A] [Semiring B] variable [Algebra R S] [Algebra S A] [Algebra S B] variable [Algebra R A] [Algebra R B] variable [IsScalarTower R S A] [IsScalarTower R S B] variable {A S B} open IsScalarTower namespace AlgHom /-- R ⟶ S induces S-Alg ⥤ R-Alg -/ def restrictScalars (f : A →ₐ[S] B) : A →ₐ[R] B := { (f : A →+* B) with commutes' := fun r => by rw [algebraMap_apply R S A, algebraMap_apply R S B] exact f.commutes (algebraMap R S r) } #align alg_hom.restrict_scalars AlgHom.restrictScalars theorem restrictScalars_apply (f : A →ₐ[S] B) (x : A) : f.restrictScalars R x = f x := rfl #align alg_hom.restrict_scalars_apply AlgHom.restrictScalars_apply @[simp] theorem coe_restrictScalars (f : A →ₐ[S] B) : (f.restrictScalars R : A →+* B) = f := rfl #align alg_hom.coe_restrict_scalars AlgHom.coe_restrictScalars @[simp] theorem coe_restrict_scalars' (f : A →ₐ[S] B) : (restrictScalars R f : A → B) = f := rfl #align alg_hom.coe_restrict_scalars' AlgHom.coe_restrict_scalars' theorem restrictScalars_injective : Function.Injective (restrictScalars R : (A →ₐ[S] B) → A →ₐ[R] B) := fun _ _ h => AlgHom.ext (AlgHom.congr_fun h : _) #align alg_hom.restrict_scalars_injective AlgHom.restrictScalars_injective end AlgHom namespace AlgEquiv /-- R ⟶ S induces S-Alg ⥤ R-Alg -/ def restrictScalars (f : A ≃ₐ[S] B) : A ≃ₐ[R] B := { (f : A ≃+* B) with commutes' := fun r => by rw [algebraMap_apply R S A, algebraMap_apply R S B] exact f.commutes (algebraMap R S r) } #align alg_equiv.restrict_scalars AlgEquiv.restrictScalars theorem restrictScalars_apply (f : A ≃ₐ[S] B) (x : A) : f.restrictScalars R x = f x := rfl #align alg_equiv.restrict_scalars_apply AlgEquiv.restrictScalars_apply @[simp] theorem coe_restrictScalars (f : A ≃ₐ[S] B) : (f.restrictScalars R : A ≃+* B) = f := rfl #align alg_equiv.coe_restrict_scalars AlgEquiv.coe_restrictScalars @[simp] theorem coe_restrict_scalars' (f : A ≃ₐ[S] B) : (restrictScalars R f : A → B) = f := rfl #align alg_equiv.coe_restrict_scalars' AlgEquiv.coe_restrict_scalars' theorem restrictScalars_injective : Function.Injective (restrictScalars R : (A ≃ₐ[S] B) → A ≃ₐ[R] B) := fun _ _ h => AlgEquiv.ext (AlgEquiv.congr_fun h : _) #align alg_equiv.restrict_scalars_injective AlgEquiv.restrictScalars_injective end AlgEquiv end Homs namespace Submodule variable {M} variable [CommSemiring R] [Semiring A] [Algebra R A] [AddCommMonoid M] variable [Module R M] [Module A M] [IsScalarTower R A M] /-- If `A` is an `R`-algebra such that the induced morphism `R →+* A` is surjective, then the `R`-module generated by a set `X` equals the `A`-module generated by `X`. -/ theorem restrictScalars_span (hsur : Function.Surjective (algebraMap R A)) (X : Set M) : restrictScalars R (span A X) = span R X := by refine' ((span_le_restrictScalars R A X).antisymm fun m hm => _).symm refine' span_induction hm subset_span (zero_mem _) (fun _ _ => add_mem) fun a m hm => _ obtain ⟨r, rfl⟩ := hsur a simpa [algebraMap_smul] using smul_mem _ r hm #align submodule.restrict_scalars_span Submodule.restrictScalars_span theorem coe_span_eq_span_of_surjective (h : Function.Surjective (algebraMap R A)) (s : Set M) : (Submodule.span A s : Set M) = Submodule.span R s := congr_arg ((↑) : Submodule R M → Set M) (Submodule.restrictScalars_span R A h s) #align submodule.coe_span_eq_span_of_surjective Submodule.coe_span_eq_span_of_surjective end Submodule section Semiring variable {R S A} namespace Submodule section Module variable [Semiring R] [Semiring S] [AddCommMonoid A] variable [Module R S] [Module S A] [Module R A] [IsScalarTower R S A] open IsScalarTower theorem smul_mem_span_smul_of_mem {s : Set S} {t : Set A} {k : S} (hks : k ∈ span R s) {x : A} (hx : x ∈ t) : k • x ∈ span R (s • t) := span_induction hks (fun c hc => subset_span <| Set.mem_smul.2 ⟨c, x, hc, hx, rfl⟩) (by rw [zero_smul]; exact zero_mem _) (fun c₁ c₂ ih₁ ih₂ => by rw [add_smul]; exact add_mem ih₁ ih₂) fun b c hc => by rw [IsScalarTower.smul_assoc]; exact smul_mem _ _ hc #align submodule.smul_mem_span_smul_of_mem Submodule.smul_mem_span_smul_of_mem variable [SMulCommClass R S A] theorem smul_mem_span_smul {s : Set S} (hs : span R s = ⊤) {t : Set A} {k : S} {x : A} (hx : x ∈ span R t) : k • x ∈ span R (s • t) := span_induction hx (fun x hx => smul_mem_span_smul_of_mem (hs.symm ▸ mem_top) hx) (by rw [smul_zero]; exact zero_mem _) (fun x y ihx ihy => by rw [smul_add]; exact add_mem ihx ihy) fun c x hx => smul_comm c k x ▸ smul_mem _ _ hx #align submodule.smul_mem_span_smul Submodule.smul_mem_span_smul theorem smul_mem_span_smul' {s : Set S} (hs : span R s = ⊤) {t : Set A} {k : S} {x : A} (hx : x ∈ span R (s • t)) : k • x ∈ span R (s • t) := span_induction hx (fun x hx => by let ⟨p, q, _hp, hq, hpq⟩ := Set.mem_smul.1 hx rw [← hpq, smul_smul] exact smul_mem_span_smul_of_mem (hs.symm ▸ mem_top) hq) (by rw [smul_zero]; exact zero_mem _) (fun x y ihx ihy => by rw [smul_add]; exact add_mem ihx ihy) fun c x hx => smul_comm c k x ▸ smul_mem _ _ hx #align submodule.smul_mem_span_smul' Submodule.smul_mem_span_smul' theorem span_smul_of_span_eq_top {s : Set S} (hs : span R s = ⊤) (t : Set A) : span R (s • t) = (span S t).restrictScalars R := le_antisymm (span_le.2 fun _x hx => let ⟨p, _q, _hps, hqt, hpqx⟩ := Set.mem_smul.1 hx hpqx ▸ (span S t).smul_mem p (subset_span hqt)) fun _p hp => span_induction hp (fun x hx => one_smul S x ▸ smul_mem_span_smul hs (subset_span hx)) (zero_mem _) (fun _ _ => add_mem) fun _k _x hx => smul_mem_span_smul' hs hx #align submodule.span_smul_of_span_eq_top Submodule.span_smul_of_span_eq_top end Module section Algebra variable [CommSemiring R] [Semiring S] [AddCommMonoid A] variable [Algebra R S] [Module S A] [Module R A] [IsScalarTower R S A] /-- A variant of `Submodule.span_image` for `algebraMap`. -/ theorem span_algebraMap_image (a : Set R) : Submodule.span R (algebraMap R S '' a) = (Submodule.span R a).map (Algebra.linearMap R S) := (Submodule.span_image <| Algebra.linearMap R S).trans rfl #align submodule.span_algebra_map_image Submodule.span_algebraMap_image theorem span_algebraMap_image_of_tower {S T : Type _} [CommSemiring S] [Semiring T] [Module R S] [IsScalarTower R S S] [Algebra R T] [Algebra S T] [IsScalarTower R S T] (a : Set S) : Submodule.span R (algebraMap S T '' a) = (Submodule.span R a).map ((Algebra.linearMap S T).restrictScalars R) := (Submodule.span_image <| (Algebra.linearMap S T).restrictScalars R).trans rfl #align submodule.span_algebra_map_image_of_tower Submodule.span_algebraMap_image_of_tower theorem map_mem_span_algebraMap_image {S T : Type _} [CommSemiring S] [Semiring T] [Algebra R S] [Algebra R T] [Algebra S T] [IsScalarTower R S T] (x : S) (a : Set S) (hx : x ∈ Submodule.span R a) : algebraMap S T x ∈ Submodule.span R (algebraMap S T '' a) := by rw [span_algebraMap_image_of_tower, mem_map] exact ⟨x, hx, rfl⟩ #align submodule.map_mem_span_algebra_map_image Submodule.map_mem_span_algebraMap_image end Algebra end Submodule end Semiring section Ring namespace Algebra variable [CommSemiring R] [Semiring A] [Algebra R A] variable [AddCommGroup M] [Module A M] [Module R M] [IsScalarTower R A M] theorem lsmul_injective [NoZeroSMulDivisors A M] {x : A} (hx : x ≠ 0) : Function.Injective (lsmul R M x) := smul_right_injective _ hx #align algebra.lsmul_injective Algebra.lsmul_injective end Algebra end Ring
[STATEMENT] lemma prefix_minus_concat: assumes "prefix s t" shows "(t - s) @ z = (t @ z) - s" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (t - s) @ z = t @ z - s [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: prefix s t goal (1 subgoal): 1. (t - s) @ z = t @ z - s [PROOF STEP] by (simp add: Sublist.prefix_length_le minus_list_def)
theory BExp imports AExp begin subsection "Boolean Expressions" datatype bexp = Bc bool | Not bexp | And bexp bexp | Less aexp aexp fun bval :: "bexp \<Rightarrow> state \<Rightarrow> bool" where "bval (Bc v) s = v" | "bval (Not b) s = (\<not> bval b s)" | "bval (And b\<^sub>1 b\<^sub>2) s = (bval b\<^sub>1 s \<and> bval b\<^sub>2 s)" | "bval (Less a\<^sub>1 a\<^sub>2) s = (aval a\<^sub>1 s < aval a\<^sub>2 s)" value "bval (Less (V ''x'') (Plus (N 3) (V ''y''))) <''x'' := 3, ''y'' := 1>" subsection "Constant Folding" text \<open>Optimizing constructors:\<close> fun less :: "aexp \<Rightarrow> aexp \<Rightarrow> bexp" where "less (N n\<^sub>1) (N n\<^sub>2) = Bc(n\<^sub>1 < n\<^sub>2)" | "less a\<^sub>1 a\<^sub>2 = Less a\<^sub>1 a\<^sub>2" fun "and" :: "bexp \<Rightarrow> bexp \<Rightarrow> bexp" where "and (Bc True) b = b" | "and b (Bc True) = b" | "and (Bc False) b = Bc False" | "and b (Bc False) = Bc False" | "and b\<^sub>1 b\<^sub>2 = And b\<^sub>1 b\<^sub>2" lemma bval_and[simp]: "bval (and b1 b2) s = (bval b1 s \<and> bval b2 s)" apply(induction b1 b2 rule: and.induct) apply auto done fun not :: "bexp \<Rightarrow> bexp" where "not (Bc v) = Bc(\<not> v)" | "not b = Not b" lemma bval_not[simp]: "bval (not b) s = (\<not> bval b s)" apply(induction ) apply auto done text \<open>Now the overall optimizer:\<close> fun bsimp :: "bexp \<Rightarrow> bexp" where "bsimp (Bc v) = Bc v" | "bsimp (Not b) = not(bsimp b)" | "bsimp (And b\<^sub>1 b\<^sub>2) = and (bsimp b\<^sub>1) (bsimp b\<^sub>2)" | "bsimp (Less a\<^sub>1 a\<^sub>2) = less (asimp a\<^sub>1) (asimp a\<^sub>2)" value "bsimp (And (Less (N 0) (N 1)) b)" value "bsimp (And (Less (N 1) (N 0)) (Bc True))" theorem "bval (bsimp b) s = bval b s" apply(induction b) apply auto done end
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Mario Carneiro, Johan Commelin -/ import data.int.modeq import number_theory.padics.padic_numbers import ring_theory.discrete_valuation_ring import topology.metric_space.cau_seq_filter /-! # p-adic integers This file defines the p-adic integers `ℤ_p` as the subtype of `ℚ_p` with norm `≤ 1`. We show that `ℤ_p` * is complete * is nonarchimedean * is a normed ring * is a local ring * is a discrete valuation ring The relation between `ℤ_[p]` and `zmod p` is established in another file. ## Important definitions * `padic_int` : the type of p-adic numbers ## Notation We introduce the notation `ℤ_[p]` for the p-adic integers. ## Implementation notes Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically by taking `[fact (nat.prime p)] as a type class argument. Coercions into `ℤ_p` are set up to work with the `norm_cast` tactic. ## References * [F. Q. Gouêva, *p-adic numbers*][gouvea1997] * [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019] * <https://en.wikipedia.org/wiki/P-adic_number> ## Tags p-adic, p adic, padic, p-adic integer -/ open padic metric local_ring noncomputable theory open_locale classical /-- The p-adic integers ℤ_p are the p-adic numbers with norm ≤ 1. -/ def padic_int (p : ℕ) [fact p.prime] := {x : ℚ_[p] // ∥x∥ ≤ 1} notation `ℤ_[`p`]` := padic_int p namespace padic_int /-! ### Ring structure and coercion to `ℚ_[p]` -/ variables {p : ℕ} [fact p.prime] instance : has_coe ℤ_[p] ℚ_[p] := ⟨subtype.val⟩ lemma ext {x y : ℤ_[p]} : (x : ℚ_[p]) = y → x = y := subtype.ext_iff_val.2 /-- Addition on ℤ_p is inherited from ℚ_p. -/ instance : has_add ℤ_[p] := ⟨λ ⟨x, hx⟩ ⟨y, hy⟩, ⟨x+y, le_trans (padic_norm_e.nonarchimedean _ _) (max_le_iff.2 ⟨hx,hy⟩)⟩⟩ /-- Multiplication on ℤ_p is inherited from ℚ_p. -/ instance : has_mul ℤ_[p] := ⟨λ ⟨x, hx⟩ ⟨y, hy⟩, ⟨x*y, begin rw padic_norm_e.mul, apply mul_le_one; {assumption <|> apply norm_nonneg} end⟩⟩ /-- Negation on ℤ_p is inherited from ℚ_p. -/ instance : has_neg ℤ_[p] := ⟨λ ⟨x, hx⟩, ⟨-x, by simpa⟩⟩ /-- Subtraction on ℤ_p is inherited from ℚ_p. -/ instance : has_sub ℤ_[p] := ⟨λ ⟨x, hx⟩ ⟨y, hy⟩, ⟨x - y, by { rw sub_eq_add_neg, rw ← norm_neg at hy, exact le_trans (padic_norm_e.nonarchimedean _ _) (max_le_iff.2 ⟨hx, hy⟩) }⟩⟩ /-- Zero on ℤ_p is inherited from ℚ_p. -/ instance : has_zero ℤ_[p] := ⟨⟨0, by norm_num⟩⟩ instance : inhabited ℤ_[p] := ⟨0⟩ /-- One on ℤ_p is inherited from ℚ_p. -/ instance : has_one ℤ_[p] := ⟨⟨1, by norm_num⟩⟩ @[simp] lemma mk_zero {h} : (⟨0, h⟩ : ℤ_[p]) = (0 : ℤ_[p]) := rfl @[simp] lemma val_eq_coe (z : ℤ_[p]) : z.val = z := rfl @[simp, norm_cast] lemma coe_add : ∀ (z1 z2 : ℤ_[p]), ((z1 + z2 : ℤ_[p]) : ℚ_[p]) = z1 + z2 | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp, norm_cast] lemma coe_mul : ∀ (z1 z2 : ℤ_[p]), ((z1 * z2 : ℤ_[p]) : ℚ_[p]) = z1 * z2 | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp, norm_cast] lemma coe_neg : ∀ (z1 : ℤ_[p]), ((-z1 : ℤ_[p]) : ℚ_[p]) = -z1 | ⟨_, _⟩ := rfl @[simp, norm_cast] lemma coe_sub : ∀ (z1 z2 : ℤ_[p]), ((z1 - z2 : ℤ_[p]) : ℚ_[p]) = z1 - z2 | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp, norm_cast] lemma coe_one : ((1 : ℤ_[p]) : ℚ_[p]) = 1 := rfl @[simp, norm_cast] lemma coe_coe : ∀ n : ℕ, ((n : ℤ_[p]) : ℚ_[p]) = n | 0 := rfl | (k+1) := by simp [coe_coe] @[simp, norm_cast] lemma coe_coe_int : ∀ (z : ℤ), ((z : ℤ_[p]) : ℚ_[p]) = z | (int.of_nat n) := by simp | -[1+n] := by simp @[simp, norm_cast] lemma coe_zero : ((0 : ℤ_[p]) : ℚ_[p]) = 0 := rfl instance : ring ℤ_[p] := by refine_struct { add := (+), mul := (*), neg := has_neg.neg, zero := (0 : ℤ_[p]), one := 1, sub := has_sub.sub, npow := @npow_rec _ ⟨(1 : ℤ_[p])⟩ ⟨(*)⟩, nsmul := @nsmul_rec _ ⟨(0 : ℤ_[p])⟩ ⟨(+)⟩, zsmul := @zsmul_rec _ ⟨(0 : ℤ_[p])⟩ ⟨(+)⟩ ⟨has_neg.neg⟩ }; intros; try { refl }; ext; simp; ring /-- The coercion from ℤ[p] to ℚ[p] as a ring homomorphism. -/ def coe.ring_hom : ℤ_[p] →+* ℚ_[p] := { to_fun := (coe : ℤ_[p] → ℚ_[p]), map_zero' := rfl, map_one' := rfl, map_mul' := coe_mul, map_add' := coe_add } @[simp, norm_cast] lemma coe_pow (x : ℤ_[p]) (n : ℕ) : (↑(x^n) : ℚ_[p]) = (↑x : ℚ_[p])^n := coe.ring_hom.map_pow x n @[simp] lemma mk_coe : ∀ (k : ℤ_[p]), (⟨k, k.2⟩ : ℤ_[p]) = k | ⟨_, _⟩ := rfl /-- The inverse of a p-adic integer with norm equal to 1 is also a p-adic integer. Otherwise, the inverse is defined to be 0. -/ def inv : ℤ_[p] → ℤ_[p] | ⟨k, _⟩ := if h : ∥k∥ = 1 then ⟨1/k, by simp [h]⟩ else 0 instance : char_zero ℤ_[p] := { cast_injective := λ m n h, nat.cast_injective $ show (m:ℚ_[p]) = n, by { rw subtype.ext_iff at h, norm_cast at h, exact h } } @[simp, norm_cast] lemma coe_int_eq (z1 z2 : ℤ) : (z1 : ℤ_[p]) = z2 ↔ z1 = z2 := suffices (z1 : ℚ_[p]) = z2 ↔ z1 = z2, from iff.trans (by norm_cast) this, by norm_cast /-- A sequence of integers that is Cauchy with respect to the `p`-adic norm converges to a `p`-adic integer. -/ def of_int_seq (seq : ℕ → ℤ) (h : is_cau_seq (padic_norm p) (λ n, seq n)) : ℤ_[p] := ⟨⟦⟨_, h⟩⟧, show ↑(padic_seq.norm _) ≤ (1 : ℝ), begin rw padic_seq.norm, split_ifs with hne; norm_cast, { exact zero_le_one }, { apply padic_norm.of_int } end ⟩ end padic_int namespace padic_int /-! ### Instances We now show that `ℤ_[p]` is a * complete metric space * normed ring * integral domain -/ variables (p : ℕ) [fact p.prime] instance : metric_space ℤ_[p] := subtype.metric_space instance complete_space : complete_space ℤ_[p] := have is_closed {x : ℚ_[p] | ∥x∥ ≤ 1}, from is_closed_le continuous_norm continuous_const, this.complete_space_coe instance : has_norm ℤ_[p] := ⟨λ z, ∥(z : ℚ_[p])∥⟩ variables {p} protected lemma mul_comm : ∀ z1 z2 : ℤ_[p], z1*z2 = z2*z1 | ⟨q1, h1⟩ ⟨q2, h2⟩ := show (⟨q1*q2, _⟩ : ℤ_[p]) = ⟨q2*q1, _⟩, by simp [_root_.mul_comm] protected lemma zero_ne_one : (0 : ℤ_[p]) ≠ 1 := show (⟨(0 : ℚ_[p]), _⟩ : ℤ_[p]) ≠ ⟨(1 : ℚ_[p]), _⟩, from mt subtype.ext_iff_val.1 zero_ne_one protected lemma eq_zero_or_eq_zero_of_mul_eq_zero : ∀ (a b : ℤ_[p]), a * b = 0 → a = 0 ∨ b = 0 | ⟨a, ha⟩ ⟨b, hb⟩ := λ h : (⟨a * b, _⟩ : ℤ_[p]) = ⟨0, _⟩, have a * b = 0, from subtype.ext_iff_val.1 h, (mul_eq_zero.1 this).elim (λ h1, or.inl (by simp [h1]; refl)) (λ h2, or.inr (by simp [h2]; refl)) lemma norm_def {z : ℤ_[p]} : ∥z∥ = ∥(z : ℚ_[p])∥ := rfl variables (p) instance : normed_comm_ring ℤ_[p] := { dist_eq := λ ⟨_, _⟩ ⟨_, _⟩, rfl, norm_mul := λ ⟨_, _⟩ ⟨_, _⟩, norm_mul_le _ _, mul_comm := padic_int.mul_comm } instance : norm_one_class ℤ_[p] := ⟨norm_def.trans norm_one⟩ instance is_absolute_value : is_absolute_value (λ z : ℤ_[p], ∥z∥) := { abv_nonneg := norm_nonneg, abv_eq_zero := λ ⟨_, _⟩, by simp [norm_eq_zero], abv_add := λ ⟨_,_⟩ ⟨_, _⟩, norm_add_le _ _, abv_mul := λ _ _, by simp only [norm_def, padic_norm_e.mul, padic_int.coe_mul]} variables {p} instance : is_domain ℤ_[p] := { eq_zero_or_eq_zero_of_mul_eq_zero := λ x y, padic_int.eq_zero_or_eq_zero_of_mul_eq_zero x y, exists_pair_ne := ⟨0, 1, padic_int.zero_ne_one⟩, .. padic_int.normed_comm_ring p } end padic_int namespace padic_int /-! ### Norm -/ variables {p : ℕ} [fact p.prime] lemma norm_le_one : ∀ z : ℤ_[p], ∥z∥ ≤ 1 | ⟨_, h⟩ := h @[simp] lemma norm_mul (z1 z2 : ℤ_[p]) : ∥z1 * z2∥ = ∥z1∥ * ∥z2∥ := by simp [norm_def] @[simp] theorem nonarchimedean : ∀ (q r : ℤ_[p]), ∥q + r∥ ≤ max (∥q∥) (∥r∥) | ⟨_, _⟩ ⟨_, _⟩ := padic_norm_e.nonarchimedean _ _ theorem norm_add_eq_max_of_ne : ∀ {q r : ℤ_[p]}, ∥q∥ ≠ ∥r∥ → ∥q+r∥ = max (∥q∥) (∥r∥) | ⟨_, _⟩ ⟨_, _⟩ := padic_norm_e.add_eq_max_of_ne lemma norm_eq_of_norm_add_lt_right {z1 z2 : ℤ_[p]} (h : ∥z1 + z2∥ < ∥z2∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw norm_add_eq_max_of_ne hne; apply le_max_right) h lemma norm_eq_of_norm_add_lt_left {z1 z2 : ℤ_[p]} (h : ∥z1 + z2∥ < ∥z1∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw norm_add_eq_max_of_ne hne; apply le_max_left) h @[simp] lemma padic_norm_e_of_padic_int (z : ℤ_[p]) : ∥(↑z : ℚ_[p])∥ = ∥z∥ := by simp [norm_def] lemma norm_int_cast_eq_padic_norm (z : ℤ) : ∥(z : ℤ_[p])∥ = ∥(z : ℚ_[p])∥ := by simp [norm_def] @[simp] lemma norm_eq_padic_norm {q : ℚ_[p]} (hq : ∥q∥ ≤ 1) : @norm ℤ_[p] _ ⟨q, hq⟩ = ∥q∥ := rfl @[simp] lemma norm_p : ∥(p : ℤ_[p])∥ = p⁻¹ := show ∥((p : ℤ_[p]) : ℚ_[p])∥ = p⁻¹, by exact_mod_cast padic_norm_e.norm_p @[simp] lemma norm_p_pow (n : ℕ) : ∥(p : ℤ_[p])^n∥ = p^(-n:ℤ) := show ∥((p^n : ℤ_[p]) : ℚ_[p])∥ = p^(-n:ℤ), by { convert padic_norm_e.norm_p_pow n, simp, } private def cau_seq_to_rat_cau_seq (f : cau_seq ℤ_[p] norm) : cau_seq ℚ_[p] (λ a, ∥a∥) := ⟨ λ n, f n, λ _ hε, by simpa [norm, norm_def] using f.cauchy hε ⟩ variables (p) instance complete : cau_seq.is_complete ℤ_[p] norm := ⟨ λ f, have hqn : ∥cau_seq.lim (cau_seq_to_rat_cau_seq f)∥ ≤ 1, from padic_norm_e_lim_le zero_lt_one (λ _, norm_le_one _), ⟨ ⟨_, hqn⟩, λ ε, by simpa [norm, norm_def] using cau_seq.equiv_lim (cau_seq_to_rat_cau_seq f) ε⟩⟩ end padic_int namespace padic_int variables (p : ℕ) [hp_prime : fact p.prime] include hp_prime lemma exists_pow_neg_lt {ε : ℝ} (hε : 0 < ε) : ∃ (k : ℕ), ↑p ^ -((k : ℕ) : ℤ) < ε := begin obtain ⟨k, hk⟩ := exists_nat_gt ε⁻¹, use k, rw ← inv_lt_inv hε (_root_.zpow_pos_of_pos _ _), { rw [zpow_neg₀, inv_inv₀, zpow_coe_nat], apply lt_of_lt_of_le hk, norm_cast, apply le_of_lt, convert nat.lt_pow_self _ _ using 1, exact hp_prime.1.one_lt }, { exact_mod_cast hp_prime.1.pos } end lemma exists_pow_neg_lt_rat {ε : ℚ} (hε : 0 < ε) : ∃ (k : ℕ), ↑p ^ -((k : ℕ) : ℤ) < ε := begin obtain ⟨k, hk⟩ := @exists_pow_neg_lt p _ ε (by exact_mod_cast hε), use k, rw (show (p : ℝ) = (p : ℚ), by simp) at hk, exact_mod_cast hk end variable {p} lemma norm_int_lt_one_iff_dvd (k : ℤ) : ∥(k : ℤ_[p])∥ < 1 ↔ ↑p ∣ k := suffices ∥(k : ℚ_[p])∥ < 1 ↔ ↑p ∣ k, by rwa norm_int_cast_eq_padic_norm, padic_norm_e.norm_int_lt_one_iff_dvd k lemma norm_int_le_pow_iff_dvd {k : ℤ} {n : ℕ} : ∥(k : ℤ_[p])∥ ≤ ((↑p)^(-n : ℤ)) ↔ ↑p^n ∣ k := suffices ∥(k : ℚ_[p])∥ ≤ ((↑p)^(-n : ℤ)) ↔ ↑(p^n) ∣ k, by simpa [norm_int_cast_eq_padic_norm], padic_norm_e.norm_int_le_pow_iff_dvd _ _ /-! ### Valuation on `ℤ_[p]` -/ /-- `padic_int.valuation` lifts the p-adic valuation on `ℚ` to `ℤ_[p]`. -/ def valuation (x : ℤ_[p]) := padic.valuation (x : ℚ_[p]) lemma norm_eq_pow_val {x : ℤ_[p]} (hx : x ≠ 0) : ∥x∥ = p^(-x.valuation) := begin convert padic.norm_eq_pow_val _, contrapose! hx, exact subtype.val_injective hx end @[simp] lemma valuation_zero : valuation (0 : ℤ_[p]) = 0 := padic.valuation_zero @[simp] lemma valuation_one : valuation (1 : ℤ_[p]) = 0 := padic.valuation_one @[simp] lemma valuation_p : valuation (p : ℤ_[p]) = 1 := by simp [valuation, -cast_eq_of_rat_of_nat] lemma valuation_nonneg (x : ℤ_[p]) : 0 ≤ x.valuation := begin by_cases hx : x = 0, { simp [hx] }, have h : (1 : ℝ) < p := by exact_mod_cast hp_prime.1.one_lt, rw [← neg_nonpos, ← (zpow_strict_mono h).le_iff_le], show (p : ℝ) ^ -valuation x ≤ p ^ 0, rw [← norm_eq_pow_val hx], simpa using x.property, end @[simp] lemma valuation_p_pow_mul (n : ℕ) (c : ℤ_[p]) (hc : c ≠ 0) : (↑p ^ n * c).valuation = n + c.valuation := begin have : ∥↑p ^ n * c∥ = ∥(p ^ n : ℤ_[p])∥ * ∥c∥, { exact norm_mul _ _ }, have aux : ↑p ^ n * c ≠ 0, { contrapose! hc, rw mul_eq_zero at hc, cases hc, { refine (hp_prime.1.ne_zero _).elim, exact_mod_cast (pow_eq_zero hc) }, { exact hc } }, rwa [norm_eq_pow_val aux, norm_p_pow, norm_eq_pow_val hc, ← zpow_add₀, ← neg_add, zpow_inj, neg_inj] at this, { exact_mod_cast hp_prime.1.pos }, { exact_mod_cast hp_prime.1.ne_one }, { exact_mod_cast hp_prime.1.ne_zero }, end section units /-! ### Units of `ℤ_[p]` -/ local attribute [reducible] padic_int lemma mul_inv : ∀ {z : ℤ_[p]}, ∥z∥ = 1 → z * z.inv = 1 | ⟨k, _⟩ h := begin have hk : k ≠ 0, from λ h', @zero_ne_one ℚ_[p] _ _ (by simpa [h'] using h), unfold padic_int.inv, rw [norm_eq_padic_norm] at h, rw dif_pos h, apply subtype.ext_iff_val.2, simp [mul_inv_cancel hk], end lemma inv_mul {z : ℤ_[p]} (hz : ∥z∥ = 1) : z.inv * z = 1 := by rw [mul_comm, mul_inv hz] lemma is_unit_iff {z : ℤ_[p]} : is_unit z ↔ ∥z∥ = 1 := ⟨λ h, begin rcases is_unit_iff_dvd_one.1 h with ⟨w, eq⟩, refine le_antisymm (norm_le_one _) _, have := mul_le_mul_of_nonneg_left (norm_le_one w) (norm_nonneg z), rwa [mul_one, ← norm_mul, ← eq, norm_one] at this end, λ h, ⟨⟨z, z.inv, mul_inv h, inv_mul h⟩, rfl⟩⟩ lemma norm_lt_one_add {z1 z2 : ℤ_[p]} (hz1 : ∥z1∥ < 1) (hz2 : ∥z2∥ < 1) : ∥z1 + z2∥ < 1 := lt_of_le_of_lt (nonarchimedean _ _) (max_lt hz1 hz2) lemma norm_lt_one_mul {z1 z2 : ℤ_[p]} (hz2 : ∥z2∥ < 1) : ∥z1 * z2∥ < 1 := calc ∥z1 * z2∥ = ∥z1∥ * ∥z2∥ : by simp ... < 1 : mul_lt_one_of_nonneg_of_lt_one_right (norm_le_one _) (norm_nonneg _) hz2 @[simp] lemma mem_nonunits {z : ℤ_[p]} : z ∈ nonunits ℤ_[p] ↔ ∥z∥ < 1 := by rw lt_iff_le_and_ne; simp [norm_le_one z, nonunits, is_unit_iff] /-- A `p`-adic number `u` with `∥u∥ = 1` is a unit of `ℤ_[p]`. -/ def mk_units {u : ℚ_[p]} (h : ∥u∥ = 1) : units ℤ_[p] := let z : ℤ_[p] := ⟨u, le_of_eq h⟩ in ⟨z, z.inv, mul_inv h, inv_mul h⟩ @[simp] lemma mk_units_eq {u : ℚ_[p]} (h : ∥u∥ = 1) : ((mk_units h : ℤ_[p]) : ℚ_[p]) = u := rfl @[simp] lemma norm_units (u : units ℤ_[p]) : ∥(u : ℤ_[p])∥ = 1 := is_unit_iff.mp $ by simp /-- `unit_coeff hx` is the unit `u` in the unique representation `x = u * p ^ n`. See `unit_coeff_spec`. -/ def unit_coeff {x : ℤ_[p]} (hx : x ≠ 0) : units ℤ_[p] := let u : ℚ_[p] := x*p^(-x.valuation) in have hu : ∥u∥ = 1, by simp [hx, nat.zpow_ne_zero_of_pos (by exact_mod_cast hp_prime.1.pos) x.valuation, norm_eq_pow_val, zpow_neg, inv_mul_cancel, -cast_eq_of_rat_of_nat], mk_units hu @[simp] lemma unit_coeff_coe {x : ℤ_[p]} (hx : x ≠ 0) : (unit_coeff hx : ℚ_[p]) = x * p ^ (-x.valuation) := rfl lemma unit_coeff_spec {x : ℤ_[p]} (hx : x ≠ 0) : x = (unit_coeff hx : ℤ_[p]) * p ^ int.nat_abs (valuation x) := begin apply subtype.coe_injective, push_cast, have repr : (x : ℚ_[p]) = (unit_coeff hx) * p ^ x.valuation, { rw [unit_coeff_coe, mul_assoc, ← zpow_add₀], { simp }, { exact_mod_cast hp_prime.1.ne_zero } }, convert repr using 2, rw [← zpow_coe_nat, int.nat_abs_of_nonneg (valuation_nonneg x)], end end units section norm_le_iff /-! ### Various characterizations of open unit balls -/ lemma norm_le_pow_iff_le_valuation (x : ℤ_[p]) (hx : x ≠ 0) (n : ℕ) : ∥x∥ ≤ p ^ (-n : ℤ) ↔ ↑n ≤ x.valuation := begin rw norm_eq_pow_val hx, lift x.valuation to ℕ using x.valuation_nonneg with k hk, simp only [int.coe_nat_le, zpow_neg₀, zpow_coe_nat], have aux : ∀ n : ℕ, 0 < (p ^ n : ℝ), { apply pow_pos, exact_mod_cast hp_prime.1.pos }, rw [inv_le_inv (aux _) (aux _)], have : p ^ n ≤ p ^ k ↔ n ≤ k := (strict_mono_pow hp_prime.1.one_lt).le_iff_le, rw [← this], norm_cast, end lemma mem_span_pow_iff_le_valuation (x : ℤ_[p]) (hx : x ≠ 0) (n : ℕ) : x ∈ (ideal.span {p ^ n} : ideal ℤ_[p]) ↔ ↑n ≤ x.valuation := begin rw [ideal.mem_span_singleton], split, { rintro ⟨c, rfl⟩, suffices : c ≠ 0, { rw [valuation_p_pow_mul _ _ this, le_add_iff_nonneg_right], apply valuation_nonneg, }, contrapose! hx, rw [hx, mul_zero], }, { rw [unit_coeff_spec hx] { occs := occurrences.pos [2] }, lift x.valuation to ℕ using x.valuation_nonneg with k hk, simp only [int.nat_abs_of_nat, units.is_unit, is_unit.dvd_mul_left, int.coe_nat_le], intro H, obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le H, simp only [pow_add, dvd_mul_right], } end lemma norm_le_pow_iff_mem_span_pow (x : ℤ_[p]) (n : ℕ) : ∥x∥ ≤ p ^ (-n : ℤ) ↔ x ∈ (ideal.span {p ^ n} : ideal ℤ_[p]) := begin by_cases hx : x = 0, { subst hx, simp only [norm_zero, zpow_neg₀, zpow_coe_nat, inv_nonneg, iff_true, submodule.zero_mem], exact_mod_cast nat.zero_le _ }, rw [norm_le_pow_iff_le_valuation x hx, mem_span_pow_iff_le_valuation x hx], end lemma norm_le_pow_iff_norm_lt_pow_add_one (x : ℤ_[p]) (n : ℤ) : ∥x∥ ≤ p ^ n ↔ ∥x∥ < p ^ (n + 1) := begin rw norm_def, exact padic.norm_le_pow_iff_norm_lt_pow_add_one _ _, end lemma norm_lt_pow_iff_norm_le_pow_sub_one (x : ℤ_[p]) (n : ℤ) : ∥x∥ < p ^ n ↔ ∥x∥ ≤ p ^ (n - 1) := by rw [norm_le_pow_iff_norm_lt_pow_add_one, sub_add_cancel] lemma norm_lt_one_iff_dvd (x : ℤ_[p]) : ∥x∥ < 1 ↔ ↑p ∣ x := begin have := norm_le_pow_iff_mem_span_pow x 1, rw [ideal.mem_span_singleton, pow_one] at this, rw [← this, norm_le_pow_iff_norm_lt_pow_add_one], simp only [zpow_zero, int.coe_nat_zero, int.coe_nat_succ, add_left_neg, zero_add], end @[simp] lemma pow_p_dvd_int_iff (n : ℕ) (a : ℤ) : (p ^ n : ℤ_[p]) ∣ a ↔ ↑p ^ n ∣ a := by rw [← norm_int_le_pow_iff_dvd, norm_le_pow_iff_mem_span_pow, ideal.mem_span_singleton] end norm_le_iff section dvr /-! ### Discrete valuation ring -/ instance : local_ring ℤ_[p] := local_of_nonunits_ideal zero_ne_one $ λ x y, by simp; exact norm_lt_one_add lemma p_nonnunit : (p : ℤ_[p]) ∈ nonunits ℤ_[p] := have (p : ℝ)⁻¹ < 1, from inv_lt_one $ by exact_mod_cast hp_prime.1.one_lt, by simp [this] lemma maximal_ideal_eq_span_p : maximal_ideal ℤ_[p] = ideal.span {p} := begin apply le_antisymm, { intros x hx, rw ideal.mem_span_singleton, simp only [local_ring.mem_maximal_ideal, mem_nonunits] at hx, rwa ← norm_lt_one_iff_dvd, }, { rw [ideal.span_le, set.singleton_subset_iff], exact p_nonnunit } end lemma prime_p : prime (p : ℤ_[p]) := begin rw [← ideal.span_singleton_prime, ← maximal_ideal_eq_span_p], { apply_instance }, { exact_mod_cast hp_prime.1.ne_zero } end lemma irreducible_p : irreducible (p : ℤ_[p]) := prime.irreducible prime_p instance : discrete_valuation_ring ℤ_[p] := discrete_valuation_ring.of_has_unit_mul_pow_irreducible_factorization ⟨p, irreducible_p, λ x hx, ⟨x.valuation.nat_abs, unit_coeff hx, by rw [mul_comm, ← unit_coeff_spec hx]⟩⟩ lemma ideal_eq_span_pow_p {s : ideal ℤ_[p]} (hs : s ≠ ⊥) : ∃ n : ℕ, s = ideal.span {p ^ n} := discrete_valuation_ring.ideal_eq_span_pow_irreducible hs irreducible_p open cau_seq instance : is_adic_complete (maximal_ideal ℤ_[p]) ℤ_[p] := { prec' := λ x hx, begin simp only [← ideal.one_eq_top, smul_eq_mul, mul_one, smodeq.sub_mem, maximal_ideal_eq_span_p, ideal.span_singleton_pow, ← norm_le_pow_iff_mem_span_pow] at hx ⊢, let x' : cau_seq ℤ_[p] norm := ⟨x, _⟩, swap, { intros ε hε, obtain ⟨m, hm⟩ := exists_pow_neg_lt p hε, refine ⟨m, λ n hn, lt_of_le_of_lt _ hm⟩, rw [← neg_sub, norm_neg], exact hx hn }, { refine ⟨x'.lim, λ n, _⟩, have : (0:ℝ) < p ^ (-n : ℤ), { apply zpow_pos_of_pos, exact_mod_cast hp_prime.1.pos }, obtain ⟨i, hi⟩ := equiv_def₃ (equiv_lim x') this, by_cases hin : i ≤ n, { exact (hi i le_rfl n hin).le, }, { push_neg at hin, specialize hi i le_rfl i le_rfl, specialize hx hin.le, have := nonarchimedean (x n - x i) (x i - x'.lim), rw [sub_add_sub_cancel] at this, refine this.trans (max_le_iff.mpr ⟨hx, hi.le⟩), } }, end } end dvr end padic_int
# coding: utf-8 # Distributed under the terms of the MIT License. from ababe.stru.element import Specie import numpy as np class Site(object): def __init__(self, position, ele): self._position = tuple(position) if isinstance(ele, Specie): self._element = ele elif isinstance(ele, int): self._element = Specie.from_num(ele) else: self._element = Specie(ele) def __eq__(self, other): return self.position == other.position and self.element == other.element @property def position(self): return self._position @position.setter def position(self, atuple): self._position = tuple(atuple) @property def element(self): return self._element @element.setter def element(self, ele): self._element = ele
variable (P Q R S : Prop) /- Lean has the logical connectives `and`, `or`, `not` built-in. Lean has special tactics to help us deal with them. New tactics: `cases'`, `split`, `left` and `right` # And (conjunction) `P and Q` is written `P ∧ Q`. This is True iff P and Q are both True. # cases Given `h : P ∧ Q` in the local context we can use `cases h with hp hq` to get the two parts so `hp : P` and `hq : Q` replace `h : P ∧ Q` -/ -- 01 example (h : P ∧ Q) : P:= by exact h.1 /- If our goal is `⊢ P ∧ Q` then we can use `split` to create two new goals one `⊢ P` and the other `⊢ Q` -/ -- 02 example (hp : P) (hq : Q) : P ∧ Q := by apply And.intro exact hp exact hq /- Dot notation: if we have `(hpq : P ∧ Q)` then `hpq.1 : P` and `hpq.2 : Q` (This `dot` notation is very common in Lean.) Conversely if we have `(hp : P)` and `(hq : Q)` then `⟨hp,hq⟩ : P ∧ Q` i.e. `⟨hp,hq⟩` is a term of type `P ∧ Q`. The angled brackets are typed `\<` and `\>` -/ -- 03 example (hpq : P ∧ Q) : Q ∧ P :=by apply And.intro exact hpq.2 exact hpq.1 -- or more simply `exact ⟨hpq.2,hpq.1⟩,` -- Having introduced `→` and `∧` we get `iff` (written `↔`) for free -- `P ↔ Q` is: `P → Q` and `Q → P` -- 04 example : P ∧ Q ↔ Q ∧ P := by apply Iff.intro · intro pq exact ⟨pq.2,pq.1⟩ · intro qp apply And.intro exact qp.2 exact qp.1 -- 05 example : P ∧ Q → Q :=by intro h exact h.2 -- in Lean `P ∧ Q ∧ R` means `P ∧ (Q ∧ R)` (∧ is right-associative) -- Find a single line `exact ...` solution to the following. -- (Hint: what are h.1 and h.2 in this example?) -- 06 example (h: P ∧ Q ∧ R ∧ S ) : R :=by exact h.2.2.1 -- 07 example : P → Q → P ∧ Q :=by intro p q exact ⟨p,q⟩ -- 08 example : P ∧ Q → Q ∧ R → P ∧ R :=by intro pq qr exact ⟨pq.1,qr.2⟩ -- 09 example : P ∧ R ∧ Q → Q ∧ P ∧ R :=by intro pqr exact ⟨pqr.2.2,pqr.1,pqr.2.1⟩ /- # Or (disjunction) The proposition `P or Q` is written `P ∨ Q`. `P ∨ Q` is True iff P is True or Q is True. If our goal is `⊢ P ∨ Q` then we can accomplish this by either giving a term of type `P` or a term of type `Q`. We indicate which by using `left` for `P` and `right` for Q. -/ -- 10 example (hp : P) : Q ∨ P :=by exact Or.inr hp /- Given `(hpq : P ∨ Q)` in the local context we can use `cases hpq with hp hq` to split our goal into two subgoals, one in which `hp : P` and the other in which `hq : Q` -/ -- 11 example (hpq : P ∨ Q) : Q ∨ P :=by cases hpq with | inl hp => exact Or.inr hp | inr hq => exact Or.inl hq -- 12 example : (P ∨ Q) ∧ (P → Q) → Q :=by intro ⟨hporq,hpq⟩ cases hporq with | inl hp => apply hpq hp | inr hq => exact hq -- 13 example : (P ∨ Q) ∧ (P ∨ R) → P ∨ (Q ∧ R):=by intro ⟨pq,pr⟩ cases pq with | inl p => exact Or.inl p | inr q => cases pr with | inl p => exact Or.inl p | inr r=> exact Or.inr ⟨q,r⟩ -- 14 example : (P ∨ Q) ∧ (R ∨ S) → (P ∧ R) ∨ (P ∧ S) ∨ (Q ∧ R) ∨ (Q ∧ S):=by intro ⟨pq,rs⟩ cases pq with | inl p => cases rs with | inl r => exact Or.inl ⟨p,r⟩ | inr s => apply Or.inr $ Or.inl ⟨p,s⟩ | inr q => cases rs with | inl r => exact Or.inr $ Or.inr $ Or.inl ⟨q,r⟩ | inr s => apply Or.inr $ Or.inr $ Or.inr ⟨q,s⟩ example (p q r : Prop) : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) := by apply Iff.intro · intro ⟨hp,hqr⟩ cases hqr with |inl hq => exact Or.inl ⟨hp,hq⟩ |inr hr => exact Or.inr ⟨hp,hr⟩ · intro hpqpr cases hpqpr with |inl hpq => exact ⟨hpq.1,Or.inl hpq.2⟩ |inr hpr => exact ⟨hpr.1,Or.inr hpr.2⟩ /- There are two special propositions : `False` and `True` To prove `True` we use `triv` You shouldn't be able to prove `False`. If you have `False` in the local context then you have a `contradiction` -/ #check True -- 15 example : True :=by trivial -- 16 example: P → True :=by intro _ trivial -- 17 example : False → P:=by intro f contradiction -- 18 example : False → True:=by intro _ trivial -- 19 example : True → False → True → False → True :=by intro _ _ _ _ trivial /- # Negation If `P : Prop` then `not P` is denoted `¬ P` this is defined to be `P → False` -/ -- 20 example : ¬P ↔ (P → False):=by apply Iff.intro · intro hnp hp contradiction · intro hpf hnp exact hpf hnp -- 21 example : ¬ True → False :=by intro nt apply nt trivial -- 22 example : ¬ False → True :=by intro _ trivial -- 23 example : P → ¬¬P :=by intro hp intro nnp contradiction -- 24 example (hp : P) (hnp : ¬ P) : Q ∧ R → ¬ Q :=by intro _ _ contradiction -- Can you explain how the following proof works? -- 25 example (hp : P) (hnp : ¬ P) : Q :=by cases (hnp hp) -- Hint: what is `(hnp hp)`?
module Microclimate using Unitful, NCDatasets, FieldMetadata, FieldDefaults using Unitful: W, m, °C, hr, mol, K, s, J, Mg, g, kg, L, kPa, Pa import FieldMetadata: default, units, limits, @units, @limits export AbstractMicroclimate, AbstractLayeredMicroclimate, AbstractMicroclimGrid, MicroclimGrid, AbstractMicroclimPoint, MicroclimPoint, AbstractMicroclimInstant, MicroclimInstant, AbstractMicroclimControl, MicroclimControl, LinearLayerInterpolator, LinearLayerInterpolators export radiation, snowdepth, airtemperature, relhumidity, windspeed, soiltemperature, soilwaterpotential, soilwatercontent export mean_soiltemperature, mean_soilwaterpotential, mean_soilwatercontent export weightedmean, layermax export load_grid, load_point export download_microclim include("interpolation.jl") include("types.jl") include("netcdf.jl") include("files.jl") end # module
module Text.WebIDL.Types.Argument import Data.Bitraversable import Data.Bifoldable import Data.Traversable import Text.WebIDL.Types.Attribute import Text.WebIDL.Types.Identifier import Text.WebIDL.Types.Numbers import Text.WebIDL.Types.StringLit import Text.WebIDL.Types.Type import Generics.Derive %language ElabReflection ||| ConstValue :: ||| BooleanLiteral ||| FloatLiteral ||| integer ||| ||| BooleanLiteral :: ||| true ||| false public export data ConstValue = B Bool | F FloatLit | I IntLit %runElab derive "ConstValue" [Generic,Meta,Eq,Show,HasAttributes] ||| Default :: ||| = DefaultValue ||| ε ||| ||| (part of Default)] DefaultValue :: ||| ConstValue ||| string ||| [ ] ||| { } ||| null public export data Default = None | EmptyList | EmptySet | Null | S StringLit | C ConstValue %runElab derive "Default" [Generic,Meta,Eq,Show,HasAttributes] ||| ArgumentName :: ||| ArgumentNameKeyword ||| identifier public export record ArgumentName where constructor MkArgName value : String %runElab derive "ArgumentName" [Generic,Meta,Eq,Show,HasAttributes] public export record ArgF (a : Type) (b : Type) where constructor MkArg attrs : a type : IdlTypeF a b name : ArgumentName %runElab derive "ArgF" [Generic,Meta,Eq,Show] public export Arg : Type Arg = ArgF ExtAttributeList Identifier public export record OptArgF (a : Type) (b : Type) where constructor MkOptArg attrs : a typeAttrs : a type : IdlTypeF a b name : ArgumentName def : Default %runElab derive "OptArgF" [Generic,Meta,Eq,Show] public export OptArg : Type OptArg = OptArgF ExtAttributeList Identifier ||| ArgumentList :: ||| Argument Arguments ||| ε ||| ||| Arguments :: ||| , Argument Arguments ||| ε ||| ||| Argument :: ||| ExtendedAttributeList ArgumentRest ||| ||| Ellipsis :: ||| ... ||| ε ||| ArgumentRest :: ||| optional TypeWithExtendedAttributes ArgumentName Default ||| Type Ellipsis ArgumentName public export data ArgumentListF : (a : Type) -> (b : Type) -> Type where VarArg : (args : List $ ArgF a b) -> (vararg : ArgF a b) -> ArgumentListF a b NoVarArg : (args : List $ ArgF a b) -> (optArgs : List $ OptArgF a b) -> ArgumentListF a b %runElab derive "ArgumentListF" [Generic,Meta,Eq,Show] public export ArgumentList : Type ArgumentList = ArgumentListF ExtAttributeList Identifier -------------------------------------------------------------------------------- -- Implementations -------------------------------------------------------------------------------- mutual export Bifunctor ArgF where bimap = assert_total bimapDefault export Bifoldable ArgF where bifoldr = bifoldrDefault export Bitraversable ArgF where bitraverse f g (MkArg a t n) = [| MkArg (f a) (bitraverse f g t) (pure n) |] export Functor (ArgF a) where map = bimap id export Foldable (ArgF a) where foldr = bifoldr (const id) export Traversable (ArgF a) where traverse = bitraverse pure mutual export Bifunctor OptArgF where bimap = assert_total bimapDefault export Bifoldable OptArgF where bifoldr = bifoldrDefault export Bitraversable OptArgF where bitraverse f g (MkOptArg a1 a2 t n d) = [| MkOptArg (f a1) (f a2) (bitraverse f g t) (pure n) (pure d) |] export Functor (OptArgF a) where map = bimap id export Foldable (OptArgF a) where foldr = bifoldr (const id) export Traversable (OptArgF a) where traverse = bitraverse pure mutual export Bifunctor ArgumentListF where bimap = assert_total bimapDefault export Bifoldable ArgumentListF where bifoldr = bifoldrDefault export Bitraversable ArgumentListF where bitraverse f g (VarArg as a) = [| VarArg (traverse (bitraverse f g) as) (bitraverse f g a) |] bitraverse f g (NoVarArg as os) = [| NoVarArg (traverse (bitraverse f g) as) (traverse (bitraverse f g) os) |] export Functor (ArgumentListF a) where map = bimap id export Foldable (ArgumentListF a) where foldr = bifoldr (const id) export Traversable (ArgumentListF a) where traverse = bitraverse pure export HasAttributes a => HasAttributes (ArgumentListF a b) where attributes = bifoldMap attributes (const Nil)
{-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE BangPatterns #-} module Polestar.Type where import Data.Complex import Data.Monoid import Data.Ord -- variable name (for debugging) newtype Id = Id String deriving (Show) -- ordering: s <: t implies s < t data PrimType -- numeric types = PTyZero | PTyNat | PTyInt | PTyNNReal -- non-negative real number | PTyReal | PTyImaginary | PTyComplex -- boolean | PTyTrue | PTyFalse | PTyBool -- other | PTyUnit deriving (Eq,Ord,Show,Enum,Bounded) data Type = TyPrim !PrimType | TyArr Type Type | TyAll Id !(Maybe Type) Type | TyRef !Int | TyTuple [Type] -- must have 2 or more elements | TyInter [Type] -- must have 2 or more elements deriving (Eq,Show) pattern TyZero = TyPrim PTyZero pattern TyNat = TyPrim PTyNat pattern TyInt = TyPrim PTyInt pattern TyNNReal = TyPrim PTyNNReal pattern TyReal = TyPrim PTyReal pattern TyImaginary = TyPrim PTyImaginary pattern TyComplex = TyPrim PTyComplex pattern TyTrue = TyPrim PTyTrue pattern TyFalse = TyPrim PTyFalse pattern TyBool = TyPrim PTyBool pattern TyUnit = TyPrim PTyUnit pattern TyPair a b = TyTuple [a,b] -- compound canonical type -- no pair of the components have subtyping relation type CanonicalType = [ICanonicalType] -- individual canonical type data ICanonicalType = CTyPrim !PrimType | CTyArr CanonicalType ICanonicalType | CTyAll Id CanonicalType ICanonicalType | CTyRef !Int | CTyTuple [ICanonicalType] deriving (Eq,Show) pattern CTyTrue = CTyPrim PTyTrue pattern CTyFalse = CTyPrim PTyFalse pattern CTyBool = CTyPrim PTyBool data Builtin -- unary = BNegate | BLogicalNot | BNatToInt | BNatToNNReal | BIntToNat -- max(n,0) | BIntToReal | BNNRealToReal | BRealToComplex | BMkImaginary | BImaginaryToComplex | BRealPart | BImagPart | BAbs | BSqrt | BExp | BExpm1 | BLog | BLog1p | BSin | BCos | BTan | BSinh | BCosh | BTanh | BAsin | BAcos | BAtan | BAsinh | BAcosh | BAtanh -- TODO: factorial -- TODO: exp, log, expm1, log1p -- TODO: trigonometric functions and hyperbolic functions -- binary | BAdd | BSub | BMul | BDiv | BPow | BTSubNat -- truncated subtraction | BLt | BLe | BEqual | BMax | BMin | BIntDiv | BIntMod | BGcd | BLcm | BLogicalAnd | BLogicalOr -- TODO: binomial coefficients -- other primitives | BIterate -- | BUnsafeGlue deriving (Eq,Show,Enum,Bounded) data PrimValue = PVZero | PVInt !Integer | PVReal !Double | PVImaginary !Double | PVComplex !(Complex Double) | PVBool !Bool | PVUnit | PVBuiltin !Builtin deriving (Eq,Show) data Term = TmPrim !PrimValue -- primitive value | TmAbs Id Type Term -- lambda abstraction | TmTyAbs Id !(Maybe Type) Term -- bounded type abstraction | TmRef !Int -- variable (de Bruijn index) | TmApp Term Term -- function application | TmTyApp Term Type -- type application | TmLet Id Term Term -- let-in | TmAlt Id [Type] Term -- type alternation | TmIf Term Term Term -- if-then-else | TmTuple [Term] -- tuple | TmProj Term !Int -- projection | TmCoerce Term Type -- coercion | TmCoherentTuple [Term] -- coherent tuple deriving (Eq,Show) data Binding = VarBind Id CanonicalType | TyVarBind Id CanonicalType | AnonymousBind deriving (Eq,Show) isUnary :: Builtin -> Bool isUnary f = case f of BNegate -> True BLogicalNot -> True BNatToInt -> True BNatToNNReal -> True BIntToNat -> True BIntToReal -> True BNNRealToReal -> True BRealToComplex -> True BMkImaginary -> True BImaginaryToComplex -> True BRealPart -> True BImagPart -> True BAbs -> True BSqrt -> True BExp -> True BExpm1 -> True BLog -> True BLog1p -> True BSin -> True BCos -> True BTan -> True BSinh -> True BCosh -> True BTanh -> True BAsin -> True BAcos -> True BAtan -> True BAsinh -> True BAcosh -> True BAtanh -> True _ -> False isBinary :: Builtin -> Bool isBinary f = case f of BAdd -> True BSub -> True BMul -> True BDiv -> True BPow -> True BTSubNat -> True BLt -> True BLe -> True BEqual -> True BMax -> True BMin -> True BIntDiv -> True BIntMod -> True BGcd -> True BLcm -> True BLogicalAnd -> True BLogicalOr -> True _ -> False isValue :: Term -> Bool isValue t = case t of TmPrim _ -> True TmAbs _ _ _ -> True TmTyAbs _ _ _ -> True TmApp (TmPrim (PVBuiltin f)) x | isBinary f -> isValue x -- partial application TmTyApp (TmPrim (PVBuiltin BIterate)) ty -> True TmApp (TmTyApp (TmPrim (PVBuiltin BIterate)) ty) x -> isValue x TmApp (TmApp (TmTyApp (TmPrim (PVBuiltin BIterate)) ty) x) y -> isValue x && isValue y TmTuple xs -> all isValue xs TmCoherentTuple xs -> all isValue xs _ -> False getCTypeFromContext :: [Binding] -> Int -> CanonicalType getCTypeFromContext ctx i | 0 <= i && i < length ctx = case ctx !! i of VarBind _ ty -> ty b -> error ("TmRef: expected a variable binding, found " ++ show b) | otherwise = error "TmRef: index out of bounds" getTypeFromContext :: [Binding] -> Int -> Type getTypeFromContext ctx i = canonicalToOrdinary $ getCTypeFromContext ctx i getCBoundFromContext :: [Binding] -> Int -> CanonicalType getCBoundFromContext ctx i | i < length ctx = case ctx !! i of TyVarBind _ b -> b b -> error ("TyRef: expected a type variable binding, found " ++ show b) | otherwise = error "TyRef: index out of bounds" getBoundFromContext :: [Binding] -> Int -> Maybe Type getBoundFromContext ctx i = canonicalToOrdinaryM $ getCBoundFromContext ctx i typeShift :: Int -> Int -> Type -> Type -- typeShift 0 _ ty = ty typeShift !delta = go where go !i ty = case ty of TyPrim _ -> ty TyArr u v -> TyArr (go i u) (go (i + 1) v) TyAll name b t -> TyAll name (typeShift delta i <$> b) (typeShift delta (i + 1) t) TyRef j | j >= i, j + delta >= 0 -> TyRef (j + delta) | j >= i, j + delta < 0 -> error "typeShift: negative index" | otherwise -> ty TyTuple tys -> TyTuple $ map (go i) tys TyInter tys -> TyInter $ map (go i) tys typeShiftC :: Int -> Int -> CanonicalType -> CanonicalType -- typeShiftC 0 _ = id typeShiftC !delta !i = map (typeShiftI delta i) typeShiftI :: Int -> Int -> ICanonicalType -> ICanonicalType typeShiftI !delta = go where go :: Int -> ICanonicalType -> ICanonicalType go !i ty = case ty of CTyPrim _ -> ty CTyArr u v -> CTyArr (map (go i) u) (go (i + 1) v) CTyAll name b t -> CTyAll name (map (go i) b) (go (i + 1) t) CTyRef j | j >= i, j + delta >= 0 -> CTyRef (j + delta) | j >= i, j + delta < 0 -> error "typeShift: negative index" | otherwise -> ty CTyTuple tys -> CTyTuple $ map (go i) tys typeSubstD :: Int -> Type -> Int -> Type -> Type typeSubstD !depth s !i ty = case ty of TyPrim _ -> ty TyArr u v -> TyArr (typeSubstD depth s i u) (typeSubstD (depth + 1) s (i + 1) v) TyAll name b t -> TyAll name (typeSubstD depth s i <$> b) (typeSubstD (depth + 1) s (i + 1) t) TyRef j | j == i -> typeShift depth 0 s | j > i -> TyRef (j - 1) | otherwise -> ty TyTuple tys -> TyTuple $ map (typeSubstD depth s i) tys TyInter tys -> TyInter $ map (typeSubstD depth s i) tys typeSubst = typeSubstD 0 typeSubstCD :: Int -> CanonicalType -> Int -> ICanonicalType -> CanonicalType typeSubstCD !depth s !i ty = case ty of CTyPrim _ -> return ty CTyArr u v -> CTyArr (u >>= typeSubstCD depth s i) <$> typeSubstCD (depth + 1) s (i + 1) v CTyAll name b t -> CTyAll name (b >>= typeSubstCD depth s i) <$> typeSubstCD (depth + 1) s (i + 1) t CTyRef j | j == i -> typeShiftC depth 0 s | j > i -> return $ CTyRef (j - 1) | otherwise -> return ty CTyTuple tys -> CTyTuple <$> mapM (typeSubstCD depth s i) tys typeSubstC = typeSubstCD 0 canonicalToOrdinary :: CanonicalType -> Type canonicalToOrdinary [] = error "canonicalToOrdinary: Top type" canonicalToOrdinary [t] = iCanonicalToOrdinary t canonicalToOrdinary tys = TyInter $ map iCanonicalToOrdinary tys canonicalToOrdinaryM :: CanonicalType -> Maybe Type canonicalToOrdinaryM [] = Nothing canonicalToOrdinaryM [t] = Just $ iCanonicalToOrdinary t canonicalToOrdinaryM tys = Just $ TyInter $ map iCanonicalToOrdinary tys iCanonicalToOrdinary :: ICanonicalType -> Type iCanonicalToOrdinary (CTyPrim p) = TyPrim p iCanonicalToOrdinary (CTyArr u v) = TyArr (canonicalToOrdinary u) (iCanonicalToOrdinary v) iCanonicalToOrdinary (CTyAll name b t) = TyAll name (canonicalToOrdinaryM b) (iCanonicalToOrdinary t) iCanonicalToOrdinary (CTyRef i) = TyRef i iCanonicalToOrdinary (CTyTuple tys) = TyTuple $ map iCanonicalToOrdinary tys instance Eq Id where _ == _ = True {- instance Ord ICanonicalType where compare (CTyPrim p) (CTyPrim p') = compare p p' compare (CTyArr s t) (CTyArr s' t') = compare (Down s) (Down s') <> compare t t' compare (CTyAll _ s t) (CTyAll _ s' t') = compare (Down s) (Down s') <> compare t t' compare (CTyRef i) (CTyRef i') = compare i i' compare (CTyTuple tys) (CTyTuple tys') = compare tys tys' compare (CTyPrim _) _ = LT compare _ (CTyPrim _) = GT compare (CTyArr _ _) _ = LT compare _ (CTyArr _ _) = GT compare (CTyAll _ _ _) _ = LT compare _ (CTyAll _ _ _) = GT compare (CTyRef _) _ = LT compare _ (CTyRef _) = GT -- compare (CTyTuple _) _ = LT -- compare _ (CTyTuple _) = GT -}
module Wflow using Dates using TOML using LightGraphs using NCDatasets using StaticArrays using Statistics using UnPack using CSV using Random using DataFrames mutable struct Clock time::DateTime iteration::Int Δt::Second end include("io.jl") """ Model{N,L,V,R,W} Composite type that represents all different aspects of a Wflow Model, such as the network, parameters, clock, configuration and input and output. """ struct Model{N,L,V,R,W} config::Config # all configuration options network::N # connectivity information, directed graph lateral::L # lateral model that holds lateral state, moves along network vertical::V # vertical model that holds vertical state, independent of each other clock::Clock # to keep track of simulation time reader::R # provides the model with dynamic input writer::W # writes model output end # prevent a large printout of model components and arrays Base.show(io::IO, m::Model) = print(io, "model of type ", typeof(m)) include("horizontal_process.jl") include("hbv.jl") include("sbm.jl") include("reservoir_lake.jl") include("hbv_model.jl") include("sbm_model.jl") include("flow.jl") include("vertical_process.jl") include("groundwater/connectivity.jl") include("groundwater/aquifer.jl") include("groundwater/boundary_conditions.jl") include("sbm_gwf_model.jl") include("utils.jl") """ run_simulation(tomlpath::String) run_simulation(config::Config) run_simulation(model::Model) Run an entire simulation starting either from a path to a TOML settings file, a prepared `Config` object, or an initialized `Model` object. This allows more flexibility if you want to for example modify a `Config` before initializing the `Model`. """ function run_simulation(tomlpath) config = Config(tomlpath) run_simulation(config) end function run_simulation(config::Config) modeltype = config.model.type model = if modeltype == "sbm" initialize_sbm_model(config) elseif modeltype == "sbm_gwf" initialize_sbm_gwf_model(config) elseif modeltype == "hbv" initialize_hbv_model(config) else error("unknown model type") end run_simulation(model) end function run_simulation(model::Model; close_files = true) @unpack network, config, writer, clock = model # in the case of sbm_gwf it's currently a bit hard to use dispatch update_func = config.model.type == "sbm_gwf" ? update_sbm_gwf : update while true model = update_func(model) is_finished(clock, config) && break end # write output state NetCDF # undo the clock advance at the end of the last iteration, since there won't # be a next step, and then the output state falls on the correct time rewind!(clock) write_netcdf_timestep(model, writer.state_dataset, writer.state_parameters) reset_clock!(model.clock, config) # option to support running function twice without re-initializing # and thus opening the NetCDF files if close_files Wflow.close_files(model, delete_output = false) end return model end end # module
-- @@stderr -- dtrace: failed to compile script test/unittest/types/err.D_OP_SCALAR.badlogop.d: [D_OP_SCALAR] line 20: operator && requires operands of scalar type
State Before: α : Type u_1 M : Type ?u.2198 N : Type u_2 P : Type ?u.2204 inst✝² : DecidableEq α inst✝¹ : DecidableEq N inst✝ : Zero N f g : α →₀ N ⊢ ↑(neLocus f g) = {x | ↑f x ≠ ↑g x} State After: case h α : Type u_1 M : Type ?u.2198 N : Type u_2 P : Type ?u.2204 inst✝² : DecidableEq α inst✝¹ : DecidableEq N inst✝ : Zero N f g : α →₀ N x✝ : α ⊢ x✝ ∈ ↑(neLocus f g) ↔ x✝ ∈ {x | ↑f x ≠ ↑g x} Tactic: ext State Before: case h α : Type u_1 M : Type ?u.2198 N : Type u_2 P : Type ?u.2204 inst✝² : DecidableEq α inst✝¹ : DecidableEq N inst✝ : Zero N f g : α →₀ N x✝ : α ⊢ x✝ ∈ ↑(neLocus f g) ↔ x✝ ∈ {x | ↑f x ≠ ↑g x} State After: no goals Tactic: exact mem_neLocus
\section{Implementation} \label{sec:implementation} The model described in \cref{sec:model} can be implemented as a \ac{WFST}. In particular, the model can be decomposed in two transducers, one for each term. The final model is given by the composition of the two transducer. \subsection{First term: $\prod_{i=1}^n P(w_i | t_i)$} The first transducer $\lambda_{word2concept}$ assigns the tag with the highest probability to each word. The transducer has a single state $0$ with many self transitions. For each unique pair $(w_i, t_j)$, a self transition $w_i \rightarrow t_j$ is added to the transducer. The cost associated to the transitions is computed as the negative logarithm of the probability of the pair $P(w_i, t_j)$: \begin{equation*} cost(w_i \rightarrow t_j) = -ln(P(w_i, t_j)). \end{equation*} In addition, we must take care of \ac{OOV} words, i.e. words that are never observed in the training data and thus not present in lexicon. Since we can not make any assumption about the concepts probability for unknown words, we choose a uniform distribution. Thus, we add one extra self transition $\langle unk \rangle \rightarrow t_j$ for each concept $t_j$ with cost: \begin{equation*} cost(\langle unk \rangle \rightarrow t_j) = -ln \Big( \frac{1}{n_{concepts}} \Big). \end{equation*} $\langle unk \rangle$ is a special token used for the \ac{OOV} words. The model is implemented with a Bash script that computes all counts, costs and transition for the transducer. The lexicons are computed using \texttt{OpenGrm NGram}. The transducer is compiled to the \texttt{FST} format using \texttt{OpenFst}. \subsection{Second term: $\prod_{i=1}^n P(t_i | t_{i-1})$} The second transducer $\lambda_{concept\_lm}$ is a language model for the concepts. It takes as input a sequence of concepts and computes its probability given the predecessors and the observed training data. A general problem with language models is data sparseness: since the language has an underlying structure and the training data is limited, not all tuples $(t_i, ..., t_m)$ are observed. As a consequence, most probabilities have value $0$, which makes the probability of most words sequences $0$ as well. To solve this problem, we introduce smoothing: the unseen tuples are assigned a small probability even though the real observed probability is $0$. The probability of frequent tuples is slightly reduced to make the joint probability sum up to $1$. Many different smoothing methods have been proposed in the literature. A simple technique is the Laplace smoothing: we add imaginary training data with all possible n-gram combinations, each of them with frequency $1$. For instance, for the bigram case, we can compute the smoothed probability as: \begin{equation*} P(t_i | t_{i-1}) = \frac{C(t_{i-1}, t_i) + 1}{C(t_{i-1}) + V}, \end{equation*} where $V$ is the size of the vocabulary of pairs $(t_i | t_{i-1})$. \cref{sec:performances} compares the performances of different smoothing methods on our model. Opposite to the first term, we do not need to take care of \ac{OOV} words, since the first transducer can produce only concepts in the concepts' lexicon. \subsection{Concept tagging} To compute the most probable sequence of tags, each sentence is first compiled to a \ac{FSA} $\lambda_{sentence}$. For each word $w_i$, we define a state $i$ and a transition from state $i-1$ to state $i$ that translate word $w_i$ in itself. The initial state is $0$, the final state is $n$, where $n$ is equal to the length of the sentence. \cref{fig:fsa_sentence} shows an example. \begin{figure}[h] \centering \includegraphics[width=0.95\columnwidth]{figures/fsa} \caption{\ac{FSA} for the sentence ``star of thor''.} \label{fig:fsa_sentence} \end{figure} The most probable sequence of tags can be computed as the shortest path in the \ac{FST} given by the composition: \begin{equation*} \lambda_{sentence} \circ \lambda_{word2concept} \circ \lambda_{concept\_lm}. \end{equation*} The shortest path is computed by the \texttt{OpenFst} library using the Viterbi algorithm. This model is implemented in the file \texttt{model/v1.sh}.
-- Andreas, 2013-02-26 module Issue799a where data D (A : Set1) : Set where d : D A x : D Set x = d {A = _} -- correct parameter name y : D Set y = d {B = _} -- wrong parameter name, should give error
If $f$ is analytic at $z$, then the $n$th derivative of $-f$ at $z$ is $-f^{(n)}(z)$.
using gcSolver using Plots using OrdinaryDiffEq using DiffEqDevTools rxntfR = ones(gcSolver.Nparams) * 0.2 prob = gcSolver.runCkineSetup([500.0], rxntfR) setups = [ Dict(:alg => AutoTsit5(Rodas5())), Dict(:alg => AutoTsit5(Kvaerno5())), Dict(:alg => AutoVern9(Rodas5())), Dict(:alg => AutoVern9(KenCarp5())), Dict(:alg => AutoVern9(Kvaerno5())), ] test_sol = solve(prob, AutoTsit5(Rodas5()), reltol = 1.0e-16, abstol = 1.0e-16) tols = 1.0 ./ 10.0 .^ LinRange(4, 12, 30) wp = WorkPrecisionSet(prob, tols, tols, setups; save_everystep = false, appxsol = test_sol, maxiters = Int(1e6)) plot(wp)
{-# OPTIONS --without-K #-} open import HoTT.Base open import HoTT.Equivalence open import HoTT.Identity module HoTT.Identity.Pi where open variables private variable f g h : Π A P module _ {f g : Π A P} where -- Axiom 2.9.3 - function extensionality postulate happly-isequiv : isequiv (happly {f = f} {g}) module _ where open qinv (isequiv→qinv happly-isequiv) renaming (g to happly⁻¹) abstract funext : f ~ g → f == g funext = happly⁻¹ =Π-η : funext ∘ happly ~ id =Π-η = η =Π-β : happly ∘ funext ~ id =Π-β = ε =Π-equiv : f == g ≃ f ~ g =Π-equiv = happly , happly-isequiv funext-∙ₕ : (α : f ~ g) (β : g ~ h) → funext (α ∙ₕ β) == funext α ∙ funext β funext-∙ₕ α β = ap funext (funext λ x → (happly (=Π-β α) x ⋆ happly (=Π-β β) x) ⁻¹) ∙ p where p : funext (happly (funext α) ∙ₕ happly (funext β)) == funext α ∙ funext β p rewrite funext α rewrite funext β = =Π-η refl funext-ap : {P : A → 𝒰 i} {Q : A → 𝒰 j} {g h : Π A P} (f : {a : A} → P a → Q a) (α : g ~ h) → funext (ap f ∘ α) == ap (f ∘_) (funext α) funext-ap f α = ap (λ α → funext (ap f ∘ α)) (=Π-β α) ⁻¹ ∙ p where p : funext (ap f ∘ happly (funext α)) == ap (f ∘_) (funext α) p rewrite funext α = =Π-η refl
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import category_theory.endomorphism import category_theory.category.Cat import algebra.category.Mon.basic import combinatorics.quiver.single_obj /-! # Single-object category > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Single object category with a given monoid of endomorphisms. It is defined to facilitate transfering some definitions and lemmas (e.g., conjugacy etc.) from category theory to monoids and groups. ## Main definitions Given a type `α` with a monoid structure, `single_obj α` is `unit` type with `category` structure such that `End (single_obj α).star` is the monoid `α`. This can be extended to a functor `Mon ⥤ Cat`. If `α` is a group, then `single_obj α` is a groupoid. An element `x : α` can be reinterpreted as an element of `End (single_obj.star α)` using `single_obj.to_End`. ## Implementation notes - `category_struct.comp` on `End (single_obj.star α)` is `flip (*)`, not `(*)`. This way multiplication on `End` agrees with the multiplication on `α`. - By default, Lean puts instances into `category_theory` namespace instead of `category_theory.single_obj`, so we give all names explicitly. -/ universes u v w namespace category_theory /-- Abbreviation that allows writing `category_theory.single_obj` rather than `quiver.single_obj`. -/ abbreviation single_obj := quiver.single_obj namespace single_obj variables (α : Type u) /-- One and `flip (*)` become `id` and `comp` for morphisms of the single object category. -/ instance category_struct [has_one α] [has_mul α] : category_struct (single_obj α) := { hom := λ _ _, α, comp := λ _ _ _ x y, y * x, id := λ _, 1 } /-- Monoid laws become category laws for the single object category. -/ instance category [monoid α] : category (single_obj α) := { comp_id' := λ _ _, one_mul, id_comp' := λ _ _, mul_one, assoc' := λ _ _ _ _ x y z, (mul_assoc z y x).symm } lemma id_as_one [monoid α] (x : single_obj α) : 𝟙 x = 1 := rfl lemma comp_as_mul [monoid α] {x y z : single_obj α} (f : x ⟶ y) (g : y ⟶ z) : f ≫ g = g * f := rfl /-- Groupoid structure on `single_obj α`. See <https://stacks.math.columbia.edu/tag/0019>. -/ instance groupoid [group α] : groupoid (single_obj α) := { inv := λ _ _ x, x⁻¹, inv_comp' := λ _ _, mul_right_inv, comp_inv' := λ _ _, mul_left_inv } /-- Abbreviation that allows writing `category_theory.single_obj.star` rather than `quiver.single_obj.star`. -/ abbreviation star : single_obj α := quiver.single_obj.star α /-- The endomorphisms monoid of the only object in `single_obj α` is equivalent to the original monoid α. -/ def to_End [monoid α] : α ≃* End (single_obj.star α) := { map_mul' := λ x y, rfl, .. equiv.refl α } lemma to_End_def [monoid α] (x : α) : to_End α x = x := rfl /-- There is a 1-1 correspondence between monoid homomorphisms `α → β` and functors between the corresponding single-object categories. It means that `single_obj` is a fully faithful functor. See <https://stacks.math.columbia.edu/tag/001F> -- although we do not characterize when the functor is full or faithful. -/ def map_hom (α : Type u) (β : Type v) [monoid α] [monoid β] : (α →* β) ≃ (single_obj α) ⥤ (single_obj β) := { to_fun := λ f, { obj := id, map := λ _ _, ⇑f, map_id' := λ _, f.map_one, map_comp' := λ _ _ _ x y, f.map_mul y x }, inv_fun := λ f, { to_fun := @functor.map _ _ _ _ f (single_obj.star α) (single_obj.star α), map_one' := f.map_id _, map_mul' := λ x y, f.map_comp y x }, left_inv := λ ⟨f, h₁, h₂⟩, rfl, right_inv := λ f, by cases f; obviously } lemma map_hom_id (α : Type u) [monoid α] : map_hom α α (monoid_hom.id α) = 𝟭 _ := rfl lemma map_hom_comp {α : Type u} {β : Type v} [monoid α] [monoid β] (f : α →* β) {γ : Type w} [monoid γ] (g : β →* γ) : map_hom α γ (g.comp f) = map_hom α β f ⋙ map_hom β γ g := rfl /-- Given a function `f : C → G` from a category to a group, we get a functor `C ⥤ G` sending any morphism `x ⟶ y` to `f y * (f x)⁻¹`. -/ @[simps] def difference_functor {C G} [category C] [group G] (f : C → G) : C ⥤ single_obj G := { obj := λ _, (), map := λ x y _, f y * (f x)⁻¹, map_id' := by { intro, rw [single_obj.id_as_one, mul_right_inv] }, map_comp' := by { intros, rw [single_obj.comp_as_mul, ←mul_assoc, mul_left_inj, mul_assoc, inv_mul_self, mul_one] } } end single_obj end category_theory open category_theory namespace monoid_hom /-- Reinterpret a monoid homomorphism `f : α → β` as a functor `(single_obj α) ⥤ (single_obj β)`. See also `category_theory.single_obj.map_hom` for an equivalence between these types. -/ @[reducible] def to_functor {α : Type u} {β : Type v} [monoid α] [monoid β] (f : α →* β) : (single_obj α) ⥤ (single_obj β) := single_obj.map_hom α β f @[simp] lemma id_to_functor (α : Type u) [monoid α] : (id α).to_functor = 𝟭 _ := rfl @[simp] lemma comp_to_functor {α : Type u} {β : Type v} [monoid α] [monoid β] (f : α →* β) {γ : Type w} [monoid γ] (g : β →* γ) : (g.comp f).to_functor = f.to_functor ⋙ g.to_functor := rfl end monoid_hom namespace units variables (α : Type u) [monoid α] /-- The units in a monoid are (multiplicatively) equivalent to the automorphisms of `star` when we think of the monoid as a single-object category. -/ def to_Aut : αˣ ≃* Aut (single_obj.star α) := (units.map_equiv (single_obj.to_End α)).trans $ Aut.units_End_equiv_Aut _ @[simp] lemma to_Aut_hom (x : αˣ) : (to_Aut α x).hom = single_obj.to_End α x := rfl @[simp] lemma to_Aut_inv (x : αˣ) : (to_Aut α x).inv = single_obj.to_End α (x⁻¹ : αˣ) := rfl end units namespace Mon open category_theory /-- The fully faithful functor from `Mon` to `Cat`. -/ def to_Cat : Mon ⥤ Cat := { obj := λ x, Cat.of (single_obj x), map := λ x y f, single_obj.map_hom x y f } instance to_Cat_full : full to_Cat := { preimage := λ x y, (single_obj.map_hom x y).inv_fun, witness' := λ x y, by apply equiv.right_inv } instance to_Cat_faithful : faithful to_Cat := { map_injective' := λ x y, by apply equiv.injective } end Mon
In 1925, a couple from the small Dutch community of Pella, Iowa, invested in a newfangled invention — a window screen that rolled up and down like a shade. Today, that invention is the basis for one of the most trusted names in windows — Pella. A family owned business selling European lace evolves into Heritage Lace, an integrated manufacturer/marketer of quality home textiles. These are just some of the many success stories you’ll hear about as you explore the possibilities in Marion County, Iowa.
#' Create a javascript context #' @export create_context <- function() { # create js environment js <- V8::v8() # source js files inkjs <- system.file("js", "ink.js", package = "inkr") js$source(inkjs) # return context js } #' Remove a javascript context #' @inheritParams load_story #' @export remove_context <- function(js) { rm(js) }
The 31st British Filk Convention, 1st to 3rd February, 2019. Best Western Hotel, Marks Tey, Colchester. These pages have been prepared by Rick Hewett and the ConCom. Artwork by Miki Dennis. They are hosted by FilkNet and mirrored on Zen Homepages. If you have any comments about them you'd like to share then please email them to thirtyone-et at contabile.org.uk . This page was last updated on Fri 12th Oct. 2018.
For any real vector $e$, we have $a e + c \leq b e + d$ if and only if $(a - b) e + c \leq d$.
lemma componentsI: "x \<in> U \<Longrightarrow> connected_component_set U x \<in> components U"
(** ** Constructions related to ltowers opver an object by Vladimir Voevodsky, started on Feb. 3, 2015. *) Unset Automatic Introduction. Require Export lBsystems.ltowers. (** ltowers of objects over an object *) Definition ltower_over_carrier { T : ltower } ( A : T ) := total2 ( fun X : T => isover X A ) . Definition obj_over_constr { T : ltower } { A : T } { X : T } ( isov : isover X A ) : ltower_over_carrier A := tpair ( fun X : T => isover X A ) _ isov . Definition isov_isov { T : ltower } { A : T } ( X : ltower_over_carrier A ) : isover ( pr1 X ) A := pr2 X . Definition ltower_over_ll { T : ltower } { A : T } ( X : ltower_over_carrier A ) : nat := ll ( pr1 X ) - ll A . Definition ltower_over_ft { T : ltower } { A : T } ( X : ltower_over_carrier A ) : ltower_over_carrier A . Proof . intros . destruct ( isover_choice ( isov_isov X ) ) as [ isov | eq ] . exact ( tpair _ ( ft ( pr1 X ) ) isov ) . exact ( tpair ( fun X : T => isover X A ) A ( isover_XX A ) ) . Defined. Lemma ltower_over_ll_ft_eq { T : ltower } { A : T } ( X : ltower_over_carrier A ) : ltower_over_ll ( ltower_over_ft X ) = ltower_over_ll X - 1 . Proof . intros . unfold ltower_over_ft . destruct ( isover_choice ( isov_isov X ) ) as [ isov | eq ] . unfold ltower_over_ll . simpl . rewrite ll_ft . rewrite natminusassoc . rewrite natpluscomm . rewrite <- natminusassoc . apply idpath . unfold ltower_over_ll . simpl . rewrite natminusnn . rewrite <- eq . rewrite natminusnn . apply idpath . Defined. Lemma ispointed_ltower_over_int { T : ltower } ( A : T ) : iscontr ( total2 ( fun X : ltower_over_carrier A => ltower_over_ll X = 0 ) ) . Proof. intros . assert ( weq1 : weq ( total2 ( fun X : ltower_over_carrier A => ltower_over_ll X = 0 ) ) ( total2 ( fun X : T => dirprod ( isover X A ) ( ll X - ll A = 0 ) ) ) ) . apply weqtotal2asstor . assert ( weq2 : weq ( total2 ( fun X : T => dirprod ( isover X A ) ( ll X - ll A = 0 ) ) ) ( total2 ( fun X : T => A = X ) ) ) . refine ( weqfibtototal _ _ _ ) . intro X . assert ( weq3 : weq (dirprod (isover X A) (ll X - ll A = 0)) (dirprod (ll X - ll A = 0) (isover X A)) ) . apply weqdirprodcomm . assert ( weq4 : weq (dirprod (ll X - ll A = 0) (isover X A)) (dirprod (ll X - ll A = 0) ( A = X ) ) ) . refine ( weqfibtototal _ _ _ ) . intro eq . unfold isover . rewrite eq . apply idweq. assert ( weq5 : weq (dirprod (ll X - ll A = 0) (A = X)) (dirprod (A = X)(ll X - ll A = 0))). apply weqdirprodcomm . assert ( weq6 : weq (dirprod (A = X) (ll X - ll A = 0)) ( A = X ) ) . apply weqpr1 . intro eq . rewrite eq . rewrite natminusnn . apply iscontraprop1 . apply isasetnat . apply idpath . apply ( weqcomp weq3 ( weqcomp weq4 ( weqcomp weq5 weq6 ) ) ) . assert ( weq := weqcomp weq1 weq2 ) . apply ( iscontrweqb weq ) . apply iscontrpathsfrom . Defined. Lemma ltower_over_ll0_eq { T : ltower } { A : T } ( X : ltower_over_carrier A ) ( eq0 : ltower_over_ll X = 0 ) : ltower_over_ft X = X . Proof . intros . assert ( eq0' : ltower_over_ll ( ltower_over_ft X ) = 0 ) . rewrite ltower_over_ll_ft_eq . rewrite eq0 . apply idpath . assert ( int : tpair ( fun X' => ltower_over_ll X' = 0 ) _ eq0' = tpair ( fun X' => ltower_over_ll X' = 0 ) X eq0 ) . apply ( proofirrelevancecontr ( ispointed_ltower_over_int _ ) _ _ ) . apply ( maponpaths ( @pr1 _ ( fun X' => ltower_over_ll X' = 0 ) ) int ) . Defined. Definition ltower_over { T : ltower } ( A : T ) : ltower := ltower_constr ( @ltower_over_ll _ A ) ( @ltower_over_ft _ A ) ( @ltower_over_ll_ft_eq _ A ) ( @ltower_over_ll0_eq _ A ) . (** The name of the following function comes from the word octothrope that is the official name for the "pound sign". This symbol, as a subscript, is used sometimes to denote the left adjoint to the pull-back functor that takes a presheaf represneted by p : X -> B over B to the presheaf represented by X. *) Definition pocto { T : ltower } { A : T } ( X : ltower_over A ) : T := pr1 X . Definition ll_pocto { T : ltower } { A : T } ( X : ltower_over A ) : ll ( pocto X ) = ll X + ll A . Proof. intros . change ( ll X ) with ( ltower_over_ll X ) . unfold ltower_over_ll . rewrite minusplusnmm . apply idpath . apply ( isover_geh ( pr2 X ) ) . Defined. Definition ispointed_ltower_over { T : ltower } ( A : T ) : ispointed_type ( ltower_over A ) := ispointed_ltower_over_int A . Definition pltower_over { T : ltower } ( A : T ) : pltower := pltower_constr ( ispointed_ltower_over A ) . Definition ltower_over_to_pltower_over { T : ltower } ( A : T ) ( X : ltower_over A ) : pltower_over A := X . Lemma ltower_over_ftn { T : ltower } { A : T } ( n : nat ) ( X : ltower_over A ) ( ge : ll X >= n ) : pr1 ( ftn n X ) = ftn n ( pr1 X ) . Proof . intros T A n . induction n . intros . apply idpath . intros. rewrite <- ftn_ft . rewrite <- ftn_ft . assert ( int : ft ( pr1 X ) = pr1 ( ft X ) ) . change ( ft X ) with ( ltower_over_ft X ) . unfold ltower_over_ft . destruct ( isover_choice (isov_isov X) ) as [ isov | eq ] . simpl . apply idpath . assert ( absd : empty ) . change ( ll X ) with ( ll ( pr1 X ) - ll A ) in ge . rewrite <- eq in ge . rewrite natminusnn in ge . apply ( ge ( natgthsn0 _ ) ) . destruct absd . rewrite int . refine ( IHn ( ft X ) _ ) . apply ( ll_ft_gtn ge ) . Defined. (** **** Standard constructions of over-objects *) Definition X_over_X { T : ltower } ( X : T ) : ltower_over X := obj_over_constr ( isover_XX X ) . Lemma ll_X_over_X { T : ltower } ( X : T ) : ll ( X_over_X X ) = 0 . Proof. intros . change _ with ( ll X - ll X = 0 ) . apply natminusnn . Defined. Definition X_over_ftX { T : ltower } ( X : T ) : ltower_over ( ft X ) := obj_over_constr ( isover_X_ftX X ) . Lemma ll_X_over_ftX { T : ltower } { X : T } ( gt0 : ll X > 0 ) : ll ( X_over_ftX X ) = 1 . Proof. intros. change _ with ( ltower_over_ll (X_over_ftX X) = 1 ) . unfold ltower_over_ll . rewrite ll_ft . change _ with ( ll X - ( ll X - 1 ) = 1 ) . apply natminusmmk . apply ( @natgthminus1togeh 1 _ gt0 ) . Defined. (** The projection pocto from the over-tower to the tower is over-monotone *) Lemma ll_over_minus_ll_over { T : ltower } { A : T } ( X1 X2 : ltower_over A ) : ll X1 - ll X2 = ll ( pocto X1 ) - ll ( pocto X2 ) . Proof . intros . destruct X1 as [ X1 isov1 ] . destruct X2 as [ X2 isov2 ] . unfold ll . simpl . unfold ltower_over_ll . simpl . change _ with ( ( ll X1 - ll A ) - ( ll X2 - ll A ) = ( ll X1 - ll X2 ) ) . rewrite natminusassoc . rewrite natpluscomm . rewrite ( minusplusnmm _ _ ( isover_geh isov2 ) ) . apply idpath . Defined. Definition isovmonot_pocto { T : ltower } ( A : T ) { X Y : ltower_over A } ( isov : isover X Y ) : isover ( pocto X ) ( pocto Y ) . Proof . intros . destruct X as [ X isovX ] . destruct Y as [ Y isovY ] . simpl . assert ( int := maponpaths pr1 isov ) . simpl in int . rewrite ltower_over_ftn in int . simpl in int . rewrite ll_over_minus_ll_over in int . simpl in int . exact int . exact ( natminuslehn _ _ ) . Defined. Lemma isllmonot_pocto { T : ltower } { A : T } : isllmonot ( @pocto T A ) . Proof . intros . unfold isllmonot . intros X Y . apply ( ! ( ll_over_minus_ll_over X Y ) ) . Defined. (** **** The projection pocto and ft *) Lemma ft_pocto { T : ltower } { A : T } { X : ltower_over A } ( gt0 : ll X > 0 ) : ft ( pocto X ) = pocto ( ft X ) . Proof. intros . change ( ft X ) with ( ltower_over_ft X ) . unfold ltower_over_ft . destruct (isover_choice (isov_isov X)) as [ isov | eq ] . simpl . apply idpath . assert ( absd : empty ) . assert ( eq0 : ll X = 0 ) . change _ with ( ll ( pr1 X ) - ll A = 0 ) . rewrite <- eq . apply natminusnn . rewrite eq0 in gt0 . apply ( negnatgthnn _ gt0 ) . destruct absd . Defined. (** **** Some functions between over-towers *) Definition to_ltower_over { T : pltower } ( X : T ) : ltower_over ( cntr T ) . Proof . intros . exact ( obj_over_constr ( isoverll0 ( ll_cntr T ) X ) ) . Defined. Lemma ll_to_ltower_over { T : pltower } ( X : T ) : ll ( to_ltower_over X ) = ll X . Proof . intros. unfold ll . simpl . unfold ltower_over_ll . rewrite ll_cntr . rewrite natminuseqn . apply idpath . Defined. Lemma isllmonot_to_ltower_over ( T : pltower ) : isllmonot ( @to_ltower_over T ) . Proof . unfold isllmonot . intros . repeat rewrite ll_to_ltower_over . apply idpath . Defined. Lemma isbased_to_ltower_over ( T : pltower ) : isbased ( @to_ltower_over T ) . Proof . intros . unfold isbased. intros X eq0 . rewrite ll_to_ltower_over . exact eq0 . Defined. (** The following constructions probably work for all ltowers but we only give a proof for ltowers of sets in the file hSet_ltowers.v . Definition ovmonot_to_over_pocto { T : ltower } { X : T } { X' : ltower_over X } : ovmonot_fun ( ltower_over X' ) ( ltower_over ( pocto X' ) ) . Definition ovmonot_over { T1 T2 : ltower } ( f : ovmonot_fun T1 T2 ) ( X : T1 ) : ovmonot_fun ( ltower_over X ) ( ltower_over ( f X ) ) . Definition lft { T : hSet_ltower } { X : T } { X' : ltower_over X } ( X'' : ltower_over ( pocto X' ) ) : ltower_over X' . Definition ovmonot_second { T : ltower } { X Y : T } ( f : ovmonot_fun ( ltower_over X ) ( ltower_over Y ) ) ( X' : ltower_over X ) : ovmonot_fun ( ltower_over ( pocto X' ) ) ( ltower_over ( pocto ( f X' ) ) ) . Lemma isovmonot_to_ltower_over { T : ltower } ( is : ispointed T ) : isovmonot ( to_ltower_over is ) . *) (* End of the file ltowers_over.v *)
theory Induction_Demo imports Main begin subsection{* Generalization *} fun itrev :: "'a list \<Rightarrow> 'a list \<Rightarrow> 'a list" where "itrev [] ys = ys" | "itrev (x#xs) ys = itrev xs (x#ys)" value "itrev [1,2,3::int] [6,7,8]" lemma "itrev xs ys = rev xs @ ys" apply (induction xs arbitrary: ys) apply (auto) done lemma itrev_rev_aux: "itrev xs ys = rev xs @ ys" apply (induction xs ys rule: itrev.induct) apply (auto) done lemma "itrev xs [] = rev xs" by (auto simp: itrev_rev_aux) subsection{* Computation Induction *} fun sep :: "'a \<Rightarrow> 'a list \<Rightarrow> 'a list" where "sep a [] = []" | "sep a [x] = [x]" | "sep a (x#y#zs) = x # a # sep a (y#zs)" lemma "map f (sep a xs) = sep (f a) (map f xs)" apply(induction a xs rule: sep.induct) apply auto done subsection {* Auxiliary Lemmas *} hide_const rev (* Get predefined rev of standard lib out of way! *) fun rev where "rev [] = []" | "rev (x#xs) = rev xs @ [x]" lemma "rev (xs @ [a]) = a # rev xs" apply (induction xs) apply auto done
Formal statement is: lemma le_measureD1: "A \<le> B \<Longrightarrow> space A \<le> space B" Informal statement is: If $A \le B$, then $A$ is a subset of $B$.
Formal statement is: lemma continuous_at_avoid: fixes f :: "'a::metric_space \<Rightarrow> 'b::t1_space" assumes "continuous (at x) f" and "f x \<noteq> a" shows "\<exists>e>0. \<forall>y. dist x y < e \<longrightarrow> f y \<noteq> a" Informal statement is: If $f$ is continuous at $x$ and $f(x) \neq a$, then there exists an $\epsilon > 0$ such that $f(y) \neq a$ for all $y$ with $|x - y| < \epsilon$.
#' @export a = 'sub$a' #' @export b = 'sub$b' #' @export c = 'sub$c' #' @export d = 'sub$d'
If $f$ and $g$ are eventually equal and $f$ converges to $l$ in $X$, then $g$ converges to $l$ in $X$.
Formal statement is: lemma contour_integral_primitive_lemma: fixes f :: "complex \<Rightarrow> complex" and g :: "real \<Rightarrow> complex" assumes "a \<le> b" and "\<And>x. x \<in> S \<Longrightarrow> (f has_field_derivative f' x) (at x within S)" and "g piecewise_differentiable_on {a..b}" "\<And>x. x \<in> {a..b} \<Longrightarrow> g x \<in> S" shows "((\<lambda>x. f'(g x) * vector_derivative g (at x within {a..b})) has_integral (f(g b) - f(g a))) {a..b}" Informal statement is: If $f$ is differentiable on $S$ and $g$ is piecewise differentiable on $[a,b]$ with $g([a,b]) \subseteq S$, then $\int_a^b f'(g(x)) g'(x) dx = f(g(b)) - f(g(a))$.
[STATEMENT] lemma b_assn_invalid_merge1: "hn_invalid (b_assn A P) x y \<or>\<^sub>A hn_invalid (b_assn A P') x y \<Longrightarrow>\<^sub>t hn_invalid (b_assn A (\<lambda>x. P x \<or> P' x)) x y" [PROOF STATE] proof (prove) goal (1 subgoal): 1. hn_invalid (b_assn A P) x y \<or>\<^sub>A hn_invalid (b_assn A P') x y \<Longrightarrow>\<^sub>t hn_invalid (b_assn A (\<lambda>x. P x \<or> P' x)) x y [PROOF STEP] by (sep_auto simp: hn_ctxt_def invalid_assn_def entailst_def)
||| The `Javascript` code generator. module Compiler.ES.Javascript import Compiler.ES.Codegen import Compiler.Common import Compiler.CompileExpr import Core.Context import Core.TT import Core.Options import Libraries.Utils.Path import System import System.File import Data.Maybe import Data.String import Libraries.Data.String.Extra %default covering ||| Compile a TT expression to Javascript compileToJS : Ref Ctxt Defs -> ClosedTerm -> Core String compileToJS c tm = compileToES c Javascript tm ["browser", "javascript"] htmlHeader : String htmlHeader = concat $ the (List String) $ [ "<html>\n" , " <head>\n" , " <meta charset='utf-8'>\n" , " </head>\n" , " <body>\n" , " <script type='text/javascript'>\n" ] htmlFooter : String htmlFooter = concat $ the (List String) $ [ "\n </script>\n" , " </body>\n" , "</html>" ] addHeaderAndFooter : String -> String -> String addHeaderAndFooter outfile es = case toLower <$> extension outfile of Just "html" => htmlHeader ++ es ++ htmlFooter _ => es ||| Javascript implementation of the `compileExpr` interface. compileExpr : Ref Ctxt Defs -> (tmpDir : String) -> (outputDir : String) -> ClosedTerm -> (outfile : String) -> Core (Maybe String) compileExpr c tmpDir outputDir tm outfile = do es <- compileToJS c tm let res = addHeaderAndFooter outfile es let out = outputDir </> outfile Core.writeFile out res pure (Just out) ||| Node implementation of the `executeExpr` interface. executeExpr : Ref Ctxt Defs -> (tmpDir : String) -> ClosedTerm -> Core () executeExpr c tmpDir tm = throw $ InternalError "Javascript backend is only able to compile, use Node instead" ||| Codegen wrapper for Javascript implementation. export codegenJavascript : Codegen codegenJavascript = MkCG compileExpr executeExpr Nothing Nothing
lemma homotopic_with_prod_topology: assumes "homotopic_with p X1 Y1 f f'" and "homotopic_with q X2 Y2 g g'" and r: "\<And>i j. \<lbrakk>p i; q j\<rbrakk> \<Longrightarrow> r(\<lambda>(x,y). (i x, j y))" shows "homotopic_with r (prod_topology X1 X2) (prod_topology Y1 Y2) (\<lambda>z. (f(fst z),g(snd z))) (\<lambda>z. (f'(fst z), g'(snd z)))"
From compcert.common Require Errors. From trancert.lib Require Decidability Tac. Open Scope error_monad_scope. Import Errors Tac. Section Decidability. Import lib.Decidability. Variable A: Type. Hypothesis Hdec: eq_dec A. Definition res_eq_dec : eq_dec (res A). unfold eq_dec, dec in *. intros [] []; decide_equality. Qed. End Decidability. Hint Resolve res_eq_dec : decidable_prop. Ltac autoMinv := match goal with [ H : (do _ <- _ ; _) = OK _ |- _ ] => monadInv H end. Ltac res_cases := match goal with | [ H : match ?x with | _ => _ end = OK _ |- _ ] => let Hfresh := fresh "Heq" in destruct x eqn: Hfresh; try discriminate | [ H : match ?x with | _ => _ end = Error _ |- _ ] => let Hfresh := fresh "Heq" in destruct x eqn: Hfresh; try discriminate end. Ltac autores := repeat (res_cases || autoMinv || autoinj || (progress auto) || intros || (simpl in *) ). Definition to_prop {A B} (T:A -> res B) : (A -> B -> Prop) := fun x x' => T x = OK x'. (** Implicit conversion from [res] into [option]. *) Coercion error_to_option {T} (e: res T) : option T := match e with | OK x => Some x | Error x => None end.
(* @TAG(OTHER_LGPL) *) (* Author: Norbert Schirmer Maintainer: Norbert Schirmer, norbert.schirmer at web de License: LGPL *) (* Title: HoareTotalDef.thy Author: Norbert Schirmer, TU Muenchen Copyright (C) 2004-2008 Norbert Schirmer Some rights reserved, TU Muenchen This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) section {* Hoare Logic for Total Correctness *} theory HoareTotalDef imports HoarePartialDef Termination begin subsection {* Validity of Hoare Tuples: @{text "\<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A"} *} definition validt :: "[('s,'p,'f) body,'f set,'s assn,('s,'p,'f) com,'s assn,'s assn] \<Rightarrow> bool" ("_\<Turnstile>\<^sub>t\<^bsub>'/_\<^esub>/ _ _ _,_" [61,60,1000, 20, 1000,1000] 60) where "\<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A \<equiv> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A \<and> (\<forall>s \<in> Normal ` P. \<Gamma>\<turnstile>c\<down>s)" definition cvalidt:: "[('s,'p,'f) body,('s,'p) quadruple set,'f set, 's assn,('s,'p,'f) com,'s assn,'s assn] \<Rightarrow> bool" ("_,_\<Turnstile>\<^sub>t\<^bsub>'/_\<^esub>/ _ _ _,_" [61,60, 60,1000, 20, 1000,1000] 60) where "\<Gamma>,\<Theta>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A \<equiv> (\<forall>(P,p,Q,A)\<in>\<Theta>. \<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P (Call p) Q,A) \<longrightarrow> \<Gamma> \<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" notation (ascii) validt ("_|=t'/_/ _ _ _,_" [61,60,1000, 20, 1000,1000] 60) and cvalidt ("_,_|=t'/_ / _ _ _,_" [61,60,60,1000, 20, 1000,1000] 60) subsection {* Properties of Validity *} lemma validtI: "\<lbrakk>\<And>s t. \<lbrakk>\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> \<Rightarrow> t;s \<in> P;t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A; \<And>s. s \<in> P \<Longrightarrow> \<Gamma>\<turnstile> c\<down>(Normal s) \<rbrakk> \<Longrightarrow> \<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" by (auto simp add: validt_def valid_def) lemma cvalidtI: "\<lbrakk>\<And>s t. \<lbrakk>\<forall>(P,p,Q,A)\<in>\<Theta>. \<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P (Call p) Q,A;\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> \<Rightarrow> t;s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A; \<And>s. \<lbrakk>\<forall>(P,p,Q,A)\<in>\<Theta>. \<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P (Call p) Q,A; s\<in>P\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>c\<down>(Normal s)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" by (auto simp add: cvalidt_def validt_def valid_def) lemma cvalidt_postD: "\<lbrakk>\<Gamma>,\<Theta>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A; \<forall>(P,p,Q,A)\<in>\<Theta>. \<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P (Call p) Q,A;\<Gamma>\<turnstile>\<langle>c,Normal s \<rangle> \<Rightarrow> t; s \<in> P;t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A" by (simp add: cvalidt_def validt_def valid_def) lemma cvalidt_termD: "\<lbrakk>\<Gamma>,\<Theta>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A; \<forall>(P,p,Q,A)\<in>\<Theta>. \<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P (Call p) Q,A;s \<in> P\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>c\<down>(Normal s)" by (simp add: cvalidt_def validt_def valid_def) lemma validt_augment_Faults: assumes valid:"\<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" assumes F': "F \<subseteq> F'" shows "\<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F'\<^esub> P c Q,A" using valid F' by (auto intro: valid_augment_Faults simp add: validt_def) subsection {* The Hoare Rules: @{text "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" } *} inductive "hoaret"::"[('s,'p,'f) body,('s,'p) quadruple set,'f set, 's assn,('s,'p,'f) com,'s assn,'s assn] => bool" ("(3_,_/\<turnstile>\<^sub>t\<^bsub>'/_\<^esub> (_/ (_)/ _,_))" [61,60,60,1000,20,1000,1000]60) for \<Gamma>::"('s,'p,'f) body" where Skip: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> Q Skip Q,A" | Basic: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> {s. f s \<in> Q} (Basic f) Q,A" | Spec: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> {s. (\<forall>t. (s,t) \<in> r \<longrightarrow> t \<in> Q) \<and> (\<exists>t. (s,t) \<in> r)} (Spec r) Q,A" | Seq: "\<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c\<^sub>1 R,A; \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P Seq c\<^sub>1 c\<^sub>2 Q,A" | Cond: "\<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> (P \<inter> b) c\<^sub>1 Q,A; \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> (P \<inter> - b) c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P (Cond b c\<^sub>1 c\<^sub>2) Q,A" | While: "\<lbrakk>wf r; \<forall>\<sigma>. \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> ({\<sigma>} \<inter> P \<inter> b) c ({t. (t,\<sigma>)\<in>r} \<inter> P),A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P (While b c) (P \<inter> - b),A" | Guard: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> (g \<inter> P) c Q,A \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A" | Guarantee: "\<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P (Guard f g c) Q,A" | CallRec: "\<lbrakk>(P,p,Q,A) \<in> Specs; wf r; Specs_wf = (\<lambda>p \<sigma>. (\<lambda>(P,q,Q,A). (P \<inter> {s. ((s,q),(\<sigma>,p)) \<in> r},q,Q,A)) ` Specs); \<forall>(P,p,Q,A)\<in> Specs. p \<in> dom \<Gamma> \<and> (\<forall>\<sigma>. \<Gamma>,\<Theta> \<union> Specs_wf p \<sigma>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> ({\<sigma>} \<inter> P) (the (\<Gamma> p)) Q,A) \<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P (Call p) Q,A" | DynCom: "\<forall>s \<in> P. \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P (c s) Q,A \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P (DynCom c) Q,A" | Throw: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> A Throw Q,A" | Catch: "\<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A" | Conseq: "\<forall>s \<in> P. \<exists>P' Q' A'. \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P' c Q',A' \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" | Asm: "(P,p,Q,A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P (Call p) Q,A" | ExFalso: "\<lbrakk>\<Gamma>,\<Theta>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" -- {* This is a hack rule that enables us to derive completeness for an arbitrary context @{text "\<Theta>"}, from completeness for an empty context.*} text {* Does not work, because of rule ExFalso, the context @{text \<Theta>} is to blame. A weaker version with empty context can be derived from soundness later on. *} lemma hoaret_to_hoarep: assumes hoaret: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P p Q,A" shows "\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F\<^esub> P p Q,A" using hoaret proof (induct) case Skip thus ?case by (rule hoarep.intros) next case Basic thus ?case by (rule hoarep.intros) next case Seq thus ?case by - (rule hoarep.intros) next case Cond thus ?case by - (rule hoarep.intros) next case (While r \<Theta> F P b c A) hence "\<forall>\<sigma>. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F\<^esub> ({\<sigma>} \<inter> P \<inter> b) c ({t. (t, \<sigma>) \<in> r} \<inter> P),A" by iprover hence "\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F\<^esub> (P \<inter> b) c P,A" by (rule HoarePartialDef.conseq) blast then show "\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F\<^esub> P While b c (P \<inter> - b),A" by (rule hoarep.While) next case Guard thus ?case by - (rule hoarep.intros) (*next case (CallRec A F P Procs Q Z \<Theta> p r) hence hyp: "\<forall>p\<in>Procs. \<forall>\<tau> Z. \<Gamma>,\<Theta> \<union> (\<Union>q\<in>Procs. \<Union>Z. {(P q Z \<inter> {s. ((s, q), \<tau>, p) \<in> r}, Call q, Q q Z,A q Z)})\<turnstile>\<^bsub>/F\<^esub> ({\<tau>} \<inter> P p Z) (the (\<Gamma> p)) (Q p Z),(A p Z)" by blast have "\<forall>p\<in>Procs. \<forall>Z. \<Gamma>,\<Theta> \<union> (\<Union>q\<in>Procs. \<Union>Z. {(P q Z, Call q, Q q Z,A q Z)})\<turnstile>\<^bsub>/F\<^esub> (P p Z) (the (\<Gamma> p)) (Q p Z),(A p Z)" proof (intro ballI allI) fix p Z assume "p \<in> Procs" with hyp have hyp': "\<And> \<tau>. \<Gamma>,\<Theta> \<union> (\<Union>q\<in>Procs. \<Union>Z. {(P q Z \<inter> {s. ((s, q), \<tau>, p) \<in> r}, Call q, Q q Z, A q Z)})\<turnstile>\<^bsub>/F\<^esub> ({\<tau>} \<inter> P p Z) (the (\<Gamma> p)) (Q p Z),(A p Z)" by blast have "\<forall>\<tau>. \<Gamma>,\<Theta> \<union> (\<Union>q\<in>Procs. \<Union>Z. {(P q Z, Call q, Q q Z,A q Z)})\<turnstile>\<^bsub>/F\<^esub> ({\<tau>} \<inter> P p Z) (the (\<Gamma> p)) (Q p Z),(A p Z)" (is "\<forall>\<tau>. \<Gamma>,?\<Theta>'\<turnstile>\<^bsub>/F\<^esub> ({\<tau>} \<inter> P p Z) (the (\<Gamma> p)) (Q p Z),(A p Z)") proof (rule allI, rule WeakenContext [OF hyp'],clarify) fix \<tau> P' c Q' A' assume "(P', c, Q', A') \<in> \<Theta> \<union> (\<Union>q\<in>Procs. \<Union>Z. {(P q Z \<inter> {s. ((s, q), \<tau>, p) \<in> r}, Call q, Q q Z, A q Z)})" (is "(P', c, Q', A') \<in> \<Theta> \<union> ?Spec") then show "\<Gamma>,?\<Theta>'\<turnstile>\<^bsub>/F\<^esub> P' c Q',A'" proof (cases rule: UnE [consumes 1]) assume "(P',c,Q',A') \<in> \<Theta>" then show ?thesis by (blast intro: HoarePartialDef.Asm) next assume "(P',c,Q',A') \<in> ?Spec" then show ?thesis proof (clarify) fix q Z assume q: "q \<in> Procs" show "\<Gamma>,?\<Theta>'\<turnstile>\<^bsub>/F\<^esub> (P q Z \<inter> {s. ((s, q), \<tau>, p) \<in> r}) Call q (Q q Z),(A q Z)" proof - from q have "\<Gamma>,?\<Theta>'\<turnstile>\<^bsub>/F\<^esub> (P q Z) Call q (Q q Z),(A q Z)" by - (rule HoarePartialDef.Asm,blast) thus ?thesis by (rule HoarePartialDef.conseqPre) blast qed qed qed qed then show "\<Gamma>,\<Theta> \<union> (\<Union>q\<in>Procs. \<Union>Z. {(P q Z, Call q, Q q Z,A q Z)}) \<turnstile>\<^bsub>/F\<^esub> (P p Z) (the (\<Gamma> p)) (Q p Z),(A p Z)" by (rule HoarePartialDef.conseq) blast qed thus ?case by - (rule hoarep.CallRec)*) next case DynCom thus ?case by (blast intro: hoarep.DynCom) next case Throw thus ?case by - (rule hoarep.Throw) next case Catch thus ?case by - (rule hoarep.Catch) next case Conseq thus ?case by - (rule hoarep.Conseq,blast) next case Asm thus ?case by (rule HoarePartialDef.Asm) next case (ExFalso \<Theta> F P c Q A) assume "\<Gamma>,\<Theta>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" hence "\<Gamma>,\<Theta>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A" oops lemma hoaret_augment_context: assumes deriv: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P p Q,A" shows "\<And>\<Theta>'. \<Theta> \<subseteq> \<Theta>' \<Longrightarrow> \<Gamma>,\<Theta>'\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P p Q,A" using deriv proof (induct) case (CallRec P p Q A Specs r Specs_wf \<Theta> F \<Theta>') have aug: "\<Theta> \<subseteq> \<Theta>'" by fact then have h: "\<And>\<tau> p. \<Theta> \<union> Specs_wf p \<tau> \<subseteq> \<Theta>' \<union> Specs_wf p \<tau>" by blast have "\<forall>(P,p,Q,A)\<in>Specs. p \<in> dom \<Gamma> \<and> (\<forall>\<tau>. \<Gamma>,\<Theta> \<union> Specs_wf p \<tau>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> ({\<tau>} \<inter> P) (the (\<Gamma> p)) Q,A \<and> (\<forall>x. \<Theta> \<union> Specs_wf p \<tau> \<subseteq> x \<longrightarrow> \<Gamma>,x\<turnstile>\<^sub>t\<^bsub>/F\<^esub> ({\<tau>} \<inter> P) (the (\<Gamma> p)) Q,A))" by fact hence "\<forall>(P,p,Q,A)\<in>Specs. p \<in> dom \<Gamma> \<and> (\<forall>\<tau>. \<Gamma>,\<Theta>'\<union> Specs_wf p \<tau> \<turnstile>\<^sub>t\<^bsub>/F\<^esub> ({\<tau>} \<inter> P) (the (\<Gamma> p)) Q,A)" apply (clarify) apply (rename_tac P p Q A) apply (drule (1) bspec) apply (clarsimp) apply (erule_tac x=\<tau> in allE) apply clarify apply (erule_tac x="\<Theta>' \<union> Specs_wf p \<tau>" in allE) apply (insert aug) apply auto done with CallRec show ?case by - (rule hoaret.CallRec) next case DynCom thus ?case by (blast intro: hoaret.DynCom) next case (Conseq P \<Theta> F c Q A \<Theta>') from Conseq have "\<forall>s \<in> P. (\<exists>P' Q' A'. (\<Gamma>,\<Theta>' \<turnstile>\<^sub>t\<^bsub>/F\<^esub> P' c Q',A') \<and> s \<in> P'\<and> Q' \<subseteq> Q \<and> A' \<subseteq> A)" by blast with Conseq show ?case by - (rule hoaret.Conseq) next case (ExFalso \<Theta> F P c Q A \<Theta>') have "\<Gamma>,\<Theta>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" "\<not> \<Gamma>\<Turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" "\<Theta> \<subseteq> \<Theta>'" by fact+ then show ?case by (fastforce intro: hoaret.ExFalso simp add: cvalidt_def) qed (blast intro: hoaret.intros)+ subsection {* Some Derived Rules *} lemma Conseq': "\<forall>s. s \<in> P \<longrightarrow> (\<exists>P' Q' A'. (\<forall> Z. \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> (P' Z) c (Q' Z),(A' Z)) \<and> (\<exists>Z. s \<in> P' Z \<and> (Q' Z \<subseteq> Q) \<and> (A' Z \<subseteq> A))) \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" apply (rule Conseq) apply (rule ballI) apply (erule_tac x=s in allE) apply (clarify) apply (rule_tac x="P' Z" in exI) apply (rule_tac x="Q' Z" in exI) apply (rule_tac x="A' Z" in exI) apply blast done lemma conseq:"\<lbrakk>\<forall>Z. \<Gamma>,\<Theta> \<turnstile>\<^sub>t\<^bsub>/F\<^esub> (P' Z) c (Q' Z),(A' Z); \<forall>s. s \<in> P \<longrightarrow> (\<exists> Z. s\<in>P' Z \<and> (Q' Z \<subseteq> Q)\<and> (A' Z \<subseteq> A))\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" by (rule Conseq) blast theorem conseqPrePost: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P' c Q',A' \<Longrightarrow> P \<subseteq> P' \<Longrightarrow> Q' \<subseteq> Q \<Longrightarrow> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" by (rule conseq [where ?P'="\<lambda>Z. P'" and ?Q'="\<lambda>Z. Q'"]) auto lemma conseqPre: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P' c Q,A \<Longrightarrow> P \<subseteq> P' \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" by (rule conseq) auto lemma conseqPost: "\<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q',A'\<Longrightarrow> Q' \<subseteq> Q \<Longrightarrow> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> P c Q,A" by (rule conseq) auto lemma Spec_wf_conv: "(\<lambda>(P, q, Q, A). (P \<inter> {s. ((s, q), \<tau>, p) \<in> r}, q, Q, A)) ` (\<Union>p\<in>Procs. \<Union>Z. {(P p Z, p, Q p Z, A p Z)}) = (\<Union>q\<in>Procs. \<Union>Z. {(P q Z \<inter> {s. ((s, q), \<tau>, p) \<in> r}, q, Q q Z, A q Z)})" apply (rule) apply fastforce apply (fastforce simp add: image_def) done lemma CallRec': "\<lbrakk>p\<in>Procs; Procs \<subseteq> dom \<Gamma>; wf r; \<forall>p\<in>Procs. \<forall>\<tau> Z. \<Gamma>,\<Theta>\<union>(\<Union>q\<in>Procs. \<Union>Z. {((P q Z) \<inter> {s. ((s,q),(\<tau>,p)) \<in> r},q,Q q Z,(A q Z))}) \<turnstile>\<^sub>t\<^bsub>/F\<^esub> ({\<tau>} \<inter> (P p Z)) (the (\<Gamma> p)) (Q p Z),(A p Z)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<turnstile>\<^sub>t\<^bsub>/F\<^esub> (P p Z) (Call p) (Q p Z),(A p Z)" apply (rule CallRec [where Specs="\<Union>p\<in>Procs. \<Union>Z. {((P p Z),p,Q p Z,A p Z)}" and r=r]) apply blast apply assumption apply (rule refl) apply (clarsimp) apply (rename_tac p') apply (rule conjI) apply blast apply (intro allI) apply (rename_tac Z \<tau>) apply (drule_tac x=p' in bspec, assumption) apply (erule_tac x=\<tau> in allE) apply (erule_tac x=Z in allE) apply (fastforce simp add: Spec_wf_conv) done end
open import Data.List hiding ([_]) renaming (_∷_ to _∷ₗ_) open import Data.Maybe open import Data.Product open import AEff open import EffectAnnotations open import Renamings open import Substitutions open import Types open import Relation.Binary.PropositionalEquality hiding ([_]) open import Relation.Nullary module Preservation where -- BINDING CONTEXTS BCtx = List VType -- WELL-TYPED EVALUATION CONTEXTS data _⊢E[_]⦂_ (Γ : Ctx) : (Δ : BCtx) → CType → Set where [-] : {C : CType} → ------------- Γ ⊢E[ [] ]⦂ C let=_`in_ : {Δ : BCtx} {X Y : VType} {o : O} {i : I} → Γ ⊢E[ Δ ]⦂ X ! (o , i) → Γ ∷ X ⊢M⦂ Y ! (o , i) → ------------------------ Γ ⊢E[ Δ ]⦂ Y ! (o , i) ↑ : {Δ : BCtx} {X : VType} {o : O} {i : I} → (op : Σₛ) → op ∈ₒ o → Γ ⊢V⦂ ``(payload op) → Γ ⊢E[ Δ ]⦂ X ! (o , i) → ------------------------ Γ ⊢E[ Δ ]⦂ X ! (o , i) ↓ : {Δ : BCtx} {X : VType} {o : O} {i : I} (op : Σₛ) → Γ ⊢V⦂ ``(payload op) → Γ ⊢E[ Δ ]⦂ X ! (o , i) → --------------------------- Γ ⊢E[ Δ ]⦂ X ! op ↓ₑ (o , i) promise_∣_↦_`in_ : {Δ : BCtx} {X Y : VType} {o o' : O} {i i' : I} → (op : Σₛ) → lkpᵢ op i ≡ just (o' , i') → Γ ∷ ``(payload op) ⊢M⦂ ⟨ X ⟩ ! (o' , i') → Γ ∷ ⟨ X ⟩ ⊢E[ Δ ]⦂ Y ! (o , i) → ------------------------------------------ Γ ⊢E[ X ∷ₗ Δ ]⦂ Y ! (o , i) coerce : {Δ : BCtx} {X : VType} {o o' : O} {i i' : I} → o ⊑ₒ o' → i ⊑ᵢ i' → Γ ⊢E[ Δ ]⦂ X ! (o , i) → ------------------------ Γ ⊢E[ Δ ]⦂ X ! (o' , i') -- MERGING AN ORDINARY CONTEXT AND A BINDING CONTEXT infix 30 _⋈_ _⋈_ : Ctx → BCtx → Ctx Γ ⋈ [] = Γ Γ ⋈ (X ∷ₗ Δ) = (Γ ∷ ⟨ X ⟩) ⋈ Δ -- FINDING THE TYPE OF THE HOLE OF A WELL-TYPED EVALUATION CONTEXT hole-ty-e : {Γ : Ctx} {Δ : BCtx} {C : CType} → Γ ⊢E[ Δ ]⦂ C → CType hole-ty-e {_} {_} {C} [-] = C hole-ty-e (let= E `in M) = hole-ty-e E hole-ty-e (↑ op p V E) = hole-ty-e E hole-ty-e (↓ op V E) = hole-ty-e E hole-ty-e (promise op ∣ p ↦ M `in E) = hole-ty-e E hole-ty-e (coerce p q E) = hole-ty-e E -- FILLING A WELL-TYPED EVALUATION CONTEXT {- LEMMA 3.5 -} infix 30 _[_] _[_] : {Γ : Ctx} {Δ : BCtx} {C : CType} → (E : Γ ⊢E[ Δ ]⦂ C) → Γ ⋈ Δ ⊢M⦂ (hole-ty-e E) → Γ ⊢M⦂ C [-] [ M ] = M (let= E `in N) [ M ] = let= (E [ M ]) `in N ↑ op p V E [ M ] = ↑ op p V (E [ M ]) ↓ op V E [ M ] = ↓ op V (E [ M ]) (promise op ∣ p ↦ N `in E) [ M ] = promise op ∣ p ↦ N `in (E [ M ]) coerce p q E [ M ] = coerce p q (E [ M ]) -- STRENGTHENING OF GROUND VALUES WRT BOUND PROMISES strengthen-var : {Γ : Ctx} → (Δ : BCtx) → {A : BType} → `` A ∈ Γ ⋈ Δ → `` A ∈ Γ strengthen-var [] x = x strengthen-var (y ∷ₗ Δ) x with strengthen-var Δ x ... | Tl p = p strengthen-val : {Γ : Ctx} {Δ : BCtx} {A : BType} → Γ ⋈ Δ ⊢V⦂ `` A → Γ ⊢V⦂ `` A strengthen-val {_} {Δ} (` x) = ` strengthen-var Δ x strengthen-val (``_ c) = ``_ c strengthen-val-[] : {Γ : Ctx} {A : BType} → (V : Γ ⋈ [] ⊢V⦂ `` A) → -------------------- strengthen-val {Δ = []} V ≡ V strengthen-val-[] (` x) = refl strengthen-val-[] (``_ c) = refl -- SMALL-STEP OPERATIONAL SEMANTICS FOR WELL-TYPED COMPUTATIONS -- (ADDITIONALLY SERVES AS THE PRESERVATION THEOREM) {- THEOREM 3.6 -} infix 10 _↝_ data _↝_ {Γ : Ctx} : {C : CType} → Γ ⊢M⦂ C → Γ ⊢M⦂ C → Set where -- COMPUTATIONAL RULES apply : {X : VType} {C : CType} → (M : Γ ∷ X ⊢M⦂ C) → (V : Γ ⊢V⦂ X) → ---------------------- (ƛ M) · V ↝ M [ id-subst [ V ]s ]m let-return : {X Y : VType} {o : O} {i : I} → (V : Γ ⊢V⦂ X) → (N : Γ ∷ X ⊢M⦂ Y ! (o , i)) → ----------------------------- let= (return V) `in N ↝ N [ id-subst [ V ]s ]m let-↑ : {X Y : VType} {o : O} {i : I} {op : Σₛ} → (p : op ∈ₒ o) → (V : Γ ⊢V⦂ ``(payload op)) → (M : Γ ⊢M⦂ X ! (o , i)) → (N : Γ ∷ X ⊢M⦂ Y ! (o , i)) → ----------------------------- let= (↑ op p V M) `in N ↝ ↑ op p V (let= M `in N) let-promise : {X Y Z : VType} {o o' : O} {i i' : I} {op : Σₛ} → (p : lkpᵢ op i ≡ just (o' , i')) → (M₁ : Γ ∷ ``(payload op) ⊢M⦂ ⟨ X ⟩ ! (o' , i')) → (M₂ : Γ ∷ ⟨ X ⟩ ⊢M⦂ Y ! (o , i)) → (N : Γ ∷ Y ⊢M⦂ Z ! (o , i)) → --------------------------------------------------------------------------- let= (promise op ∣ p ↦ M₁ `in M₂) `in N ↝ (promise op ∣ p ↦ M₁ `in (let= M₂ `in (M-rename (comp-ren exchange wk₁) N))) letrec-unfold : {X : VType} {C D : CType} (M : Γ ∷ (X ⇒ C) ∷ X ⊢M⦂ C) → (N : Γ ∷ (X ⇒ C) ⊢M⦂ D) → ---------------------------------------- (letrec M `in N) ↝ N [ id-subst [ ƛ (letrec M-rename wk₃ M `in M-rename exchange M) ]s ]m promise-↑ : {X Y : VType} {o o' : O} {i i' : I} {op op' : Σₛ} → (p : lkpᵢ op i ≡ just (o' , i')) → (q : op' ∈ₒ o) → (V : Γ ∷ ⟨ X ⟩ ⊢V⦂ ``(payload op')) → (M : Γ ∷ ``(payload op) ⊢M⦂ ⟨ X ⟩ ! (o' , i')) → (N : Γ ∷ ⟨ X ⟩ ⊢M⦂ Y ! (o , i)) → -------------------------------------------- (promise op ∣ p ↦ M `in (↑ op' q V N)) ↝ ↑ op' q (strengthen-val {Δ = X ∷ₗ []} V) (promise op ∣ p ↦ M `in N) ↓-return : {X : VType} {o : O} {i : I} {op : Σₛ} → (V : Γ ⊢V⦂ ``(payload op)) → (W : Γ ⊢V⦂ X) → ---------------------------------------------------------------- ↓ {o = o} {i = i} op V (return W) ↝ return {o = proj₁ (op ↓ₑ (o , i))} {i = proj₂ (op ↓ₑ (o , i))} W ↓-↑ : {X : VType} {o : O} {i : I} {op : Σₛ} {op' : Σₛ} → (p : op' ∈ₒ o) → (V : Γ ⊢V⦂ ``(payload op)) → (W : Γ ⊢V⦂ ``(payload op')) → (M : Γ ⊢M⦂ X ! (o , i)) → ------------------------------- ↓ op V (↑ op' p W M) ↝ ↑ op' (↓ₑ-⊑ₒ op' p) W (↓ op V M) ↓-promise-op : {X Y : VType} {o o' : O} {i i' : I} {op : Σₛ} → (p : lkpᵢ op i ≡ just (o' , i')) → (V : Γ ⊢V⦂ ``(payload op)) → (M : Γ ∷ ``(payload op) ⊢M⦂ ⟨ X ⟩ ! (o' , i')) → (N : Γ ∷ ⟨ X ⟩ ⊢M⦂ Y ! (o , i)) → --------------------------------------------------------------------------------------- ↓ op V (promise op ∣ p ↦ M `in N ) ↝ (let= (coerce (↓ₑ-⊑ₒ-o' {o} p) (↓ₑ-⊑ₒ-i' {o} p) (M [ id-subst [ V ]s ]m)) `in ↓ op (V-rename wk₁ V) ((M-rename (comp-ren exchange wk₁) N) [ id-subst [ ` Hd ]s ]m)) ↓-promise-op' : {X Y : VType} {o o' : O} {i i' : I} {op op' : Σₛ} → (p : ¬ op ≡ op') → (q : lkpᵢ op' i ≡ just (o' , i')) → (V : Γ ⊢V⦂ ``(payload op)) → (M : Γ ∷ ``(payload op') ⊢M⦂ ⟨ X ⟩ ! (o' , i')) → (N : Γ ∷ ⟨ X ⟩ ⊢M⦂ Y ! (o , i)) → ------------------------------------------------------------------------------------------ ↓ op V (promise op' ∣ q ↦ M `in N ) ↝ promise_∣_↦_`in_ {o' = proj₁ (lkpᵢ-↓ₑ-neq {o = o} {i = i} p q)} {i' = proj₁ (proj₂ (lkpᵢ-↓ₑ-neq {o = o} {i = i} p q))} op' (proj₁ (proj₂ (proj₂ (lkpᵢ-↓ₑ-neq {o = o} {i = i} p q)))) (coerce (proj₁ (proj₂ (proj₂ (proj₂ (lkpᵢ-↓ₑ-neq {o = o} {i = i} p q))))) (proj₂ (proj₂ (proj₂ (proj₂ (lkpᵢ-↓ₑ-neq {o = o} {i = i} p q))))) M) (↓ op (V-rename wk₁ V) N) await-promise : {X : VType} {C : CType} → (V : Γ ⊢V⦂ X) → (M : Γ ∷ X ⊢M⦂ C) → -------------------- await ⟨ V ⟩ until M ↝ M [ id-subst [ V ]s ]m -- EVALUATION CONTEXT RULE context : {Δ : BCtx} {C : CType} → (E : Γ ⊢E[ Δ ]⦂ C) → {M N : Γ ⋈ Δ ⊢M⦂ (hole-ty-e E)} → M ↝ N → ------------------------------- E [ M ] ↝ E [ N ] -- COERCION RULES -- (THE RESULT OF WORKING WITH WELL-TYPED SYNTAX AND MAKING SUBSUMPTION INTO AN EXPLICIT COERCION) coerce-return : {X : VType} {o o' : O} {i i' : I} {p : o ⊑ₒ o'} {q : i ⊑ᵢ i'} → (V : Γ ⊢V⦂ X) → -------------------------------- coerce p q (return V) ↝ return V coerce-↑ : {X : VType} {o o' : O} {i i' : I} {p : o ⊑ₒ o'} {q : i ⊑ᵢ i'} {op : Σₛ} → (r : op ∈ₒ o) → (V : Γ ⊢V⦂ ``(payload op)) → (M : Γ ⊢M⦂ X ! (o , i)) → ------------------------------- coerce p q (↑ op r V M) ↝ ↑ op (p op r) V (coerce p q M) coerce-promise : {X Y : VType} {o o' o'' : O} {i i' i'' : I} {p : o ⊑ₒ o'} {q : i ⊑ᵢ i'} {op : Σₛ} → (r : lkpᵢ op i ≡ just (o'' , i'')) (M : Γ ∷ ``(payload op) ⊢M⦂ ⟨ X ⟩ ! (o'' , i'')) → (N : Γ ∷ ⟨ X ⟩ ⊢M⦂ Y ! (o , i)) → ------------------------------------------------------------------ coerce p q (promise op ∣ r ↦ M `in N) ↝ promise_∣_↦_`in_ {o' = lkpᵢ-nextₒ q r} {i' = lkpᵢ-nextᵢ q r} op (lkpᵢ-next-eq q r) (coerce (lkpᵢ-next-⊑ₒ q r) (lkpᵢ-next-⊑ᵢ q r) M) (coerce p q N)
{-# OPTIONS --cubical --safe #-} module Cubical.Foundations.FunExtEquiv where open import Cubical.Foundations.Prelude open import Cubical.Foundations.Equiv open import Cubical.Foundations.Univalence private variable ℓ ℓ₁ ℓ₂ ℓ₃ : Level -- Function extensionality is an equivalence module _ {A : Type ℓ} {B : A → Type ℓ₁} {f g : (x : A) → B x} where private fib : (p : f ≡ g) → fiber funExt p fib p = (funExt⁻ p , refl) funExt-fiber-isContr : (p : f ≡ g) → (fi : fiber funExt p) → fib p ≡ fi funExt-fiber-isContr p (h , eq) i = (funExt⁻ (eq (~ i)) , λ j → eq (~ i ∨ j)) funExt-isEquiv : isEquiv funExt equiv-proof funExt-isEquiv p = (fib p , funExt-fiber-isContr p) funExtEquiv : (∀ x → f x ≡ g x) ≃ (f ≡ g) funExtEquiv = (funExt {B = B} , funExt-isEquiv) funExtPath : (∀ x → f x ≡ g x) ≡ (f ≡ g) funExtPath = ua funExtEquiv -- Function extensionality for binary functions funExt₂ : {A : Type ℓ} {B : A → Type ℓ₁} {C : (x : A) → B x → Type ℓ₂} {f g : (x : A) → (y : B x) → C x y} → ((x : A) (y : B x) → f x y ≡ g x y) → f ≡ g funExt₂ p i x y = p x y i -- Function extensionality for binary functions is an equivalence module _ {A : Type ℓ} {B : A → Type ℓ₁} {C : (x : A) → B x → Type ℓ₂} {f g : (x : A) → (y : B x) → C x y} where private appl₂ : f ≡ g → ∀ x y → f x y ≡ g x y appl₂ eq x y i = eq i x y fib : (p : f ≡ g) → fiber funExt₂ p fib p = (appl₂ p , refl) funExt₂-fiber-isContr : (p : f ≡ g) → (fi : fiber funExt₂ p) → fib p ≡ fi funExt₂-fiber-isContr p (h , eq) i = (appl₂ (eq (~ i)) , λ j → eq (~ i ∨ j)) funExt₂-isEquiv : isEquiv funExt₂ equiv-proof funExt₂-isEquiv p = (fib p , funExt₂-fiber-isContr p) funExt₂Equiv : (∀ x y → f x y ≡ g x y) ≃ (f ≡ g) funExt₂Equiv = (funExt₂ , funExt₂-isEquiv) funExt₂Path : (∀ x y → f x y ≡ g x y) ≡ (f ≡ g) funExt₂Path = ua funExt₂Equiv -- Function extensionality for ternary functions funExt₃ : {A : Type ℓ} {B : A → Type ℓ₁} {C : (x : A) → B x → Type ℓ₂} {D : (x : A) → (y : B x) → C x y → Type ℓ₃} {f g : (x : A) → (y : B x) → (z : C x y) → D x y z} → ((x : A) (y : B x) (z : C x y) → f x y z ≡ g x y z) → f ≡ g funExt₃ p i x y z = p x y z i -- Function extensionality for ternary functions is an equivalence module _ {A : Type ℓ} {B : A → Type ℓ₁} {C : (x : A) → B x → Type ℓ₂} {D : (x : A) → (y : B x) → C x y → Type ℓ₃} {f g : (x : A) → (y : B x) → (z : C x y) → D x y z} where private appl₃ : f ≡ g → ∀ x y z → f x y z ≡ g x y z appl₃ eq x y z i = eq i x y z fib : (p : f ≡ g) → fiber funExt₃ p fib p = (appl₃ p , refl) funExt₃-fiber-isContr : (p : f ≡ g) → (fi : fiber funExt₃ p) → fib p ≡ fi funExt₃-fiber-isContr p (h , eq) i = (appl₃ (eq (~ i)) , λ j → eq (~ i ∨ j)) funExt₃-isEquiv : isEquiv funExt₃ equiv-proof funExt₃-isEquiv p = (fib p , funExt₃-fiber-isContr p) funExt₃Equiv : (∀ x y z → f x y z ≡ g x y z) ≃ (f ≡ g) funExt₃Equiv = (funExt₃ , funExt₃-isEquiv) funExt₃Path : (∀ x y z → f x y z ≡ g x y z) ≡ (f ≡ g) funExt₃Path = ua funExt₃Equiv -- Puzzle: Can one generalize this to n-ary functions?
Formal statement is: lemma continuous_at_Inf_antimono: fixes f :: "'a::{linorder_topology,conditionally_complete_linorder} \<Rightarrow> 'b::{linorder_topology,conditionally_complete_linorder}" assumes "antimono f" and cont: "continuous (at_right (Inf S)) f" and S: "S \<noteq> {}" "bdd_below S" shows "f (Inf S) = (SUP s\<in>S. f s)" Informal statement is: If $f$ is an antimonotone function and $f$ is continuous at the right of the infimum of a nonempty set $S$ that is bounded below, then $f$ applied to the infimum of $S$ is equal to the supremum of $f$ applied to the elements of $S$.
Require Import Metalib.Metatheory. Require Import Program.Equality. Require Export DoubleUnfolding. Module Anchor. Inductive typ : Set := | typ_top : typ | typ_nat : typ | typ_bvar : nat -> typ | typ_fvar : var -> typ | typ_mu : typ -> typ | typ_arrow : typ -> typ -> typ | typ_rcd : typ -> typ -> typ . Coercion typ_bvar : nat >-> typ. Coercion typ_fvar : atom >-> typ. Fixpoint open_tt_rec (K : nat) (U : typ) (T : typ) {struct T} : typ := match T with | typ_nat => typ_nat | typ_top => typ_top | typ_bvar J => if K === J then U else (typ_bvar J) | typ_fvar X => typ_fvar X | typ_arrow T1 T2 => typ_arrow (open_tt_rec K U T1) (open_tt_rec K U T2) | typ_mu T => typ_mu (open_tt_rec (S K) U T) | typ_rcd T1 T2 => typ_rcd (open_tt_rec K U T1) (open_tt_rec K U T2) end. (* T type U name *) Definition open_tt T U := open_tt_rec 0 U T. (** Types as locally closed pre-types *) Inductive type : typ -> Prop := | type_top : type typ_top | type_nat : type typ_nat | type_var : forall X, type (typ_fvar X) | type_arrow : forall T1 T2, type T1 -> type T2 -> type (typ_arrow T1 T2) | type_rcd : forall T1 T2, type T1 -> type T2 -> type (typ_rcd T1 T2) | type_mu : forall L T, (forall X, X \notin L -> type (open_tt T (typ_fvar X))) -> type (typ_mu T) . Hint Constructors type : core. Fixpoint subst_tt (Z : atom) (U : typ) (T : typ) {struct T} : typ := match T with | typ_top => typ_top | typ_nat => typ_nat | typ_bvar J => typ_bvar J | typ_fvar X => if X == Z then U else (typ_fvar X) | typ_arrow T1 T2 => typ_arrow (subst_tt Z U T1) (subst_tt Z U T2) | typ_mu T => typ_mu (subst_tt Z U T) | typ_rcd T1 T2 => typ_rcd (subst_tt Z U T1) (subst_tt Z U T2) end. Fixpoint fv_tt (T : typ) {struct T} : atoms := match T with | typ_top => {} | typ_nat => {} | typ_bvar J => {} | typ_fvar X => {{ X }} | typ_arrow T1 T2 => (fv_tt T1) `union` (fv_tt T2) | typ_mu T => (fv_tt T) | typ_rcd T1 T2 => fv_tt T1 \u fv_tt T2 end. Inductive binding : Set := | bind_sub : binding. Definition env := list (atom * binding). Notation empty := (@nil (atom * binding)). Inductive WF : env -> typ -> Prop := | WF_top : forall E, WF E typ_top | WF_nat : forall E, WF E typ_nat | WF_fvar : forall X E, binds X bind_sub E -> WF E (typ_fvar X) | WF_arrow : forall E A B, WF E A -> WF E B -> WF E (typ_arrow A B) | WF_rcd : forall E T1 T2, WF E T1 -> WF E T2 -> WF E (typ_rcd T1 T2) | WF_rec : forall L E A, (forall X, X \notin L -> WF (X ~ bind_sub ++ E) (open_tt A X)) -> WF E (typ_mu A). Inductive WFS : env -> typ -> Prop := | WFS_top : forall E, WFS E typ_top | WFS_nat : forall E, WFS E typ_nat | WFS_fvar : forall X E, binds X bind_sub E -> WFS E (typ_fvar X) | WFS_arrow : forall E A B, WFS E A -> WFS E B -> WFS E (typ_arrow A B) | WFS_rcd : forall E T1 T2, WFS E T1 -> WFS E T2 -> WFS E (typ_rcd T1 T2) | WFS_rec : forall L E A, (forall X, X \notin L -> WFS (X ~ bind_sub ++ E) (open_tt A (typ_rcd X (open_tt A X)))) -> (forall X, X \notin L -> WFS (X ~ bind_sub ++ E) (open_tt A X)) -> WFS E (typ_mu A). Inductive wf_env : env -> Prop := | wf_env_empty : wf_env empty | wf_env_sub : forall (E : env) (X : atom) , wf_env E -> X \notin dom E -> wf_env (X ~ bind_sub ++ E) . Inductive Sub : env -> typ -> typ -> Prop := | S_nat: forall E, wf_env E -> Sub E typ_nat typ_nat | S_fvar: forall E X, wf_env E -> WFS E (typ_fvar X) -> Sub E (typ_fvar X) (typ_fvar X) | S_top : forall E A, wf_env E -> WFS E A -> Sub E A typ_top | S_arrow: forall E A1 A2 B1 B2, Sub E B1 A1 -> Sub E A2 B2 -> Sub E (typ_arrow A1 A2) (typ_arrow B1 B2) | S_rec: forall L A1 A2 E, (forall X, X \notin L -> WFS (X ~ bind_sub ++ E) (open_tt A1 X)) -> (forall X, X \notin L -> WFS (X ~ bind_sub ++ E) (open_tt A2 X)) -> (forall X, X \notin L -> Sub (X ~ bind_sub ++ E) (open_tt A1 (typ_rcd X (open_tt A1 X))) (open_tt A2 (typ_rcd X (open_tt A2 X)))) -> Sub E (typ_mu A1) (typ_mu A2) | S_rcd : forall A B S T E, Sub E A B -> Sub E S T -> Sub E T S -> Sub E (typ_rcd S A) (typ_rcd T B) . Inductive sub : env -> typ -> typ -> Prop := | Sa_nat: forall E, wf_env E -> sub E typ_nat typ_nat | Sa_fvar: forall E X, wf_env E -> WF E (typ_fvar X) -> sub E (typ_fvar X) (typ_fvar X) | Sa_top : forall E A, wf_env E -> WF E A -> sub E A typ_top | Sa_arrow: forall E A1 A2 B1 B2, sub E B1 A1 -> sub E A2 B2 -> sub E (typ_arrow A1 A2) (typ_arrow B1 B2) | Sa_rec: forall L A1 A2 E, (forall X, X \notin L -> sub (X ~ bind_sub ++ E) (open_tt A1 X) (open_tt A2 X)) -> (forall X, X \notin L -> sub (X ~ bind_sub ++ E) (open_tt A1 (open_tt A1 X)) (open_tt A2 (open_tt A2 X))) -> sub E (typ_mu A1) (typ_mu A2) | Sa_rcd : forall A B S T E, sub E A B -> sub E S T -> sub E T S -> sub E (typ_rcd S A) (typ_rcd T B) . Lemma subst_tt_intro_rec : forall X T2 U k, X `notin` fv_tt T2 -> open_tt_rec k U T2 = subst_tt X U (open_tt_rec k (typ_fvar X) T2). Proof with congruence || auto. induction T2; intros U k Fr; simpl in *; f_equal... destruct (k === n)... simpl. destruct (X == X)... destruct (a == X)... contradict Fr; fsetdec. Qed. Lemma subst_tt_intro : forall X T2 U, X `notin` fv_tt T2 -> open_tt T2 U = subst_tt X U (open_tt T2 X). Proof. intros. unfold open_tt. apply subst_tt_intro_rec... assumption. Qed. Lemma open_tt_rec_type_aux : forall T j V i U, i <> j -> open_tt_rec j V T = open_tt_rec i U (open_tt_rec j V T) -> T = open_tt_rec i U T. Proof with congruence || eauto. induction T; intros j V i U Neq H; simpl in *; inversion H; f_equal... destruct (j === n)... destruct (i === n)... Qed. Lemma open_tt_rec_type : forall T U k, type T -> T = open_tt_rec k U T. Proof with auto. intros T U k Htyp. revert k. induction Htyp; intros k; simpl; f_equal... unfold open_tt in *. pick fresh X. apply open_tt_rec_type_aux with (j:=0) (V:=X). auto. auto. Qed. Lemma subst_tt_fresh : forall Z U T, Z `notin` fv_tt T -> T = subst_tt Z U T. Proof with auto. induction T; simpl; intro H; f_equal... destruct (a == Z)... contradict H; fsetdec. Qed. Lemma subst_tt_open_tt_rec : forall T1 T2 X P k, type P -> subst_tt X P (open_tt_rec k T2 T1) = open_tt_rec k (subst_tt X P T2) (subst_tt X P T1). Proof with auto. intros T1 T2 X P k WP. revert k. induction T1; intros k; simpl; f_equal... destruct (k === n); subst... destruct (a == X); subst... apply open_tt_rec_type... Qed. Lemma subst_tt_open_tt : forall T1 T2 (X:atom) P, type P -> subst_tt X P (open_tt T1 T2) = open_tt (subst_tt X P T1) (subst_tt X P T2). Proof with auto. intros. unfold open_tt. apply subst_tt_open_tt_rec... Qed. Lemma subst_tt_open_tt_var : forall (X Y:atom) P T, Y <> X -> type P -> open_tt (subst_tt X P T) Y = subst_tt X P (open_tt T Y). Proof with congruence || auto. intros X Y P T Neq Wu. unfold open_tt. rewrite subst_tt_open_tt_rec... simpl. destruct (Y == X)... Qed. Lemma subst_tt_type : forall Z P T, type T -> type P -> type (subst_tt Z P T). Proof with auto. intros Z P T HT HP. induction HT; simpl... destruct (X == Z)... pick fresh Y and apply type_mu... rewrite subst_tt_open_tt_var... Qed. Hint Constructors WF WFS Sub sub: core. Lemma notin_fv_tt_open_aux : forall X U T, X `notin` fv_tt T -> X \notin fv_tt U -> X `notin` fv_tt (open_tt T U). Proof with auto. intros. simpl. unfold open_tt. unfold open_tt_rec. generalize 0. induction T;simpl in *;intros... destruct (n0==n)... Qed. Lemma WF_type: forall E A, WF E A -> type A. Proof with auto. intros. induction H... apply type_mu with (L:=L)... Qed. Lemma WF_weakening: forall E1 E2 T E, WF (E1 ++ E2) T -> WF (E1 ++ E ++ E2) T. Proof with auto. intros. generalize dependent E. dependent induction H;intros... - apply WF_rec with (L:=L)... intros. rewrite_alist (([(X, bind_sub)] ++ E1) ++ E ++ E2). apply H0... Qed. Lemma subst_tt_wf: forall A B E X, WF E A -> WF E B -> WF E (subst_tt X A B). Proof with auto. intros. generalize dependent A. dependent induction H0;intros;simpl in *... - destruct (X0==X)... - apply WF_rec with (L:=L \u {{X}} \u fv_tt A0). intros. rewrite subst_tt_open_tt_var... apply H0... rewrite_alist (nil ++ [(X0, bind_sub)] ++ E). apply WF_weakening... apply WF_type in H1... Qed. Lemma wfs_to_wf: forall E A, WFS E A -> WF E A. Proof with auto. intros. induction H... apply WF_rec with (L:=L)... Qed. Lemma WFS_weakening: forall E1 E2 T E, WFS (E1 ++ E2) T -> WFS (E1 ++ E ++ E2) T. Proof with auto. intros. generalize dependent E. dependent induction H;intros... - apply WFS_rec with (L:=L);intros... + rewrite_alist (([(X, bind_sub)] ++ E1) ++ E ++ E2). apply H0... + rewrite_alist (([(X, bind_sub)] ++ E1) ++ E ++ E2). apply H2... Qed. Lemma WFS_type: forall E A, WFS E A -> type A. Proof with auto. intros. induction H... apply type_mu with (L:=L)... Qed. Lemma rcd_transform2:forall A C (X Y :atom), X <> Y -> type C -> (open_tt (subst_tt X C A) (typ_rcd Y (open_tt (subst_tt X C A) Y))) = (subst_tt X C (open_tt A (typ_rcd Y (open_tt A Y)))). Proof with auto. intros. rewrite subst_tt_open_tt... f_equal... simpl... destruct (Y==X)... destruct H... f_equal... rewrite subst_tt_open_tt_var... Qed. Lemma subst_tt_wfs: forall A B E X, WFS E A -> WFS E B -> WFS E (subst_tt X A B). Proof with auto. intros. generalize dependent A. dependent induction H0;intros;simpl in *... - destruct (X0==X)... - apply WFS_rec with (L:=L \u {{X}} \u fv_tt A0);intros... + rewrite rcd_transform2... apply H0... rewrite_alist (nil ++ [(X0, bind_sub)] ++ E). apply WFS_weakening... apply WFS_type in H3... + rewrite subst_tt_open_tt_var... apply H2... rewrite_alist (nil ++ [(X0, bind_sub)] ++ E). apply WFS_weakening... apply WFS_type in H3... Qed. Lemma wf_to_wfs: forall E A, WF E A -> WFS E A. Proof with auto. intros. induction H... apply WFS_rec with (L:=L \u fv_tt A)... intros. rewrite subst_tt_intro with (X:=X)... apply subst_tt_wfs... Qed. Lemma sub_regular : forall E A B, sub E A B -> WF E A /\ WF E B /\ wf_env E. Proof with auto. intros. dependent induction H;try solve [destruct_hypos;repeat split;auto]... split. apply WF_rec with (L:=L)... intros. apply H0 in H3. destruct_hypos... split. apply WF_rec with (L:=L)... intros. apply H0 in H3. destruct_hypos... pick fresh X. specialize_x_and_L X L. destruct_hypos. inversion H4... Qed. Lemma Sub_regular : forall E A B, Sub E A B -> WFS E A /\ WFS E B /\ wf_env E. Proof with auto. intros. dependent induction H;try solve [destruct_hypos;repeat split;auto]... split. apply WFS_rec with (L:=L);intros... eapply H2... split. apply WFS_rec with (L:=L);intros... eapply H2... pick fresh X. specialize_x_and_L X L. destruct_hypos. inversion H4... Qed. Lemma WF_subst_rcd: forall E A, WF E A -> forall X B, type B -> WF E (subst_tt X (typ_rcd X B) A) -> WF E (subst_tt X B A). Proof with auto. intros E A H. induction H;intros;simpl in *... - destruct (X==X0)... inversion H1... - dependent destruction H2... - dependent destruction H2... - dependent destruction H2... apply WF_rec with (L:=L \u L0 \u fv_tt A \u fv_tt B \u {{X}}). intros. rewrite subst_tt_open_tt_var... apply H0... rewrite <- subst_tt_open_tt_var... apply H2... Qed. Lemma open_var_distinct : forall C i j A B , i <> j -> type A -> type B -> open_tt_rec i A (open_tt_rec j B C) = open_tt_rec j B (open_tt_rec i A C). Proof with congruence || eauto. intros C. induction C;intros;simpl;try solve [f_equal;eauto]... - destruct (j==n)... destruct (i==n)... subst... simpl... destruct (n==n)... rewrite <- open_tt_rec_type... destruct (i==n)... simpl... destruct (i==n)... rewrite <- open_tt_rec_type... simpl... destruct (i==n)... destruct (j==n)... Qed. Lemma notin_fv_tt_open_tt_rec : forall T X U n, X `notin` fv_tt T -> X \notin fv_tt U -> X `notin` fv_tt (open_tt_rec n U T). Proof with auto. induction T;intros;simpl in *;intros... destruct (n0==n)... Qed. Lemma subst_var_false: forall A X E C, sub E (subst_tt X (typ_rcd X C) A) X -> False. Proof with auto. induction A;intros;simpl in H;try solve [inversion H]... destruct (a==X);subst... inversion H... inversion H... Qed. Lemma sub_subst_rcd_dismiss: forall E E1 A B X C D, sub (E1++[(X, bind_sub)] ++ E) (subst_tt X (typ_rcd X C) A) (subst_tt X (typ_rcd X D) B) -> type C -> type D -> WF (E1 ++ [(X, bind_sub)] ++ E) A -> WF (E1 ++ [(X, bind_sub)] ++ E) B -> sub (E1++[(X, bind_sub)] ++ E) A B. Proof with auto. intros. dependent induction H... - induction A;simpl in *;try solve [inversion x|inversion x0]... induction B;simpl in *;try solve [inversion x|inversion x0]... destruct (a==X);simpl in *;try solve [inversion x]... destruct (a==X);simpl in *;try solve [inversion x0]... - induction A;simpl in *;try solve [inversion x|inversion x0]... destruct (a==X);simpl in *;try solve [inversion x0]... induction B;simpl in *;try solve [inversion x|inversion x0]... destruct (a0==X);simpl in *;try solve [inversion x]... rewrite <- x. rewrite <- x0... - induction B;simpl in *;try solve [inversion x|inversion x0]... destruct (a==X);simpl in *;try solve [inversion x]... - induction A;simpl in *;try solve [inversion x|inversion x0]... destruct (a==X);simpl in *;try solve [inversion x0]... induction B;simpl in *;try solve [inversion x|inversion x0]... destruct (a==X);simpl in *;try solve [inversion x]... clear IHA1 IHA2 IHB1 IHB2. inversion x;inversion x0;clear x x0. dependent destruction H3. dependent destruction H4. constructor... apply IHsub1 with (C:=D) (D:=C)... apply IHsub2 with (C:=C) (D:=D)... - induction A;simpl in *;try solve [inversion x|inversion x0]... destruct (a==X);simpl in *;try solve [inversion x0]... induction B;simpl in *;try solve [inversion x|inversion x0]... destruct (a==X);simpl in *;try solve [inversion x]... clear IHA IHB. inversion x;inversion x0;clear x x0. dependent destruction H5. dependent destruction H6. apply Sa_rec with (L:=L \u {{X}} \u L0 \u L1 \u fv_tt A \u fv_tt B \u fv_tt C \u fv_tt D);intros... + rewrite_alist (([(X0, bind_sub)] ++ E1) ++ (X, bind_sub) :: E). apply H0 with (X0:=X0) (C:=C) (D:=D)... * rewrite H9. rewrite subst_tt_open_tt_var... * rewrite H8. rewrite subst_tt_open_tt_var... * rewrite_alist ([(X0, bind_sub)] ++ E1 ++ (X, bind_sub) :: E)... * rewrite_alist ([(X0, bind_sub)] ++ E1 ++ (X, bind_sub) :: E)... + rewrite_alist (([(X0, bind_sub)] ++ E1) ++ (X, bind_sub) :: E). apply H2 with (X0:=X0) (C:=C) (D:=D)... * rewrite H9. rewrite subst_tt_open_tt_var... rewrite <- subst_tt_open_tt... * rewrite H8. rewrite subst_tt_open_tt_var... rewrite <- subst_tt_open_tt... * rewrite subst_tt_intro with (X:=X0)... rewrite_alist ([(X0, bind_sub)] ++ E1 ++ (X, bind_sub) :: E). apply subst_tt_wf... * rewrite subst_tt_intro with (X:=X0)... rewrite_alist ([(X0, bind_sub)] ++ E1 ++ (X, bind_sub) :: E). apply subst_tt_wf... - induction A;simpl in *;try solve [inversion x|inversion x0]... destruct (a==X);simpl in *;try solve [inversion x0]... + induction B;simpl in *;try solve [inversion x|inversion x0]... destruct (a0==X);simpl in *;try solve [inversion x]... * subst. constructor... apply sub_regular in H0... destruct_hypos... * clear IHB1 IHB2. inversion x0;inversion x;clear x x0. subst. apply subst_var_false in H1... destruct H1. + induction B;simpl in *;try solve [inversion x|inversion x0]... destruct (a==X);simpl in *;try solve [inversion x]... * clear IHA1 IHA2. inversion x0;inversion x;clear x x0. subst. apply subst_var_false in H0... destruct H0. * clear IHA1 IHA2 IHB1 IHB2. inversion x0;inversion x;clear x x0. dependent destruction H4. dependent destruction H5. constructor... apply IHsub1 with (C:=C) (D:=D)... apply IHsub2 with (C:=C) (D:=D)... apply IHsub3 with (C:=D) (D:=C)... Qed. Lemma sub_subst_rcd: forall E A B, sub E A B -> forall X C D, sub E (subst_tt X (typ_rcd X C) A) (subst_tt X (typ_rcd X D) B) -> type C -> type D -> sub E (subst_tt X C A) (subst_tt X D B). Proof with auto. intros E A B H. induction H;intros... - simpl in *. destruct (X==X0)... dependent destruction H1... - simpl in *. constructor... apply sub_regular in H1. destruct_hypos. apply WF_subst_rcd... - simpl in *... dependent destruction H1... - simpl in *. dependent destruction H3... apply Sa_rec with (L:=L \u L0 \u {{X}} \u fv_tt A1 \u fv_tt A2);intros. + rewrite subst_tt_open_tt_var... rewrite subst_tt_open_tt_var... apply H0... rewrite <- subst_tt_open_tt_var... rewrite <- subst_tt_open_tt_var... apply H3... + rewrite subst_tt_open_tt_var... rewrite subst_tt_open_tt_var... rewrite <- subst_tt_open_tt... rewrite <- subst_tt_open_tt... apply H2... rewrite subst_tt_open_tt... rewrite <- subst_tt_open_tt_var... rewrite subst_tt_open_tt... rewrite <- subst_tt_open_tt_var... apply H4... - simpl in *... dependent destruction H2... Qed. Lemma rcd_transform: forall A B (X Y :atom), X <> Y -> type B -> type (open_tt A Y) -> subst_tt X (typ_rcd X B) (open_tt A (typ_rcd Y (open_tt A Y))) = open_tt (subst_tt X (typ_rcd X B) A) (typ_rcd Y (open_tt (subst_tt X (typ_rcd X B) A) Y)). Proof with auto. intros. rewrite subst_tt_open_tt... f_equal... simpl... destruct (Y==X)... destruct H... f_equal... rewrite subst_tt_open_tt... f_equal... rewrite <- subst_tt_fresh... Qed. Lemma Sub_subst_rcd: forall E A B, Sub E A B -> forall X C D, Sub E (subst_tt X C A) (subst_tt X D B) -> WFS E C -> WFS E D -> WFS E X -> Sub E (subst_tt X (typ_rcd X C) A) (subst_tt X (typ_rcd X D) B). Proof with auto. intros E A B H. induction H;intros... - simpl in *. destruct (X==X0);subst... - simpl in *. constructor... apply subst_tt_wfs... - simpl in *... dependent destruction H1... - simpl in *. dependent destruction H3... apply S_rec with (L:=L \u L0 \u {{X}} \u fv_tt A1 \u fv_tt A2);intros. + rewrite subst_tt_open_tt_var... apply subst_tt_wfs... constructor. rewrite_alist (nil ++ [(X0, bind_sub)] ++ E). apply WFS_weakening... rewrite_alist (nil ++ [(X0, bind_sub)] ++ E). apply WFS_weakening... apply H... constructor... apply WFS_type in H6... + rewrite subst_tt_open_tt_var... apply subst_tt_wfs... constructor. rewrite_alist (nil ++ [(X0, bind_sub)] ++ E). apply WFS_weakening... rewrite_alist (nil ++ [(X0, bind_sub)] ++ E). apply WFS_weakening... apply H0... constructor... apply WFS_type in H7... + assert (type C) by (apply WFS_type in H6;auto)... assert (type D) by (apply WFS_type in H7;auto)... rewrite <- rcd_transform... rewrite <- rcd_transform... apply H2... rewrite <- rcd_transform2... rewrite <- rcd_transform2... apply H5... rewrite_alist (nil ++ [(X0, bind_sub)] ++ E). apply WFS_weakening... rewrite_alist (nil ++ [(X0, bind_sub)] ++ E). apply WFS_weakening... rewrite_alist (nil ++ [(X0, bind_sub)] ++ E). apply WFS_weakening... specialize_x_and_L X0 L. apply WFS_type in H0... specialize_x_and_L X0 L. apply WFS_type in H... - simpl in *... dependent destruction H2... Qed. Lemma sub_to_Sub: forall E A B, sub E A B -> Sub E A B. Proof with auto. intros. induction H;try solve [constructor;auto;apply wf_to_wfs;auto]... apply S_rec with (L:=L \u fv_tt A1 \u fv_tt A2);intros... - specialize_x_and_L X L. apply Sub_regular in H0. destruct_hypos... - specialize_x_and_L X L. apply Sub_regular in H0. destruct_hypos... - rewrite subst_tt_intro with (X:=X)... remember (subst_tt X (typ_rcd X (open_tt A1 X)) (open_tt A1 X)). rewrite subst_tt_intro with (X:=X)... subst. apply Sub_subst_rcd... rewrite <- subst_tt_intro... rewrite <- subst_tt_intro... specialize_x_and_L X L. apply Sub_regular in H0. destruct_hypos... specialize_x_and_L X L. apply Sub_regular in H0. destruct_hypos... Qed. Lemma open_twice_to_once: forall E1 E2 X A1 A2, sub (E1 ++ [(X, bind_sub)] ++ E2) (open_tt A1 (typ_rcd X (open_tt A1 X))) (open_tt A2 (typ_rcd X (open_tt A2 X))) -> X \notin fv_tt A1 \u fv_tt A2 -> WF (E1 ++ [(X, bind_sub)] ++ E2) (open_tt A1 X) -> WF (E1 ++ [(X, bind_sub)] ++ E2) (open_tt A2 X) -> sub (E1 ++ [(X, bind_sub)] ++ E2) (open_tt A1 X) (open_tt A2 X). Proof with auto. intros. rewrite subst_tt_intro with (X:=X) in H... remember (subst_tt X (typ_rcd X (open_tt A1 X)) (open_tt A1 X)). rewrite subst_tt_intro with (X:=X) in H... subst. apply sub_subst_rcd_dismiss in H... apply WF_type in H1... apply WF_type in H2... Qed. Lemma Sub_to_sub: forall E A B, Sub E A B -> sub E A B. Proof with auto. intros. induction H;try solve [constructor;auto;apply wfs_to_wf;auto]... apply Sa_rec with (L:=L \u fv_tt A1 \u fv_tt A2);intros... - specialize_x_and_L X L. rewrite_alist (nil ++ [(X, bind_sub)] ++ E) in H2. apply open_twice_to_once in H2... apply wfs_to_wf in H... apply wfs_to_wf in H0... - assert (Hq:=H2). specialize_x_and_L X L. rewrite_alist (nil ++ [(X, bind_sub)] ++ E) in H2. apply open_twice_to_once in H2... apply sub_subst_rcd with (X:=X) (C:=open_tt A1 X) (D:=open_tt A2 X) in H2... rewrite <- subst_tt_intro in H2... rewrite <- subst_tt_intro in H2... rewrite <- subst_tt_intro... rewrite <- subst_tt_intro... apply WFS_type in H... apply WFS_type in H0... apply wfs_to_wf in H... apply wfs_to_wf in H0... Qed. End Anchor. (* ========================================================== *) (* ========================================================== *) (* ========================================================== *) (* ========================================================== *) (* ========================================================== *) (* ========================================================== *) (* ========================================================== *) (* ========================================================== *) (* ========================================================== *) (* ========================================================== *) (* ========================================================== *) Fixpoint upcast (A:typ) : Anchor.typ := match A with | typ_nat => Anchor.typ_nat | typ_top => Anchor.typ_top | typ_fvar x => Anchor.typ_fvar x | typ_bvar b => Anchor.typ_bvar b | typ_arrow s t => Anchor.typ_arrow (upcast s) (upcast t) | typ_mu s => Anchor.typ_mu (upcast s) end. Fixpoint upcast_env (E:env) : Anchor.env := match E with | nil => nil | (x,bind_sub)::E' => (x,Anchor.bind_sub)::(upcast_env E') | (x,bind_typ _)::E' => (x,Anchor.bind_sub)::(upcast_env E') end. Lemma notin_dom_upcast: forall E a, a `notin` dom E -> a `notin` dom (upcast_env E). Proof with auto. induction E;intros... destruct a. simpl in *. destruct b... Qed. Lemma In_upcast:forall E X, In (X, bind_sub) E -> In (X, Anchor.bind_sub) (upcast_env E). Proof with auto. induction E;intros... destruct a... simpl in *... destruct H... inversion H. apply in_eq... destruct b... apply in_cons... apply in_cons... Qed. Lemma upcast_open : forall A B, upcast (open_tt A B) = Anchor.open_tt (upcast A) (upcast B). Proof with auto. intros. unfold open_tt. unfold Anchor.open_tt. generalize 0. generalize dependent B. induction A;intros;simpl;try solve [f_equal;auto]... - destruct (n0==n);simpl... Qed. Lemma upcast_open_var : forall A (X:atom), upcast (open_tt A X) = Anchor.open_tt (upcast A) (Anchor.typ_fvar X). Proof with auto. intros. rewrite upcast_open... Qed. Lemma WF_upcast : forall E A, WF E A -> Anchor.WF (upcast_env E) (upcast A). Proof with auto. intros. induction H;simpl in *... - constructor... unfold binds in *. apply In_upcast... - apply Anchor.WF_rec with (L:=L \u Anchor.fv_tt (upcast A));intros... specialize_x_and_L X L. rewrite upcast_open in H0... Qed. Lemma wf_env_upcast : forall E, wf_env E -> Anchor.wf_env (upcast_env E). Proof with auto using notin_dom_upcast. intros. induction E;simpl... constructor... destruct a. dependent destruction H. constructor... constructor... Qed. Lemma double_unfolding_upcast : forall E A B, sub E A B -> Anchor.sub (upcast_env E) (upcast A) (upcast B). Proof with auto using wf_env_upcast, WF_upcast. intros. induction H;simpl... - constructor... constructor... unfold binds in *. apply In_upcast... - apply Anchor.Sa_rec with (L:=L \u Anchor.fv_tt (upcast A1) \u Anchor.fv_tt (upcast A2));intros... + rewrite <- upcast_open_var... rewrite <- upcast_open_var... apply H0... + rewrite <- upcast_open_var... rewrite <- upcast_open_var... rewrite <- upcast_open... rewrite <- upcast_open... apply H2... Qed. Lemma double_unfolding_to_Anchor_unfolding : forall E A B, sub E A B -> Anchor.Sub (upcast_env E) (upcast A) (upcast B). Proof with auto. intros. apply double_unfolding_upcast in H. apply Anchor.sub_to_Sub... Qed. Fixpoint erase (A:Anchor.typ) : typ := match A with | Anchor.typ_nat => typ_nat | Anchor.typ_top => typ_top | Anchor.typ_fvar x => typ_fvar x | Anchor.typ_bvar b => typ_bvar b | Anchor.typ_arrow s t => typ_arrow (erase s) (erase t) | Anchor.typ_mu s => typ_mu (erase s) | Anchor.typ_rcd l t => erase t end. Fixpoint erase_env (E:Anchor.env) : env := match E with | nil => nil | (x,Anchor.bind_sub)::E' => (x,bind_sub)::(erase_env E') end. Lemma notin_dom_downcast: forall E a, a `notin` dom E -> a `notin` dom (erase_env E). Proof with auto. induction E;intros... destruct a. simpl in *. destruct b... Qed. Lemma In_downcast:forall E X, In (X, Anchor.bind_sub) E -> In (X, bind_sub) (erase_env E). Proof with auto. induction E;intros... destruct a... simpl in *... destruct H... inversion H. apply in_eq... destruct b... apply in_cons... Qed. Lemma downcast_open : forall A B, erase (Anchor.open_tt A B) = open_tt (erase A) (erase B). Proof with auto. intros. unfold open_tt. unfold Anchor.open_tt. generalize 0. generalize dependent B. induction A;intros;simpl;try solve [f_equal;auto]... - destruct (n0==n);simpl... Qed. Lemma downcast_open_var : forall A (X:atom), erase (Anchor.open_tt A (Anchor.typ_fvar X)) = open_tt (erase A) X. Proof with auto. intros. rewrite downcast_open... Qed. Lemma WF_downcast : forall E A, Anchor.WF E A -> WF (erase_env E) (erase A). Proof with auto. intros. induction H;simpl in *... - constructor... unfold binds in *. apply In_downcast... - apply WF_rec with (L:=L \u fv_tt (erase A));intros... specialize_x_and_L X L. rewrite downcast_open in H0... specialize_x_and_L X L. rewrite downcast_open in H0... rewrite subst_tt_intro with (X:=X)... apply subst_tt_wf... Qed. Lemma wf_env_downcast : forall E, Anchor.wf_env E -> wf_env (erase_env E). Proof with auto using notin_dom_downcast. intros. induction E;simpl... destruct a. dependent destruction H. constructor... Qed. Lemma double_unfolding_downcast : forall E A B, Anchor.sub E A B -> sub (erase_env E) (erase A) (erase B). Proof with auto using wf_env_downcast, WF_downcast. intros. induction H;simpl... - constructor... dependent destruction H0. unfold binds in *. apply In_downcast... - apply sa_rec with (L:=L \u fv_tt (erase A1) \u fv_tt (erase A2));intros... + rewrite <- downcast_open_var... rewrite <- downcast_open_var... apply H0... + rewrite <- downcast_open_var... rewrite <- downcast_open_var... rewrite <- downcast_open... rewrite <- downcast_open... apply H2... Qed. Lemma Anchor_unfolding_to_double_unfolding: forall E A B, Anchor.Sub E A B -> sub (erase_env E) (erase A) (erase B). Proof with auto. intros. apply double_unfolding_downcast... apply Anchor.Sub_to_sub... Qed.
module Elem where open import Prelude open import Star Elem : {X : Set}(R : Rel X) -> Rel X Elem R x y = Star (LeqBool [×] R) (false , x) (true , y)
Formal statement is: lemma islimpt_eq_acc_point: fixes l :: "'a :: t1_space" shows "l islimpt S \<longleftrightarrow> (\<forall>U. l\<in>U \<longrightarrow> open U \<longrightarrow> infinite (U \<inter> S))" Informal statement is: A point $l$ is a limit point of a set $S$ if and only if every open neighborhood of $l$ contains infinitely many points of $S$.
[STATEMENT] lemma listrel_rtrancl_refl[iff]: "(xs,xs) \<in> listrel(r\<^sup>*)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (xs, xs) \<in> listrel (r\<^sup>*) [PROOF STEP] using listrel_refl_on[of UNIV, OF refl_rtrancl] [PROOF STATE] proof (prove) using this: refl_on (lists UNIV) (listrel (?r2\<^sup>*)) goal (1 subgoal): 1. (xs, xs) \<in> listrel (r\<^sup>*) [PROOF STEP] by(auto simp: refl_on_def)
/** * @file bblas_cutil.c * * @brief BBLAS testing utilities for float _Complex routines. * * BBLAS is a software package provided by Univ. of Manchester, * Univ. of Tennessee. * * @version 1.0.0 * @author Samuel D. Relton * @author Pedro V. Lara * @author Mawussi Zounon * @date 2016-02-20 * * Contains routines used in the testing to modify randomly generated matrices * and compute the average error over an entire batch etc. * **/ #ifndef DOXYGEN_SHOULD_SKIP_THIS /** * Code generation * @generated from bblas_zutil.c normal z -> c, Mon Jun 6 09:44:14 2016 **/ #endif #include "bblas_common.h" #if defined(BBLAS_WITH_MKL) #include <mkl_lapacke.h> #else #include <lapacke.h> #endif /** Include complex functions since using float complex precision **/ #define COMPLEX /** Quick access to the matrix elements **/ #define A(i,j) A[i + j*lda] /** * Make a matrix symmetric/Hermitian. Makes diagonal real. * Sets Aji = conj( Aij ) for j < i, that is, copy & conjugate * lower triangle to upper triangle. **/ void bblas_cmake_hermitian(int lda, int N, BBLAS_Complex32_t* A) { int i, j; for( i=0; i < N; ++i ) { A(i,i) = creal( A(i,i) ); for( j=0; j < i; ++j ) { A(j,i) = conj( A(i,j) ); } } } #ifdef COMPLEX /** * Make a matrix complex-symmetric * Does NOT make diagonal real. * Sets Aji = Aij for j < i, that is, * copy lower triangle to upper triangle. **/ void bblas_cmake_symmetric(int lda, int N, BBLAS_Complex32_t* A) { int i, j; for( i=0; i < N; ++i ) { for( j=0; j < i; ++j ) { A(j,i) = A(i,j); } } } #endif /** * irandRange generates a random value (int) * in the range min_n and max_n **/ int irandRange(int min_n, int max_n) { return rand() % (max_n - min_n + 1) + min_n; } /** * bblas_crandRange generates a random value (BBLAS_Complex32_t) * in the range [0,max_n]: TODO replace by generic */ BBLAS_Complex32_t bblas_crandRange( int max_n ) { return ( BBLAS_Complex32_t )rand()/( BBLAS_Complex32_t )( RAND_MAX/max_n ); } /** * Computes statistics of the relative errors to summarise them for the user. **/ void bblas_cstatistic(bblas_ctest_t *test) { enum BBLAS_ROUTINE routine = test->routine; /*Compute avg(M), avg(N), avg(K) */ if(test->batch_opts == BBLAS_VARIABLE) { if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { test->avgM = bblas_avgarrayI(test->M, test->batch_count); } if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYRK) || (routine == BBLAS_HERK) || (routine == BBLAS_SYR2K) || (routine == BBLAS_HER2K)) { test->avgK = bblas_avgarrayI(test->K, test->batch_count); } test->avgN = bblas_avgarrayI(test->N, test->batch_count); } else if (test->batch_opts == BBLAS_FIXED) { if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { test->avgM = test->M[0]; } if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYRK) || (routine == BBLAS_HERK) || (routine == BBLAS_SYR2K) || (routine == BBLAS_HER2K)) { test->avgK = test->K[0]; } test->avgN = test->N[0]; } else { bblas_error("testing_cgemm_batch.c", "wrong batch_opts value"); } /*Statistics on the error */ switch(test->target) { case BBLAS_MKL: test->mkl_min_error = bblas_cminarrayD(test->mkl_error, test->batch_count); test->mkl_avg_error = bblas_cavgarrayD(test->mkl_error, test->batch_count); test->mkl_max_error = bblas_cmaxarrayD(test->mkl_error, test->batch_count); test->mkl_std_error = bblas_cstdarrayD(test->mkl_error, test->batch_count); break; case BBLAS_CUBLAS: case BBLAS_MAGMA: test->device_min_error = bblas_cminarrayD(test->device_error, test->batch_count); test->device_avg_error = bblas_cavgarrayD(test->device_error, test->batch_count); test->device_max_error = bblas_cmaxarrayD(test->device_error, test->batch_count); test->device_std_error = bblas_cstdarrayD(test->device_error, test->batch_count); break; case BBLAS_OTHER: test->other_min_error = bblas_cminarrayD(test->other_error, test->batch_count); test->other_avg_error = bblas_cavgarrayD(test->other_error, test->batch_count); test->other_max_error = bblas_cmaxarrayD(test->other_error, test->batch_count); test->other_std_error = bblas_cstdarrayD(test->other_error, test->batch_count); break; default: printf("In bblas_cstatistic(): Target no defined\n"); exit(EXIT_FAILURE); } } /** * Print a matrix. **/ void bblas_cprintmatrix(BBLAS_Complex32_t *matrix, int row, int col) { /*Local variables */ int i, j; for (i=0; i < row; i++) { printf("\n\n"); for (j=0; j < col; j++) { #ifdef COMPLEX printf("%1.2f + %1.2f\t", creal(matrix[i*col+j]), cimag(matrix[i*col+j])); #else printf("%1.2f",matrix[i*col+j]); #endif } } printf("\n"); } /** * Decide whether a batch is fixed or variable. **/ char* bblas_getoption(enum BBLAS_OPTS opts) { /*Local variable */ char funcname[] = "bblas_getoption"; switch(opts) { case BBLAS_VARIABLE: return "BATCH OPTION: VARIABLE"; break; case BBLAS_FIXED: return "BATCH OPTION: FIXED"; break; default: printf("ERROR in %s, undefined bblas routine name\n",funcname); exit(EXIT_FAILURE); } } /** * Get the name of the current test routine. **/ char* bblas_getroutine(enum BBLAS_ROUTINE routine) { /*Local variable */ char funcname[] = "bblas_getroutine"; switch(routine) { case BBLAS_GEMM: return "CGEMM"; break; case BBLAS_HEMM: return "CHEMM"; break; case BBLAS_HER2K: return "CHER2K"; break; case BBLAS_HERK: return "CHERK"; break; case BBLAS_SYMM: return "CSYMM"; break; case BBLAS_SYR2K: return "CSYR2K"; break; case BBLAS_SYRK: return "CSYRK"; break; case BBLAS_TRMM: return "CTRMM"; break; case BBLAS_TRSM: return "CTRSM"; break; default: printf("ERROR in %s, undefined bblas routine name\n",funcname); exit(EXIT_FAILURE); } } /** * Computes the maximum value of an array of real floats. **/ float bblas_cmaxarrayD(float *myArray, int size) { int iter; float maxValue = myArray[0]; for (iter = 0; iter < size; ++iter) { if ( myArray[iter] > maxValue ) { maxValue = myArray[iter]; } } return maxValue; } /** * Computes the minimum value of an array of real floats. **/ float bblas_cminarrayD(float *myArray, int size) { int iter; float minValue = myArray[0]; for (iter = 0; iter < size; ++iter) { if ( myArray[iter] < minValue ) { minValue = myArray[iter]; } } return minValue; } /** * Computes the mean value of an array of real floats. **/ float bblas_cavgarrayD(float *myArray, int size) { int iter; float avg = 0.; for (iter = 0; iter < size; ++iter) { avg += myArray[iter]; } return avg/size; } /** * Computes the standard deviation of an array of real floats. **/ float bblas_cstdarrayD(float *myArray, int size) { int iter; float avg, sd=0.; avg = bblas_cavgarrayD(myArray, size); for (iter = 0; iter < size; ++iter) { sd += (myArray[iter] -avg)*(myArray[iter] -avg); } return sd/size; } /** * Computes the minimum value of an array of integers. **/ int bblas_minarrayI(int *myArray, int size) { int iter; int minValue = myArray[0]; for (iter = 0; iter < size; ++iter) { if ( myArray[iter] < minValue ) { minValue = myArray[iter]; } } return minValue; } /** * Computes the mean of an array of integers. **/ int bblas_avgarrayI(int *myArray, int size) { int iter; int avg = 0; for (iter = 0; iter < size; ++iter) { avg += myArray[iter]; } return avg/size; } /** * Transform BBLAS enum values for <tt>trans</tt>, <tt>uplo</tt> etc. to human-readable strings. **/ char* bblas_op2char(unsigned int op) { char *opname = (char*)malloc(30*sizeof(char)); switch(op) { case BblasNoTrans: strcpy(opname,"CblasNoTrans"); break; case BblasTrans: strcpy(opname,"CblasTrans"); break; case BblasConjTrans: strcpy(opname,"CblasConjTrans"); break; case BblasLower: strcpy(opname,"CblasLower"); break; case BblasUpper: strcpy(opname,"CblasUpper"); break; case BblasNonUnit: strcpy(opname,"CblasNonUnit"); break; case BblasUnit: strcpy(opname,"CblasUnit"); break; case BblasLeft: strcpy(opname,"CblasLeft"); break; case BblasRight: strcpy(opname,"CblasRight"); break; default: return 0; exit(EXIT_FAILURE); } return opname; } /** * Get the amount of data needed. **/ int bblas_cnbdata(bblas_ctest_t *test) { enum BBLAS_OPTS batch_opts = test->batch_opts; int nb_data; char function_name[NAME_LENGTH] ="bblas_getdatacount"; switch(batch_opts) { case BBLAS_VARIABLE: nb_data = test->batch_count; break; case BBLAS_FIXED: nb_data = 1; break; default: bblas_fatal_error(function_name, "wrong batch_opts value"); } return nb_data; } /** * Inject an error into the computation if this is set in the input file. **/ void bblas_cset_error(bblas_ctest_t *test) { int nb_data = bblas_cnbdata(test); int routine = test->routine; int error_index = irandRange(0, nb_data); if (test->global_error){ test->batch_count = -1; return; } if (test->batch_opts == BBLAS_FIXED) { error_index = 0; } if (test->set_error) { if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) || (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)) { test->M[error_index] = -1; }else if ((routine == BBLAS_SYRK) || (routine == BBLAS_HERK) || (routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K)) { test->K[error_index] = -1; } } } /** * Check whether a computation has passed or failed our accuracy test. * When new_accuracy=1 in the input file this uses an appropriate * forward/backward error bound, * otherwise this looks at the relative error. **/ void bblas_cpassed_failed(bblas_ctest_t *test, float error, char *result, int info) { float eps = LAPACKE_slamch_work('e'); /* Use our new accuracy test based on forward/backward error analysis*/ if (test->new_accuracy) { if( (error > 1) || (info)) { strcpy(result, "FAILED"); }else { strcpy(result, "PASSED"); } }else { /* Use old accuracy test based on the relative error */ if((error > eps*test->tolerance) || (info)) { strcpy(result, "FAILED"); }else { strcpy(result, "PASSED"); } } } /** * Set the batch_count. **/ void bblas_cset_batch_count(bblas_ctest_t *test) { test->batch_count = test->minbatch_count* (test->current_iter+1); } #undef COMPLEX
Goals Against ; GAA = Goals Against Average ; SA = Shots Against ; SV
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.shapes.equalizers /-! # Split coequalizers We define what it means for a triple of morphisms `f g : X ⟶ Y`, `π : Y ⟶ Z` to be a split coequalizer: there is a section `s` of `π` and a section `t` of `g`, which additionally satisfy `t ≫ f = π ≫ s`. In addition, we show that every split coequalizer is a coequalizer (`category_theory.is_split_coequalizer.is_coequalizer`) and absolute (`category_theory.is_split_coequalizer.map`) A pair `f g : X ⟶ Y` has a split coequalizer if there is a `Z` and `π : Y ⟶ Z` making `f,g,π` a split coequalizer. A pair `f g : X ⟶ Y` has a `G`-split coequalizer if `G f, G g` has a split coequalizer. These definitions and constructions are useful in particular for the monadicity theorems. ## TODO Dualise to split equalizers. -/ namespace category_theory universes v v₂ u u₂ variables {C : Type u} [category.{v} C] variables {D : Type u₂} [category.{v} D] variables (G : C ⥤ D) variables {X Y : C} (f g : X ⟶ Y) /-- A split coequalizer diagram consists of morphisms f π X ⇉ Y → Z g satisfying `f ≫ π = g ≫ π` together with morphisms t s X ← Y ← Z satisfying `s ≫ π = 𝟙 Z`, `t ≫ g = 𝟙 Y` and `t ≫ f = π ≫ s`. The name "coequalizer" is appropriate, since any split coequalizer is a coequalizer, see `category_theory.is_split_coequalizer.is_coequalizer`. Split coequalizers are also absolute, since a functor preserves all the structure above. -/ structure is_split_coequalizer {Z : C} (π : Y ⟶ Z) := (right_section : Z ⟶ Y) (left_section : Y ⟶ X) (condition : f ≫ π = g ≫ π) (right_section_π : right_section ≫ π = 𝟙 Z) (left_section_bottom : left_section ≫ g = 𝟙 Y) (left_section_top : left_section ≫ f = π ≫ right_section) instance {X : C} : inhabited (is_split_coequalizer (𝟙 X) (𝟙 X) (𝟙 X)) := ⟨⟨𝟙 _, 𝟙 _, rfl, category.id_comp _, category.id_comp _, rfl⟩⟩ open is_split_coequalizer attribute [reassoc] condition attribute [simp, reassoc] right_section_π left_section_bottom left_section_top variables {f g} /-- Split coequalizers are absolute: they are preserved by any functor. -/ @[simps] def is_split_coequalizer.map {Z : C} {π : Y ⟶ Z} (q : is_split_coequalizer f g π) (F : C ⥤ D) : is_split_coequalizer (F.map f) (F.map g) (F.map π) := { right_section := F.map q.right_section, left_section := F.map q.left_section, condition := by rw [←F.map_comp, q.condition, F.map_comp], right_section_π := by rw [←F.map_comp, q.right_section_π, F.map_id], left_section_bottom := by rw [←F.map_comp, q.left_section_bottom, F.map_id], left_section_top := by rw [←F.map_comp, q.left_section_top, F.map_comp] } section open limits /-- A split coequalizer clearly induces a cofork. -/ @[simps X] def is_split_coequalizer.as_cofork {Z : C} {h : Y ⟶ Z} (t : is_split_coequalizer f g h) : cofork f g := cofork.of_π h t.condition @[simp] lemma is_split_coequalizer.as_cofork_π {Z : C} {h : Y ⟶ Z} (t : is_split_coequalizer f g h) : t.as_cofork.π = h := rfl /-- The cofork induced by a split coequalizer is a coequalizer, justifying the name. In some cases it is more convenient to show a given cofork is a coequalizer by showing it is split. -/ def is_split_coequalizer.is_coequalizer {Z : C} {h : Y ⟶ Z} (t : is_split_coequalizer f g h) : is_colimit t.as_cofork := cofork.is_colimit.mk' _ $ λ s, ⟨t.right_section ≫ s.π, by { dsimp, rw [← t.left_section_top_assoc, s.condition, t.left_section_bottom_assoc] }, λ m hm, by { simp [←hm] }⟩ end variables (f g) /-- The pair `f,g` is a split pair if there is a `h : Y ⟶ Z` so that `f, g, h` forms a split coequalizer in `C`. -/ class has_split_coequalizer : Prop := (splittable [] : ∃ {Z : C} (h : Y ⟶ Z), nonempty (is_split_coequalizer f g h)) /-- The pair `f,g` is a `G`-split pair if there is a `h : G Y ⟶ Z` so that `G f, G g, h` forms a split coequalizer in `D`. -/ abbreviation functor.is_split_pair : Prop := has_split_coequalizer (G.map f) (G.map g) /-- Get the coequalizer object from the typeclass `is_split_pair`. -/ noncomputable def has_split_coequalizer.coequalizer_of_split [has_split_coequalizer f g] : C := (has_split_coequalizer.splittable f g).some /-- Get the coequalizer morphism from the typeclass `is_split_pair`. -/ noncomputable def has_split_coequalizer.coequalizer_π [has_split_coequalizer f g] : Y ⟶ has_split_coequalizer.coequalizer_of_split f g := (has_split_coequalizer.splittable f g).some_spec.some /-- The coequalizer morphism `coequalizer_ι` gives a split coequalizer on `f,g`. -/ noncomputable def has_split_coequalizer.is_split_coequalizer [has_split_coequalizer f g] : is_split_coequalizer f g (has_split_coequalizer.coequalizer_π f g) := classical.choice (has_split_coequalizer.splittable f g).some_spec.some_spec /-- If `f, g` is split, then `G f, G g` is split. -/ instance map_is_split_pair [has_split_coequalizer f g] : has_split_coequalizer (G.map f) (G.map g) := { splittable := ⟨_, _, ⟨is_split_coequalizer.map (has_split_coequalizer.is_split_coequalizer f g) _⟩⟩ } namespace limits /-- If a pair has a split coequalizer, it has a coequalizer. -/ @[priority 1] instance has_coequalizer_of_has_split_coequalizer [has_split_coequalizer f g] : has_coequalizer f g := has_colimit.mk ⟨_, (has_split_coequalizer.is_split_coequalizer f g).is_coequalizer⟩ end limits end category_theory
lemma eventually_subseq: "strict_mono r \<Longrightarrow> eventually P sequentially \<Longrightarrow> eventually (\<lambda>n. P (r n)) sequentially"
module Injective %default total interface Injective (op : t -> t) where inj : (a : t) -> (b : t) -> op a = op b -> a = b inj' : {a : t} -> {b : t} -> op a = op b -> a = b inj' {a} {b} = inj a b Injective S where inj = succInjective
{-# OPTIONS --without-K #-} module PInj where open import Codata.Delay renaming (length to dlength ; map to dmap ) open import Codata.Thunk open import Relation.Binary.PropositionalEquality open import Size open import Level open import Data.Product -- A pair of partial functions that are supposed to form a partial bijection. record _⊢_⇔_ (i : Size) {ℓ : Level} (A : Set ℓ) (B : Set ℓ) : Set ℓ where constructor pre-pinj-i field forward : A -> Delay B i backward : B -> Delay A i open _⊢_⇔_
[STATEMENT] lemma inR1': "\<Gamma> \<Rightarrow> G, H, \<Delta> \<down> n \<Longrightarrow> \<Gamma> \<Rightarrow> H, G, \<Delta> \<down> n" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<Gamma> \<Rightarrow> G, H, \<Delta> \<down> n \<Longrightarrow> \<Gamma> \<Rightarrow> H, G, \<Delta> \<down> n [PROOF STEP] by(simp add: add_mset_commute)
#include "stdafx.h" #include <boost/test/unit_test.hpp> #include "FileReaderModule.h" #include "ExternalSinkModule.h" #include "FrameMetadata.h" #include "FrameMetadataFactory.h" #include "Frame.h" #include "Logger.h" #include "AIPExceptions.h" #include "CudaMemCopy.h" #include "ResizeNPPI.h" #include "test_utils.h" BOOST_AUTO_TEST_SUITE(resizenppi_tests) BOOST_AUTO_TEST_CASE(mono_1920x1080) { auto width = 1920; auto height = 1080; auto fileReader = boost::shared_ptr<FileReaderModule>(new FileReaderModule(FileReaderModuleProps("./data/mono_1920x1080.raw"))); auto metadata = framemetadata_sp(new RawImageMetadata(width, height, ImageMetadata::ImageType::MONO, CV_8UC1, 0, CV_8U, FrameMetadata::HOST, true)); auto rawImagePin = fileReader->addOutputPin(metadata); auto stream = cudastream_sp(new ApraCudaStream); auto copy1 = boost::shared_ptr<Module>(new CudaMemCopy(CudaMemCopyProps(cudaMemcpyHostToDevice, stream))); fileReader->setNext(copy1); auto m2 = boost::shared_ptr<Module>(new ResizeNPPI(ResizeNPPIProps(width >> 1, height >> 1, stream))); copy1->setNext(m2); auto copy2 = boost::shared_ptr<Module>(new CudaMemCopy(CudaMemCopyProps(cudaMemcpyDeviceToHost, stream))); m2->setNext(copy2); auto outputPinId = copy2->getAllOutputPinsByType(FrameMetadata::RAW_IMAGE)[0]; auto m3 = boost::shared_ptr<ExternalSinkModule>(new ExternalSinkModule()); copy2->setNext(m3); BOOST_TEST(fileReader->init()); BOOST_TEST(copy1->init()); BOOST_TEST(m2->init()); BOOST_TEST(copy2->init()); BOOST_TEST(m3->init()); fileReader->step(); copy1->step(); m2->step(); copy2->step(); auto frames = m3->pop(); BOOST_TEST((frames.find(outputPinId) != frames.end())); auto outFrame = frames[outputPinId]; BOOST_TEST(outFrame->getMetadata()->getFrameType() == FrameMetadata::RAW_IMAGE); Test_Utils::saveOrCompare("./data/testOutput/resizenppi_tests_mono_1920x1080_to_960x540.raw", (const uint8_t *)outFrame->data(), outFrame->size(), 0); } BOOST_AUTO_TEST_CASE(overlay_1920x960_BGRA) { auto width = 1920; auto height = 960; auto fileReader = boost::shared_ptr<FileReaderModule>(new FileReaderModule(FileReaderModuleProps("./data/overlay_1920x960_BGRA.raw"))); auto metadata = framemetadata_sp(new RawImageMetadata(width, height, ImageMetadata::ImageType::BGRA, CV_8UC4, 0, CV_8U, FrameMetadata::HOST, true)); auto rawImagePin = fileReader->addOutputPin(metadata); auto stream = cudastream_sp(new ApraCudaStream); auto copy1 = boost::shared_ptr<Module>(new CudaMemCopy(CudaMemCopyProps(cudaMemcpyHostToDevice, stream))); fileReader->setNext(copy1); auto m2 = boost::shared_ptr<Module>(new ResizeNPPI(ResizeNPPIProps(width >> 1, height >> 1, stream))); copy1->setNext(m2); auto copy2 = boost::shared_ptr<Module>(new CudaMemCopy(CudaMemCopyProps(cudaMemcpyDeviceToHost, stream))); m2->setNext(copy2); auto outputPinId = copy2->getAllOutputPinsByType(FrameMetadata::RAW_IMAGE)[0]; auto m3 = boost::shared_ptr<ExternalSinkModule>(new ExternalSinkModule()); copy2->setNext(m3); BOOST_TEST(fileReader->init()); BOOST_TEST(copy1->init()); BOOST_TEST(m2->init()); BOOST_TEST(copy2->init()); BOOST_TEST(m3->init()); fileReader->step(); copy1->step(); m2->step(); copy2->step(); auto frames = m3->pop(); BOOST_TEST((frames.find(outputPinId) != frames.end())); auto outFrame = frames[outputPinId]; BOOST_TEST(outFrame->getMetadata()->getFrameType() == FrameMetadata::RAW_IMAGE); Test_Utils::saveOrCompare("./data/testOutput/resizenppi_tests_overlay_1920x960_BGRA_to_960x480_C4.raw", (const uint8_t *)outFrame->data(), outFrame->size(), 0); } BOOST_AUTO_TEST_CASE(yuv420_640x360) { // metadata is known auto width = 640; auto height = 360; auto fileReader = boost::shared_ptr<FileReaderModule>(new FileReaderModule(FileReaderModuleProps("./data/yuv420_640x360.raw"))); auto metadata = framemetadata_sp(new RawImagePlanarMetadata(width, height, ImageMetadata::ImageType::YUV420, size_t(0), CV_8U)); auto rawImagePin = fileReader->addOutputPin(metadata); auto stream = cudastream_sp(new ApraCudaStream); auto copy1 = boost::shared_ptr<Module>(new CudaMemCopy(CudaMemCopyProps(cudaMemcpyHostToDevice, stream))); fileReader->setNext(copy1); auto m2 = boost::shared_ptr<Module>(new ResizeNPPI(ResizeNPPIProps(width >> 1, height >> 1, stream))); copy1->setNext(m2); auto copy2 = boost::shared_ptr<Module>(new CudaMemCopy(CudaMemCopyProps(cudaMemcpyDeviceToHost, stream))); m2->setNext(copy2); auto outputPinId = copy2->getAllOutputPinsByType(FrameMetadata::RAW_IMAGE_PLANAR)[0]; auto m3 = boost::shared_ptr<ExternalSinkModule>(new ExternalSinkModule()); copy2->setNext(m3); BOOST_TEST(fileReader->init()); BOOST_TEST(copy1->init()); BOOST_TEST(m2->init()); BOOST_TEST(copy2->init()); BOOST_TEST(m3->init()); fileReader->step(); copy1->step(); m2->step(); copy2->step(); auto frames = m3->pop(); BOOST_TEST((frames.find(outputPinId) != frames.end())); auto outFrame = frames[outputPinId]; BOOST_TEST(outFrame->getMetadata()->getFrameType() == FrameMetadata::RAW_IMAGE_PLANAR); Test_Utils::saveOrCompare("./data/testOutput/resizenppi_tests_yuv420_640x360_to_320x180.raw", (const uint8_t *)outFrame->data(), outFrame->size(), 0); } BOOST_AUTO_TEST_CASE(perf, *boost::unit_test::disabled()) { LoggerProps logprops; logprops.logLevel = boost::log::trivial::severity_level::info; Logger::initLogger(logprops); // metadata is known auto width = 3840; auto height = 2160; auto fileReader = boost::shared_ptr<FileReaderModule>(new FileReaderModule(FileReaderModuleProps("./data/4k.yuv"))); auto metadata = framemetadata_sp(new RawImageMetadata(width, height, 1, CV_8UC1, width, CV_8U)); auto rawImagePin = fileReader->addOutputPin(metadata); auto stream = cudastream_sp(new ApraCudaStream); auto copy1 = boost::shared_ptr<Module>(new CudaMemCopy(CudaMemCopyProps(cudaMemcpyHostToDevice, stream))); fileReader->setNext(copy1); auto m2 = boost::shared_ptr<Module>(new ResizeNPPI(ResizeNPPIProps(width >> 1, height >> 1, stream))); copy1->setNext(m2); auto copy2 = boost::shared_ptr<Module>(new CudaMemCopy(CudaMemCopyProps(cudaMemcpyDeviceToHost, stream))); m2->setNext(copy2); auto outputPinId = copy2->getAllOutputPinsByType(FrameMetadata::RAW_IMAGE)[0]; auto m3 = boost::shared_ptr<ExternalSinkModule>(new ExternalSinkModule()); copy2->setNext(m3); BOOST_TEST(fileReader->init()); BOOST_TEST(copy1->init()); BOOST_TEST(m2->init()); BOOST_TEST(copy2->init()); BOOST_TEST(m3->init()); for (auto i = 0; i < 1; i++) { fileReader->step(); copy1->step(); m2->step(); copy2->step(); m3->pop(); } } BOOST_AUTO_TEST_SUITE_END()
<unk> , Eric . Reviewed work : Image and Reality of the Israel @-@ Palestine Conflict by Norman Finkelstein , Journal of Palestine Studies , Vol . 33 , No. 3 , Special Issue in Honor of Edward W. Said . ( Spring , 2004 ) , pp. 123 – 124 .
[STATEMENT] lemma term_subst_eq_rev: "t \<cdot> \<sigma> = t \<cdot> \<tau> \<Longrightarrow> \<forall>x \<in> vars_term t. \<sigma> x = \<tau> x" [PROOF STATE] proof (prove) goal (1 subgoal): 1. t \<cdot> \<sigma> = t \<cdot> \<tau> \<Longrightarrow> \<forall>x\<in>vars_term t. \<sigma> x = \<tau> x [PROOF STEP] by (induct t) simp_all
program main integer :: nx, ny, nz, nsd=3, isd real*4, allocatable :: xyz(:,:,:,:) real*8, allocatable :: xyz2(:,:,:,:) open(10,file='grid.dat',form='unformatted') read(10) nx, ny, nz allocate( xyz(nx,ny,nz,nsd), xyz2(nx,ny,nz,nsd) ) read(10) ((((xyz(i,j,k,isd),i=1,nx),j=1,ny),k=1,nz),isd=1,nsd) close(10) xyz2 = xyz open(10,file='grid.r8',form='unformatted') write(10) nx, ny, nz write(10) ((((xyz2(i,j,k,isd),i=1,nx),j=1,ny),k=1,nz),isd=1,nsd) close(10) end program main
#' ecustools is deprecated! #' #' @name ecustools #' @docType package NULL
[STATEMENT] lemma R_skip: "1 \<le> Ref p p" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (1::'a) \<le> Ref p p [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. (1::'a) \<le> Ref p p [PROOF STEP] have "H p 1 p" [PROOF STATE] proof (prove) goal (1 subgoal): 1. H p (1::'a) p [PROOF STEP] by (simp add: H_skip) [PROOF STATE] proof (state) this: H p (1::'a) p goal (1 subgoal): 1. (1::'a) \<le> Ref p p [PROOF STEP] thus ?thesis [PROOF STATE] proof (prove) using this: H p (1::'a) p goal (1 subgoal): 1. (1::'a) \<le> Ref p p [PROOF STEP] by (rule R2) [PROOF STATE] proof (state) this: (1::'a) \<le> Ref p p goal: No subgoals! [PROOF STEP] qed \<comment> \<open> Abort \<close>
[STATEMENT] lemma qstar_inductr: "z \<squnion> y \<cdot> x \<le> y \<Longrightarrow> z \<cdot> qstar x \<le> y" [PROOF STATE] proof (prove) goal (1 subgoal): 1. z \<squnion> y \<cdot> x \<le> y \<Longrightarrow> z \<cdot> qstar x \<le> y [PROOF STEP] by (subst powers_distl, auto intro!: Sup_least power_inductr)
(* Title: HOL/Auth/n_german_lemma_inv__16_on_rules.thy Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences *) header{*The n_german Protocol Case Study*} theory n_german_lemma_inv__16_on_rules imports n_german_lemma_on_inv__16 begin section{*All lemmas on causal relation between inv__16*} lemma lemma_inv__16_on_rules: assumes b1: "r \<in> rules N" and b2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__16 p__Inv2)" shows "invHoldForRule s f r (invariants N)" proof - have c1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)\<or> (\<exists> i. i\<le>N\<and>r=n_SendReqS i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvReqE N i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendInvAck i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendGntS i)\<or> (\<exists> i. i\<le>N\<and>r=n_SendGntE N i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvGntS i)\<or> (\<exists> i. i\<le>N\<and>r=n_RecvGntE i)" apply (cut_tac b1, auto) done moreover { assume d1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_StoreVsinv__16) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqS i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendReqSVsinv__16) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendReqE__part__0Vsinv__16) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendReqE__part__1Vsinv__16) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvReqSVsinv__16) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvReqEVsinv__16) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendInv__part__0Vsinv__16) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendInv__part__1Vsinv__16) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendInvAckVsinv__16) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvInvAckVsinv__16) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendGntSVsinv__16) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_SendGntEVsinv__16) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvGntSVsinv__16) done } moreover { assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)" have "invHoldForRule s f r (invariants N)" apply (cut_tac b2 d1, metis n_RecvGntEVsinv__16) done } ultimately show "invHoldForRule s f r (invariants N)" by satx qed end
# This file holds the definition of the Retirement type. This type is used to # describe the particulars of retirement due to age/end of career. # The Retirement type requires no additional types. requiredTypes = [ ] for reqType in requiredTypes if !isdefined( Symbol( uppercase( string( reqType[ 1 ] ) ) * reqType[ 2:end ] ) ) include( joinpath( typePath, reqType * ".jl" ) ) end # if !isdefined( Symbol( ... end # for reqType in requiredTypes export Retirement """ This type defines a retirement scheme for mandatory retirement of personnel members based on age or tenure. The type contains the following fields: * `maxCareerLength::Float64`: the maximum length of a personnel member's career. Set this to 0 to ignore this criterion. * `retireAge::Float64`: the mandatory retirement age. Set this to 0 to ignore this criterion. * `retireFreq::Float64`: the length of the time interval between two retirement checks. * `retireOffset::Float64`: the offset of the retirement schedule with respect to the start of the simulation. * 'isEither::Bool': a flag indicating whether either of the criteria (age or tenure) must be satisfied for retirement, or both. """ type Retirement maxCareerLength::Float64 retireAge::Float64 retireFreq::Float64 retireOffset::Float64 isEither::Bool function Retirement( ; freq::T1 = 1.0, offset::T2 = 0.0, maxCareer::T3 = 0.0, retireAge::T4 = 0.0, isEither::Bool = true ) where T1 <: Real where T2 <: Real where T3 <: Real where T4 <: Real if freq <= 0.0 error( "Retirement cycle length must be > 0.0." ) end # if freq < 0.0 if maxCareer < 0.0 error( "Maximal career length must be ⩾ 0.0." ) end # if maxCareer < 0.0 if retireAge < 0.0 error( "Mandatory retirement age must be ⩾ 0.0." ) end # if maxCareer < 0.0 newRet = new() newRet.maxCareerLength = maxCareer newRet.retireAge = retireAge newRet.retireFreq = freq newRet.retireOffset = freq > 0.0 ? ( offset % freq + ( offset < 0.0 ? freq : 0.0 ) ) : 0.0 newRet.isEither = isEither return newRet end # Retirement( freq, offset, maxCareer, retireAge ) end # type Retirement
lemma AE_space: "AE x in M. x \<in> space M"
[STATEMENT] lemma eqButPID_not_PID_sharedWith: "eqButPID s s1 \<Longrightarrow> pid \<noteq> PID \<Longrightarrow> sharedWith s pid = sharedWith s1 pid" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>eqButPID s s1; pid \<noteq> PID\<rbrakk> \<Longrightarrow> sharedWith s pid = sharedWith s1 pid [PROOF STEP] unfolding eqButPID_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>admin s = admin s1 \<and> pendingUReqs s = pendingUReqs s1 \<and> userReq s = userReq s1 \<and> userIDs s = userIDs s1 \<and> user s = user s1 \<and> pass s = pass s1 \<and> pendingFReqs s = pendingFReqs s1 \<and> friendReq s = friendReq s1 \<and> friendIDs s = friendIDs s1 \<and> sentOuterFriendIDs s = sentOuterFriendIDs s1 \<and> recvOuterFriendIDs s = recvOuterFriendIDs s1 \<and> postIDs s = postIDs s1 \<and> admin s = admin s1 \<and> eeqButPID (post s) (post s1) \<and> owner s = owner s1 \<and> vis s = vis s1 \<and> pendingSApiReqs s = pendingSApiReqs s1 \<and> sApiReq s = sApiReq s1 \<and> serverApiIDs s = serverApiIDs s1 \<and> serverPass s = serverPass s1 \<and> outerPostIDs s = outerPostIDs s1 \<and> outerPost s = outerPost s1 \<and> outerOwner s = outerOwner s1 \<and> outerVis s = outerVis s1 \<and> pendingCApiReqs s = pendingCApiReqs s1 \<and> cApiReq s = cApiReq s1 \<and> clientApiIDs s = clientApiIDs s1 \<and> clientPass s = clientPass s1 \<and> eeqButPID_F (sharedWith s) (sharedWith s1); pid \<noteq> PID\<rbrakk> \<Longrightarrow> sharedWith s pid = sharedWith s1 pid [PROOF STEP] using eeqButPID_F_not_PID [PROOF STATE] proof (prove) using this: \<lbrakk>eeqButPID_F ?sw ?sw1.0; ?pid \<noteq> PID\<rbrakk> \<Longrightarrow> ?sw ?pid = ?sw1.0 ?pid goal (1 subgoal): 1. \<lbrakk>admin s = admin s1 \<and> pendingUReqs s = pendingUReqs s1 \<and> userReq s = userReq s1 \<and> userIDs s = userIDs s1 \<and> user s = user s1 \<and> pass s = pass s1 \<and> pendingFReqs s = pendingFReqs s1 \<and> friendReq s = friendReq s1 \<and> friendIDs s = friendIDs s1 \<and> sentOuterFriendIDs s = sentOuterFriendIDs s1 \<and> recvOuterFriendIDs s = recvOuterFriendIDs s1 \<and> postIDs s = postIDs s1 \<and> admin s = admin s1 \<and> eeqButPID (post s) (post s1) \<and> owner s = owner s1 \<and> vis s = vis s1 \<and> pendingSApiReqs s = pendingSApiReqs s1 \<and> sApiReq s = sApiReq s1 \<and> serverApiIDs s = serverApiIDs s1 \<and> serverPass s = serverPass s1 \<and> outerPostIDs s = outerPostIDs s1 \<and> outerPost s = outerPost s1 \<and> outerOwner s = outerOwner s1 \<and> outerVis s = outerVis s1 \<and> pendingCApiReqs s = pendingCApiReqs s1 \<and> cApiReq s = cApiReq s1 \<and> clientApiIDs s = clientApiIDs s1 \<and> clientPass s = clientPass s1 \<and> eeqButPID_F (sharedWith s) (sharedWith s1); pid \<noteq> PID\<rbrakk> \<Longrightarrow> sharedWith s pid = sharedWith s1 pid [PROOF STEP] by auto
Formal statement is: lemma nonneg_incseq_Bseq_subseq_iff: fixes f :: "nat \<Rightarrow> real" and g :: "nat \<Rightarrow> nat" assumes "\<And>x. f x \<ge> 0" "incseq f" "strict_mono g" shows "Bseq (\<lambda>x. f (g x)) \<longleftrightarrow> Bseq f" Informal statement is: If $f$ is a nonnegative increasing sequence, then $f$ is a bounded sequence if and only if the subsequence $f \circ g$ is a bounded sequence.
lemma ZfunD: "Zfun f F \<Longrightarrow> 0 < r \<Longrightarrow> eventually (\<lambda>x. norm (f x) < r) F"
Formal statement is: lemma homotopy_eqv_contractibility: fixes S :: "'a::real_normed_vector set" and T :: "'b::real_normed_vector set" shows "S homotopy_eqv T \<Longrightarrow> (contractible S \<longleftrightarrow> contractible T)" Informal statement is: If two topological spaces are homotopy equivalent, then they are contractible if and only if they are contractible.
import substances math.fuzzy open set topological_space classical set_option pp.generalized_field_notation true local attribute [instance] prop_decidable noncomputable theory -- tentative idea for formalizing ppc via intensional similarities -- in a variant of nuclear trope theory namespace ontology variable {ω : ontology} namespace iontology /-- Intensional similarity relation -/ structure sim (Ω : ω.iontology) := (r : Ω.ientity → Ω.ientity → ω.world → fuzzy) (reflexive : ∀ {e : Ω.ientity} {w}, e.exists w → r e e w = 1) (symmetric : ∀ {e₁ e₂}, r e₁ e₂ = r e₂ e₁) -- I think this follows from the stronger property of transitivity discussed by Zadeh (triangular : ∀ (w) e₁ e₂ e₃, ((r e₁ e₂ w) : ℝ) * (r e₂ e₃ w) ≤ r e₁ e₃ w) (tolerance : fuzzy := 0) -- TODO: prove this as a theorem, follows from triangular inequality -- (subst : ∀ e₁ e₂, r e₁ e₂ = 1 → ∀ e₃, r e₁ e₃ = r e₂ e₃) -- these principles are probably wrong, will think about them later. -- consubstantial entities with the same essence are exactly similar -- (coessence : ∀ e₁ e₂, 0 < r e₁ e₂ → e₁ ≈ e₂ → r e₁ e₂ = 1) -- -- substances do not have the same essence as their accidents -- (essence : ∀ e₁ e₂, 0 < r e₁ e₂ → e₁ ≈ e₂ → e₁ ⇎ e₂ → ¬ e₁.up.compatible e₂) attribute [class] sim attribute [simp, refl] sim.reflexive attribute [simp, symm] sim.symmetric section basic variables {Ω : ω.iontology} [sim : Ω.sim] (e : Ω.ientity) include sim /-- An entity is said to be **wholly dissimilar** to another if their similarity is always 0. -/ def wdiss (e' : Ω.ientity) : Prop := ∀ w, 0 = sim.r e e' w /-- An entity is said to be **similar** to another, if it is not wholly dissimilar to it, i.e. if their similarity is strictly greater than 0. -/ def similar (e' : Ω.ientity) : Prop := ¬ wdiss e e' /-- An entity is said to be **exactly similar** to, or **indiscernible** from, another if their similarity is always 1. -/ def esimilar (e' : Ω.ientity) : Prop := ∀ w, 1 = sim.r e e' w local infixr ` ≅ `:50 := similar local infixr ` ≇ `:50 := wdiss -- TODO: maybe set == notation for esimilar. -- fuzzy needs has_Inf. Will need to migrate to newer -- version of mathlib to make this work properly. /-- Infimum degree of similarity between two entities. Introduced so we can get rid of possible worlds. -/ def ientity.sim (e₁ : Ω.ientity) (e₂ : Ω.ientity) : fuzzy := sorry --Inf $ sim.r e₁ e₂ '' univ -- -- TODO: check later if this is indeed a good definition -- /-- A **bare particular** is an entity wholly dissimilar to any entity distinct from itself. -/ -- def ientity.bare : Prop := ∀ e', e' ≠ e → e' ≇ e -- /-- A **trope like** entity is a non-bare particular which is incompatible with any entity -- distinct, similar and consubstantial to itself. -/ -- def ientity.trope_like : Prop := ¬ e.bare ∧ ∀ e', e' ≠ e → e' ≈ e → e' ≅ e → ¬ e'.up.compatible e -- /-- A **strongly trope like** entity is an entity which is only similar to trope like entities. -/ -- def ientity.strope_like : Prop := ∀ e', e' ≅ e → e'.trope_like -- /-- A **bare like** entity is an entity wholly dissimilar from all trope like entities, -- which is however not necessarily a bare particular. -/ -- def ientity.substratum : Prop := ∀ e' : Ω.ientity, e'.trope_like → e' ≇ e -- substrata in the same nucleus (i.e. equivalent) have the same essence -- def substratum_sim : Prop := ∀ e₁ e₂ : Ω.ientity, e₁.substratum → e₂.substratum → e₁ ≡ e₂ → e₁ ≅ e₂ -- -- whatever -- def sim_closure : Prop := ∀ e₁ e₂ : Ω.ientity, e₁.trope → e₁ ≅ e₂ → e₂.trope -- TODO: we may need a notion of the origin trope being more perfect than -- the caused entity. -- def ppc (c : Ω.ientity → Ω.ientity → ω.event) : Prop := -- ∀ e₁ e₂, ⋄c e₁ e₂ → -- ∃ trope, trope ≈ e₁ ∧ trope ≅ e₂ ∧ trope ≠ e₂ -- ∧ trope.strope_like ∧ c e₁ e₂ ⇒' trope.exists ∧ -- ∀ e₃, c e₃ trope ∩ c e₁ e₂ ⇒ c e₃ e₂ -- needs has_Inf /-- Infimum possible degree of similarity among entities of a set. -/ def inf_sim (C : set Ω.ientity) : fuzzy := sorry --Inf {d : fuzzy | ∃ (w : ω.world) e₁ e₂ ∈ C, sim.r e₁ e₂ w = d} /-- Infimum degree of similarity among entities in a possible world. -/ def sim.inf_sim_at (sim : Ω.sim) (w : ω.world) : fuzzy := sorry --Inf {d : fuzzy | ∃ e₁ e₂ ∈ w, sim.r e₁ e₂ w = d} -- needs has_Sup /-- Supremum possible degree of similarity among entities of a set. -/ def sup_sim (C : set Ω.ientity) : fuzzy := sorry -- Sup {d : fuzzy | ∃ (w : ω.world) e₁ e₂ ∈ C, e₁ ≠ e₂ ∧ sim.r e₁ e₂ w = d} /-- Supremum degree of similarity among distinct entities in a possible world. -/ def sim.sup_sim_at (sim : Ω.sim) (w : ω.world) : fuzzy := sorry -- Sup {d : fuzzy | ∃ e₁ e₂ ∈ w, e₁ ≠ e₂ ∧ sim.r e₁ e₂ w = d} -- needs has_Sup /-- Supremum possible degree of similarity between a set and an entity. -/ def sdsim (e : Ω.ientity) (C : set Ω.ientity) : fuzzy := sorry --Sup {d : fuzzy | ∃ (w : ω.world) e' ∈ C, sim.r e e' w = d} /-- Supremum degree of similarity between an entity and the entities which exist in a possible world. -/ def sdsim_at (e : Ω.ientity) (w : ω.world) : fuzzy := sorry --Sup {d : fuzzy | ∃ e' ∈ w, sim.r e e' w = d} /-- A **resemblance class** is a set of entities which always resemble each other at least as much as they might resemble any entity outside of the set. -/ def rclass (C : set Ω.ientity) : Prop := ∀ e ∈ C, sdsim e (-C) ≤ inf_sim C /-- A **strict resemblance class** is a set of entities which always resemble each other more than they might resemble any entity outside of the set. -/ def srclass (C : set Ω.ientity) : Prop := ∀ e ∈ C, sdsim e (-C) < inf_sim C -- don't know if we will need it. Left incomplete -- /-- A **local resemblance class** is a set of entities which, within some world `w`, -- resemble each other more than they -- resemble, in `w`, any entity outside of the set. -/ -- def lrclass (C : set Ω.ientity) (w : ω.world) : Prop := -- ∀ e ∈ C, sdsim e (-C) ≤ inf_sim C /-- A set of entities is **simply independent** if its distinct elements are pairwise independent, i.e. incomparable. -/ def sindependent (C : set Ω.ientity) : Prop := ∀ e₁ e₂ ∈ C, e₁ ≠ e₂ → e₁ ≢ e₂ /-- A **clique** of degree **d**, or d-clique, is a set of entities which are similar to each other to degree at least **d** in any possible world. -/ def clique (d : fuzzy) (C : set Ω.ientity) : Prop := ∀ (w : ω.world) (e₁ e₂ : Ω.ientity), e₁ ∈ C → e₂ ∈ C → d ≤ sim.r e₁ e₂ w /-- An **existential clique** of degree **d**, or d-eclique, is a set of entities which are similar to each other to degree at least **d** in any possible world in which both exist. Every clique is an existential clique, but the converse need not hold. -/ def eclique (d : fuzzy) (C : set Ω.ientity) : Prop := ∀ (w : ω.world) (e₁ e₂ : Ω.ientity), e₁ ∈ C → e₂ ∈ C → e₁.exists w → e₂.exists w → d ≤ sim.r e₁ e₂ w /-- A **maximum clique** of degree **d**, or d-mclique, is a d-clique which cannot be enlarged. -/ def mclique (d : fuzzy) (C : set Ω.ientity) : Prop := clique d C ∧ ∀ C' : set Ω.ientity, clique d C' → C ⊆ C' → C = C' /-- An **analogical clique** of degree **d**, or d-aclique, is a d-mclique which is also a resemblance class. -/ def aclique (d : fuzzy) (C : set Ω.ientity) : Prop := mclique d C ∧ rclass C /-- A **strict analogical clique** of degree **d**, or d-aclique, is a d-mclique which is also a strict resemblance class. -/ def saclique (d : fuzzy) (C : set Ω.ientity) : Prop := mclique d C ∧ srclass C /-- A **near perfect clique** of degree **d**, or d-npclique, is an infinite d-saclique. -/ def npclique (d : fuzzy) (C : set Ω.ientity) : Prop := set.infinite C ∧ saclique d C /-- An entity is a **trope** if and only if its similarity to any other entities does not vary across time and worlds (beyond the allowed tolerance). -/ def ientity.trope (e : Ω.ientity) : Prop := ∀ e' w w', abs ((sim.r e e' w : ℝ) - sim.r e e' w') ≤ sim.tolerance -- TODO: consider bumping the definition below to full independence -- (lack of entailment between aggregates, lack of generic dependences) later. -- Also consider specifying that the clique should not contain entities from -- different corners of the ontological square. -- These are some of the conditions I term "univocity conditions". -- For now, it won't matter much to produce a very strict definition of univocity -- for perfect cliques. The basic idea of them can be expressed just -- with the following conditions. /-- A **perfect clique** of degree **d**, or d-pclique, is a simply independent d-npclique, which does not contain both tropes and non-tropes. -/ def pclique (d : fuzzy) (C : set Ω.ientity) : Prop := npclique d C ∧ sindependent C ∧ ¬ ∃ e t : Ω.ientity, e ∈ C ∧ t ∈ C ∧ t.trope ∧ ¬e.trope /-- The **degrees of analogy** of an entity **e** is the set of degrees for which **e** has a near perfect clique. An entity is said to be analogically similar to **e** if it resembles the things resembling **e** to at least some of these degrees. -/ def ientity.danalogy (e : Ω.ientity) : set fuzzy := {d : fuzzy | ∃ (C : set Ω.ientity), e ∈ C ∧ npclique d C} /-- The **analogies** of an entity **e** is the set of near perfect cliques containing **e**. An entity is said to analogically similar to **e** if it shares a near perfect clique with **e**. -/ def ientity.analogies (e : Ω.ientity) : set $ set Ω.ientity := {C : set Ω.ientity | ∃ d, e ∈ C ∧ npclique d C} /-- The **degrees of genera** of an entity **e** is the set of degrees for which **e** has a perfect clique. An entity is said to be in one of the same genus as **e** if it resembles the things resembling **e** to at least some of these degrees. -/ def ientity.dgenera (e : Ω.ientity) : set fuzzy := {d : fuzzy | ∃ (C : set Ω.ientity), e ∈ C ∧ pclique d C} /-- The **genera** of an entity **e** is the set of perfect cliques containing **e**. An entity is said to be in one of the same genus as **e** if it shares a perfect clique with **e**. -/ def ientity.genera (e : Ω.ientity) : set $ set Ω.ientity := {C : set Ω.ientity | ∃ d, e ∈ C ∧ pclique d C} /-- An entity is said to be **quasi-unintelligible** if it does not admit analogies of degree greater than 0. In this case, it either has no essence, or at least its essence cannot be explained by resemblance nominalism, but only by trope-resemblance nominalism. -/ def ientity.qunint (e : Ω.ientity) : Prop := ¬ ∃ d ∈ e.danalogy, (0 : fuzzy) < d /-- An entity is said to be **unintelligible** if it quasi-unintelligible and is not existentially equivalent to any non-quasi-unintelligible tropes. If it were equivalent to some such tropes, i.e. if it had *essential* tropes, its essence might be explainable in terms of the essences of its tropes. An unintelligible entity however has no essence of any sort. -/ def ientity.unint (e : Ω.ientity) : Prop := e.qunint ∧ ∀ t : Ω.ientity, t.trope → t ⇔ e → t.qunint /-- An entity is said to be **partially intelligible** if it is not unintelligible. -/ def ientity.pint (e : Ω.ientity) : Prop := ¬ e.unint /-- An entity is said to be **bare** if it is not a member of any genus. In this case, it either has no univocal essence, or at least its essence cannot be explained by resemblance nominalism, but only by trope-resemblance nominalism. -/ def ientity.bare (e : Ω.ientity) : Prop := e.genera = ∅ /-- An entity is said to be **fully bare** if it is bare and is not existentially equivalent to any non-bare tropes. If it were equivalent to some non-bare tropes, i.e. if it had *essential* tropes, its essence might be explainable in terms of the essences of its tropes. A fully bare entity however has no univocal essence of any sort (other than its haecceity). -/ def ientity.fbare (e : Ω.ientity) : Prop := e.bare ∧ ∀ t : Ω.ientity, t.trope → t ⇔ e → t.bare /-- An entity is said to be **normal** if it has a genus. -/ def ientity.normal (e : Ω.ientity) : Prop := e.genera.nonempty /-- An entity is said to be (fully) **intelligible** if it is partially intelligible and normal if it is a trope. We should expect all entities to be intelligible. -/ def ientity.int (e : Ω.ientity) : Prop := e.pint ∧ e.trope → e.normal -- TODO: revise the following two definitions to use genera directly in case they don't -- define what is intended: /-- An entity is said to be **generically unclassifiable** if it doesn't have a greatest genus. -/ def ientity.gunclass (e : Ω.ientity) : Prop := ¬ ∃ d ∈ e.dgenera, ∀ d' ∈ e.dgenera, d ≤ d' /-- An entity is said to be **specifically unclassifiable** if it doesn't have an infima species. -/ def ientity.sunclass (e : Ω.ientity) : Prop := ¬ ∃ d ∈ e.dgenera, ∀ d' ∈ e.dgenera, d' ≤ d /-- An entity is said to be **partially unclassifiable** if it is either specifically or generically unclassifiable. -/ def ientity.punclass (e : Ω.ientity) : Prop := e.gunclass ∨ e.sunclass /-- An entity is said to be **unclassifiable** if it is both specifically or generically unclassifiable. -/ def ientity.unclass (e : Ω.ientity) : Prop := e.gunclass ∧ e.sunclass /-- An entity is said to be **classifiable** if it is not partially unclassifiable. -/ def ientity.class (e : Ω.ientity) : Prop := ¬ e.punclass /-- An entity is said to be **partially classifiable** if it is not unclassifiable. -/ def ientity.pclass (e : Ω.ientity) : Prop := ¬ e.unclass /-- An entity is said to be **fully classifiable** if it is normal and has a finite number of genera. It can then be classified taxonomically without appeal to its tropes. -/ def ientity.fclass (e : Ω.ientity) : Prop := e.genera.finite ∧ e.normal end basic section principles variables {Ω : ω.iontology} [sim : Ω.sim] include sim def esse_of_possibilia : Prop := ∀ (e₁ e₂ : Ω.ientity), 0 < e₁.sim e₂ end principles section basic_theorems variables {Ω : ω.iontology} [sim : Ω.sim] include sim /-- **Universal Analogy of Being** -/ lemma uab : ∀ e, ∃ (d : fuzzy) (C : set Ω.ientity), aclique d C ∧ e ∈ C := begin intros e, use [0, univ], simp, constructor, constructor, simp [clique], intros, admit, intros, apply eq_of_subset_of_subset, assumption, simp, clear e, simp [rclass], intro e, suffices c : sdsim e ∅ = 0, rw c, -- needs appropriate type classes for this to work: admit, --exact zero_le (inf_sim univ), admit, end -- TODO: It seems that we could prove the following result for acliques, -- if we assume full blown transitivity of the similarity relation. -- The principle is that the similarity between x and z, is ≤ to the -- least of the similarities between x and y, and z and y, for all y. This implies that if -- the similarities between x and y, and z and y, are the same, then the similarity between x and z -- should be at least as high. In the second lemma we however know that the similarity between -- t₁ and t₂ is strictly capped at d, and yet that they should both be at least d-similar to t, which -- is absurd given transitivity, but not given mere triangularity. -- TODO: It seems possible that we might also just be able to prove that under transitivity -- all acliques are sacliques. This remains to be investigated. -- admits are only due to the type classes problem. lemma saclique_disjoint : ∀ d (C C' : set Ω.ientity), C ≠ C' → saclique d C → saclique d C' → C ∩ C' = ∅ := begin intros d C C' neq h₁ h₂, have c₁ : ∃ t₁ ∈ C, t₁ ∉ C', by_contradiction contra, push_neg at contra, replace h₁ := h₁.1.2, replace h₂ := h₂.1.1, specialize h₁ C' h₂ contra, contradiction, have c₂ : ∃ t₂ ∈ C', t₂ ∉ C, by_contradiction contra, push_neg at contra, replace h₂ := h₂.1.2, replace h₁ := h₁.1.1, specialize h₂ C h₁ contra, cases h₂, contradiction, by_contradiction contra, simp [ext_iff] at contra, obtain ⟨t, h₁t, h₂t⟩ := contra, obtain ⟨t₁, h₁t₁, h₂t₁⟩ := c₁, obtain ⟨t₂, h₁t₂, h₂t₂⟩ := c₂, replace h₁ := h₁.2, simp [srclass] at h₁, specialize h₁ t h₁t, replace h₂ := h₂.2, simp [srclass] at h₂, specialize h₂ t h₂t, have c₁ : t.sim t₂ ≤ sdsim t (-C), admit, have c₁' : inf_sim (C) ≤ t.sim t₁, admit, have c₁'' : t.sim t₂ < t.sim t₁, have := lt_of_le_of_lt c₁ h₁, exact lt_of_lt_of_le this c₁', have c₂ : t.sim t₁ ≤ sdsim t (-C'), admit, have c₂' : inf_sim (C') ≤ t.sim t₂, admit, have c₂'' : t.sim t₁ < t.sim t₂, have := lt_of_le_of_lt c₂ h₂, exact lt_of_lt_of_le this c₂', have c₃ := lt_trans c₁'' c₂'', simp [lt_irrefl] at c₃, contradiction, end lemma saclique_not_subset : ∀ d d' (C C' : set Ω.ientity), C ≠ C' → saclique d C → saclique d' C' → C ∩ C' ≠ ∅ → d ≤ d' → ¬ C ⊆ C' := sorry lemma saclique_ssubset : ∀ d d' (C C' : set Ω.ientity), saclique d C → saclique d' C' → C ∩ C' ≠ ∅ → d ≤ d' → C' ⊆ C := begin intros d d' C C' h₁ h₂ h₃ h₄, by_cases h : C = C', cases h, refl, have c₁ : ∃ t₁ ∈ C, t₁ ∉ C', by_contradiction absurd, push_neg at absurd, have c := saclique_not_subset d d' C C' h h₁ h₂ h₃ h₄, contradiction, by_contradiction contra, simp [has_subset.subset, set.subset] at contra, simp [ext_iff] at h₃, obtain ⟨t, h₁t, h₂t⟩ := h₃, obtain ⟨t₁, h₁t₁, h₂t₁⟩ := c₁, obtain ⟨t₂, h₁t₂, h₂t₂⟩ := contra, replace h₁ := h₁.2, simp [srclass] at h₁, specialize h₁ t h₁t, replace h₂ := h₂.2, simp [srclass] at h₂, specialize h₂ t h₂t, have c₁ : t.sim t₂ ≤ sdsim t (-C), admit, have c₁' : inf_sim (C) ≤ t.sim t₁, admit, have c₁'' : t.sim t₂ < t.sim t₁, have := lt_of_le_of_lt c₁ h₁, exact lt_of_lt_of_le this c₁', have c₂ : t.sim t₁ ≤ sdsim t (-C'), admit, have c₂' : inf_sim (C') ≤ t.sim t₂, admit, have c₂'' : t.sim t₁ < t.sim t₂, have := lt_of_le_of_lt c₂ h₂, exact lt_of_lt_of_le this c₂', have c₃ := lt_trans c₁'' c₂'', simp [lt_irrefl] at c₃, contradiction, end end basic_theorems section being -- We lift tropes to a structure to generate a namespace for dot notation: structure trope (Ω : ω.iontology) [sim : Ω.sim] := (up : Ω.ientity) (p : up.trope) variables {Ω : ω.iontology} [sim : Ω.sim] (t : Ω.trope) include sim /-- A **proper trope** is a normal trope incompatible with any distinct consubstantial trope in the same genus as itself. -/ def trope.proper (t : Ω.trope) : Prop := t.normal ∧ ∀ (C) d ∈ t.genera, ptclique d C t → ∀ t' ∈ C, t' ≠ t → t'.up ≈ t.up → ¬⋄(t'.up.exists ∩ t.up.exists) /-- A **composable trope** is an improper normal trope. Composable tropes "compose" to achieve some characteristic rather than being singularly responsible for the characteristic. A 1kg composable trope, for instance, could be composed with another 1kg composable trope, to characterize its object as being 2kg. -/ def trope.composable (t : Ω.trope) : Prop := ¬t.proper ∧ t.normal /-- A **complemented trope** is a proper trope for which there exists another distinct consubstantial proper trope sharing a genus. -/ def trope.complemented (t : Ω.trope) : Prop := t.proper ∧ ∃ (C : set Ω.trope) d ∈ t.genera, t ∈ C ∧ ptclique d C ∧ ∃ t' ∈ C, t' ≠ t ∧ t'.up ≈ t.up ∧ t'.proper /-- An **eminent** trope is a composable trope non-vacuously compatible with all complemented tropes in all of its genera. Naturally, they are not consubstantial to these complemented tropes. Mental tropes are eminent tropes, for consider the trope in virtue of which you are thinking about a square, this appears to be composable with a trope in virtue of which you are thinking about a circle, since they compose to characterize you as thinking about some square and some circle (I do not mean to say you are thinking about a squared-circle). These tropes are members of the same genus of "mental geometric figure tropes". Furthermore, these tropes are compatible with the existence of extra-mental squares and circles, which are objects characterized by complemented "square" and "circular" tropes. It is unclear to us whether there are any non-eminent composable tropes, or any non-mental eminent tropes. -/ def trope.eminent (t : Ω.trope) : Prop := t.composable ∧ ∀ (C) d ∈ t.genera, ptclique d C t → (∃ (t' : Ω.trope), t' ∈ C ∧ t'.complemented) ∧ ∀ (t' : Ω.trope), t' ∈ C → t'.complemented → ⋄(t'.up.exists ∩ t.up.exists) /-- A **formal** trope is a non-eminent normal trope. -/ def trope.formal (t : Ω.trope) : Prop := ¬t.eminent ∧ t.normal end being end iontology end ontology
\section{Filesystem} \begin{frame}[fragile] \frametitle{Filesystem} \end{frame}
import Rings.Lefschetz open Lefschetz open fol open Fields namespace fol variable {L : Language} def no_finite_model (T : Theory L) : Prop := ∀ (M : Model T), infinite M.1 end fol namespace Lefschetz_current /-- Lefschetz part 1. Any sentence or its negation can be deduced in ACF₀-/ theorem is_complete'_ACF₀ : is_complete' ACF₀ := begin sorry end end Lefschetz_current
Formal statement is: proposition (in metric_space) completeE: assumes "complete s" and "\<forall>n. f n \<in> s" and "Cauchy f" obtains l where "l \<in> s" and "f \<longlonglongrightarrow> l" Informal statement is: If $s$ is a complete metric space and $(f_n)$ is a Cauchy sequence in $s$, then there exists $l \in s$ such that $f_n \to l$.
In the summer semester 2015 the TH Georg Agricola assigns scholarships to excellent students for their studies in the context of the national scholarship program. The TH Georg Agricola gives eight scholarships. The scholarships are partially promoted with private funds (companies, endowment or private persons) and with funds of the federation. 2. is before of his admission at the TH or is already matriculated at the university. The selection criteria consider next to good study marks as well as the applicant’s personal situation such as family background or migration background, commitment and the willingness to take over social responsibilities. Applicants who are the best of their study year may have better chances to get a scholarship. The funding is shut out if the student is taking substantive funding according to §§ 1 Abs. 3 or 4 Abs. 1 S. 1 of the law for the national scholarship program (StipG) of 21st June 2010. If the monthly average is fewer than 30 Euro applicants may be able to get the funding. The scholarship is amounted to 300 Euro monthly and initially it is for two semesters.
module math.Epsilon import xquant.Core.Types %default total class Epsilon a where infinitessimal : a -> Bool instance Epsilon Fl where infinitessimal x = abs x < 0.00000001 instance Epsilon Amp where infinitessimal x = realPart (abs x) < 0.00000001 instance Epsilon (Vect n Fl) where infinitessimal = all infinitessimal instance Epsilon (Vect n Amp) where infinitessimal = all infinitessimal instance Epsilon (Vect n (Vect m Fl)) where infinitessimal = all infinitessimal instance Epsilon (Vect n (Vect m Amp)) where infinitessimal = all infinitessimal sumSq : (Functor t, Foldable t, Neg a) => t a -> a sumSq = sum . map ((\n => n*n) . abs) data Real : Amp -> Type where IsReal : (z : Amp) -> {auto isinf : infinitessimal (imagPart z) = True} -> Real z {- *quantum> :r Type checking ./math/Epsilon.idr ./math/Epsilon.idr:20:10: Overlapping instance: Epsilon (Complex Double) already defined approximates : Epsilon -} {-} --instance (Neg a, Epsilon a) => Epsilon (Vect n a) where -- infinitessimal = infinitessimal . sumSq --data Infinitessimal : Type where -- Infini : Epsilon a => (x : a) -> {auto isep : infinitessimal x = True} -> Infinitessimal x -- data Unitary : (mat : Matrix n n (Complex Float)) -> Type where -- IsUnitary : {prf : mat <> dagger )} -}
!------------------------------------------------------------------------------ !------------------------------------------------------------------------------ ! pen : Coupled pendula (or rotations in coupled Josephson junctions) !------------------------------------------------------------------------------ !------------------------------------------------------------------------------ SUBROUTINE FUNC(NDIM,U,ICP,PAR,IJAC,F,DFDU,DFDP) ! ---------- ---- IMPLICIT NONE INTEGER, INTENT(IN) :: NDIM, ICP(*), IJAC DOUBLE PRECISION, INTENT(IN) :: U(NDIM), PAR(*) DOUBLE PRECISION, INTENT(OUT) :: F(NDIM) DOUBLE PRECISION, INTENT(INOUT) :: DFDU(NDIM,NDIM), DFDP(NDIM,*) DOUBLE PRECISION GAMMA,EPS,RI,PH1,PH2,PS1,PS2 GAMMA = PAR(1) EPS = PAR(2) RI = PAR(3) PH1=U(1) PH2=U(2) PS1=U(3) PS2=U(4) F(1)= PS1 F(2)= PS2 F(3)= -EPS*PS1 - SIN(PH1) + RI + GAMMA*(PH2-PH1) F(4)= -EPS*PS2 - SIN(PH2) + RI + GAMMA*(PH1-PH2) END SUBROUTINE FUNC SUBROUTINE STPNT(NDIM,U,PAR,T) ! ---------- ----- IMPLICIT NONE INTEGER, INTENT(IN) :: NDIM DOUBLE PRECISION, INTENT(INOUT) :: U(NDIM),PAR(*) DOUBLE PRECISION, INTENT(IN) :: T DOUBLE PRECISION GAMMA,EPS,RI GAMMA=0.175 EPS=0.1 RI=0.4 PAR(1)=GAMMA PAR(2)=EPS PAR(3)=RI ! Set the actual period (since the data in pen.dat have scaled time variable) PAR(11)=1.5738797205 END SUBROUTINE STPNT SUBROUTINE BCND END SUBROUTINE BCND SUBROUTINE ICND END SUBROUTINE ICND SUBROUTINE FOPT END SUBROUTINE FOPT SUBROUTINE PVLS END SUBROUTINE PVLS
{- This second-order signature was created from the following second-order syntax description: syntax Prod | P type _⊗_ : 2-ary | l40 term pair : α β -> α ⊗ β | ⟨_,_⟩ fst : α ⊗ β -> α snd : α ⊗ β -> β theory (fβ) a : α b : β |> fst (pair(a, b)) = a (sβ) a : α b : β |> snd (pair(a, b)) = b (pη) p : α ⊗ β |> pair (fst(p), snd(p)) = p -} module Prod.Signature where open import SOAS.Context -- Type declaration data PT : Set where _⊗_ : PT → PT → PT infixl 40 _⊗_ open import SOAS.Syntax.Signature PT public open import SOAS.Syntax.Build PT public -- Operator symbols data Pₒ : Set where pairₒ fstₒ sndₒ : {α β : PT} → Pₒ -- Term signature P:Sig : Signature Pₒ P:Sig = sig λ { (pairₒ {α}{β}) → (⊢₀ α) , (⊢₀ β) ⟼₂ α ⊗ β ; (fstₒ {α}{β}) → (⊢₀ α ⊗ β) ⟼₁ α ; (sndₒ {α}{β}) → (⊢₀ α ⊗ β) ⟼₁ β } open Signature P:Sig public
State Before: α : Type u β : Type v γ : Type w inst✝¹ : Group α inst✝ : MulAction α β g h : α a : β ⊢ g • a ∈ orbit α (h • a) State After: no goals Tactic: simp only [orbit_smul, mem_orbit]
The opening of the following game between two world @-@ class players , another Symmetrical English , took a similar course :
-- like name map, but able to return ambiguous names module Data.ANameMap import Core.Name import Data.List import Data.NameMap import Data.StringMap %default total export record ANameMap a where constructor MkANameMap -- for looking up by exact (completely qualified) names exactNames : NameMap a -- for looking up by name root or partially qualified (so possibly -- ambiguous) names. This doesn't store machine generated names. hierarchy : StringMap (List (Name, a)) export empty : ANameMap a empty = MkANameMap empty empty ||| Given a Name, and an ANameMap, look up that name exactly export lookupExact : Name -> ANameMap a -> Maybe a lookupExact n dict = lookup n (exactNames dict) export lookupName : Name -> ANameMap a -> List (Name, a) lookupName n dict = case userNameRoot n of Nothing => case lookupExact n dict of Nothing => [] Just res => [(n, res)] Just r => case lookup r (hierarchy dict) of Nothing => [] Just ns => filter (matches n . fst) ns addToHier : Name -> a -> StringMap (List (Name, a)) -> StringMap (List (Name, a)) addToHier n val hier -- Only add user defined names. Machine generated names can only be -- found with the exactNames = case userNameRoot n of Nothing => hier Just root => case lookup root hier of Nothing => insert root [(n, val)] hier Just ns => insert root (update val ns) hier where update : a -> List (Name, a) -> List (Name, a) update val [] = [(n, val)] update val (old :: xs) = if n == fst old then (n, val) :: xs else old :: update val xs export addName : Name -> a -> ANameMap a -> ANameMap a addName n val (MkANameMap dict hier) = let dict' = insert n val dict hier' = addToHier n val hier in MkANameMap dict' hier' export toList : ANameMap a -> List (Name, a) toList dict = toList (exactNames dict) export fromList : List (Name, a) -> ANameMap a fromList = fromList' empty where fromList' : ANameMap a -> List (Name, a) -> ANameMap a fromList' acc [] = acc fromList' acc ((k, v) :: ns) = fromList' (addName k v acc) ns -- Merge two contexts, with entries in the first overriding entries in -- the second export merge : ANameMap a -> ANameMap a -> ANameMap a merge (MkANameMap exact hier) ctxt = insertFrom (toList exact) ctxt where insertFrom : List (Name, a) -> ANameMap a -> ANameMap a insertFrom [] ctxt = ctxt insertFrom ((n, val) :: cs) ctxt = insertFrom cs (addName n val ctxt)
{-# OPTIONS --without-K --safe #-} open import Categories.Category.Core -- Reflexive pairs and reflexive coequalizers -- https://ncatlab.org/nlab/show/reflexive+coequalizer module Categories.Diagram.ReflexivePair {o ℓ e} (𝒞 : Category o ℓ e) where open import Level open import Categories.Diagram.Coequalizer 𝒞 open Category 𝒞 open HomReasoning open Equiv private variable A B R : Obj -- A reflexive pair can be thought of as a vast generalization of a reflexive relation. -- To see this, consider the case in 'Set' where 'R ⊆ A × A', and 'f' and 'g' are the projections. -- Then, our morphism 's' would have to look something like the diagonal morphism due to the -- restriction it is a section of both 'f' and 'g'. record IsReflexivePair (f g : R ⇒ A) (s : A ⇒ R) : Set e where field sectionₗ : f ∘ s ≈ id sectionᵣ : g ∘ s ≈ id section : f ∘ s ≈ g ∘ s section = sectionₗ ○ ⟺ sectionᵣ record ReflexivePair (f g : R ⇒ A) : Set (ℓ ⊔ e) where field s : A ⇒ R isReflexivePair : IsReflexivePair f g s open IsReflexivePair isReflexivePair public
module Data.Scientific -- TODO: don't export everything publicly? import Data.Fin import Data.List public export data Coefficient : (b : Nat) -> Type where CoeffInt : Fin (S b) -> Coefficient (S (S b)) CoeffFloat : Fin (S b) -> List (Fin (S (S b))) -> Fin (S b) -> Coefficient (S (S b)) public export Eq (Coefficient b) where (CoeffInt x) == (CoeffInt y) = x == y (CoeffFloat x xs x') == (CoeffFloat y ys y') = x == y && xs == ys && x' == y' _ == _ = False public export Ord (Coefficient b) where compare (CoeffInt x) (CoeffInt y) = compare x y compare (CoeffInt x) (CoeffFloat y ys y') = case compare x y of EQ => LT comp => comp compare (CoeffFloat x xs x') (CoeffInt y) = case compare x y of EQ => GT comp => comp compare (CoeffFloat x xs x') (CoeffFloat y ys y') = compare (FS x :: xs `snoc` FS x') (FS y :: ys `snoc` FS y') private prettyShowDigit : Fin 10 -> Char prettyShowDigit x = case x of 0 => '0' 1 => '1' 2 => '2' 3 => '3' 4 => '4' 5 => '5' 6 => '6' 7 => '7' 8 => '8' 9 => '9' private prettyShowCoefficient : Coefficient 10 -> String prettyShowCoefficient (CoeffInt x) = pack [ prettyShowDigit (FS x) ] prettyShowCoefficient (CoeffFloat x xs x') = pack $ [ prettyShowDigit (FS x), '.' ] ++ map prettyShowDigit xs ++ [ prettyShowDigit (FS x') ] public export data Sign = Positive | Negative public export Eq Sign where Positive == Positive = True Negative == Negative = True _ == _ = False public export Ord Sign where compare Positive Positive = EQ compare Positive Negative = GT compare Negative Positive = LT compare Negative Negative = EQ private prettyShowSign : Sign -> String prettyShowSign s = case s of Positive => "" Negative => "-" public export data Scientific : (b : Nat) -> Type where SciZ : Scientific b Sci : Sign -> Coefficient b -> Integer -> Scientific b public export Eq (Scientific b) where SciZ == SciZ = True (Sci s c e) == (Sci s' c' e') = s == s' && c == c' && e == e' _ == _ = False public export Ord (Scientific b) where compare SciZ SciZ = EQ compare SciZ (Sci s _ _) = case s of Positive => LT Negative => GT compare (Sci s _ _) SciZ = case s of Positive => GT Negative => LT compare (Sci s c e) (Sci s' c' e') = case (s, s') of (Positive, Positive) => case compare e e' of EQ => compare c c' comp => comp (Positive, Negative) => GT (Negative, Positive) => LT (Negative, Negative) => case compare e' e of EQ => compare c' c comp => comp export negate : Scientific b -> Scientific b negate SciZ = SciZ negate (Sci s c e) = let s' = case s of Positive => Negative Negative => Positive in Sci s' c e export abs : Scientific b -> Scientific b abs SciZ = SciZ abs (Sci _ c e) = Sci Positive c e -- TODO: What happens, when Integer is negative? Low priority, since this is private. private ||| The digits of an Integer, least significant first. integerDigits : {b : _} -> Integer -> List (Fin (S (S b))) integerDigits 0 = [] integerDigits x = d :: integerDigits r where d : Fin (S (S b)) d = restrict (S b) x r : Integer r = x `div` natToInteger (S (S b)) private removeLeadingZeros : List (Fin (S (S b))) -> Maybe (Fin (S b), List (Fin (S (S b)))) removeLeadingZeros [] = Nothing removeLeadingZeros (FZ :: xs) = removeLeadingZeros xs removeLeadingZeros (FS x :: xs) = Just (x, xs) private fromDigits : List (Fin (S (S b))) -> Scientific (S (S b)) fromDigits ys = case removeLeadingZeros $ reverse ys of Nothing => SciZ Just (x, ys') => case removeLeadingZeros $ reverse ys' of Nothing => Sci Positive (CoeffInt x) (cast $ length ys') Just (x', xs) => Sci Positive (CoeffFloat x (reverse xs) x') (cast $ length ys') export fromFin : Fin (S (S b)) -> Scientific (S (S b)) fromFin FZ = SciZ fromFin (FS x) = Sci Positive (CoeffInt x) 0 export fromInteger : {b : _} -> Integer -> Scientific (S (S b)) fromInteger x = if x < 0 then negate $ fromIntegerPositive x else fromIntegerPositive x where fromIntegerPositive : Integer -> Scientific (S (S b)) fromIntegerPositive = fromDigits . integerDigits . abs export fromNat : {b : _} -> Nat -> Scientific (S (S b)) fromNat = fromInteger . natToInteger ||| All bits of a Coefficient, least significant first. coefficientBits : Coefficient (S (S b)) -> List (Fin (S (S b))) coefficientBits (CoeffInt x) = [FS x] coefficientBits (CoeffFloat x xs x') = reverse $ FS x :: xs ++ [FS x'] -- TODO: currently add and subtract require equal lengths for the coefficients -- adds 1 bit (might be zero) addBits : {b : _} -> (carry : Bool) -> List (Fin (S (S b))) -> List (Fin (S (S b))) -> List (Fin (S (S b))) addBits False [] [] = [FZ] addBits True [] [] = [FS FZ] addBits carry p@[] q@(y :: ys) = addBits carry q p -- TODO: case can be avoided when one is larger than the other addBits False (x :: xs) [] = x :: addBits False xs [] addBits True (x :: xs) [] = case strengthen $ FS x of Left _ => FZ :: addBits True xs [] Right x' => x' :: addBits False xs [] addBits carry (x :: xs) (y :: ys) = restrict (S b) addition :: addBits (addition >= natToInteger (S (S b))) xs ys where addition : Integer addition = if carry then finToInteger x + finToInteger y + 1 else finToInteger x + finToInteger y subtractBits : {b : _} -> (borrow : Bool) -> List (Fin (S (S b))) -> List (Fin (S (S b))) -> List (Fin (S (S b))) subtractBits False [] [] = [FZ] subtractBits True [] [] = ?thatShouldntHappen1 subtractBits borrow [] (x :: xs) = ?thatShouldntHappen2 subtractBits False (x :: xs) [] = x :: subtractBits False xs [] subtractBits True (FZ :: xs) [] = last :: subtractBits True xs [] subtractBits True ((FS x) :: xs) [] = weaken x :: subtractBits False xs [] subtractBits borrow (x :: xs) (y :: ys) = ?subtractBits_rhs_4 export plus : {b : _} -> Scientific (S (S b)) -> Scientific (S (S b)) -> Scientific (S (S b)) plus SciZ y = y plus x SciZ = x -- TODO: finish plus plus x@(Sci s c e) y@(Sci s' c' e') = case compare e e' of GT => plus y x _ => ?asdasd where exponentDifference : Nat exponentDifference = integerToNat $ e' - e bits : List (Fin (S (S b))) bits = addBits False (coefficientBits c ++ replicate exponentDifference FZ) (coefficientBits c') s'' : Sign c'' : Coefficient (S (S b)) e'' : Integer e'' = e' + ?additionalExponent bits ||| Multiply two Coefficients and return True in the Bool, when the product is greater than the base. multCoefficents : {b : _} -> Coefficient (S (S b)) -> Coefficient (S (S b)) -> (Coefficient (S (S b)), Bool) multCoefficents (CoeffInt x) (CoeffInt y) = case integerToFin res (S b) of Nothing => (CoeffInt $ restrict b res, True) Just fin => (CoeffInt fin, False) where res : Integer res = (finToInteger x + 1) * (finToInteger y + 1) - 1 multCoefficents a@(CoeffInt x) b@(CoeffFloat y ys y') = multCoefficents b a -- TODO: finish multCoefficents multCoefficents (CoeffFloat x xs x') (CoeffInt y) = ?multCoefficents_rhs_2 multCoefficents (CoeffFloat x xs x') (CoeffFloat y ys y') = ?multCoefficents_rhs_3 export mult : {b : _} -> Scientific (S (S b)) -> Scientific (S (S b)) -> Scientific (S (S b)) mult SciZ y = SciZ mult x SciZ = SciZ mult (Sci s c e) (Sci s' c' e') = Sci s'' c'' e'' where coefficientPair : (Coefficient (S (S b)), Bool) coefficientPair = multCoefficents c c' s'' : Sign s'' = if s == s' then Positive else Negative c'' : Coefficient (S (S b)) c'' = fst coefficientPair e'' : Integer e'' = if snd coefficientPair then e + e' + 1 else e + e' -- -- TODO: consider other implementations: -- -- - Fractional might not terminate, because of infinite representation -- -- - Integral doesn't sound like it would fit, but mod and div make still make sense -- public export -- Num (Scientific (S (S b))) where -- -- (+) = plus -- -- (*) = mult -- -- fromInteger = fromInteger --public export --Neg (Scientific (S (S b))) where -- -- negate = negate --public export --Abs (Scientific (S (S b))) where -- -- abs = abs export prettyShowScientific : Scientific 10 -> String prettyShowScientific SciZ = "0" prettyShowScientific (Sci s c e) = prettyShowSign s ++ prettyShowCoefficient c ++ prettyExponent where prettyExponent : String prettyExponent = case e of 0 => "" x => "e" ++ show x
{-# OPTIONS --without-K #-} open import HoTT.Base open import HoTT.Identity module HoTT.Homotopy where open variables private variable f g : A → B -- Lemma 2.4.3 ~-natural : (α : f ~ g) {x y : A} (p : x == y) → α x ∙ ap g p == ap f p ∙ α y ~-natural α {x} refl rewrite α x = refl ~-natural-id : (α : f ~ id) {x y : A} (p : x == y) → α x ∙ p == ap f p ∙ α y ~-natural-id α {x} refl rewrite α x = refl -- Corollary 2.4.4 ~-natural-comm : {f : A → A} (α : f ~ id) → α ∘ f ~ ap f ∘ α ~-natural-comm {f = f} α x = cancelᵣ (α (f x) ∙ₗ ap-id (α x) ⁻¹ ∙ ~-natural α (α x)) module ~-Reasoning where _~⟨_⟩_ : (f : Π A P) {g h : Π A P} → f ~ g → g ~ h → f ~ h x ~⟨ α ⟩ β = α ∙ₕ β infixr 2 _~⟨_⟩_ _∎ : (f : Π A P) → f ~ f _ ∎ = reflₕ infix 3 _∎
(* then/else branch swapped *) Definition intersect(A B: list E): list E := fold_left (fun res a => if in_dec eeq a B then res else a :: res) A nil.
module Quantities.Information import Quantities.Core %default total %access public export Information : Dimension Information = MkDimension "Information" Bit : ElemUnit Information Bit = MkElemUnit "bit" 1 Byte : ElemUnit Information Byte = < one "byte" equals 8 Bit > -- Binary prefixes for multiples of bits/bytes -- Based on http://en.wikipedia.org/wiki/Binary_prefix twoToTheTen : String -> Nat -> ElemUnit q -> ElemUnit q twoToTheTen pre power (MkElemUnit name f) = < one (pre ++ name) equals (pow 1024.0 power) (MkElemUnit name f) > kibi : ElemUnit q -> ElemUnit q kibi = twoToTheTen "kibi" 1 ki : ElemUnit q -> ElemUnit q ki = kibi mebi : ElemUnit q -> ElemUnit q mebi = twoToTheTen "mebi" 2 mi : ElemUnit q -> ElemUnit q mi = mebi gibi : ElemUnit q -> ElemUnit q gibi = twoToTheTen "gibi" 3 gi : ElemUnit q -> ElemUnit q gi = gibi tebi : ElemUnit q -> ElemUnit q tebi = twoToTheTen "tebi" 4 ti : ElemUnit q -> ElemUnit q ti = tebi pebi : ElemUnit q -> ElemUnit q pebi = twoToTheTen "pebi" 5 pi : ElemUnit q -> ElemUnit q pi = pebi exbi : ElemUnit q -> ElemUnit q exbi = twoToTheTen "exbi" 6 ei : ElemUnit q -> ElemUnit q ei = exbi zebi : ElemUnit q -> ElemUnit q zebi = twoToTheTen "zebi" 7 zi : ElemUnit q -> ElemUnit q zi = zebi yobi : ElemUnit q -> ElemUnit q yobi = twoToTheTen "yobi" 8 yi : ElemUnit q -> ElemUnit q yi = yobi -- Please Note: kibi byte /= kilo byte
S+G has provided design and permitting services to the Solid Waste community since 1991. Our firm was involved in the promulgation of RCRA Subtitle-D rules and understands the basis of these rules. Since that time, we have been employing innovative and tested techniques to maximize return on investment. S+G has permitted Subtitle-D landfill cells across the Southeast and has significant experience in a variety of regulatory and physical terrains.
/- Copyright (c) 2022 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import category_theory.preadditive.opposite import algebra.category.Module.basic import algebra.category.Group.preadditive /-! # The Yoneda embedding for preadditive categories The Yoneda embedding for preadditive categories sends an object `Y` to the presheaf sending an object `X` to the group of morphisms `X ⟶ Y`. At each point, we get an additional `End Y`-module structure. We also show that this presheaf is additive and that it is compatible with the normal Yoneda embedding in the expected way and deduce that the preadditive Yoneda embedding is fully faithful. ## TODO * The Yoneda embedding is additive itself -/ universes v u open category_theory.preadditive opposite namespace category_theory variables {C : Type u} [category.{v} C] [preadditive C] /-- The Yoneda embedding for preadditive categories sends an object `Y` to the presheaf sending an object `X` to the `End Y`-module of morphisms `X ⟶ Y`. -/ @[simps] def preadditive_yoneda_obj (Y : C) : Cᵒᵖ ⥤ Module.{v} (End Y) := { obj := λ X, Module.of _ (X.unop ⟶ Y), map := λ X X' f, { to_fun := λ g, f.unop ≫ g, map_add' := λ g g', comp_add _ _ _ _ _ _, map_smul' := λ r g, eq.symm $ category.assoc _ _ _ } } /-- The Yoneda embedding for preadditive categories sends an object `Y` to the presheaf sending an object `X` to the group of morphisms `X ⟶ Y`. At each point, we get an additional `End Y`-module structure, see `preadditive_yoneda_obj`. -/ @[simps] def preadditive_yoneda : C ⥤ (Cᵒᵖ ⥤ AddCommGroup.{v}) := { obj := λ Y, preadditive_yoneda_obj Y ⋙ forget₂ _ _, map := λ Y Y' f, { app := λ X, { to_fun := λ g, g ≫ f, map_zero' := limits.zero_comp, map_add' := λ g g', add_comp _ _ _ _ _ _ }, naturality' := λ X X' g, AddCommGroup.ext _ _ _ _ $ λ x, category.assoc _ _ _ }, map_id' := λ X, by { ext, simp }, map_comp' := λ X Y Z f g, by { ext, simp } } /-- The Yoneda embedding for preadditive categories sends an object `X` to the copresheaf sending an object `Y` to the `End X`-module of morphisms `X ⟶ Y`. -/ @[simps] def preadditive_coyoneda_obj (X : Cᵒᵖ) : C ⥤ Module.{v} (End X) := { obj := λ Y, Module.of _ (unop X ⟶ Y), map := λ Y Y' f, { to_fun := λ g, g ≫ f, map_add' := λ g g', add_comp _ _ _ _ _ _, map_smul' := λ r g, category.assoc _ _ _ } } /-- The Yoneda embedding for preadditive categories sends an object `X` to the copresheaf sending an object `Y` to the group of morphisms `X ⟶ Y`. At each point, we get an additional `End X`-module structure, see `preadditive_coyoneda_obj`. -/ @[simps] def preadditive_coyoneda : Cᵒᵖ ⥤ (C ⥤ AddCommGroup.{v}) := { obj := λ X, preadditive_coyoneda_obj X ⋙ forget₂ _ _, map := λ X X' f, { app := λ Y, { to_fun := λ g, f.unop ≫ g, map_zero' := limits.comp_zero, map_add' := λ g g', comp_add _ _ _ _ _ _ }, naturality' := λ Y Y' g, AddCommGroup.ext _ _ _ _ $ λ x, eq.symm $ category.assoc _ _ _ }, map_id' := λ X, by { ext, simp }, map_comp' := λ X Y Z f g, by { ext, simp } } instance additive_yoneda_obj (X : C) : functor.additive (preadditive_yoneda_obj X) := {} instance additive_yoneda_obj' (X : C) : functor.additive (preadditive_yoneda.obj X) := {} instance additive_coyoneda_obj (X : Cᵒᵖ) : functor.additive (preadditive_coyoneda_obj X) := {} instance additive_coyoneda_obj' (X : Cᵒᵖ) : functor.additive (preadditive_coyoneda.obj X) := {} /-- Composing the preadditive yoneda embedding with the forgetful functor yields the regular Yoneda embedding. -/ @[simp] lemma whiskering_preadditive_yoneda : preadditive_yoneda ⋙ (whiskering_right Cᵒᵖ AddCommGroup (Type v)).obj (forget AddCommGroup) = yoneda := rfl /-- Composing the preadditive yoneda embedding with the forgetful functor yields the regular Yoneda embedding. -/ @[simp] lemma whiskering_preadditive_coyoneda : preadditive_coyoneda ⋙ (whiskering_right C AddCommGroup (Type v)).obj (forget AddCommGroup) = coyoneda := rfl instance preadditive_yoneda_full : full (preadditive_yoneda : C ⥤ Cᵒᵖ ⥤ AddCommGroup) := let yoneda_full : full (preadditive_yoneda ⋙ (whiskering_right Cᵒᵖ AddCommGroup (Type v)).obj (forget AddCommGroup)) := yoneda.yoneda_full in by exactI full.of_comp_faithful preadditive_yoneda ((whiskering_right Cᵒᵖ AddCommGroup (Type v)).obj (forget AddCommGroup)) instance preadditive_coyoneda_full : full (preadditive_coyoneda : Cᵒᵖ ⥤ C ⥤ AddCommGroup) := let coyoneda_full : full (preadditive_coyoneda ⋙ (whiskering_right C AddCommGroup (Type v)).obj (forget AddCommGroup)) := coyoneda.coyoneda_full in by exactI full.of_comp_faithful preadditive_coyoneda ((whiskering_right C AddCommGroup (Type v)).obj (forget AddCommGroup)) instance preadditive_yoneda_faithful : faithful (preadditive_yoneda : C ⥤ Cᵒᵖ ⥤ AddCommGroup) := faithful.of_comp_eq whiskering_preadditive_yoneda instance preadditive_coyoneda_faithful : faithful (preadditive_coyoneda : Cᵒᵖ ⥤ C ⥤ AddCommGroup) := faithful.of_comp_eq whiskering_preadditive_coyoneda end category_theory
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import logic.equiv.basic /-! # Extra lemmas about `ulift` and `plift` In this file we provide `subsingleton`, `unique`, `decidable_eq`, and `is_empty` instances for `ulift α` and `plift α`. We also prove `ulift.forall`, `ulift.exists`, `plift.forall`, and `plift.exists`. -/ universes u v namespace plift variables {α : Sort u} {β : Sort v} instance [subsingleton α] : subsingleton (plift α) := equiv.plift.subsingleton instance [unique α] : unique (plift α) := equiv.plift.unique instance [decidable_eq α] : decidable_eq (plift α) := equiv.plift.decidable_eq instance [is_empty α] : is_empty (plift α) := equiv.plift.is_empty @[simp] lemma «forall» {p : plift α → Prop} : (∀ x, p x) ↔ ∀ x : α, p (plift.up x) := equiv.plift.forall_congr_left' @[simp] lemma «exists» {p : plift α → Prop} : (∃ x, p x) ↔ ∃ x : α, p (plift.up x) := equiv.plift.exists_congr_left end plift namespace ulift variables {α : Type u} {β : Type v} instance [subsingleton α] : subsingleton (ulift α) := equiv.ulift.subsingleton instance [unique α] : unique (ulift α) := equiv.ulift.unique instance [decidable_eq α] : decidable_eq (ulift α) := equiv.ulift.decidable_eq instance [is_empty α] : is_empty (ulift α) := equiv.ulift.is_empty @[simp] lemma «forall» {p : ulift α → Prop} : (∀ x, p x) ↔ ∀ x : α, p (ulift.up x) := equiv.ulift.forall_congr_left' @[simp] lemma «exists» {p : ulift α → Prop} : (∃ x, p x) ↔ ∃ x : α, p (ulift.up x) := equiv.ulift.exists_congr_left end ulift
State Before: 𝕜 : Type u_1 inst✝¹⁰ : NontriviallyNormedField 𝕜 D : Type uD inst✝⁹ : NormedAddCommGroup D inst✝⁸ : NormedSpace 𝕜 D E : Type uE inst✝⁷ : NormedAddCommGroup E inst✝⁶ : NormedSpace 𝕜 E F : Type uF inst✝⁵ : NormedAddCommGroup F inst✝⁴ : NormedSpace 𝕜 F G : Type uG inst✝³ : NormedAddCommGroup G inst✝² : NormedSpace 𝕜 G X : Type ?u.315358 inst✝¹ : NormedAddCommGroup X inst✝ : NormedSpace 𝕜 X s s₁ t u : Set E f f₁ : E → F g : F → G x x₀ : E c : F b : E × F → G m n : ℕ∞ p : E → FormalMultilinearSeries 𝕜 E F e : F ≃L[𝕜] G ⊢ ContDiff 𝕜 n (↑e ∘ f) ↔ ContDiff 𝕜 n f State After: no goals Tactic: simp only [← contDiffOn_univ, e.comp_contDiffOn_iff]
module Main import Data.Vect %default total data Ty = TyBool | TyInt | TyFun Ty Ty interpTy : Ty -> Type interpTy TyBool = Bool interpTy TyInt = Integer interpTy (TyFun a b) = interpTy a -> interpTy b data HasType : (i : Fin n) -> Vect n Ty -> Ty -> Type where Stop : HasType FZ (t :: ctx) t Pop : HasType k ctx t -> HasType (FS k) (u :: ctx) t data Expr : Vect n Ty -> Ty -> Type where Var : HasType i ctx t -> Expr ctx t Val : (x : Integer) -> Expr ctx TyInt Lam : Expr (a :: ctx) t -> Expr ctx (TyFun a t) App : Expr ctx (TyFun a t) -> Expr ctx a -> Expr ctx t Op : (interpTy a -> interpTy b -> interpTy c) -> Expr ctx a -> Expr ctx b -> Expr ctx c If : Expr ctx TyBool -> Lazy (Expr ctx a) -> Lazy (Expr ctx a) -> Expr ctx a data Env : Vect n Ty -> Type where Nil : Env Nil (::) : interpTy a -> Env ctx -> Env (a :: ctx) lookup : HasType i ctx t -> Env ctx -> interpTy t lookup Stop (x :: xs) = x lookup (Pop k) (x :: xs) = lookup k xs interp : Env ctx -> Expr ctx t -> interpTy t interp env (Var i) = lookup i env interp env (Val n) = n interp env (Lam sc) = \x => interp (x :: env) sc interp env (App f s) = interp env f (interp env s) interp env (Op op x y) = op (interp env x) (interp env y) interp env (If x t e) = if interp env x then interp env t else interp env e add : Expr ctx (TyFun TyInt (TyFun TyInt TyInt)) add = Lam (Lam (Op (+) (Var Stop) (Var (Pop Stop)))) partial fac : Expr ctx (TyFun TyInt TyInt) fac = Lam (If (Op (==) (Var Stop) (Val 0)) (Val 1) (Op (*) (App fac (Op (-) (Var Stop) (Val 1))) (Var Stop))) partial main : IO () main = do putStr "Enter a number: " x <- getLine printLn (interp [] fac (cast x))
[STATEMENT] lemma red_external_New_typeof_addrD: "\<lbrakk> P,t \<turnstile> \<langle>a\<bullet>M(vs), h\<rangle> -ta\<rightarrow>ext \<langle>va, h'\<rangle>; NewHeapElem a' x \<in> set \<lbrace>ta\<rbrace>\<^bsub>o\<^esub>; hconf h \<rbrakk> \<Longrightarrow> typeof_addr h' a' = Some x" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>P,t \<turnstile> \<langle>a\<bullet>M(vs),h\<rangle> -ta\<rightarrow>ext \<langle>va,h'\<rangle>; NewHeapElem a' x \<in> set \<lbrace>ta\<rbrace>\<^bsub>o\<^esub>; hconf h\<rbrakk> \<Longrightarrow> typeof_addr h' a' = \<lfloor>x\<rfloor> [PROOF STEP] by(erule red_external.cases)(auto dest: heap_clone_typeof_addrD)
Formal statement is: lemma netlimit_within_interior: fixes x :: "'a::{t2_space,perfect_space}" assumes "x \<in> interior S" shows "netlimit (at x within S) = x" Informal statement is: If $x$ is in the interior of $S$, then the limit of any net converging to $x$ within $S$ is $x$.
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro -/ import algebra.group.pi import algebra.group_power.lemmas import logic.function.iterate /-! # The group of permutations (self-equivalences) of a type `α` This file defines the `group` structure on `equiv.perm α`. -/ universes u v namespace equiv variables {α : Type u} {β : Type v} namespace perm instance perm_group : group (perm α) := { mul := λ f g, equiv.trans g f, one := equiv.refl α, inv := equiv.symm, mul_assoc := λ f g h, (trans_assoc _ _ _).symm, one_mul := trans_refl, mul_one := refl_trans, mul_left_inv := self_trans_symm } theorem mul_apply (f g : perm α) (x) : (f * g) x = f (g x) := equiv.trans_apply _ _ _ theorem one_apply (x) : (1 : perm α) x = x := rfl @[simp] lemma inv_apply_self (f : perm α) (x) : f⁻¹ (f x) = x := f.symm_apply_apply x @[simp] lemma apply_inv_self (f : perm α) (x) : f (f⁻¹ x) = x := f.apply_symm_apply x lemma one_def : (1 : perm α) = equiv.refl α := rfl lemma mul_def (f g : perm α) : f * g = g.trans f := rfl lemma inv_def (f : perm α) : f⁻¹ = f.symm := rfl @[simp] lemma coe_mul (f g : perm α) : ⇑(f * g) = f ∘ g := rfl @[simp] lemma coe_one : ⇑(1 : perm α) = id := rfl lemma eq_inv_iff_eq {f : perm α} {x y : α} : x = f⁻¹ y ↔ f x = y := f.eq_symm_apply lemma inv_eq_iff_eq {f : perm α} {x y : α} : f⁻¹ x = y ↔ x = f y := f.symm_apply_eq lemma zpow_apply_comm {α : Type*} (σ : perm α) (m n : ℤ) {x : α} : (σ ^ m) ((σ ^ n) x) = (σ ^ n) ((σ ^ m) x) := by rw [←equiv.perm.mul_apply, ←equiv.perm.mul_apply, zpow_mul_comm] @[simp] lemma iterate_eq_pow (f : perm α) : ∀ n, f^[n] = ⇑(f ^ n) | 0 := rfl | (n + 1) := by { rw [function.iterate_succ, pow_add, iterate_eq_pow], refl } /-! Lemmas about mixing `perm` with `equiv`. Because we have multiple ways to express `equiv.refl`, `equiv.symm`, and `equiv.trans`, we want simp lemmas for every combination. The assumption made here is that if you're using the group structure, you want to preserve it after simp. -/ @[simp] lemma trans_one {α : Sort*} {β : Type*} (e : α ≃ β) : e.trans (1 : perm β) = e := equiv.trans_refl e @[simp] lemma mul_refl (e : perm α) : e * equiv.refl α = e := equiv.trans_refl e @[simp] lemma one_symm : (1 : perm α).symm = 1 := equiv.refl_symm @[simp] lemma refl_inv : (equiv.refl α : perm α)⁻¹ = 1 := equiv.refl_symm @[simp] lemma one_trans {α : Type*} {β : Sort*} (e : α ≃ β) : (1 : perm α).trans e = e := equiv.refl_trans e @[simp] lemma refl_mul (e : perm α) : equiv.refl α * e = e := equiv.refl_trans e @[simp] lemma inv_trans_self (e : perm α) : e⁻¹.trans e = 1 := equiv.symm_trans_self e @[simp] lemma mul_symm (e : perm α) : e * e.symm = 1 := equiv.symm_trans_self e @[simp] lemma self_trans_inv (e : perm α) : e.trans e⁻¹ = 1 := equiv.self_trans_symm e @[simp] lemma symm_mul (e : perm α) : e.symm * e = 1 := equiv.self_trans_symm e /-! Lemmas about `equiv.perm.sum_congr` re-expressed via the group structure. -/ @[simp] lemma sum_congr_mul {α β : Type*} (e : perm α) (f : perm β) (g : perm α) (h : perm β) : sum_congr e f * sum_congr g h = sum_congr (e * g) (f * h) := sum_congr_trans g h e f @[simp] lemma sum_congr_inv {α β : Type*} (e : perm α) (f : perm β) : (sum_congr e f)⁻¹ = sum_congr e⁻¹ f⁻¹ := sum_congr_symm e f @[simp] lemma sum_congr_one {α β : Type*} : sum_congr (1 : perm α) (1 : perm β) = 1 := sum_congr_refl /-- `equiv.perm.sum_congr` as a `monoid_hom`, with its two arguments bundled into a single `prod`. This is particularly useful for its `monoid_hom.range` projection, which is the subgroup of permutations which do not exchange elements between `α` and `β`. -/ @[simps] def sum_congr_hom (α β : Type*) : perm α × perm β →* perm (α ⊕ β) := { to_fun := λ a, sum_congr a.1 a.2, map_one' := sum_congr_one, map_mul' := λ a b, (sum_congr_mul _ _ _ _).symm} lemma sum_congr_hom_injective {α β : Type*} : function.injective (sum_congr_hom α β) := begin rintros ⟨⟩ ⟨⟩ h, rw prod.mk.inj_iff, split; ext i, { simpa using equiv.congr_fun h (sum.inl i), }, { simpa using equiv.congr_fun h (sum.inr i), }, end @[simp] lemma sum_congr_swap_one {α β : Type*} [decidable_eq α] [decidable_eq β] (i j : α) : sum_congr (equiv.swap i j) (1 : perm β) = equiv.swap (sum.inl i) (sum.inl j) := sum_congr_swap_refl i j @[simp] lemma sum_congr_one_swap {α β : Type*} [decidable_eq α] [decidable_eq β] (i j : β) : sum_congr (1 : perm α) (equiv.swap i j) = equiv.swap (sum.inr i) (sum.inr j) := sum_congr_refl_swap i j /-! Lemmas about `equiv.perm.sigma_congr_right` re-expressed via the group structure. -/ @[simp] lemma sigma_congr_right_mul {α : Type*} {β : α → Type*} (F : Π a, perm (β a)) (G : Π a, perm (β a)) : sigma_congr_right F * sigma_congr_right G = sigma_congr_right (F * G) := sigma_congr_right_trans G F @[simp] lemma sigma_congr_right_inv {α : Type*} {β : α → Type*} (F : Π a, perm (β a)) : (sigma_congr_right F)⁻¹ = sigma_congr_right (λ a, (F a)⁻¹) := sigma_congr_right_symm F @[simp] lemma sigma_congr_right_one {α : Type*} {β : α → Type*} : (sigma_congr_right (1 : Π a, equiv.perm $ β a)) = 1 := sigma_congr_right_refl /-- `equiv.perm.sigma_congr_right` as a `monoid_hom`. This is particularly useful for its `monoid_hom.range` projection, which is the subgroup of permutations which do not exchange elements between fibers. -/ @[simps] def sigma_congr_right_hom {α : Type*} (β : α → Type*) : (Π a, perm (β a)) →* perm (Σ a, β a) := { to_fun := sigma_congr_right, map_one' := sigma_congr_right_one, map_mul' := λ a b, (sigma_congr_right_mul _ _).symm } lemma sigma_congr_right_hom_injective {α : Type*} {β : α → Type*} : function.injective (sigma_congr_right_hom β) := begin intros x y h, ext a b, simpa using equiv.congr_fun h ⟨a, b⟩, end /-- `equiv.perm.subtype_congr` as a `monoid_hom`. -/ @[simps] def subtype_congr_hom (p : α → Prop) [decidable_pred p] : (perm {a // p a}) × (perm {a // ¬ p a}) →* perm α := { to_fun := λ pair, perm.subtype_congr pair.fst pair.snd, map_one' := perm.subtype_congr.refl, map_mul' := λ _ _, (perm.subtype_congr.trans _ _ _ _).symm } lemma subtype_congr_hom_injective (p : α → Prop) [decidable_pred p] : function.injective (subtype_congr_hom p) := begin rintros ⟨⟩ ⟨⟩ h, rw prod.mk.inj_iff, split; ext i; simpa using equiv.congr_fun h i end /-- If `e` is also a permutation, we can write `perm_congr` completely in terms of the group structure. -/ @[simp] lemma perm_congr_eq_mul (e p : perm α) : e.perm_congr p = e * p * e⁻¹ := rfl section extend_domain /-! Lemmas about `equiv.perm.extend_domain` re-expressed via the group structure. -/ variables (e : perm α) {p : β → Prop} [decidable_pred p] (f : α ≃ subtype p) @[simp] lemma extend_domain_one : extend_domain 1 f = 1 := extend_domain_refl f @[simp] lemma extend_domain_inv : (e.extend_domain f)⁻¹ = e⁻¹.extend_domain f := rfl @[simp] lemma extend_domain_mul (e e' : perm α) : (e.extend_domain f) * (e'.extend_domain f) = (e * e').extend_domain f := extend_domain_trans _ _ _ /-- `extend_domain` as a group homomorphism -/ @[simps] def extend_domain_hom : perm α →* perm β := { to_fun := λ e, extend_domain e f, map_one' := extend_domain_one f, map_mul' := λ e e', (extend_domain_mul f e e').symm } lemma extend_domain_hom_injective : function.injective (extend_domain_hom f) := (injective_iff_map_eq_one (extend_domain_hom f)).mpr (λ e he, ext (λ x, f.injective (subtype.ext ((extend_domain_apply_image e f x).symm.trans (ext_iff.mp he (f x)))))) @[simp] end extend_domain /-- If the permutation `f` fixes the subtype `{x // p x}`, then this returns the permutation on `{x // p x}` induced by `f`. -/ def subtype_perm (f : perm α) {p : α → Prop} (h : ∀ x, p x ↔ p (f x)) : perm {x // p x} := ⟨λ x, ⟨f x, (h _).1 x.2⟩, λ x, ⟨f⁻¹ x, (h (f⁻¹ x)).2 $ by simpa using x.2⟩, λ _, by simp only [perm.inv_apply_self, subtype.coe_eta, subtype.coe_mk], λ _, by simp only [perm.apply_inv_self, subtype.coe_eta, subtype.coe_mk]⟩ @[simp] lemma subtype_perm_apply (f : perm α) {p : α → Prop} (h : ∀ x, p x ↔ p (f x)) (x : {x // p x}) : subtype_perm f h x = ⟨f x, (h _).1 x.2⟩ := rfl @[simp] lemma subtype_perm_one (p : α → Prop) (h : ∀ x, p x ↔ p ((1 : perm α) x)) : @subtype_perm α 1 p h = 1 := equiv.ext $ λ ⟨_, _⟩, rfl /-- The inclusion map of permutations on a subtype of `α` into permutations of `α`, fixing the other points. -/ def of_subtype {p : α → Prop} [decidable_pred p] : perm (subtype p) →* perm α := { to_fun := λ f, ⟨λ x, if h : p x then f ⟨x, h⟩ else x, λ x, if h : p x then f⁻¹ ⟨x, h⟩ else x, λ x, have h : ∀ h : p x, p (f ⟨x, h⟩), from λ h, (f ⟨x, h⟩).2, by { simp only [], split_ifs at *; simp only [perm.inv_apply_self, subtype.coe_eta, subtype.coe_mk, not_true, *] at * }, λ x, have h : ∀ h : p x, p (f⁻¹ ⟨x, h⟩), from λ h, (f⁻¹ ⟨x, h⟩).2, by { simp only [], split_ifs at *; simp only [perm.apply_inv_self, subtype.coe_eta, subtype.coe_mk, not_true, *] at * }⟩, map_one' := begin ext, dsimp, split_ifs; refl, end, map_mul' := λ f g, equiv.ext $ λ x, begin by_cases h : p x, { have h₁ : p (f (g ⟨x, h⟩)), from (f (g ⟨x, h⟩)).2, have h₂ : p (g ⟨x, h⟩), from (g ⟨x, h⟩).2, simp only [h, h₂, coe_fn_mk, perm.mul_apply, dif_pos, subtype.coe_eta] }, { simp only [h, coe_fn_mk, perm.mul_apply, dif_neg, not_false_iff] } end } lemma of_subtype_subtype_perm {f : perm α} {p : α → Prop} [decidable_pred p] (h₁ : ∀ x, p x ↔ p (f x)) (h₂ : ∀ x, f x ≠ x → p x) : of_subtype (subtype_perm f h₁) = f := equiv.ext $ λ x, begin rw [of_subtype, subtype_perm], by_cases hx : p x, { simp only [hx, coe_fn_mk, dif_pos, monoid_hom.coe_mk, subtype.coe_mk]}, { haveI := classical.prop_decidable, simp only [hx, not_not.mp (mt (h₂ x) hx), coe_fn_mk, dif_neg, not_false_iff, monoid_hom.coe_mk] } end lemma of_subtype_apply_of_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) {x : α} (hx : p x) : of_subtype f x = f ⟨x, hx⟩ := dif_pos hx @[simp] lemma of_subtype_apply_coe {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) (x : subtype p) : of_subtype f x = f x := subtype.cases_on x $ λ _, of_subtype_apply_of_mem f lemma of_subtype_apply_of_not_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) {x : α} (hx : ¬ p x) : of_subtype f x = x := dif_neg hx lemma mem_iff_of_subtype_apply_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) (x : α) : p x ↔ p ((of_subtype f : α → α) x) := if h : p x then by simpa only [of_subtype, h, coe_fn_mk, dif_pos, true_iff, monoid_hom.coe_mk] using (f ⟨x, h⟩).2 else by simp [h, of_subtype_apply_of_not_mem f h] @[simp] lemma subtype_perm_of_subtype {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) : subtype_perm (of_subtype f) (mem_iff_of_subtype_apply_mem f) = f := equiv.ext $ λ ⟨x, hx⟩, by { dsimp [subtype_perm, of_subtype], simp only [show p x, from hx, dif_pos, subtype.coe_eta] } @[simp] lemma default_perm {n : Type*} : (default : perm n) = 1 := rfl /-- Permutations on a subtype are equivalent to permutations on the original type that fix pointwise the rest. -/ @[simps] protected def subtype_equiv_subtype_perm (p : α → Prop) [decidable_pred p] : perm (subtype p) ≃ {f : perm α // ∀ a, ¬p a → f a = a} := { to_fun := λ f, ⟨f.of_subtype, λ a, f.of_subtype_apply_of_not_mem⟩, inv_fun := λ f, (f : perm α).subtype_perm (λ a, ⟨decidable.not_imp_not.1 $ λ hfa, (f.val.injective (f.prop _ hfa) ▸ hfa), decidable.not_imp_not.1 $ λ ha hfa, ha $ f.prop a ha ▸ hfa⟩), left_inv := equiv.perm.subtype_perm_of_subtype, right_inv := λ f, subtype.ext (equiv.perm.of_subtype_subtype_perm _ $ λ a, not.decidable_imp_symm $ f.prop a) } lemma subtype_equiv_subtype_perm_apply_of_mem {α : Type*} {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) {a : α} (h : p a) : perm.subtype_equiv_subtype_perm p f a = f ⟨a, h⟩ := f.of_subtype_apply_of_mem h lemma subtype_equiv_subtype_perm_apply_of_not_mem {α : Type*} {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) {a : α} (h : ¬ p a) : perm.subtype_equiv_subtype_perm p f a = a := f.of_subtype_apply_of_not_mem h variables (e : perm α) (ι : α ↪ β) open_locale classical /-- Noncomputable version of `equiv.perm.via_fintype_embedding` that does not assume `fintype` -/ noncomputable def via_embedding : perm β := extend_domain e (of_injective ι.1 ι.2) lemma via_embedding_apply (x : α) : e.via_embedding ι (ι x) = ι (e x) := extend_domain_apply_image e (of_injective ι.1 ι.2) x lemma via_embedding_apply_of_not_mem (x : β) (hx : x ∉ _root_.set.range ι) : e.via_embedding ι x = x := extend_domain_apply_not_subtype e (of_injective ι.1 ι.2) hx /-- `via_embedding` as a group homomorphism -/ noncomputable def via_embedding_hom : perm α →* perm β:= extend_domain_hom (of_injective ι.1 ι.2) lemma via_embedding_hom_apply : via_embedding_hom ι e = via_embedding e ι := rfl lemma via_embedding_hom_injective : function.injective (via_embedding_hom ι) := extend_domain_hom_injective (of_injective ι.1 ι.2) end perm section swap variables [decidable_eq α] @[simp] lemma swap_inv (x y : α) : (swap x y)⁻¹ = swap x y := rfl @[simp] lemma swap_mul_self (i j : α) : swap i j * swap i j = 1 := swap_swap i j lemma swap_mul_eq_mul_swap (f : perm α) (x y : α) : swap x y * f = f * swap (f⁻¹ x) (f⁻¹ y) := equiv.ext $ λ z, begin simp only [perm.mul_apply, swap_apply_def], split_ifs; simp only [perm.apply_inv_self, *, perm.eq_inv_iff_eq, eq_self_iff_true, not_true] at * end lemma mul_swap_eq_swap_mul (f : perm α) (x y : α) : f * swap x y = swap (f x) (f y) * f := by rw [swap_mul_eq_mul_swap, perm.inv_apply_self, perm.inv_apply_self] lemma swap_apply_apply (f : perm α) (x y : α) : swap (f x) (f y) = f * swap x y * f⁻¹ := by rw [mul_swap_eq_swap_mul, mul_inv_cancel_right] /-- Left-multiplying a permutation with `swap i j` twice gives the original permutation. This specialization of `swap_mul_self` is useful when using cosets of permutations. -/ @[simp] lemma swap_mul_self_mul (i j : α) (σ : perm α) : equiv.swap i j * (equiv.swap i j * σ) = σ := by rw [←mul_assoc, swap_mul_self, one_mul] /-- Right-multiplying a permutation with `swap i j` twice gives the original permutation. This specialization of `swap_mul_self` is useful when using cosets of permutations. -/ @[simp] lemma mul_swap_mul_self (i j : α) (σ : perm α) : (σ * equiv.swap i j) * equiv.swap i j = σ := by rw [mul_assoc, swap_mul_self, mul_one] /-- A stronger version of `mul_right_injective` -/ @[simp] lemma swap_mul_involutive (i j : α) : function.involutive ((*) (equiv.swap i j)) := swap_mul_self_mul i j /-- A stronger version of `mul_left_injective` -/ @[simp] lemma mul_swap_involutive (i j : α) : function.involutive (* (equiv.swap i j)) := mul_swap_mul_self i j @[simp] lemma swap_eq_one_iff {i j : α} : swap i j = (1 : perm α) ↔ i = j := swap_eq_refl_iff lemma swap_mul_eq_iff {i j : α} {σ : perm α} : swap i j * σ = σ ↔ i = j := ⟨(assume h, have swap_id : swap i j = 1 := mul_right_cancel (trans h (one_mul σ).symm), by {rw [←swap_apply_right i j, swap_id], refl}), (assume h, by erw [h, swap_self, one_mul])⟩ lemma mul_swap_eq_iff {i j : α} {σ : perm α} : σ * swap i j = σ ↔ i = j := ⟨(assume h, have swap_id : swap i j = 1 := mul_left_cancel (trans h (one_mul σ).symm), by {rw [←swap_apply_right i j, swap_id], refl}), (assume h, by erw [h, swap_self, mul_one])⟩ lemma swap_mul_swap_mul_swap {x y z : α} (hwz: x ≠ y) (hxz : x ≠ z) : swap y z * swap x y * swap y z = swap z x := equiv.ext $ λ n, by { simp only [swap_apply_def, perm.mul_apply], split_ifs; cc } end swap end equiv
proposition Heine_Borel_imp_Bolzano_Weierstrass: assumes "compact s" and "infinite t" and "t \<subseteq> s" shows "\<exists>x \<in> s. x islimpt t"
import .core namespace tts ------------------------------------------------------------------ namespace exp ------------------------------------------------------------------ variables {V : Type} [decidable_eq V] -- Type of variable names variables {k k₂ k₃ : ℕ} -- Natural numbers variables {v : V} -- Variable names variables {x : tagged V} -- Variables variables {e ea eb ed ef e₁ e₂ e₃ : exp V} -- Expressions open occurs /-- Open an expression (last parameter) with an expression (e) for a bound variable. -/ def open_exp (e : exp V) : ℕ → exp V → exp V | k (var bound x) := if k = x.tag then e else var bound x | _ (var free x) := var free x | k (app ef ea) := app (open_exp k ef) (open_exp k ea) | k (lam v eb) := lam v (open_exp k.succ eb) | k (let_ v ed eb) := let_ v (open_exp k ed) (open_exp k.succ eb) @[simp] theorem open_exp_var_bound_eq (h : k = x.tag) : open_exp e k (var bound x) = e := by simp [open_exp, h] @[simp] theorem open_exp_var_bound_ne (h : k ≠ x.tag) : open_exp e k (var bound x) = var bound x := by simp [open_exp, h] @[simp] theorem open_exp_var_free : open_exp e k (var free x) = var free x := rfl @[simp] theorem open_exp_app : open_exp e k (app ef ea) = app (open_exp e k ef) (open_exp e k ea) := rfl @[simp] theorem open_exp_lam : open_exp e k (lam v eb) = lam v (open_exp e k.succ eb) := rfl @[simp] theorem open_exp_let_ : open_exp e k (let_ v ed eb) = let_ v (open_exp e k ed) (open_exp e k.succ eb) := rfl /-- Open an expression with an expression `e` for the last bound variable (0) -/ def open_exp₀ (e : exp V) : exp V → exp V := open_exp e 0 /-- Open an expression with a free variable `x` for the last bound variable -/ def open_var (x : tagged V) : exp V → exp V := open_exp₀ (var free x) /-- Open an expression with a variable of the name `v` fresh from the variable set `L` for the last bound variable. -/ def open_fresh (v : V) (L : finset (tagged V)) : exp V → exp V := open_var $ (fresh.tagged v).gen L end /- namespace -/ exp -------------------------------------------------------- end /- namespace -/ tts --------------------------------------------------------
(****************************************************************) (* DEDUCTION NATURELLE *) (****************************************************************) (****************************************************************) (* [A] * implique_intro h : *) (* ... * Si le but est de la forme A => B rajoute A aux *) (* B * hypotèses sous le nom h et remplace le but par *) (* -------- * B. *) (* A => B * *) (****************************************************************) Ltac implique_intro h := match goal with | |- _ -> _ => try intro h | |- ~ _ => try intro h | _ => idtac "Erreur: aucun implique dans le but courant." end . (****************************************************************) (* * implique_elim h : *) (* * Si h est de la forme A=>B et le but *) (* * courant de la forme B remplace le but par A. *) (* * Si h est de la forme A et le but courant de la *) (* A A=>B * forme A=>B remplace le but par A. *) (* --------- * *) (* B * implique_elim h i j : *) (* * Si h est de la forme A=>B et i de la forme A *) (* * Cree une nouvelle hypothèse j contenant B. *) (* * *) (****************************************************************) Inductive ltac_No_arg : Set := | ltac_no_arg : ltac_No_arg. Ltac implique_elim_tac h i j := match type of i with | ltac_No_arg => match goal with | |- _ -> _ => try elim h | |- ?X1 => try apply h | _ => idtac "Erreur: l'hypotese n'est pas appliquable au but courant." end | _ => try pose ( j := h i ) | _ => idtac "Erreur: impossible de creer le resolvant des deux hypoteses." end . Tactic Notation "implique_elim" constr(h) := implique_elim_tac h ltac_no_arg ltac_no_arg. Tactic Notation "implique_elim" constr(h) constr(i) ident(j) := implique_elim_tac h i j. (****************************************************************) (* * et_elim_1 h h_decomp: *) (* A /\ B * Si h est de la forme A /\ B rajoute A aux *) (* -------- * hypotèses sous le nom h_decomp. *) (* A * *) (* * *) (****************************************************************) Ltac et_elim_1 h h_decomp := match type of h with | _ /\ _ => try ( elim h; intros h_decomp Tmp ; clear Tmp ) | _ => idtac "Erreur: l'hypotese n'est pas decomposable." end . (****************************************************************) (* * et_elim_1 h h_decomp: *) (* A /\ B * Si h est de la forme A /\ B rajoute B aux *) (* -------- * hypotèses sous le nom h_decomp. *) (* B * *) (* * *) (****************************************************************) Ltac et_elim_2 h h_decomp := match type of h with | _ /\ _ => try (elim h; intros Tmp h_decomp ; clear Tmp) | _ => idtac "Erreur: l'hypotese n'est pas decomposable." end . (****************************************************************) (* * et_intro : *) (* A B * Si le but est de la forme A /\ B Decompose le *) (* -------- * but courant en deux sous-but contenant A et B. *) (* A /\ B * *) (* * *) (****************************************************************) Ltac et_intro := match goal with | |- _ /\ _ => try split | _ => idtac "Erreur: le but courant n'est pas décomposable." end . (****************************************************************) (* * ou_intro_1 : *) (* A * Si le but est de la forme A \/ B remplace le *) (* -------- * but courant par A. *) (* A \/ B * *) (* * *) (****************************************************************) Ltac ou_intro_1 := match goal with | |- _ \/ _ => try left | _ => idtac "Erreur: introduction de l'hypotese impossible." end . (****************************************************************) (* * ou_intro_2 : *) (* B * Si le but est de la forme A \/ B remplace le *) (* -------- * but courant par B. *) (* A \/ B * *) (* * *) (****************************************************************) Ltac ou_intro_2 := match goal with | |- _ \/ _ => try right | _ => idtac "Erreur: introduction de l'hypotese impossible." end . (****************************************************************) (* * ou_elim h : *) (* A\/B A=>C B=>C * Si h est de la forme A \/ B et le but *) (* -------------- * courant de la forme C cree deux nouveaux *) (* C * buts A=>C et B=>C. *) (* * *) (****************************************************************) Ltac ou_elim h := match type of h with | _ \/ _ => try elim h | _ => idtac "Erreur: forme de l'hypotese incorrecte." end . (****************************************************************) (* * efq : *) (* _|_ * Remplace le but courant par False. *) (* ------- * *) (* A * *) (* * *) (****************************************************************) Ltac efq := try exfalso. (****************************************************************) (* * raa : *) (* ~~A * Si le but est de la forme ~~A ou *) (* ------- * (A => False => False) le remplace par A. *) (* A * *) (* * *) (****************************************************************) Ltac raa := match goal with | |- (~~ _ ) => let tmp := fresh in try (intro tmp ; apply tmp ; clear tmp) | |- ( _ -> False -> False) => let tmp := fresh in try (intro tmp ; apply tmp ; clear tmp) | _ => idtac "Erreur: reduction a l absurde impossible sur le but courant." end . (****************************************************************) (* QUANTIFICATEURS *) (****************************************************************) (****************************************************************) (* * pourtout_intro h : *) (* A * Si le but est de la forme forall x, A *) (* ------------- * le remplace par A et ajoute une instance *) (* forall x, A * de x comme hypothese. Cette nouvelle *) (* * hypothese est nommee h. *) (****************************************************************) Ltac pourtout_intro h := match goal with | |- forall _ , _ => intro h | _ => idtac "Erreur: Aucun pour tout decomposable dans le but courant." end . (****************************************************************) (* * pourtout_elim h i t : *) (* forall x, A * Si h est de la forme forall x, A cree une *) (* ------------- * nouvelle hypothese i qui est *) (* A < x:=t > * l'instantiation de h avec < x:=t >. *) (* * *) (****************************************************************) Ltac pourtout_elim h i t := match type of h with | forall _ , _ => pose ( i := h t ) | _ => idtac "Erreur: Aucun pour tout decomposable dans l'hypothese." end . (****************************************************************) (* * existe_intro t : *) (* A < x:=t > * Si le but est de la forme exists x, A *) (* ------------- * le remplace par A < x:=t >. *) (* exists x, A * *) (* * *) (****************************************************************) Ltac existe_intro t := match goal with | |- exists _ , _ => exists t | _ => idtac "Erreur: Le but courant ne contient pas de il existe decomposable." end . (****************************************************************) (* * existe_elim h i : *) (* (exists x, A) A=>B * Si le but est de la forme B et h de *) (* -------------------- * la forme (exists x, A) remplace le *) (* B * but courant par A=>B et ajout une *) (* * instance i de x dans les hypotheses *) (****************************************************************) Ltac existe_elim h i := match type of h with | exists _ , _ => elim h ; intro i | _ => idtac "Erreur : l hypothese ne contient pas de il existe decomposable." end . (****************************************************************) (* EGALITE *) (****************************************************************)
#Series temporais e analises preditivas - Fernando Amaral library(forecast) library(ggplot2) plot(Seatbelts) x1 = tslm(DriversKilled ~ trend, data=Seatbelts) x2 = tslm(DriversKilled ~ season, data=Seatbelts) x3 = tslm(DriversKilled ~ trend + season, data=Seatbelts) CV(x1) CV(x2) CV(x3) #fazendo previsao r1 = forecast(x1,h=12) r2 = forecast(x2,h=12) r3 = forecast(x3,h=12) autoplot(r1) autoplot(r2) autoplot(r3) plot(r1) lines(r2$mean, col="red") lines(r3$mean, col="green") legend("topright",legend=c("Tend","Seas","Tend + Seas"), col = c("blue","red","green"), lty=1:2, cex=0.8)
lemma Inf_lim: fixes a :: "'a::{complete_linorder,linorder_topology}" assumes "\<And>n. b n \<in> s" and "b \<longlonglongrightarrow> a" shows "Inf s \<le> a"
[GOAL] C : Type u_1 inst✝¹ : Category.{u_2, u_1} C inst✝ : ConcreteCategory C X Y : C f g : X ⟶ Y h : f = g x : (forget C).obj X ⊢ ↑f x = ↑g x [PROOFSTEP] rw [h]
import tactic import data.set import incidence_geometry def Point := ℝ × ℝ @[simp] lemma point_neq_by_coords (A B : Point) : (A ≠ B) ↔ (A.1 ≠ B.1 ∨ A.2 ≠ B.2) := begin rw ← not_iff_not, push_neg, exact prod.ext_iff end @[ext] structure LineEq := (a b c : ℝ) (h : a ≠ 0 ∨ b ≠ 0) definition line_eq (l m : LineEq) : Prop := ∃ (x : ℝ), x≠ 0 ∧ l.a = x * m.a ∧ l.b = x * m.b ∧ l.c = x * m.c lemma line_eq_refl : reflexive line_eq := begin intro l, use 1, refine ⟨zero_ne_one.symm, _, _, _⟩, { rw one_mul }, { rw one_mul }, { rw one_mul }, end lemma line_eq_symm : symmetric line_eq := begin intros l m hlm, rcases hlm with ⟨x, ⟨hx, ha, hb, hc⟩⟩ , use x⁻¹, have hxinv : x⁻¹*x = 1, { finish }, /- TODO: remove finish -/ refine ⟨inv_ne_zero hx,_,_,_⟩, { simp only [ha], rw [← mul_assoc, hxinv, one_mul] }, { simp only [hb], rw [← mul_assoc, hxinv, one_mul] }, { simp only [hc], rw [← mul_assoc, hxinv, one_mul] }, end lemma line_eq_trans : transitive line_eq := begin intros l m n hlm hmn, rcases hlm with ⟨x, ⟨hx, ha₁, hb₁, hc₁⟩⟩ , rcases hmn with ⟨y, ⟨hy, ha₂, hb₂, hc₂⟩⟩ , use x*y, refine ⟨mul_ne_zero hx hy,_,_,_⟩, { rw [ha₁, ha₂, mul_assoc] }, { rw [hb₁, hb₂, mul_assoc] }, { rw [hc₁, hc₂, mul_assoc] }, end theorem line_equiv : equivalence line_eq := ⟨line_eq_refl, line_eq_symm, line_eq_trans⟩ def Line.setoid : setoid LineEq := { r := line_eq, iseqv := line_equiv } local attribute [instance] Line.setoid def Line := quotient Line.setoid def Line.reduce : LineEq → Line := quot.mk line_eq instance : has_lift LineEq Line := { lift := Line.reduce } instance : has_coe LineEq Line := { coe := Line.reduce } def Line.mk (a b c : ℝ) (h : a ≠ 0 ∨ b ≠ 0) : Line := ↑(LineEq.mk a b c h) def has_point' (l : LineEq) (P : Point) : Prop := l.a*P.1 + l.b*P.2 + l.c = 0 theorem has_point_well_defined {l m : LineEq} (h : l ≈ m) (P : Point): has_point' l P ↔ has_point' m P := begin cases h with x h, rcases h with ⟨hx, ha, hb, hc⟩, rw [has_point', ha, hb, hc, mul_assoc, mul_assoc, ← left_distrib, ← left_distrib], rw has_point', finish, /- TODO: remove finish -/ end lemma has_point_well_defined' {l m : LineEq} (h: l ≈ m) : has_point' l = has_point' m := begin rw function.funext_iff, intro P, rw has_point_well_defined, exact h, end def has_point := quotient.lift has_point' @has_point_well_defined' noncomputable def line_from_points {A B : Point} (hAB : A ≠ B) : Line := begin rw point_neq_by_coords at hAB, by_cases hx: A.1 = B.1, { let a : ℝ := 1, let b : ℝ := 0, let c : ℝ := -(A.1+B.1)/2, have h : a ≠ 0 ∨ b ≠ 0, { left, exact ne_zero.ne a }, exact Line.mk a b c h }, { rw push_neg.not_eq at hx, let a : ℝ := -(A.2-B.2)/(A.1-B.1), let b : ℝ := 1, let c : ℝ := -(a*(A.1+B.1)-(A.2+B.2))/2, have h : a ≠ 0 ∨ b ≠ 0, { right, exact ne_zero.ne b }, exact Line.mk a b c h } end def line_from_points' : Point → Point → Prop | (x, y) (a, b) := true lemma points_in_line_from_points {A B : Point} (hAB : A ≠ B) : has_point (line_from_points hAB) A ∧ has_point (line_from_points hAB) B := begin -- rw line_from_points, split, { rw [has_point], /- TODO: ¿Cómo puedo escoger un representante canónico? ¿o puedo evitar tener que escojerlo? -/ sorry }, { sorry }, end instance : incidence_geometry Point Line := { lies_on := λ P l, has_point l P, I1 := begin intros A B hAB, use line_from_points hAB, split, { simp, exact points_in_line_from_points hAB }, { intro m, simp, intros hA hB, sorry } end, I2 := begin intro ℓ, -- cases l.h, -- { -- use Point.mk (-l.c) 0, -- use Point.mk (-l.c-l.b) 1, -- split, -- { rw [ ← push_neg.not_eq, Point.ext_iff, push_neg.not_and_distrib_eq ], -- right, -- push_neg, -- exact zero_ne_one }, -- { split, -- { rw [h, one_mul, mul_zero, add_zero, add_left_neg] }, -- { rw [h, one_mul, mul_one, sub_add_cancel, add_left_neg] }, } -- }, -- { -- use Point.mk 0 (-l.c), -- use Point.mk 1 (-l.c-l.a), -- split, -- { rw [ ← push_neg.not_eq, -- Point.ext_iff, -- push_neg.not_and_distrib_eq ], -- left, -- push_neg, -- exact zero_ne_one }, -- { split, -- { rw [h, mul_zero, one_mul, zero_add, add_left_neg] }, -- { rw [h, mul_one, one_mul, add_sub_cancel'_right, add_left_neg] }}, -- }, sorry end, I3 := begin let A : Point := (0, 1), use A, let B : Point := (1, 0), use B, let C : Point := (1, 1), use C, split, { rw [different3, point_neq_by_coords, point_neq_by_coords, point_neq_by_coords], refine ⟨_, _, _⟩, { left, exact zero_ne_one }, { left, exact zero_ne_one }, { right, exact zero_ne_one }, }, { push_neg, intros l hA hB, -- rw [ne.def, mul_one, mul_one], -- cases l.h with ha hb, -- { -- rw [ha, mul_zero, mul_one, add_zero, add_eq_zero_iff_neg_eq] at hB, -- have hc : l.c = -1, { exact hB.symm }, -- rw [ha, hc, mul_zero, zero_add, mul_one, add_eq_zero_iff_eq_neg, neg_neg ] at hA, -- rw [ha, hA, hc, add_neg_cancel_comm, push_neg.not_eq], -- exact one_ne_zero }, -- { -- rw [hb, mul_zero, mul_one, zero_add, add_eq_zero_iff_neg_eq] at hA, -- have hc : l.c = -1, { exact hA.symm }, -- rw [hc, mul_zero, mul_one, add_zero, add_eq_zero_iff_eq_neg, neg_neg] at hB, -- rw [hB, hb, hc, add_neg_cancel_comm, push_neg.not_eq], -- exact one_ne_zero }}, sorry } end }
# Decision Tree's A learning algorithm that uses _information gain_ to measure how well a feature of the data distinguishes between different classes. Information gain is measured in terms of _entropy_. Decision Tree's can be thought of as a compact representation of a function. In a binary classification scenario, this would mean that a decision tree represents a truth table. Decision tree's attempt to predict a qualitative (categorical) response by stratifying the predictor space into simpler regions. Concretely, the prediction space is divided into regions representing classes. Decision tree's can also be used in regression scenarios. ## MONK Dataset In this notebook we'll use the [MONK Dataset](https://archive.ics.uci.edu/ml/datasets/MONK's+Problems) from UC Irvine's Machine Learning Repository. The MONK dataset is a collection of artificial data which spans two classes and distributed by some underlying function. ### True Functions * MONK-1: $(a_1 = a_2) \wedge (a_5 = 1)$ * MONK-2: $a_i = 1 \text{ for exactly two } i \in \{1,2,\ldots,6\}$ * MONK-3: $(a_5 = 1 \wedge a_4 = 1) \vee (a_5 \neq 4 \wedge a_2 \neq 3)$ MONK-3 contains misclassified data (5%). In the case of noisy data, the learning algorithm may generate only partially consistent rules. ### Loading Data Data will be accessible via a dictionary, e.g. `data['monks-1']['train']` ```python from pathlib import Path data_path = Path(__name__).resolve().parents[1] / 'data' / 'MONK' m1_train = data_path / 'monks-1.train' print("A single example from MONK-1") with m1_train.open() as f: print(f.readline()) ``` A single example from MONK-1 1 1 1 1 1 3 1 data_5 Attribute information: 1. class: 0, 1 2. a1: 1, 2, 3 3. a2: 1, 2, 3 4. a3: 1, 2 5. a4: 1, 2, 3 6. a5: 1, 2, 3, 4 7. a6: 1, 2 8. Id: (A unique symbol for each instance) ```python from typing import NamedTuple data = { 'monks-1': { 'train': [], 'test': [], }, 'monks-2': { 'train': [], 'test': [], }, 'monks-3': { 'train': [], 'test': [], }, } class MonkDatum(NamedTuple): a: list label: int symbol: str for key, subkeys in data.items(): for subkey in subkeys: data_file = data_path / f"{key}.{subkey}" with data_file.open() as f: data[key][subkey] = [MonkDatum(a=line[1:7], label=line[0], symbol=line[7]) for line in (line.split() for line in f.readlines())] print(f"Loaded {key} {subkey} dataset") ``` Loaded monks-1 train dataset Loaded monks-1 test dataset Loaded monks-2 train dataset Loaded monks-2 test dataset Loaded monks-3 train dataset Loaded monks-3 test dataset ## Entropy Entropy is a measure of information. In natural language processing, entropy can be a measure of how much information there is in a grammar or how well a grammar fits a language. To compute entropy, establish a random variable $S$ over the class labels. . The entropy of any $S$ is. \begin{equation} \text{Entropy}(S) = - \sum_ip_i\log_2p_i \end{equation} $S$: A collection of samples $p_i$: Proportion of examples of class $i$ in $S$. This is a probability function $p(x)$ In a binary classification problem, $\{0, 1\} \in S$, and the entropy of $S$ would become: \begin{equation} \text{Entropy}(S) = - p_0 \log_2 p_0 - p_1 \log_2 p_1 \end{equation} The log can be measured in any base. In base 2, the units of entropy are *bits*. The intuition behind entropy is to think of it as a lower bound on the number of bits needed for an optimal length encoding scheme for some piece of information. ```python def entropy(S, p): """Compute entropy of S given probability function p""" pass ```