text
stringlengths 0
3.34M
|
---|
/-
Copyright (c) 2022 Jannis Limperg. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jannis Limperg
-/
import Aesop
set_option trace.aesop.proof true in
example : α := by
aesop
|
lemma winding_number_as_continuous_log: assumes "path p" and \<zeta>: "\<zeta> \<notin> path_image p" obtains q where "path q" "pathfinish q - pathstart q = 2 * of_real pi * \<i> * winding_number p \<zeta>" "\<And>t. t \<in> {0..1} \<Longrightarrow> p t = \<zeta> + exp(q t)" |
"""
Functions for conic geometry implemented for
use with the `sympy` symbolic math module.
Generally, for use in testing and validation.
"""
from sympy import Matrix
def center(conic):
ec = conic[:-1,:-1].inv()
eo = -conic[:-1,-1]
return ec*eo
def dual(conic):
return conic.inv()
def polar_plane(ell, point=None):
if point is None:
point = [0]*(ell.shape[0]-1)
pt_ = Matrix(list(point)+[1])
return ell*pt_
def origin_distance(polar_plane):
return polar_plane[-1]/Matrix(polar_plane[:-1]).norm()
|
program proper
integer i,A(30)
do i = 11,20
A(i) = A(i-10)+A(i+10)
enddo
do i = 11,20
call dum1(A(i), A(i-10), A(i+10))
enddo
do i = 11,20
call dum2(A(i), A(i-10)+A(i+10))
enddo
end
subroutine dum1(i,j,k)
integer i,j,k
i = j + k
end
subroutine dum2(i,j)
integer i,j
i = j
end
|
/-
Copyright (c) 2017 Daniel Selsam. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Daniel Selsam
Environments.
-/
import data.hash_map library_dev.data.list.sort .tensor .id .util .reference
namespace certigrad
def pre_env : Type := hash_map reference (λ (ref : reference), T ref.2)
attribute [reducible] pre_env
namespace pre_env
definition eqv (m₁ m₂ : pre_env) : Prop :=
∀ (ref : reference), m₁^.find ref = m₂^.find ref
local infix ~ := eqv
definition eqv.refl (m : pre_env) : m ~ m :=
assume ref, rfl
definition eqv.symm (m₁ m₂ : pre_env) : m₁ ~ m₂ → m₂ ~ m₁ :=
assume H ref, eq.symm (H ref)
definition eqv.trans (m₁ m₂ m₃ : pre_env) : m₁ ~ m₂ → m₂ ~ m₃ → m₁ ~ m₃ :=
assume H₁ H₂ ref, eq.trans (H₁ ref) (H₂ ref)
instance pdmap.eqv_setoid : setoid pre_env :=
setoid.mk eqv (mk_equivalence eqv eqv.refl eqv.symm eqv.trans)
end pre_env
def env : Type := quot pre_env.eqv
namespace env
def mk : env := quotient.mk (mk_hash_map reference.hash)
def get (ref : reference) (q : env) : T ref.2 := quotient.lift_on q
(λ (m : pre_env),
match m^.find ref with
| none := default _
| some x := x
end)
begin intros m₁ m₂ H_eqv, simp [H_eqv ref] end
def insert (ref : reference) (x : T ref.2) (q : env) : env := quotient.lift_on q
(λ (m : pre_env), quotient.mk $ m^.insert ref x)
begin
intros m₁ m₂ H_eqv, dsimp, apply quotient.sound,
intros ref',
cases (decidable.em (ref = ref')) with H_eq H_neq,
simp [hash_map.find_insert, dif_ctx_simp_congr, H_eq, dif_pos],
simp [hash_map.find_insert, dif_ctx_simp_congr, H_neq, dif_neg, H_eqv ref'],
end
def has_key (ref : reference) (q : env) : Prop := quotient.lift_on q
(λ (m : pre_env), m^.contains ref)
begin intros m₁ m₂ H_eqv, simp [hash_map.contains, H_eqv ref] end
def get_ks : Π (refs : list reference) (m : env), dvec T refs^.p2
| [] m := ⟦⟧
| (ref::refs) m := dvec.cons (get ref m) (get_ks refs m)
def insert_all : Π (refs : list reference) (vs : dvec T refs^.p2), env
| [] ⟦⟧ := env.mk
| (k::ks) (v:::vs) := env.insert k v (insert_all ks vs)
-- Facts
@[simp] lemma get.def (ref : reference) (m : pre_env) :
get ref (quotient.mk m) = match m^.find ref with | none := default _ | some x := x end := rfl
@[simp] lemma insert.def {ref : reference} {x : T ref.2} (m : pre_env) :
insert ref x (quotient.mk m) = quotient.mk (m^.insert ref x) :=
begin apply quotient.sound, apply pre_env.eqv.refl end
@[simp] lemma has_key.def (ref : reference) (m : pre_env) :
has_key ref (quotient.mk m) = m^.contains ref := rfl
@[simp] lemma bool_lift_t (b : bool) : (lift_t b : Prop) = (b = tt) := rfl
-- TODO(dhs): PR to standard library
lemma not_has_key_empty (ref : reference) : ¬ env.has_key ref env.mk :=
begin
simp [mk],
rw hash_map.contains_iff,
simp [hash_map.keys, hash_map.entries, mk_hash_map, bucket_array.as_list,
mk_array, array.foldl, array.iterate, array.iterate_aux, list.map, array.read],
end
lemma has_key_insert {ref₁ ref₂ : reference} {x₂ : T ref₂.2} {m : env} :
has_key ref₁ m → has_key ref₁ (insert ref₂ x₂ m) :=
begin
apply @quotient.induction_on _ _ (λ m, has_key ref₁ m → has_key ref₁ (insert ref₂ x₂ m)),
clear m,
intro m,
intro H_hk,
simp at *,
dsimp [hash_map.contains] at *,
rw hash_map.find_insert,
cases decidable.em (ref₂ = ref₁) with H_eq H_neq,
{
subst H_eq,
simp [dif_ctx_simp_congr, dif_pos],
dunfold option.is_some,
reflexivity,
},
{
simp [H_neq, dif_ctx_simp_congr, dif_neg],
exact H_hk
}
end
lemma has_key_insert_same (ref : reference) {x : T ref.2} (m : env) : has_key ref (insert ref x m) :=
begin
apply quotient.induction_on m,
clear m,
intro m,
simp,
dunfold hash_map.contains,
rw hash_map.find_insert_eq,
dsimp [option.is_some],
reflexivity
end
lemma has_key_insert_diff {ref₁ ref₂ : reference} {x : T ref₂.2} {m : env} :
ref₁ ≠ ref₂ → has_key ref₁ (insert ref₂ x m) → has_key ref₁ m :=
begin
apply @quotient.induction_on _ _ (λ m, ref₁ ≠ ref₂ → has_key ref₁ (insert ref₂ x m) → has_key ref₁ m),
clear m,
simp [hash_map.contains],
intros m H_neq,
rw hash_map.find_insert_ne,
intro H, exact H,
exact ne.symm H_neq
end
lemma get_insert_same (ref : reference) (x : T ref.2) (m : env) : get ref (insert ref x m) = x :=
begin
apply quotient.induction_on m, clear m, intro m,
simp,
rw hash_map.find_insert_eq,
end
lemma get_insert_diff {ref₁ ref₂ : reference} (x₂ : T ref₂.2) (m : env) : ref₁ ≠ ref₂ → get ref₁ (insert ref₂ x₂ m) = get ref₁ m :=
begin
apply @quotient.induction_on _ _ (λ m, ref₁ ≠ ref₂ → get ref₁ (insert ref₂ x₂ m) = get ref₁ m),
clear m,
intros m H_neq,
simp,
rw hash_map.find_insert,
-- TODO(dhs): annoying that we can't simplify inside the major premise
assert H_dif : (dite (ref₂ = ref₁) (λ h, some (eq.rec_on h x₂ : T ref₁.2)) (λ h, hash_map.find m ref₁)) = hash_map.find m ref₁,
simp [dif_ctx_simp_congr, dif_neg, ne.symm H_neq],
rw H_dif,
end
-- TODO(dhs): propagate precondition
lemma insert_get_same {ref : reference} {m : env} : has_key ref m → insert ref (get ref m) m = m :=
begin
apply @quotient.induction_on _ _ (λ m, has_key ref m → insert ref (get ref m) m = m),
clear m,
simp [hash_map.contains],
intros m H_has_key,
apply quotient.sound,
intro ref',
cases decidable.em (ref' = ref) with H_eq H_neq,
{
subst H_eq,
rw hash_map.find_insert_eq,
cases (hash_map.find m ref'),
{ dsimp [option.is_some] at H_has_key, injection H_has_key },
dsimp,
reflexivity
},
{
rw hash_map.find_insert_ne,
exact ne.symm H_neq
}
end
lemma insert_insert_flip {ref₁ ref₂ : reference} (x₁ : T ref₁.2) (x₂ : T ref₂.2) (m : env) :
ref₁ ≠ ref₂ → insert ref₁ x₁ (insert ref₂ x₂ m) = insert ref₂ x₂ (insert ref₁ x₁ m) :=
begin
apply @quotient.induction_on _ _ (λ m, ref₁ ≠ ref₂ → insert ref₁ x₁ (insert ref₂ x₂ m) = insert ref₂ x₂ (insert ref₁ x₁ m)),
clear m,
simp,
intros m H_neq,
apply quot.sound,
intro ref,
simp [hash_map.find_insert],
cases decidable.em (ref₁ = ref) with H_eq₁ H_neq₁,
cases decidable.em (ref₂ = ref) with H_eq₂ H_neq₂,
{ exfalso, exact H_neq (eq.trans H_eq₁ (eq.symm H_eq₂)) },
{ subst H_eq₁, simp [H_neq₂, dif_ctx_simp_congr, dif_neg, dif_pos] },
cases decidable.em (ref₂ = ref) with H_eq₂ H_neq₂,
{ subst H_eq₂, simp [H_neq₁, dif_ctx_simp_congr, dif_neg, dif_pos] },
{ simp [H_neq₁, H_neq₂, dif_ctx_simp_congr, dif_neg], }
end
lemma insert_insert_same (ref : reference) (x₁ x₂ : T ref.2) (m : env) :
insert ref x₁ (insert ref x₂ m) = insert ref x₁ m :=
begin
apply quotient.induction_on m,
clear m,
simp,
intros m,
apply quot.sound,
intro ref',
cases decidable.em (ref' = ref) with H_eq H_neq,
{ subst H_eq, simp [hash_map.find_insert_eq] },
-- TODO(dhs): simp fails for annoying reasons
rw hash_map.find_insert_ne _ _ _ _ (ne.symm H_neq),
rw hash_map.find_insert_ne _ _ _ _ (ne.symm H_neq),
rw hash_map.find_insert_ne _ _ _ _ (ne.symm H_neq)
end
lemma get_ks_env_eq (m₁ m₂ : env) :
∀ (refs : list reference), (∀ (ref : reference), ref ∈ refs → get ref m₁ = get ref m₂) → get_ks refs m₁ = get_ks refs m₂
| [] H := rfl
| (ref::refs) H :=
show get ref m₁ ::: get_ks refs m₁ = get ref m₂ ::: get_ks refs m₂, from
have H_get : get ref m₁ = get ref m₂, from H ref list.mem_of_cons_same,
have H_pre : ∀ (ref : reference), ref ∈ refs → get ref m₁ = get ref m₂, from
assume r H_r_mem,
H r (list.mem_cons_of_mem _ H_r_mem),
by rw [H_get, get_ks_env_eq _ H_pre]
lemma get_ks_insert_diff :
∀ {refs : list reference} {ref : reference} {x : T ref.2} {m : env}, ref ∉ refs → get_ks refs (insert ref x m) = get_ks refs m
| [] _ _ _ _ := rfl
| (ref::refs) ref₀ x m H_ref₀_notin :=
show get ref (insert ref₀ x m) ::: get_ks refs (insert ref₀ x m) = get ref m ::: get_ks refs m, from
have H_ne : ref ≠ ref₀, from ne.symm (list.ne_of_not_mem_cons H_ref₀_notin),
begin
rw (env.get_insert_diff _ _ H_ne),
rw get_ks_insert_diff (list.not_mem_of_not_mem_cons H_ref₀_notin),
end
lemma dvec_update_at_env {refs : list reference} {idx : ℕ} {ref : reference} (m : env) :
list.at_idx refs idx ref →
dvec.update_at (get ref m) (get_ks refs m) idx = get_ks refs m :=
begin
intro H_at_idx,
assert H_elem_at_idx : list.elem_at_idx refs idx ref, { exact list.elem_at_idx_of_at_idx H_at_idx },
induction H_elem_at_idx with xs x xs idx' x y H_elem_at_idx IH,
{ dsimp [get_ks], simp [dif_ctx_simp_congr, dif_pos] },
{ dsimp [get_ks], erw IH (list.at_idx_of_cons H_at_idx) }
end
lemma dvec_get_get_ks {refs : list reference} {idx : ℕ} {ref : reference} (m : env) :
list.at_idx refs idx ref →
dvec.get ref.2 (get_ks refs m) idx = get ref m :=
begin
intro H_at_idx,
assert H_elem_at_idx : list.elem_at_idx refs idx ref, { exact list.elem_at_idx_of_at_idx H_at_idx },
induction H_elem_at_idx with xs x xs idx' x y H_elem_at_idx IH,
{ dunfold get_ks, erw dvec.get.equations._eqn_2, simp [dif_ctx_simp_congr, dif_pos] },
{ dunfold get_ks, erw dvec.get.equations._eqn_3, exact IH (list.at_idx_of_cons H_at_idx) }
end
end env
attribute [semireducible] pre_env
end certigrad
|
import logic.equiv.basic
import tactic.norm_swap
open equiv tactic
/--
To properly test that norm_swap works without the help of the simplifier,
we turn off the simp lemmas that simplify swaps of the form
`swap x y x = y` and `swap x y y = x`.
-/
local attribute [-simp] swap_apply_left
local attribute [-simp] swap_apply_right
/--
We can check all possibilities of swapping of `0, 1, bit0 _, bit1 _` using the
64 combinations of `[0, 1, 2, 3]`. This example should execute and complete without error,
if `norm_swap.eval` is behaving properly.
-/
example : true := by do
let l : list ℕ := [0, 1, 2, 3],
let l' : list ((ℕ × ℕ) × ℕ) := (do a ← l, b ← l, c ← l, pure ((a, b), c)),
(lhs : list expr) ← mmap (λ (tup : (ℕ × ℕ) × ℕ),
to_expr ``(equiv.swap %%tup.fst.fst %%tup.fst.snd %%tup.snd)) l',
(rhs : list expr) ← mmap (λ (tup : (ℕ × ℕ) × ℕ),
if tup.snd = tup.fst.fst then to_expr ``(%%tup.fst.snd)
else if tup.snd = tup.fst.snd then to_expr ``(%%tup.fst.fst)
else to_expr ``(%%tup.snd)) l',
let eqs : list expr := list.zip_with (λ L R, `(@eq.{1} ℕ %%L %%R)) lhs rhs,
g ← get_goals,
gls ← mmap mk_meta_var eqs,
set_goals $ g ++ gls,
triv, -- to discharge the starting `true` goal
repeat $ tactic.norm_num norm_swap.eval [] (interactive.loc.ns [none]),
done
example : true := by do
let l : list ℤ := [0, 2, -1, 3, -4],
let l' := (do a ← l, b ← l, c ← l, pure ((a, b), c)),
ic ← mk_instance_cache `(ℤ),
-- we have to convert the provided `int`s into numeral form for the goals
-- to look like what they would usually: `⇑(swap -1 3) -4 = -4`, instead of
-- `⇑(swap (int.neg_succ_of_nat 0) (int.of_nat 3)) (int.neg_succ_of_nat 3) = int.neg_succ_of_nat 3`
el ← mmap (λ (tup : (ℤ × ℤ) × ℤ), do
(_, a) ← ic.of_int tup.fst.fst,
(_, b) ← ic.of_int tup.fst.snd,
(_, c) ← ic.of_int tup.snd,
pure ((a, b), c)) l',
(lhs : list expr) ← mmap (λ (tup : (expr × expr) × expr),
to_expr ``((equiv.swap %%tup.fst.fst %%tup.fst.snd) %%tup.snd)) el,
let rhs : list expr := el.map (λ (tup : (expr × expr) × expr),
if tup.snd = tup.fst.fst then tup.fst.snd
else if tup.snd = tup.fst.snd then tup.fst.fst
else tup.snd),
let eqs : list expr := list.zip_with (λ L R, `(@eq.{1} ℤ %%L %%R)) lhs rhs,
g ← get_goals,
gls ← mmap mk_meta_var eqs,
set_goals $ g ++ gls,
triv, -- to discharge the starting `true` goal
repeat $ tactic.norm_num norm_swap.eval [] (interactive.loc.ns [none]),
done
example : true := by do
let l : list ℚ := [0, (2 : ℚ) / -2, -1, 3 / 5, 4],
let l' := (do a ← l, b ← l, c ← l, pure ((a, b), c)),
ic ← mk_instance_cache `(ℚ),
-- we have to convert the provided `rat`s into numeral form for the goals
-- to look like what they would usually: `⇑(swap -1 3) -4 = -4`, like with ℤ above
el ← mmap (λ (tup : (ℚ × ℚ) × ℚ), do
(_, a) ← ic.of_rat tup.fst.fst,
(_, b) ← ic.of_rat tup.fst.snd,
(_, c) ← ic.of_rat tup.snd,
pure ((a, b), c)) l',
(lhs : list expr) ← mmap (λ (tup : (expr × expr) × expr),
to_expr ``((equiv.swap %%tup.fst.fst %%tup.fst.snd) %%tup.snd)) el,
let rhs : list expr := el.map (λ (tup : (expr × expr) × expr),
if tup.snd = tup.fst.fst then tup.fst.snd
else if tup.snd = tup.fst.snd then tup.fst.fst
else tup.snd),
let eqs : list expr := list.zip_with (λ L R, `(@eq.{1} ℚ %%L %%R)) lhs rhs,
g ← get_goals,
gls ← mmap mk_meta_var eqs,
set_goals $ g ++ gls,
triv, -- to discharge the starting `true` goal
repeat $ tactic.norm_num norm_swap.eval [] (interactive.loc.ns [none]),
done
example : swap (3 : fin 7) 5 0 = 0 := by norm_num
example : swap (fin.succ 2 : fin 7) 5 0 = 0 := by norm_num
example : swap (3 : fin 7) 5 3 = 5 := by norm_num
example : swap (3 : fin 1) 5 0 = 0 := by norm_num
example : swap (3 : fin 7) 5 10 = 12 := by norm_fin
example : swap (2 : fin 7) 4 9 = 11 := by norm_fin
example : swap (3 : fin 7) 5 0 = 0 := by norm_num
example : swap (3 : fin 7) 12 9 = 2 := by norm_num
example : swap (0 : fin (1 + 2)) (1 : fin (nat.succ (1 + 1))) ((fin.succ 1) : fin 3) = 2 :=
by norm_num
-- norm_swap doesn't generate trace output on non-swap expressions
example : (1 : ℤ) = (1 : ℕ) := by norm_num
|
/*=========================================================================
Copyright (c) Yue Sheng, University of Manchester and David Worth, STFC
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/** \file vvQuan3D.c
\brief This is a VolView plugin to calculate several characteristics from a
labelled image.
The following characteristics are calculated:
\li Volume by voxel counts
\li Equivalent sphere diameter by voxel counts
\li Bounding box diagonal
\li Principal Component Analysis
\li Ellipsoid fitting by PCA
\li Equivalent circle diameter by PCA
\li Isosurface by marching cube
\li Surface area
\li Surface volume
\li Equivalent sphere diameter from surface volume
\li Sphercity
\li Normalised surface area to volume ratio (Radius*Sa/Vol)
*/
#include "vvHelper.h"
#include "vtkVVPluginAPI.h"
#include <dlfcn.h>
#include <limits.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
/**
Struct used when calculating the number of voxels with each voxel value
*/
typedef struct {
/** The voxel value */
int value;
/** The number of voxels with this value */
int count;
} vvQuan3DVoxelCount;
/**
Comparison function for sorting the image data.
\param a Integer value
\param b Integer value
\return 1 if \c a>b; -1 if \c a<b; 0 if \c a==b.
*/
int cmpfun(void *a, void *b)
{
return ( *(int*)a - *(int*)b );
}
/**
\brief Calculate sphere diameter from the sphere volume.
Use the formula \f$ 2*(3v/(4\pi))^{\frac{1}{3}} \f$ where \f$ v \f$ is the
sphere volume.
\param volume The sphere volume
\return Diameter of the sphere
*/
double vol2dia(double volume)
{
return 2.0 * pow((3.0*volume)/(4.0*3.14159265),(1.0/3.0));
}
/**
\brief Find the (i,j,k) coordinates for each voxel id and also calculate
maximum, minimum and mean coordinates.
The positions pointer must be allocated by the calling function as follows
\code
positions = malloc(3*sizeof(int)*voxelCount);
\endcode
\param voxelSubArray Array of voxel ids
\param voxelCount Number of voxels in voxelSubArray <b>NB This is not the
length of the array</b>
\param dim The dimsnesions of the image
\param positions Pointer to matrix which will hold the (i,j,k) coordinates
\param min The minimum coordinate in each dimension
\param max The maximum coordinate in each dimension
\param mean The mean of the coordinates in each dimension
*/
void getCoords(int *voxelSubArray, int voxelCount, int dim[],
gsl_matrix *positions, int min[], int max[], int mean[])
{
int i;
int voxelId;
int icoord, jcoord, kcoord, rem;
min[0] = min[1] = min[2] = INT_MAX;
max[0] = max[1] = max[2] = INT_MIN;
mean[0] = mean[1] = mean[2] = 0;
/* Loop over the voxels and calulate i,j,k coords for each one */
for (i = 0; i < voxelCount; i++) {
voxelId = voxelSubArray[i];
kcoord = floor(voxelId / (dim[0]*dim[1]));
rem = voxelId % (dim[0]*dim[1]);
jcoord = floor(rem / dim[0]);
icoord = rem % dim[0];
//printf("voxel %d (%d,%d,%d)\n",voxelId,icoord,jcoord,kcoord);
gsl_matrix_set(positions,i,0,icoord);
gsl_matrix_set(positions,i,1,jcoord);
gsl_matrix_set(positions,i,2,kcoord);
if (icoord > max[0]) max[0] = icoord;
if (jcoord > max[1]) max[1] = jcoord;
if (kcoord > max[2]) max[2] = kcoord;
if (icoord < min[0]) min[0] = icoord;
if (jcoord < min[1]) min[1] = jcoord;
if (kcoord < min[2]) min[2] = kcoord;
mean[0] += icoord;
mean[1] += jcoord;
mean[2] += kcoord;
}
mean[0] /= voxelCount;
mean[1] /= voxelCount;
mean[2] /= voxelCount;
}
/**
\brief Calculate the data from the image
\author David Worth, STFC
\date May 2012
\todo This only works for unsigned short image type. Make it do other integer
datatypes.
\param inf Pointer to object that holds data for this plugin. The voxel size
can be obtained from it.
\param pds Pointer to object that carries information on data set to be
processed. Includes actual buffer of voxel data, number of voxels along each
dimension, voxel spacing and voxel type.
*/
static int ProcessData(void *inf, vtkVVProcessDataStruct *pds)
{
/* Information about the plugin and the image */
vtkVVPluginInfo *info = (vtkVVPluginInfo *)inf;
/* Number of voxels in each direction of image */
int *dim = info->InputVolumeDimensions;
/* Size of datatype in the image */
unsigned int rsize = info->InputVolumeScalarSize;
/* Voxel size - can be set by user in VolView */
double voxelSize = atof(info->GetGUIProperty(info, 0, VVP_GUI_VALUE));
/* Minimum and maximum raw values from image. */
double imgMin = info->InputVolumeScalarRange[0],
imgMax = info->InputVolumeScalarRange[1];
/* Array of voxel counts for each value. Array index is the value. */
int maxVoxelVals = (int)ceil(imgMax)-(int)floor(imgMin)+1;
int *voxelCounts = malloc(sizeof(int)*maxVoxelVals);
/* Array of arrays - each sub-array holding the ids of voxels with that value */
int* *voxelArray = malloc(sizeof(int*)*maxVoxelVals);
/* Pointer to sub array used when creating voxelArray */
int *voxelSubArray = NULL;
/* Index array used to write into voxelSubArray */
int *indexVoxelSubArray = malloc(sizeof(int)*maxVoxelVals);
/* Number of the non-background voxels */
int sumVoxels = 0;
/* Number of different voxel values */
int totalParticles = 0;
/* Array of (i,j,k) coordinates for voxels with a particular value */
gsl_matrix *positions = NULL;
/* Stats for voxel data for each value */
int max[3], min[3], mean[3], boundingBoxSize[3];
double boundingBoxDiam;
/* Multiplication factors based on physical voxel size */
double areaFactor = pow(voxelSize,2), volumeFactor = pow(voxelSize,3);
/* Output data */
int voxelLabel, voxelCount;
double voxelCountVolume, voxelCountDia;
/* Data used when covariance matrix is calculated */
double* *matrix = NULL;
double *row = NULL;
double* *covMatrix = NULL;
/* Data for eigenanalysis of covariance matrix */
gsl_matrix *gslCovMatrix = NULL;
gsl_vector *eval = NULL;
gsl_matrix *evecs = NULL;
gsl_eigen_symmv_workspace *workspace = NULL;
gsl_vector vector;
int result;
void *gslcblas_handle, *gsl_handle;
/* Buffer for output to user */
char buffer[1000];
int i, j = 0;
/* The raw image data */
unsigned short *ptr = (unsigned short *)pds->inData;
/* Check the data type */
switch (info->InputVolumeScalarType) {
case VTK_CHAR:
case VTK_UNSIGNED_CHAR:
case VTK_FLOAT:
case VTK_DOUBLE: {
sprintf(buffer, "Image datatype must be integer or boolean. This \
algorithm cannot continue");
info->SetProperty(info, VVP_ERROR, buffer);
return -1;
break;
}
}
printf("Image has type %d size %d\n", info->InputVolumeScalarType,rsize);
printf("The dimensions of the image are: %d, %d, %d \n",
dim[0], dim[1], dim[2]);
sprintf(buffer, "The dimensions of the image are: %d, %d, %d \n",
dim[0], dim[1], dim[2]);
printf("There are %d components\n",info->InputVolumeNumberOfComponents);
printf("The minimum value in the image is %d\n", (int)imgMin);
printf("and the maximum value is %d\n", (int)imgMax);
/* Sort the image values */
/*qsort(ptr, (size_t)(dim[0]*dim[1]*dim[2]), (size_t)info->InputVolumeScalarSize,
(__compar_fn_t)cmpfun);*/
/*
* Create array of voxel counts for each voxel value except the min value
* which we take to be the background
*/
for (i = 0; i < maxVoxelVals; i++) voxelCounts[i]=0;
for (i = 0; i < dim[0]*dim[1]*dim[2]; i++) {
if (ptr[i] != imgMin) { /* Not the minimum value */
if (ptr[i] > imgMax) printf("%d %d\n",i,ptr[i]); /* Something wrong */
/* Not seen this value before so it's a new particle */
if (voxelCounts[ptr[i]] == 0) totalParticles++;
voxelCounts[ptr[i]]++;
sumVoxels++;
}
}
/* Create the array of arrays with voxel ids for each voxel value */
for (i = 0; i < maxVoxelVals; i++) {
if (voxelCounts[i] > 0) {
/*printf("Non zero voxel count for i = %d - count is %d\n",i,voxelCounts[i]);*/
voxelArray[i] = malloc(voxelCounts[i]*sizeof(int));
}
else voxelArray[i] = NULL;
indexVoxelSubArray[i] = 0;
}
/* Now populate that array with values */
for (i = 0; i < dim[0]*dim[1]*dim[2]; i++) {
if (ptr[i] != imgMin) {
//printf("add entry to voxel array %d - entry id %d\n",ptr[i],i);
voxelSubArray = voxelArray[ptr[i]];
voxelSubArray[ indexVoxelSubArray[ptr[i]] ] = i;
indexVoxelSubArray[ptr[i]]++;
}
}
printf("Porosity is %f\n",(double)sumVoxels/(double)(dim[0]*dim[1]*dim[2]));
sprintf(buffer+strlen(buffer), "Porosity is %f\n",
(double)sumVoxels/(double)(dim[0]*dim[1]*dim[2]));
printf("Number of particles is %d\n",totalParticles);
/* Load the GSL BLAS and GSL itself. RTLD_GLOBAL means we can use the
* function names from GSL rather than having to get function pointers with
* dlsym. */
gslcblas_handle = dlopen("/usr/lib/libgslcblas.so", RTLD_LAZY|RTLD_GLOBAL);
if (!gslcblas_handle) {
printf("Error opening libgslcblas.so - %s\n",dlerror());
}
gsl_handle = dlopen("/usr/lib/libgsl.so", RTLD_LAZY|RTLD_GLOBAL);
if (!gsl_handle) {
printf("Error opening libgsl.so - %s\n",dlerror());
}
/* Allocate the GSL matrices and vectors for eigenanalysis */
gslCovMatrix = gsl_matrix_alloc(3,3);
eval = gsl_vector_alloc(3);
evecs = gsl_matrix_alloc(3,3);
workspace = gsl_eigen_symmv_alloc(3);
/* Loop over the particles */
for (i = 0; i < 1/*totalParticles*/; i++) {
/* Find the next particle with a non-zero voxel count */
while ((j < maxVoxelVals) && (voxelCounts[j] == 0)) j++;
/* Do some simple stuff */
voxelLabel = j;
voxelCount = voxelCounts[j];
voxelCountVolume = voxelCount * volumeFactor;
voxelCountDia = voxelSize*vol2dia(voxelCount);
printf("%d, %d, %f, %f",voxelLabel,voxelCount,voxelCountVolume,
voxelCountDia);
/* Find the (i,j,k) coordinates in the image of the voxels */
positions = gsl_matrix_alloc(voxelCount,3);
voxelSubArray = voxelArray[voxelLabel];
getCoords(voxelSubArray, voxelCount, dim, positions, min, max, mean);
/*printf(" (%d, %d, %d)",min[0],min[1],min[2]);
printf(" (%d, %d, %d)",max[0],max[1],max[2]);
printf(" (%d, %d, %d)",mean[0],mean[1],mean[2]);*/
boundingBoxSize[0] = max[0]-min[0]+1;
boundingBoxSize[1] = max[1]-min[1]+1;
boundingBoxSize[2] = max[2]-min[2]+1;
boundingBoxDiam = sqrt(boundingBoxSize[0]*boundingBoxSize[0] +
boundingBoxSize[1]*boundingBoxSize[1] +
boundingBoxSize[2]*boundingBoxSize[2])*voxelSize;
printf(" (%d, %d, %d)",boundingBoxSize[0],boundingBoxSize[1],
boundingBoxSize[2]);
printf(" %f", boundingBoxDiam);
/* Calculate positions-mean */
matrix = malloc(voxelCount*sizeof(double*));
for (j = 0; j < voxelCount; j++) {
row = malloc(3*sizeof(double));
row[0] = gsl_matrix_get(positions,j,0)-mean[0];
row[1] = gsl_matrix_get(positions,j,1)-mean[1];
row[2] = gsl_matrix_get(positions,j,2)-mean[2];
matrix[j] = row;
}
covMatrix = CovMat(matrix, voxelCount, 3);
for (j = 0; j < voxelCount; j++) {
free(matrix[j]);
}
free(matrix);
/*printf("\nCovariance matrix\n");
for (j = 0; j < 3; j++) {
printf("%f %f %f\n", covMatrix[j][0], covMatrix[j][1], covMatrix[j][2]);
}*/
/* To do the eigenanalysis use GNU Scientific library so create matrix
* in that format */
for (j = 0; j < 3; j++) {
gsl_matrix_set(gslCovMatrix,0,j,covMatrix[0][j]);
gsl_matrix_set(gslCovMatrix,1,j,covMatrix[1][j]);
gsl_matrix_set(gslCovMatrix,2,j,covMatrix[2][j]);
}
/* Calculate eigenvalues and vectors */
result = gsl_eigen_symmv(gslCovMatrix, eval, evecs, workspace);
printf("\nEigenvalues\n");
gsl_vector_fprintf(stdout, eval, "%g");
printf("\nEigenvectors\n");
vector = gsl_matrix_const_column(evecs,0).vector;
gsl_vector_fprintf(stdout, &vector, "%g");
printf("\n");
vector = gsl_matrix_const_column(evecs,1).vector;
gsl_vector_fprintf(stdout, &vector, "%g");
printf("\n");
vector = gsl_matrix_const_column(evecs,2).vector;
gsl_vector_fprintf(stdout, &vector, "%g");
for (j = 0; j < 3; j++) {
free(covMatrix[j]);
}
free(covMatrix);
gsl_matrix_free(positions);
printf("\n");
/* Move on to next particle */
j++;
}
dlclose(gsl_handle);
dlclose(gslcblas_handle);
info->SetProperty(info, VVP_REPORT_TEXT, buffer);
free(voxelCounts);
for (i = 0; i < maxVoxelVals; i++) {
if (voxelArray[i] != NULL) free(voxelArray[i]);
}
gsl_matrix_free(gslCovMatrix);
gsl_vector_free(eval);
gsl_matrix_free(evecs);
gsl_eigen_symmv_free(workspace);
free(voxelArray);
free(indexVoxelSubArray);
return 0;
}
/**
\brief Update the VolView GUI to display user parameters.
Sets one GUI parameter - the physical size of the voxels in the image.
\param inf Pointer to object that should be modified to set up GUI elements for
this plugin. It also contains details of the input and output images.
*/
static int UpdateGUI(void *inf)
{
int i;
vtkVVPluginInfo *info = (vtkVVPluginInfo *)inf;
info->SetGUIProperty(info, 0, VVP_GUI_LABEL, "Voxel Size");
info->SetGUIProperty(info, 0, VVP_GUI_TYPE, VVP_GUI_SCALE);
info->SetGUIProperty(info, 0, VVP_GUI_DEFAULT , "1");
info->SetGUIProperty(info, 0, VVP_GUI_HELP,
"The physical size of a voxel in the image");
/* what range should we show for possible output values */
vvPluginSetGUIScaleRange(0);
info->OutputVolumeScalarType = info->InputVolumeScalarType;
info->OutputVolumeNumberOfComponents = info->InputVolumeNumberOfComponents;
for (i = 0; i < 3; i++)
{
info->OutputVolumeDimensions[i] = info->InputVolumeDimensions[i];
info->OutputVolumeSpacing[i] = info->InputVolumeSpacing[i];
info->OutputVolumeOrigin[i] = info->InputVolumeOrigin[i];
}
return 1;
}
/**
\brief Initialise this plugin.
Sets the name and group for this plugin in the plugin list shown to the VolView
user and gives some documentation. Also defines properties so VolView can judge
the memory requirements and potential for undoing this plugin.
\param info Pointer to object that should be modified to give details about this
plugin.
*/
void VV_PLUGIN_EXPORT vvQuan3DCInit(vtkVVPluginInfo *info)
{
/* always check the version */
vvPluginVersionCheck();
/* setup information that never changes */
info->ProcessData = ProcessData;
info->UpdateGUI = UpdateGUI;
info->SetProperty(info, VVP_NAME, "Quantify 3D in C");
info->SetProperty(info, VVP_GROUP, "Quantification");
info->SetProperty(info, VVP_TERSE_DOCUMENTATION,
"Quantify several characteristics from a labelled image");
info->SetProperty(info, VVP_FULL_DOCUMENTATION,
"Quantify the following characteristics from a labelled image: Volume by \
voxel counts, Equivalent sphere diameter by voxel counts, Bounding box \
diagonal, Principal Component Analysis, Ellipsoid fitting by PCA, Equivalent \
circle diameter by PCA, Isosurface by marching cube, Surface area, Surface \
volume, Equivalent sphere diameter from surface volume, Sphercity, Normalised \
surface area to volume ratio");
info->SetProperty(info, VVP_SUPPORTS_IN_PLACE_PROCESSING, "1");
info->SetProperty(info, VVP_SUPPORTS_PROCESSING_PIECES, "1");
info->SetProperty(info, VVP_REQUIRED_Z_OVERLAP, "0");
info->SetProperty(info, VVP_NUMBER_OF_GUI_ITEMS, "1");
info->SetProperty(info, VVP_REQUIRES_SERIES_INPUT, "0");
info->SetProperty(info, VVP_SUPPORTS_PROCESSING_SERIES_BY_VOLUMES, "0");
info->SetProperty(info, VVP_PRODUCES_OUTPUT_SERIES, "0");
info->SetProperty(info, VVP_PRODUCES_PLOTTING_OUTPUT, "0");
}
|
module OidTableSVG where
import Data.Word
import qualified Data.ByteString.Lazy as LB
import Control.Monad hiding (forM_)
import Data.Foldable (forM_)
import Text.Printf
import Control.Arrow ((***))
import Data.String
import Data.Complex
import qualified Text.Blaze.Svg11 as S
import qualified Text.Blaze.Svg11.Attributes as A
import Text.Blaze.Svg11 ((!))
import Text.Blaze.Svg.Renderer.Utf8
import OidCode
import KnownCodes
import Types
import Utils
type Point = Complex Double
oidTableSvg :: Conf -> Bool -> String -> [(String, Word16)] -> LB.ByteString
oidTableSvg conf usePNG title entries
| entriesPerPage < 1 = error "OID codes too large to fit on a single page"
| otherwise = renderSvg $
S.docTypeSvg ! A.version (S.toValue "1.1")
! A.width (S.toValue (printf "%fmm" (a4w/mm) :: String))
! A.height (S.toValue (printf "%fmm" (a4h/mm) :: String))
! A.viewbox (S.toValue (printf "0 0 %f %f" a4w a4h :: String))
! A.fontFamily (S.toValue "sans-serif")
$ do
let patid d c | d == show c = d
| otherwise = printf "%s-%d" d c
-- Create patterns for the codes
S.defs $ forM_ entries $ \(d,c) ->
case code2RawCode c of
Nothing -> return ()
Just rc -> oidSVGPattern conf usePNG (patid d c) rc
-- For SVG, we put all on one page (and exceed the page if it is too big)
let chunks = [entries]
let totalPages = length chunks
forM_ (zip [1::Int ..] chunks) $ \(pageNum, thisPage) -> do
S.text_ ! A.x (S.toValue (a4w / 2))
! A.y (S.toValue (padTop + titleHeight))
! A.textAnchor (S.toValue "middle")
! A.stroke (S.toValue "black")
! A.fontSize (S.toValue (printf "%f" (12*pt) :: String))
$ fromString title
S.text_ ! A.x (S.toValue padLeft)
! A.y (S.toValue (a4h - padBot))
! A.textAnchor (S.toValue "left")
! A.stroke (S.toValue "black")
! A.fontSize (S.toValue (printf "%f" (8*pt) :: String))
$ fromString $ "Created by tttool-" ++ tttoolVersion
forM_ (zip thisPage positions) $ \((d,c), x :+ y) -> do
S.rect ! A.width (S.toValue imageWidth)
! A.height (S.toValue imageHeight)
! A.x (S.toValue x)
! A.y (S.toValue y)
! A.fill (S.toValue $ "url(#"++patid d c++")")
S.text_ ! A.x (S.toValue x)
! A.y (S.toValue (y + imageHeight + subtitleSep + subtitleHeight))
! A.textAnchor (S.toValue "left")
! A.stroke (S.toValue "black")
! A.fontSize (S.toValue (printf "%f" (8*pt) :: String))
$ fromString d
where
-- Configure-dependent dimensions (all in pt)
(imageWidth,imageHeight) = (*mm) *** (*mm) $ fromIntegral *** fromIntegral $cCodeDim conf
-- Static dimensions (all in pt)
-- Page paddings
padTop, padLeft, padBot, padRight :: Double
padTop = 1*cm
padBot = 1*cm
padLeft = 2*cm
padRight = 2*cm
titleHeight = 1*cm
titleSep = 0.5*cm
footerHeight = 0.5*cm
footerSep = 0.5*cm
imageSepH = 0.4*cm
imageSepV = 0.2*cm
subtitleHeight = 0.4*cm
subtitleSep = 0.2*cm
-- Derived dimensions (all in pt)
{-
titleRect = Rectangle
(padLeft :+ (a4h - padTop - titleHeight))
((a4w - padRight) :+ (a4h - padTop))
titleFont = Font (PDFFont Helvetica 12) black black
footerRect = Rectangle
(padLeft :+ padBot)
((a4w - padRight) :+ (padBot + footerHeight))
footerFont = Font (PDFFont Helvetica 8) black black
bodyFont = Font (PDFFont Helvetica 8) black black
-}
bodyWidth = a4w - padLeft - padRight
bodyHeight = a4h - padTop - titleHeight - titleSep - footerSep - footerHeight - padBot
positions = map (+(padLeft :+ (padTop + titleHeight + titleSep))) $
calcPositions bodyWidth bodyHeight
imageWidth (imageHeight + subtitleSep + subtitleHeight)
imageSepH imageSepV
entriesPerPage = length positions
-- Derived dimensions (all in pixels)
imageWidthPx = floor (imageWidth * px)
imageHeightPx = floor (imageHeight * px)
-- config-dependent conversion factors
px :: Double
px = fromIntegral (cDPI conf) / 72
{-
-- Makes sure the given point is at a coordinate that is a multiple
-- of an pixel
align :: Point -> Point
align pos = alignToPx (realPart pos) :+ (a4h - alignToPx (a4h - imagPart pos))
-- Makes sure the given distance is an interal mulitple of a pixel
alignToPx :: Double -> Double
alignToPx x = fromIntegral (floor (x * px)) / px
-}
calcPositions
:: Double -- ^ total width
-> Double -- ^ total height
-> Double -- ^ entry width
-> Double -- ^ entry height
-> Double -- ^ pad width
-> Double -- ^ pad height
-> [Point]
calcPositions tw th ew eh pw ph = [ x :+ ({-(th - -} y) | y <- ys , x <- xs]
where
xs = [0,ew+pw..tw-ew]
ys = [0,eh+ph..th-eh]
pt :: Double
pt = 48/2.83465
-- Conversation factor
cm :: Double
cm = 10 * mm
mm :: Double
mm = 2.83465 * pt
-- A4 dimensions
a4w, a4h :: Double
a4w = 595 * pt
a4h = 842 * pt
|
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : Infinite R
n : ℕ
p : MvPolynomial (Fin n) R
h : ∀ (x : Fin n → R), ↑(eval x) p = 0
⊢ p = 0
[PROOFSTEP]
induction' n with n ih
[GOAL]
case zero
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : Infinite R
n : ℕ
p✝ : MvPolynomial (Fin n) R
h✝ : ∀ (x : Fin n → R), ↑(eval x) p✝ = 0
p : MvPolynomial (Fin Nat.zero) R
h : ∀ (x : Fin Nat.zero → R), ↑(eval x) p = 0
⊢ p = 0
[PROOFSTEP]
apply (MvPolynomial.isEmptyRingEquiv R (Fin 0)).injective
[GOAL]
case zero.a
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : Infinite R
n : ℕ
p✝ : MvPolynomial (Fin n) R
h✝ : ∀ (x : Fin n → R), ↑(eval x) p✝ = 0
p : MvPolynomial (Fin Nat.zero) R
h : ∀ (x : Fin Nat.zero → R), ↑(eval x) p = 0
⊢ ↑(isEmptyRingEquiv R (Fin 0)) p = ↑(isEmptyRingEquiv R (Fin 0)) 0
[PROOFSTEP]
rw [RingEquiv.map_zero]
[GOAL]
case zero.a
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : Infinite R
n : ℕ
p✝ : MvPolynomial (Fin n) R
h✝ : ∀ (x : Fin n → R), ↑(eval x) p✝ = 0
p : MvPolynomial (Fin Nat.zero) R
h : ∀ (x : Fin Nat.zero → R), ↑(eval x) p = 0
⊢ ↑(isEmptyRingEquiv R (Fin 0)) p = 0
[PROOFSTEP]
convert h finZeroElim
[GOAL]
case succ
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : Infinite R
n✝ : ℕ
p✝ : MvPolynomial (Fin n✝) R
h✝ : ∀ (x : Fin n✝ → R), ↑(eval x) p✝ = 0
n : ℕ
ih : ∀ {p : MvPolynomial (Fin n) R}, (∀ (x : Fin n → R), ↑(eval x) p = 0) → p = 0
p : MvPolynomial (Fin (Nat.succ n)) R
h : ∀ (x : Fin (Nat.succ n) → R), ↑(eval x) p = 0
⊢ p = 0
[PROOFSTEP]
apply (finSuccEquiv R n).injective
[GOAL]
case succ.a
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : Infinite R
n✝ : ℕ
p✝ : MvPolynomial (Fin n✝) R
h✝ : ∀ (x : Fin n✝ → R), ↑(eval x) p✝ = 0
n : ℕ
ih : ∀ {p : MvPolynomial (Fin n) R}, (∀ (x : Fin n → R), ↑(eval x) p = 0) → p = 0
p : MvPolynomial (Fin (Nat.succ n)) R
h : ∀ (x : Fin (Nat.succ n) → R), ↑(eval x) p = 0
⊢ ↑(finSuccEquiv R n) p = ↑(finSuccEquiv R n) 0
[PROOFSTEP]
simp only [AlgEquiv.map_zero]
[GOAL]
case succ.a
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : Infinite R
n✝ : ℕ
p✝ : MvPolynomial (Fin n✝) R
h✝ : ∀ (x : Fin n✝ → R), ↑(eval x) p✝ = 0
n : ℕ
ih : ∀ {p : MvPolynomial (Fin n) R}, (∀ (x : Fin n → R), ↑(eval x) p = 0) → p = 0
p : MvPolynomial (Fin (Nat.succ n)) R
h : ∀ (x : Fin (Nat.succ n) → R), ↑(eval x) p = 0
⊢ ↑(finSuccEquiv R n) p = 0
[PROOFSTEP]
refine Polynomial.funext fun q => ?_
[GOAL]
case succ.a
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : Infinite R
n✝ : ℕ
p✝ : MvPolynomial (Fin n✝) R
h✝ : ∀ (x : Fin n✝ → R), ↑(eval x) p✝ = 0
n : ℕ
ih : ∀ {p : MvPolynomial (Fin n) R}, (∀ (x : Fin n → R), ↑(eval x) p = 0) → p = 0
p : MvPolynomial (Fin (Nat.succ n)) R
h : ∀ (x : Fin (Nat.succ n) → R), ↑(eval x) p = 0
q : MvPolynomial (Fin n) R
⊢ Polynomial.eval q (↑(finSuccEquiv R n) p) = Polynomial.eval q 0
[PROOFSTEP]
rw [Polynomial.eval_zero]
[GOAL]
case succ.a
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : Infinite R
n✝ : ℕ
p✝ : MvPolynomial (Fin n✝) R
h✝ : ∀ (x : Fin n✝ → R), ↑(eval x) p✝ = 0
n : ℕ
ih : ∀ {p : MvPolynomial (Fin n) R}, (∀ (x : Fin n → R), ↑(eval x) p = 0) → p = 0
p : MvPolynomial (Fin (Nat.succ n)) R
h : ∀ (x : Fin (Nat.succ n) → R), ↑(eval x) p = 0
q : MvPolynomial (Fin n) R
⊢ Polynomial.eval q (↑(finSuccEquiv R n) p) = 0
[PROOFSTEP]
apply ih fun x => ?_
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : Infinite R
n✝ : ℕ
p✝ : MvPolynomial (Fin n✝) R
h✝ : ∀ (x : Fin n✝ → R), ↑(eval x) p✝ = 0
n : ℕ
ih : ∀ {p : MvPolynomial (Fin n) R}, (∀ (x : Fin n → R), ↑(eval x) p = 0) → p = 0
p : MvPolynomial (Fin (Nat.succ n)) R
h : ∀ (x : Fin (Nat.succ n) → R), ↑(eval x) p = 0
q : MvPolynomial (Fin n) R
x : Fin n → R
⊢ ↑(eval x) (Polynomial.eval q (↑(finSuccEquiv R n) p)) = 0
[PROOFSTEP]
calc
_ = _ := eval_polynomial_eval_finSuccEquiv p _
_ = 0 := h _
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : Infinite R
σ : Type u_2
p q : MvPolynomial σ R
h : ∀ (x : σ → R), ↑(eval x) p = ↑(eval x) q
⊢ p = q
[PROOFSTEP]
suffices ∀ p, (∀ x : σ → R, eval x p = 0) → p = 0
by
rw [← sub_eq_zero, this (p - q)]
simp only [h, RingHom.map_sub, forall_const, sub_self]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : Infinite R
σ : Type u_2
p q : MvPolynomial σ R
h : ∀ (x : σ → R), ↑(eval x) p = ↑(eval x) q
this : ∀ (p : MvPolynomial σ R), (∀ (x : σ → R), ↑(eval x) p = 0) → p = 0
⊢ p = q
[PROOFSTEP]
rw [← sub_eq_zero, this (p - q)]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : Infinite R
σ : Type u_2
p q : MvPolynomial σ R
h : ∀ (x : σ → R), ↑(eval x) p = ↑(eval x) q
this : ∀ (p : MvPolynomial σ R), (∀ (x : σ → R), ↑(eval x) p = 0) → p = 0
⊢ ∀ (x : σ → R), ↑(eval x) (p - q) = 0
[PROOFSTEP]
simp only [h, RingHom.map_sub, forall_const, sub_self]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : Infinite R
σ : Type u_2
p q : MvPolynomial σ R
h : ∀ (x : σ → R), ↑(eval x) p = ↑(eval x) q
⊢ ∀ (p : MvPolynomial σ R), (∀ (x : σ → R), ↑(eval x) p = 0) → p = 0
[PROOFSTEP]
clear h p q
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : Infinite R
σ : Type u_2
⊢ ∀ (p : MvPolynomial σ R), (∀ (x : σ → R), ↑(eval x) p = 0) → p = 0
[PROOFSTEP]
intro p h
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : Infinite R
σ : Type u_2
p : MvPolynomial σ R
h : ∀ (x : σ → R), ↑(eval x) p = 0
⊢ p = 0
[PROOFSTEP]
obtain ⟨n, f, hf, p, rfl⟩ := exists_fin_rename p
[GOAL]
case intro.intro.intro.intro
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : Infinite R
σ : Type u_2
n : ℕ
f : Fin n → σ
hf : Function.Injective f
p : MvPolynomial (Fin n) R
h : ∀ (x : σ → R), ↑(eval x) (↑(rename f) p) = 0
⊢ ↑(rename f) p = 0
[PROOFSTEP]
suffices p = 0 by rw [this, AlgHom.map_zero]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : Infinite R
σ : Type u_2
n : ℕ
f : Fin n → σ
hf : Function.Injective f
p : MvPolynomial (Fin n) R
h : ∀ (x : σ → R), ↑(eval x) (↑(rename f) p) = 0
this : p = 0
⊢ ↑(rename f) p = 0
[PROOFSTEP]
rw [this, AlgHom.map_zero]
[GOAL]
case intro.intro.intro.intro
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : Infinite R
σ : Type u_2
n : ℕ
f : Fin n → σ
hf : Function.Injective f
p : MvPolynomial (Fin n) R
h : ∀ (x : σ → R), ↑(eval x) (↑(rename f) p) = 0
⊢ p = 0
[PROOFSTEP]
apply funext_fin
[GOAL]
case intro.intro.intro.intro.h
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : Infinite R
σ : Type u_2
n : ℕ
f : Fin n → σ
hf : Function.Injective f
p : MvPolynomial (Fin n) R
h : ∀ (x : σ → R), ↑(eval x) (↑(rename f) p) = 0
⊢ ∀ (x : Fin n → R), ↑(eval x) p = 0
[PROOFSTEP]
intro x
[GOAL]
case intro.intro.intro.intro.h
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : Infinite R
σ : Type u_2
n : ℕ
f : Fin n → σ
hf : Function.Injective f
p : MvPolynomial (Fin n) R
h : ∀ (x : σ → R), ↑(eval x) (↑(rename f) p) = 0
x : Fin n → R
⊢ ↑(eval x) p = 0
[PROOFSTEP]
classical
convert h (Function.extend f x 0)
simp only [eval, eval₂Hom_rename, Function.extend_comp hf]
[GOAL]
case intro.intro.intro.intro.h
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : Infinite R
σ : Type u_2
n : ℕ
f : Fin n → σ
hf : Function.Injective f
p : MvPolynomial (Fin n) R
h : ∀ (x : σ → R), ↑(eval x) (↑(rename f) p) = 0
x : Fin n → R
⊢ ↑(eval x) p = 0
[PROOFSTEP]
convert h (Function.extend f x 0)
[GOAL]
case h.e'_2
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : Infinite R
σ : Type u_2
n : ℕ
f : Fin n → σ
hf : Function.Injective f
p : MvPolynomial (Fin n) R
h : ∀ (x : σ → R), ↑(eval x) (↑(rename f) p) = 0
x : Fin n → R
⊢ ↑(eval x) p = ↑(eval (Function.extend f x 0)) (↑(rename f) p)
[PROOFSTEP]
simp only [eval, eval₂Hom_rename, Function.extend_comp hf]
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : Infinite R
σ : Type u_2
p q : MvPolynomial σ R
⊢ p = q → ∀ (x : σ → R), ↑(eval x) p = ↑(eval x) q
[PROOFSTEP]
rintro rfl
[GOAL]
R : Type u_1
inst✝² : CommRing R
inst✝¹ : IsDomain R
inst✝ : Infinite R
σ : Type u_2
p : MvPolynomial σ R
⊢ ∀ (x : σ → R), ↑(eval x) p = ↑(eval x) p
[PROOFSTEP]
simp only [forall_const, eq_self_iff_true]
|
module Cordial.Model.Interface.PortViews
import Data.Vect
import Data.DList
import Data.Ranged
import Text.Markup.Edda
import Cordial.Model.Common
import Cordial.Model.Specification
import Cordial.Model.Projection
import Cordial.Model.Interface.Kinds
import Cordial.Model.Interface.Ports
import Cordial.Model.Interface.PortGroup
%default total
%access public export
{-
data Necessary : (ty : OptTy)
-> (endpoint : Endpoint)
-> (optTy : OptionalTy)
-> (prf : OptionalKind endpoint optTy ty)
-> Type
-}
data SimplePort : Necessary ty endpoint opt prf -> Type where
MkSimplePort : (type : PortTy annot labelTy)
-> (pType : ProjectedPortTy labelTy endpoint type)
-> (port : Port annot
labelTy
req
endpoint
endian
type
ptype)
-> SimplePort req
data SimplePortGroup : Type where
Empty : SimplePortGroup
Add : (port : SimplePort req) -> (rest : SimplePortGroup) -> SimplePortGroup
Skip : (rest : SimplePortGroup) -> SimplePortGroup
mkSimple : PortGroup annot labelTy endpoint endian ps pps
-> SimplePortGroup
mkSimple Empty = Empty
mkSimple (Add port rest) = Add (MkSimplePort port) (mkSimple rest)
mkSimple (Skip rest) = Skip (mkSimple rest)
{-
||| A collection of ports that respects the projected port group.
|||
||| Universe that logical names arise from.
||| Are we producing/consuming information.
||| The originating projected port type that constrains the value level values.
|||
data PortGroup : (annot : Type)
-> (labelTy : Type)
-> (endpoint : Endpoint)
-> (endian : Maybe Endian)
-> (ps : PortGroupTy annot labelTy)
-> (pportTys : DList (PortTy annot labelTy) (ProjectedPortTy labelTy endpoint) ps)
-> Type
where
||| No ports
Empty : PortGroup annot labelTy endpoint endian Nil Nil
||| Add a port to the group such that the description comes from
||| the projected port list.
Add : (port : Port annot labelTy req endpoint endian (PortDesc i k l ty f dw sen opt origin dv doc)
(PPortDesc k l ty d dw sen req origin dv))
-> (rest : PortGroup annot labelTy endpoint endian ps pps)
-> PortGroup annot labelTy endpoint endian (PortDesc i k l ty f dw sen opt origin dv doc :: ps)
(PPortDesc k l ty d dw sen req origin dv :: pps)
||| Skip an optional port from the projected port list.
Skip : (rest : PortGroup annot labelTy endpoint endian ps pps)
-> PortGroup annot labelTy endpoint endian (PortDesc i k l ty f dw sen opt origin dv doc :: ps)
(PPortDesc k l ty d dw sen Optional origin dv :: pps)
-}
-- --------------------------------------------------------------------- [ EOF ]
|
(*
* Copyright 2021, Data61, CSIRO (ABN 41 687 119 230)
*
* SPDX-License-Identifier: GPL-2.0-only
*)
theory Init_R
imports
KHeap_R
begin
context begin interpretation Arch . (*FIXME: arch_split*)
(*
This provides a very simple witness that the state relation used in the first refinement proof is
non-trivial, by exhibiting a pair of related states. This helps guard against silly mistakes in
the state relation, since we currently assume that the system starts in a state satisfying
invariants and state relations.
Note that the states we exhibit are not intended to be useful states. They are just the simplest
possible states that prove non-triviality of the state relation. In particular, these states do
not satisfy the respective invariant conditions. In future, this could be improved by exhibiting
a tuple of more realistic states that are related across all levels of the refinement, and that
also satisfy respective invariant. Ultimately, we would like to prove functional correctness of
kernel initialisation. That would allow us to start from a minimal but real configuration that
would allow us to make a much smaller set of assumptions about the initial configuration of the
system.
*)
definition zeroed_arch_abstract_state ::
arch_state
where
"zeroed_arch_abstract_state \<equiv> \<lparr>
arm_asid_table = Map.empty,
arm_hwasid_table = Map.empty,
arm_next_asid = 0,
arm_asid_map = Map.empty,
arm_global_pd = 0,
arm_global_pts = [],
arm_kernel_vspace = K ArmVSpaceUserRegion
\<rparr>"
definition zeroed_main_abstract_state ::
abstract_state
where
"zeroed_main_abstract_state \<equiv> \<lparr>
kheap = Map.empty,
cdt = Map.empty,
is_original_cap = (K True),
cur_thread = 0,
idle_thread = 0,
machine_state = init_machine_state,
interrupt_irq_node = (\<lambda>irq. ucast irq << cte_level_bits),
interrupt_states = (K irq_state.IRQInactive),
arch_state = zeroed_arch_abstract_state
\<rparr>"
definition zeroed_extended_state ::
det_ext
where
"zeroed_extended_state \<equiv> \<lparr>
work_units_completed_internal = 0,
scheduler_action_internal = resume_cur_thread,
ekheap_internal = K None,
domain_list_internal = [],
domain_index_internal = 0,
cur_domain_internal = 0,
domain_time_internal = 0,
ready_queues_internal = (\<lambda>_ _. []),
cdt_list_internal = K []
\<rparr>"
definition zeroed_abstract_state ::
det_state
where
"zeroed_abstract_state \<equiv> abstract_state.extend zeroed_main_abstract_state
(state.fields zeroed_extended_state)"
definition zeroed_arch_intermediate_state ::
Arch.kernel_state
where
"zeroed_arch_intermediate_state \<equiv> ARMKernelState Map.empty Map.empty 0 Map.empty 0 [] (K ArmVSpaceUserRegion)"
definition zeroed_intermediate_state ::
global.kernel_state
where
"zeroed_intermediate_state \<equiv> \<lparr>
ksPSpace = Map.empty,
gsUserPages = Map.empty,
gsCNodes = Map.empty,
gsUntypedZeroRanges = {},
gsMaxObjectSize = 0,
ksDomScheduleIdx = 0,
ksDomSchedule = [],
ksCurDomain = 0,
ksDomainTime = 0,
ksReadyQueues = K [],
ksReadyQueuesL1Bitmap = K 0,
ksReadyQueuesL2Bitmap = K 0,
ksCurThread = 0,
ksIdleThread = 0,
ksSchedulerAction = ResumeCurrentThread,
ksInterruptState = (InterruptState 0 (K IRQInactive)),
ksWorkUnitsCompleted = 0,
ksArchState = zeroed_arch_intermediate_state,
ksMachineState = init_machine_state
\<rparr>"
lemmas zeroed_state_defs = zeroed_main_abstract_state_def zeroed_abstract_state_def
zeroed_arch_abstract_state_def zeroed_extended_state_def
zeroed_intermediate_state_def abstract_state.defs
zeroed_arch_intermediate_state_def
lemma non_empty_refine_state_relation:
"(zeroed_abstract_state, zeroed_intermediate_state) \<in> state_relation"
apply (clarsimp simp: state_relation_def zeroed_state_defs state.defs)
apply (intro conjI)
apply (clarsimp simp: pspace_relation_def pspace_dom_def)
apply (clarsimp simp: ekheap_relation_def)
apply (clarsimp simp: ready_queues_relation_def)
apply (clarsimp simp: ghost_relation_def)
apply (fastforce simp: cdt_relation_def swp_def dest: cte_wp_at_domI)
apply (clarsimp simp: cdt_list_relation_def map_to_ctes_def)
apply (clarsimp simp: revokable_relation_def map_to_ctes_def)
apply (clarsimp simp: zeroed_state_defs arch_state_relation_def)
apply (clarsimp simp: interrupt_state_relation_def irq_state_relation_def cte_level_bits_def)
done
end
end
|
import pathlib
import qpimage.integrity_check
def test_tilt_from_h5file():
""""
The data for this test was created using:
```
import numpy as np
import qpimage
size = 50
# background phase image with a tilt
bg = np.repeat(np.linspace(0, 1, size), size).reshape(size, size)
bg = .6 * bg - .8 * bg.transpose() + .2
# phase image with random noise
rsobj = np.random.RandomState(47)
phase = rsobj.rand(size, size) - .5 + bg
# create QPImage instance
with qpimage.QPImage(data=phase,
which_data="phase",
h5file="bg_tilt.h5") as qpi:
qpi.compute_bg(which_data="phase", # correct phase image
fit_offset="fit", # use bg offset from tilt fit
fit_profile="tilt", # perform 2D tilt fit
border_px=5, # use 5 px border around image
)
```
"""
h5file = pathlib.Path(__file__).parent / "data" / "bg_tilt.h5"
qpimage.integrity_check.check(h5file, checks=["background"])
if __name__ == "__main__":
# Run all tests
_loc = locals()
for _key in list(_loc.keys()):
if _key.startswith("test_") and hasattr(_loc[_key], "__call__"):
_loc[_key]()
|
```python
import pandas as pd
from pathlib import Path
import matplotlib.pyplot as plt
from collections import OrderedDict, defaultdict
from sklearn.preprocessing import LabelEncoder
import sys
import os
module_path = Path("../src/")
os.chdir(module_path)
sys.path.append(module_path)
import warnings
warnings.filterwarnings("ignore")
```
```python
from data_access.load_file import load_table, dict_to_df
from data_preparation import compute_work_item_times
from data_processing.functions import time_for_phase, set_end_date
from data_processing import features
```
First we load and preprocess the data
```python
filename = Path("../data/gdsc2_public.csv")
data = load_table(filename)
total_times = compute_work_item_times(data)
times = time_for_phase(data, end_date="2018-03-31", process=False)
times.dropna(inplace=True)
```
```python
open_wis = total_times[pd.isnull(total_times["duration_in_days"])]["work_item"].values
times_open = times[times.work_item.isin(open_wis)]
times_closed = times[~times.work_item.isin(open_wis)]
times_closed.dropna(inplace=True)
times_closed.loc[:, "receive_date"] = times_closed["from_timestamp"].apply(lambda x: x.date())
times_closed.loc[:, "drop_date"] = times_closed["to_timestamp"].apply(lambda x: x.date())
```
```python
times.loc[:, "receive_date"] = times["from_timestamp"].apply(lambda x: x.date())
times.loc[:, "drop_date"] = times["to_timestamp"].apply(lambda x: x.date())
daterange = pd.date_range(start=str(times["receive_date"].min()), end=str(times["drop_date"].max()), freq='D')
```
For easier handling we assume every working step to be closed until the last day in the dataset.
We now want to compute a measure for the experience of an employee. We define it as follow:
\begin{equation}
x^{er}_{exp}(t) = \frac{t_{spent}\sum{w^{er}_{closed}(t)}}{\sum{w_{closed}(t)}}
\end{equation}
We also want to define a measure for the workload of an employee:
\begin{equation}
x^{er}_{load}(t) = \frac{\sum{w^{er}_{open}(t)}}{\sum{w_{open}(t)}}
\end{equation}
with $t$ as time, $t_{spent}$ as time already spend in the company, $w$ being a working step and $er$ being a resource.
```python
def x_experience(times, resource, t, col="current_resource"):
assert col in times.columns, col + " not in columns of dataframe"
closed_tickets = times[times["receive_date"] < t]
er = closed_tickets[closed_tickets[col] == resource]
try:
date_diff = (t - er["receive_date"].min())
working_time = round(date_diff.total_seconds() / (24*3600), 2)
except TypeError:
working_time = 1
if pd.isna(working_time):
working_time = 1
try:
x_exp = (working_time*len(er))/len(closed_tickets)
except ZeroDivisionError:
x_exp = 0
return x_exp
```
```python
def x_workload(times, resource, t, col="current_resource"):
assert col in times.columns, col + " not in columns of dataframe"
open_tickets = times[(times["receive_date"] <= t) &
(times["drop_date"] >= t)]
er = open_tickets[open_tickets[col] == resource]
try:
x_load = (len(er))/len(open_tickets)
except ZeroDivisionError:
x_load = 0
return x_load
```
We are going to test the functions with the most frequent resource.
```python
resource = "ER_00061"
plot_df = pd.DataFrame(index=daterange, columns=["x_exp", "x_load"])
for date in daterange:
plot_df.loc[date, "x_exp"] = x_experience(times, resource, date.date())
plot_df.loc[date, "x_load"] = x_workload(times, resource, date.date())
```
The function runs without errors. We want to plot the results, the graph should show an increasing trend for the experience and some kind of fluktuation for the workload.
```python
fig, ax = plt.subplots(1, 2, figsize=(15,5), sharex=True, constrained_layout=True)
plot_df["x_exp"].plot(color='g', ax=ax[0], label="x_exp")
plot_df["x_load"].plot(color='b', ax=ax[1], label="x_load")
ax[0].set_title("Experience of most frequent resource")
ax[1].set_title("Workload of most frequent resource")
ax[0].legend()
ax[1].legend()
plt.show()
```
Now we are able to compute the two measures for every resource for a given time. To add this as a feature to our model we also need a function to aggregate the measures regarding to the multiple resources working on one work item. We define the following as the employment rate for every work item:
\begin{equation}
x^{wi}_{emp} = \frac{\sum_{er}{x^{er}_{exp}(t)x^{er}_{load}(t)}}{\sum_{er}{w^{er}}}
\end{equation}
with $t$ as the time the employee recieves the task.
```python
def employment_rate(times, work_item, resource_col="current_resource"):
assert resource_col in times.columns, resource_col + " not in columns of dateframe!"
wi = times[times["work_item"] == work_item]
resources = list(wi[resource_col].values)
res_counter = defaultdict(int)
numerator = 0
x_exp_sum = 0
x_load_sum = 0
denumerator = len(resources)
for resource in resources:
if resources.count(resource) > 1:
res_counter[resource] += 1
t = wi[wi[resource_col] == resource]["receive_date"].iloc[res_counter[resource]-1]
elif resources.count(resource) == 1:
t = wi[wi[resource_col] == resource]["receive_date"].values[0]
x_exp = x_experience(times, resource, t, resource_col)
x_load = x_workload(times, resource, t, resource_col)
x_exp_sum += x_exp
x_load_sum += x_load
numerator += (x_exp * x_load)
x_emp = numerator/denumerator
x_ex = x_exp_sum/denumerator
x_l = x_load_sum/denumerator
return x_emp, x_ex, x_l
```
Now we want to compute the measures for every work item and compare them
```python
x_emp, x_exp, x_load = employment_rate(times, "WI_000001")
```
```python
# res_df = pd.DataFrame(index=times.work_item.unique(), columns=["x_emp", "x_exp", "x_load"])
# counter = 0
# for wi in times.work_item.unique():
# x_emp, x_exp, x_load = employment_rate(times, wi)
# res_df.loc[wi, "x_emp"] = x_emp
# res_df.loc[wi, "x_exp"] = x_exp
# res_df.loc[wi, "x_load"] = x_load
# counter += 1
# if counter == 500:
# print("500 work items done!")
# counter = 0
```
Computation takes a while. We will write the data to the SQL-Server so we don't have to compute them every time.
```python
# import sqlalchemy
# engine = sqlalchemy.create_engine("XXX")
# con = engine.connect()
# # tosql = res_df.reset_index().rename(columns={"index":"work_item"})
# # tosql.to_sql(name="resource_employment_rate", con=con)
# res_df = pd.read_sql_table(table_name="resource_employment_rate", con=con)
# con.close()
```
```python
fig, ax = plt.subplots(3,1, figsize=(12,10), sharex=True, constrained_layout=True)
res_df["x_emp"].plot(ax=ax[0], label="x_emp")
ax[0].set_title("Employment rate")
ax[0].legend()
res_df["x_exp"].plot(ax=ax[1], label="x_exp")
ax[1].set_title("Experience rate")
ax[1].legend()
res_df["x_load"].plot(ax=ax[2], label="x_load")
ax[2].set_title("Workload rate")
ax[2].legend()
plt.show()
```
We want to add another feature regarding to the difficulty of a work item. Resources have days where they are closing a lot of items at once. But there are always some items that are skipping these 'closing days' so we assume that these items have a higher difficulty.
We define a closing day as
\begin{equation}
t^{er}_{close} =
\begin{cases}
1 & \frac{\sum{w^{er}_{closed}(t)}}{\sum{w^{er}_{open}(t)}} \geq 0.25 \\
0 & else
\end{cases}
\end{equation}
So if 30% of the open tickets the resource holds are closed it's a closing day. We define than the difficulty of a work item
\begin{equation}
x^{wi}_{diff} = \sum_{t}{\sum_{er}{t^{er}_{close}}}
\end{equation}
The difficulty is the sum of all closing days a work item skipped for every resource that worked on it.
Now let's implement this.
```python
def calc_t_close(times_closed, resource):
res_df = times_closed[times_closed["current_resource"] == resource]
# We calculate the number of items dropped at a drop date
t_close = pd.DataFrame(res_df["drop_date"].value_counts()).reset_index().rename(columns={"index":"drop_date",
"drop_date":"w_closed"})
# We calculate the work items that are open over a drop date
res_df["w_open"] = res_df["drop_date"].apply(lambda t: res_df[(res_df["drop_date"].apply(lambda x: x>=t)) &
(res_df["receive_date"].apply(lambda x: x<=t))].shape[0])
# Now we merge them together and calculate the percentage
t_close = pd.merge(t_close, res_df[["drop_date", "w_open"]].drop_duplicates())
t_close.loc[:, "percentage_closed"] = t_close["w_closed"] / t_close["w_open"].apply(lambda x: 1 if x==0 else x)
t_close.loc[:, "t_close"] = t_close["percentage_closed"].apply(lambda x: 1 if x >= 0.25 else 0)
close_days = t_close[t_close["t_close"] == 1]["drop_date"].values
return close_days
```
```python
times.loc[:, "x_diff"] = 0
for resource in times["current_resource"].unique():
close_days = calc_t_close(times_closed, resource)
res_df = times[times["current_resource"] == resource]
for x, y in res_df.iterrows():
difficulty = len([e for e in close_days if ((y["receive_date"]<e)&~(y["drop_date"]<=e))])
times.loc[x, "x_diff"] = difficulty
```
```python
difficulty_df = pd.DataFrame(times.groupby("work_item")["x_diff"].sum()).reset_index()
plot_df = pd.merge(total_times.dropna(), difficulty_df).drop_duplicates()
total_times_c = compute_work_item_times(set_end_date(data, "2018-03-31"))
plot_df_open = pd.merge(total_times_c[total_times_c.work_item.isin(open_wis)], difficulty_df).drop_duplicates("work_item")
```
```python
plt.figure(figsize=(15,8))
plt.scatter(x=plot_df.x_diff, y=plot_df.duration_in_days, s=4, color='g', label="closed tickets")
plt.scatter(x=plot_df_open.x_diff, y=plot_df_open.duration_in_days, s=4, color='r', label="open tickets")
plt.title("Difficulty corresponding to duration")
plt.xlabel("difficulty")
plt.ylabel("duration in days")
plt.legend()
plt.show()
```
Now the difficulty is only resource related and has a wide range of values. We should think about a better scale for that.
```python
```
|
(* Title: Jinja/J/execute_WellType.thy
Author: Christoph Petzinger
Copyright 2004 Technische Universitaet Muenchen
*)
(*
Expanded to include support for static fields and methods.
Susannah Mansky
2017, UIUC
*)
section \<open> Code Generation For WellType \<close>
theory execute_WellType
imports
WellType Examples
begin
(* Replace WT_WTs.WTCond with new intros WT_WTs.WTCond1 and WT_WTs.WTCond2 *)
lemma WTCond1:
"\<lbrakk>P,E \<turnstile> e :: Boolean; P,E \<turnstile> e\<^sub>1::T\<^sub>1; P,E \<turnstile> e\<^sub>2::T\<^sub>2; P \<turnstile> T\<^sub>1 \<le> T\<^sub>2;
P \<turnstile> T\<^sub>2 \<le> T\<^sub>1 \<longrightarrow> T\<^sub>2 = T\<^sub>1 \<rbrakk> \<Longrightarrow> P,E \<turnstile> if (e) e\<^sub>1 else e\<^sub>2 :: T\<^sub>2"
by (fastforce)
lemma WTCond2:
"\<lbrakk>P,E \<turnstile> e :: Boolean; P,E \<turnstile> e\<^sub>1::T\<^sub>1; P,E \<turnstile> e\<^sub>2::T\<^sub>2; P \<turnstile> T\<^sub>2 \<le> T\<^sub>1;
P \<turnstile> T\<^sub>1 \<le> T\<^sub>2 \<longrightarrow> T\<^sub>1 = T\<^sub>2 \<rbrakk> \<Longrightarrow> P,E \<turnstile> if (e) e\<^sub>1 else e\<^sub>2 :: T\<^sub>1"
by (fastforce)
lemmas [code_pred_intro] =
WT_WTs.WTNew
WT_WTs.WTCast
WT_WTs.WTVal
WT_WTs.WTVar
WT_WTs.WTBinOpEq
WT_WTs.WTBinOpAdd
WT_WTs.WTLAss
WT_WTs.WTFAcc
WT_WTs.WTSFAcc
WT_WTs.WTFAss
WT_WTs.WTSFAss
WT_WTs.WTCall
WT_WTs.WTSCall
WT_WTs.WTBlock
WT_WTs.WTSeq
declare
WTCond1 [code_pred_intro WTCond1]
WTCond2 [code_pred_intro WTCond2]
lemmas [code_pred_intro] =
WT_WTs.WTWhile
WT_WTs.WTThrow
WT_WTs.WTTry
WT_WTs.WTNil
WT_WTs.WTCons
code_pred
(modes: i \<Rightarrow> i \<Rightarrow> i \<Rightarrow> i \<Rightarrow> bool as type_check, i \<Rightarrow> i \<Rightarrow> i \<Rightarrow> o \<Rightarrow> bool as infer_type)
WT
proof -
case WT
from WT.prems show thesis
proof(cases (no_simp))
case (WTCond E e e1 T1 e2 T2 T)
from `x \<turnstile> T1 \<le> T2 \<or> x \<turnstile> T2 \<le> T1` show thesis
proof
assume "x \<turnstile> T1 \<le> T2"
with `x \<turnstile> T1 \<le> T2 \<longrightarrow> T = T2` have "T = T2" ..
from `xa = E` `xb = if (e) e1 else e2` `xc = T` `x,E \<turnstile> e :: Boolean`
`x,E \<turnstile> e1 :: T1` `x,E \<turnstile> e2 :: T2` `x \<turnstile> T1 \<le> T2` `x \<turnstile> T2 \<le> T1 \<longrightarrow> T = T1`
show ?thesis unfolding `T = T2` by(rule WT.WTCond1[OF refl])
next
assume "x \<turnstile> T2 \<le> T1"
with `x \<turnstile> T2 \<le> T1 \<longrightarrow> T = T1` have "T = T1" ..
from `xa = E` `xb = if (e) e1 else e2` `xc = T` `x,E \<turnstile> e :: Boolean`
`x,E \<turnstile> e1 :: T1` `x,E \<turnstile> e2 :: T2` `x \<turnstile> T2 \<le> T1` `x \<turnstile> T1 \<le> T2 \<longrightarrow> T = T2`
show ?thesis unfolding `T = T1` by(rule WT.WTCond2[OF refl])
qed
qed(assumption|erule (2) WT.that[OF refl])+
next
case WTs
from WTs.prems show thesis
by(cases (no_simp))(assumption|erule (2) WTs.that[OF refl])+
qed
notation infer_type ("_,_ \<turnstile> _ :: '_" [51,51,51]100)
definition test1 where "test1 = [],empty \<turnstile> testExpr1 :: _"
definition test2 where "test2 = [], empty \<turnstile> testExpr2 :: _"
definition test3 where "test3 = [], empty(''V'' \<mapsto> Integer) \<turnstile> testExpr3 :: _"
definition test4 where "test4 = [], empty(''V'' \<mapsto> Integer) \<turnstile> testExpr4 :: _"
definition test5 where "test5 = [classObject, (''C'',(''Object'',[(''F'',NonStatic,Integer)],[]))], empty \<turnstile> testExpr5 :: _"
definition test6 where "test6 = [classObject, classI], empty \<turnstile> testExpr6 :: _"
ML_val \<open>
val SOME(@{code Integer}, _) = Predicate.yield @{code test1};
val SOME(@{code Integer}, _) = Predicate.yield @{code test2};
val SOME(@{code Integer}, _) = Predicate.yield @{code test3};
val SOME(@{code Void}, _) = Predicate.yield @{code test4};
val SOME(@{code Void}, _) = Predicate.yield @{code test5};
val SOME(@{code Integer}, _) = Predicate.yield @{code test6};
\<close>
definition testmb_isNull where "testmb_isNull = [classObject, classA], empty([this] [\<mapsto>] [Class ''A'']) \<turnstile> mb_isNull :: _"
definition testmb_add where "testmb_add = [classObject, classA], empty([this,''i''] [\<mapsto>] [Class ''A'',Integer]) \<turnstile> mb_add :: _"
definition testmb_mult_cond where "testmb_mult_cond = [classObject, classA], empty([this,''j''] [\<mapsto>] [Class ''A'',Integer]) \<turnstile> mb_mult_cond :: _"
definition testmb_mult_block where "testmb_mult_block = [classObject, classA], empty([this,''i'',''j'',''temp''] [\<mapsto>] [Class ''A'',Integer,Integer,Integer]) \<turnstile> mb_mult_block :: _"
definition testmb_mult where "testmb_mult = [classObject, classA], empty([this,''i'',''j''] [\<mapsto>] [Class ''A'',Integer,Integer]) \<turnstile> mb_mult :: _"
ML_val \<open>
val SOME(@{code Boolean}, _) = Predicate.yield @{code testmb_isNull};
val SOME(@{code Integer}, _) = Predicate.yield @{code testmb_add};
val SOME(@{code Boolean}, _) = Predicate.yield @{code testmb_mult_cond};
val SOME(@{code Void}, _) = Predicate.yield @{code testmb_mult_block};
val SOME(@{code Integer}, _) = Predicate.yield @{code testmb_mult};
\<close>
definition test where "test = [classObject, classA], empty \<turnstile> testExpr_ClassA :: _"
ML_val \<open>
val SOME(@{code Integer}, _) = Predicate.yield @{code test};
\<close>
end
|
import field_definition
import field_results
def two (f : Type) [myfld f] : f := (myfld.one .+ myfld.one)
def four (f : Type) [myfld f] : f := ((two f) .+ (two f))
/- We have to add an additional stipulation that our fields are not of characteristic 2.-/
/- The quadratic formula is not defined for fields where 1 + 1 = 0.-/
class fld_not_char_two (f : Type _) [myfld f] :=
(not_char_two : myfld.one .+ myfld.one ≠ (myfld.zero : f))
lemma two_ne_zero (f : Type) [myfld f] [fld_not_char_two f] : (two f) ≠ myfld.zero :=
begin
unfold two, exact fld_not_char_two.not_char_two,
end
lemma two_plus_two (f : Type) [myfld f] : (two f) .+ (two f) = (two f) .* (two f) :=
begin
unfold two, rw distrib_simp f _ _ _, rw myfld.mul_comm myfld.one _, rw <- myfld.mul_one (myfld.one .+ myfld.one),
end
lemma four_ne_zero (f : Type) [myfld f] [fld_not_char_two f] : (four f) ≠ myfld.zero :=
begin
unfold four, rw two_plus_two, exact mul_nonzero f (two f) (two f) (two_ne_zero f) (two_ne_zero f),
end
lemma add_two_halves (f : Type) [myfld f] [fld_not_char_two f] :
(myfld.reciprocal (two f) (two_ne_zero f)) .+ (myfld.reciprocal (two f) (two_ne_zero f)) = myfld.one :=
begin
unfold two,
have h1 : (two f) .* (myfld.reciprocal (two f) (two_ne_zero f)) = myfld.one,
exact myfld.mul_reciprocal (two f) (two_ne_zero f),
unfold two at h1, rw distrib_simp f _ _ _ at h1,
rw myfld.mul_comm (myfld.one) _ at h1,
rw <- myfld.mul_one (myfld.reciprocal (myfld.one .+ myfld.one) (fld_not_char_two.not_char_two)) at h1,
exact h1,
end
/- Now we can move on to the preliminary work for the cubic formula.-/
/- We have to add an additional stipulation that our fields are not of characteristic 3.-/
/- The cubic formula is not defined for fields where 1 + 1 + 1 = 0.-/
def three (f : Type) [myfld f] : f := myfld.one .+ (myfld.one .+ myfld.one)
class fld_not_char_three (f : Type _) [myfld f] :=
(not_char_three : (three f) ≠ (myfld.zero : f))
def six (f : Type) [myfld f] : f := (two f) .* (three f)
lemma six_ne_zero (f : Type) [myfld f] [fld_not_char_two f] [fld_not_char_three f] : (six f) ≠ myfld.zero :=
begin
unfold six, unfold two, exact mul_nonzero f (myfld.one .+ myfld.one) (three f)
fld_not_char_two.not_char_two fld_not_char_three.not_char_three,
end
def nine (f : Type) [myfld f] : f := ((three f) .* (three f))
lemma nine_ne_zero (f : Type) [myfld f] [fld_not_char_three f] : (nine f) ≠ myfld.zero :=
begin
unfold nine, exact mul_nonzero f (three f) (three f) fld_not_char_three.not_char_three fld_not_char_three.not_char_three,
end
def twenty_seven (f : Type) [myfld f] : f := (three f) .* (nine f)
lemma twenty_seven_ne_zero (f : Type) [myfld f] [fld_not_char_three f] : (twenty_seven f) ≠ myfld.zero :=
begin
unfold twenty_seven, exact mul_nonzero f (three f) (nine f) fld_not_char_three.not_char_three (nine_ne_zero f),
end
lemma three_cubed (f : Type) [myfld f] : (cubed f (three f)) = (twenty_seven f) :=
begin
unfold cubed, unfold twenty_seven, unfold nine,
end
def nine_minus_one (f : Type) [myfld f] : (((three f) .* (three f)) .+ (.- myfld.one)) =
(cubed f (two f)) :=
begin
unfold three, unfold two, unfold cubed, simp,
end
def one_plus_three (f : Type) [myfld f] : myfld.one .+ (three f) = (two f) .* (two f) :=
begin
unfold two, unfold three, simp,
end
lemma two_x_div_two (f : Type) [myfld f] [fld_not_char_two f] (a : f) :
(myfld.reciprocal (two f) fld_not_char_two.not_char_two) .* (a .+ a) = a :=
begin
unfold two,
rw [myfld.mul_one a] {occs := occurrences.pos [1, 2]},
rw <- distrib_simp_alt f a, rw myfld.mul_comm a, rw myfld.mul_assoc, rw myfld.mul_comm (myfld.reciprocal _ _) _,
rw myfld.mul_reciprocal, rw one_mul_simp,
end |
State Before: R : Type u_1
inst✝¹ : CommRing R
inst✝ : IsDomain R
I : Ideal R
h : FG I
⊢ IsIdempotentElem I ↔ I = ⊥ ∨ I = ⊤ State After: case mp
R : Type u_1
inst✝¹ : CommRing R
inst✝ : IsDomain R
I : Ideal R
h : FG I
⊢ IsIdempotentElem I → I = ⊥ ∨ I = ⊤
case mpr
R : Type u_1
inst✝¹ : CommRing R
inst✝ : IsDomain R
I : Ideal R
h : FG I
⊢ I = ⊥ ∨ I = ⊤ → IsIdempotentElem I Tactic: constructor State Before: case mp
R : Type u_1
inst✝¹ : CommRing R
inst✝ : IsDomain R
I : Ideal R
h : FG I
⊢ IsIdempotentElem I → I = ⊥ ∨ I = ⊤ State After: case mp
R : Type u_1
inst✝¹ : CommRing R
inst✝ : IsDomain R
I : Ideal R
h : FG I
H : IsIdempotentElem I
⊢ I = ⊥ ∨ I = ⊤ Tactic: intro H State Before: case mp
R : Type u_1
inst✝¹ : CommRing R
inst✝ : IsDomain R
I : Ideal R
h : FG I
H : IsIdempotentElem I
⊢ I = ⊥ ∨ I = ⊤ State After: case mp.intro.intro
R : Type u_1
inst✝¹ : CommRing R
inst✝ : IsDomain R
e : R
he : IsIdempotentElem e
h : FG (Submodule.span R {e})
H : IsIdempotentElem (Submodule.span R {e})
⊢ Submodule.span R {e} = ⊥ ∨ Submodule.span R {e} = ⊤ Tactic: obtain ⟨e, he, rfl⟩ := (I.isIdempotentElem_iff_of_fg h).mp H State Before: case mp.intro.intro
R : Type u_1
inst✝¹ : CommRing R
inst✝ : IsDomain R
e : R
he : IsIdempotentElem e
h : FG (Submodule.span R {e})
H : IsIdempotentElem (Submodule.span R {e})
⊢ Submodule.span R {e} = ⊥ ∨ Submodule.span R {e} = ⊤ State After: case mp.intro.intro
R : Type u_1
inst✝¹ : CommRing R
inst✝ : IsDomain R
e : R
he : IsIdempotentElem e
h : FG (Submodule.span R {e})
H : IsIdempotentElem (Submodule.span R {e})
⊢ e = 0 ∨ span {e} = ⊤ Tactic: simp only [Ideal.submodule_span_eq, Ideal.span_singleton_eq_bot] State Before: case mp.intro.intro
R : Type u_1
inst✝¹ : CommRing R
inst✝ : IsDomain R
e : R
he : IsIdempotentElem e
h : FG (Submodule.span R {e})
H : IsIdempotentElem (Submodule.span R {e})
⊢ e = 0 ∨ span {e} = ⊤ State After: R : Type u_1
inst✝¹ : CommRing R
inst✝ : IsDomain R
e : R
he : IsIdempotentElem e
h : FG (Submodule.span R {e})
H : IsIdempotentElem (Submodule.span R {e})
⊢ e = 1 → span {e} = ⊤ Tactic: apply Or.imp id _ (IsIdempotentElem.iff_eq_zero_or_one.mp he) State Before: R : Type u_1
inst✝¹ : CommRing R
inst✝ : IsDomain R
e : R
he : IsIdempotentElem e
h : FG (Submodule.span R {e})
H : IsIdempotentElem (Submodule.span R {e})
⊢ e = 1 → span {e} = ⊤ State After: R : Type u_1
inst✝¹ : CommRing R
inst✝ : IsDomain R
he : IsIdempotentElem 1
h : FG (Submodule.span R {1})
H : IsIdempotentElem (Submodule.span R {1})
⊢ span {1} = ⊤ Tactic: rintro rfl State Before: R : Type u_1
inst✝¹ : CommRing R
inst✝ : IsDomain R
he : IsIdempotentElem 1
h : FG (Submodule.span R {1})
H : IsIdempotentElem (Submodule.span R {1})
⊢ span {1} = ⊤ State After: no goals Tactic: simp State Before: case mpr
R : Type u_1
inst✝¹ : CommRing R
inst✝ : IsDomain R
I : Ideal R
h : FG I
⊢ I = ⊥ ∨ I = ⊤ → IsIdempotentElem I State After: no goals Tactic: rintro (rfl | rfl) <;> simp [IsIdempotentElem] |
(* Authors: Lammich, Wimmer *)
section \<open>Generic Worklist Algorithm with Subsumption\<close>
theory Worklist_Subsumption_PW_Multiset
imports "$AFP/Refine_Imperative_HOL/Sepref" Unified_PW
begin
subsection \<open>Deriving the Standard Worklist Algorithm from the Generalized Version\<close>
(* XXX Move to misc *)
lemma mset_remove_member:
"x \<in># A - B" if "x \<in># A" "x \<notin># B"
using that
by (metis count_greater_zero_iff in_diff_count not_in_iff)
context Search_Space_Defs_Empty begin
definition "worklist_inv_frontier passed wait =
(\<forall> a \<in> passed. \<forall> a'. E a a' \<and> \<not> empty a' \<longrightarrow> (\<exists> b' \<in> passed \<union> set_mset wait. a' \<preceq> b'))"
definition "add_succ_spec wait a \<equiv> SPEC (\<lambda>(wait',brk).
if \<exists>a'. E a a' \<and> F a' then
brk
else
\<not>brk \<and> set_mset wait' \<subseteq> set_mset wait \<union> {a' . E a a'} \<and>
(\<forall> s \<in> set_mset wait \<union> {a' . E a a' \<and> \<not> empty a'}. \<exists> s' \<in> set_mset wait'. s \<preceq> s')
)"
definition "worklist_inv \<equiv> \<lambda> (passed, wait, brk).
pw_inv (passed, wait, brk) \<and>
\<not> brk \<longrightarrow> worklist_inv_frontier passed wait (* \<and>
(\<forall> a \<in> set_mset wait. \<not> empty a) *)
"
definition worklist_algo where
"worklist_algo = do
{
if F a\<^sub>0 then RETURN True
else do {
(passed, wait) \<leftarrow> RETURN ({}, {#a\<^sub>0#});
(passed, wait, brk) \<leftarrow> WHILEIT worklist_inv (\<lambda> (passed, wait, brk). \<not> brk \<and> wait \<noteq> {#})
(\<lambda> (passed, wait, brk). do
{
(a, wait) \<leftarrow> take_from_mset wait;
ASSERT (reachable a);
if (\<exists> a' \<in> passed. a \<preceq> a') then RETURN (passed, wait, brk) else
do
{
(wait,brk) \<leftarrow> add_succ_spec wait a;
let passed = insert a passed;
RETURN (passed, wait, brk)
}
}
)
(passed, wait, False);
RETURN brk
}
}
"
end
subsubsection \<open>Correctness Proof\<close>
context Search_Space' begin
lemma add_succs_ref_aux_1:
"(if (\<exists> a' \<in> passed. a \<preceq> a') then RETURN (passed, wait, brk) else
do
{
(wait,brk) \<leftarrow> add_succ_spec wait a;
let passed = insert a passed;
RETURN (passed, wait, brk)
}
) \<le> \<Down> Id (add_pw_spec passed' wait' a')"
if "(\<forall> a \<in> passed \<union> set_mset wait. \<not> F a)" "worklist_inv_frontier passed (wait + {#a#})"
"reachable a" "passed \<union> set_mset wait \<subseteq> Collect reachable" "\<not> brk" "\<not> F a"
"(wait, wait') \<in> Id" "(passed, passed') \<in> Id" "(a, a') \<in> Id"
unfolding add_pw_spec_def using that
apply auto
subgoal for b a'
unfolding worklist_inv_frontier_def
apply (frule final_non_empty)
apply clarsimp
apply (drule mono, assumption, simp, blast, blast dest: empty_E)
by (blast intro: F_mono trans dest: empty_mono)
subgoal
unfolding add_succ_spec_def by (auto simp: pw_le_iff refine_pw_simps)
subgoal premises prems for a'' b
proof -
from prems obtain b' where b': "E a'' b'" "b \<preceq> b'"
by (metis (mono_tags, lifting) empty_E mono subset_Collect_conv)
with prems have "\<not> empty b'" by - (rule empty_mono)
with b' prems(2) \<open>a'' \<in> passed'\<close> consider "b' \<preceq> a'" | "\<exists>x\<in>passed' \<union> set_mset wait'. b' \<preceq> x"
unfolding worklist_inv_frontier_def by auto
then show ?thesis
proof cases
case 1
then show ?thesis
by (meson b'(2) local.trans prems(12) prems(13) subsetCE sup.cobounded2)
next
case 2
with b'(2) show ?thesis by (auto intro: trans)
qed
qed
unfolding add_succ_spec_def by (auto simp: pw_le_iff refine_pw_simps)
context
begin
private lemma aux3:
assumes
"set_mset wait \<subseteq> Collect reachable"
"a \<in># wait"
"\<forall> s \<in> set_mset (wait - {#a#}) \<union> {a'. E a a' \<and> \<not> empty a'}. \<exists> s' \<in> set_mset wait'. s \<preceq> s'"
"worklist_inv_frontier passed wait"
shows "worklist_inv_frontier (insert a passed) wait'"
proof -
from assms(1,2) have "reachable a"
by (simp add: subset_iff)
with finitely_branching have [simp, intro!]: "finite (Collect (E a))" .
show ?thesis unfolding worklist_inv_frontier_def
apply safe
subgoal
using assms by auto
subgoal for b b'
proof -
assume A: "E b b'" "\<not> empty b'" "b \<in> passed"
with assms obtain b'' where b'': "b'' \<in> passed \<union> set_mset wait" "b' \<preceq> b''"
unfolding worklist_inv_frontier_def by blast
from this(1) show ?thesis
apply standard
subgoal
using \<open>b' \<preceq> b''\<close> by auto
subgoal
apply (cases "a = b''")
subgoal
using b''(2) by blast
subgoal premises prems
proof -
from prems have "b'' \<in># wait - {#a#}"
by (auto simp: mset_remove_member)
with assms prems \<open>b' \<preceq> b''\<close> show ?thesis
by (blast intro: local.trans)
qed
done
done
qed
done
qed
lemma add_succs_ref_aux_2:
"(if (\<exists> a' \<in> passed. a \<preceq> a') then RETURN (passed, wait, brk) else
do
{
(wait,brk) \<leftarrow> add_succ_spec wait a;
let passed = insert a passed;
RETURN (passed, wait, brk)
}
) \<le> SPEC (\<lambda> (passed, wait, brk). (\<not> brk \<longrightarrow> worklist_inv_frontier passed wait))"
if "worklist_inv_frontier passed (wait + {#a#})" "reachable a"
"passed \<union> set_mset wait \<subseteq> Collect reachable"
using that
apply clarsimp
apply safe
subgoal
unfolding worklist_inv_frontier_def by (auto intro: trans)
subgoal
unfolding add_succ_spec_def
apply (auto simp add: pw_le_iff refine_pw_simps)
apply (rule aux3)
prefer 4
apply assumption
defer
apply (simp; fail)
(* s/h *)
apply (simp add: worklist_inv_frontier_def)
by (simp add: Multiset.diff_union_cancelR; fail)
done
end \<comment> \<open>Private context\<close>
lemma add_succs_ref[refine]:
"(if (\<exists> a' \<in> passed. a \<preceq> a') then RETURN (passed, wait, brk) else
do
{
(wait,brk) \<leftarrow> add_succ_spec wait a;
let passed = insert a passed;
RETURN (passed, wait, brk)
}
) \<le>
\<Down> {((passed, wait, brk),(passed', wait',brk')).
passed = passed' \<and> wait = wait' \<and> brk = brk' \<and>
(\<not> brk \<longrightarrow> worklist_inv_frontier passed wait)} (add_pw_spec passed' wait' a')"
if "(\<forall> a \<in> passed \<union> set_mset wait. \<not> F a)" "worklist_inv_frontier passed (wait + {#a#})"
"reachable a" "passed \<union> set_mset wait \<subseteq> Collect reachable" "\<not> brk" "\<not> F a"
"(wait, wait') \<in> Id" "(passed, passed') \<in> Id" "(a, a') \<in> Id"
using add_succs_ref_aux_1[OF that] add_succs_ref_aux_2[OF that(2-4)]
by (simp add: pw_le_iff refine_pw_simps)
lemma [refine]:
"take_from_mset wait \<le>
\<Down> {((x, wait), (y, wait')).
x = y \<and> wait = wait' \<and> (\<forall> a \<in> set_mset wait. \<not> F a) \<and> set_mset wait \<subseteq> Collect reachable \<and>
worklist_inv_frontier passed (wait + {#x#}) \<and> \<not> F x} (take_from_mset wait')"
if "wait = wait'" "wait \<noteq> {#}" "(\<forall> a \<in> set_mset wait. \<not> F a)" "set_mset wait \<subseteq> Collect reachable"
"worklist_inv_frontier passed wait"
using that
by (auto 4 5 simp: pw_le_iff refine_pw_simps dest: in_diffD dest!: take_from_mset_correct)
lemma [refine]:
"RETURN ({}, {#a\<^sub>0#}) \<le> \<Down> (Id \<inter> {((p, w), (p', w')). worklist_inv (p, w, False)}) init_pw_spec"
unfolding init_pw_spec_def worklist_inv_def pw_inv_def worklist_inv_frontier_def
by (auto simp: pw_le_iff refine_pw_simps)
lemma worklist_algo_ref[refine]:
"worklist_algo \<le> \<Down> Id pw_algo"
unfolding worklist_algo_def pw_algo_def
using [[goals_limit=20]]
apply refine_rcg
unfolding pw_inv_def worklist_inv_def worklist_inv_frontier_def pw_inv_frontier_def
by auto (* slow *)
theorem worklist_algo_correct:
"worklist_algo \<le> SPEC (\<lambda> brk. brk \<longleftrightarrow> F_reachable)"
proof -
note worklist_algo_ref
also note pw_algo_correct
finally show ?thesis .
qed
end \<comment> \<open>Search Space'\<close>
context Search_Space''_Defs
begin
definition "worklist_inv_frontier' passed wait =
(\<forall> a \<in> passed. \<forall> a'. E a a' \<and> \<not> empty a' \<longrightarrow> (\<exists> b' \<in> passed \<union> set_mset wait. a' \<preceq> b'))"
definition "start_subsumed' passed wait = (\<exists> a \<in> passed \<union> set_mset wait. a\<^sub>0 \<preceq> a)"
definition "worklist_inv' \<equiv> \<lambda> (passed, wait, brk).
worklist_inv (passed, wait, brk) \<and> (\<forall> a \<in> passed. \<not> empty a) \<and> (\<forall> a \<in> set_mset wait. \<not> empty a)
"
definition "add_succ_spec' wait a \<equiv> SPEC (\<lambda>(wait',brk).
(
if \<exists>a'. E a a' \<and> F a' then
brk
else
\<not>brk \<and> set_mset wait' \<subseteq> set_mset wait \<union> {a' . E a a'} \<and>
(\<forall> s \<in> set_mset wait \<union> {a' . E a a' \<and> \<not> empty a'}. \<exists> s' \<in> set_mset wait'. s \<preceq> s')
) \<and> (\<forall> s \<in> set_mset wait'. \<not> empty s)
)"
definition worklist_algo' where
"worklist_algo' = do
{
if F a\<^sub>0 then RETURN True
else do {
let passed = {};
let wait = {#a\<^sub>0#};
(passed, wait, brk) \<leftarrow> WHILEIT worklist_inv' (\<lambda> (passed, wait, brk). \<not> brk \<and> wait \<noteq> {#})
(\<lambda> (passed, wait, brk). do
{
(a, wait) \<leftarrow> take_from_mset wait;
ASSERT (reachable a);
if (\<exists> a' \<in> passed. a \<unlhd> a') then RETURN (passed, wait, brk) else
do
{
(wait,brk) \<leftarrow> add_succ_spec' wait a;
let passed = insert a passed;
RETURN (passed, wait, brk)
}
}
)
(passed, wait, False);
RETURN brk
}
}
"
end \<comment> \<open>Search Space' Defs\<close>
context Search_Space''_start
begin
lemma worklist_algo_list_inv_ref[refine]:
fixes x x'
assumes
"\<not> F a\<^sub>0" "\<not> F a\<^sub>0"
"(x, x') \<in> {
((passed,wait,brk), (passed',wait',brk')). passed = passed' \<and> wait = wait' \<and> brk = brk' \<and>
(\<forall> a \<in> passed. \<not> empty a) \<and> (\<forall> a \<in> set_mset wait. \<not> empty a)}"
"worklist_inv x'"
shows "worklist_inv' x"
using assms
unfolding worklist_inv'_def worklist_inv_def
by auto
lemma [refine]:
"take_from_mset wait \<le>
\<Down> {((x, wait), (y, wait')). x = y \<and> wait = wait' \<and> \<not> empty x \<and>
(\<forall> a \<in> set_mset wait. \<not> empty a)} (take_from_mset wait')"
if "wait = wait'" "\<forall> a \<in> set_mset wait. \<not> empty a" "wait \<noteq> {#}"
using that
by (auto 4 5 simp: pw_le_iff refine_pw_simps dest: in_diffD dest!: take_from_mset_correct)
lemma [refine]:
"add_succ_spec' wait x \<le>
\<Down> ({(wait, wait'). wait = wait' \<and>
(\<forall> a \<in> set_mset wait. \<not> empty a)} \<times>\<^sub>r bool_rel) (add_succ_spec wait' x')"
if "wait = wait'" "x = x'" "\<forall> a \<in> set_mset wait. \<not> empty a"
using that
unfolding add_succ_spec'_def add_succ_spec_def
by (auto simp: pw_le_iff refine_pw_simps)
lemma worklist_algo'_ref[refine]: "worklist_algo' \<le> \<Down>Id worklist_algo"
using [[goals_limit=15]]
unfolding worklist_algo'_def worklist_algo_def
apply (refine_rcg)
prefer 4
apply assumption
apply refine_dref_type
by (auto simp: empty_subsumes')
end \<comment> \<open>Search Space' Start\<close>
context Search_Space''_Defs
begin
definition worklist_algo'' where
"worklist_algo'' \<equiv>
if empty a\<^sub>0 then RETURN False else worklist_algo'
"
end \<comment> \<open>Search Space' Defs\<close>
context Search_Space''
begin
lemma worklist_algo''_correct:
"worklist_algo'' \<le> SPEC (\<lambda> brk. brk \<longleftrightarrow> F_reachable)"
proof (cases "empty a\<^sub>0")
case True
then show ?thesis
unfolding worklist_algo''_def F_reachable_def reachable_def
using empty_E_star final_non_empty by auto
next
case False
interpret Search_Space''_start
by standard (rule \<open>\<not> empty _\<close>)
note worklist_algo'_ref
also note worklist_algo_correct
finally show ?thesis
using False unfolding worklist_algo''_def by simp
qed
end \<comment> \<open>Search Space''\<close>
end \<comment> \<open>End of Theory\<close>
|
(* Default settings (from HsToCoq.Coq.Preamble) *)
Generalizable All Variables.
Unset Implicit Arguments.
Set Maximal Implicit Insertion.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Require Coq.Program.Tactics.
Require Coq.Program.Wf.
(* Converted imports: *)
Require Control.Monad.Fail.
Require Control.Monad.Signatures.
Require Control.Monad.Trans.Class.
Require Data.Functor.Identity.
Require Data.Tuple.
Require GHC.Base.
Import GHC.Base.Notations.
(* Converted type declarations: *)
Inductive StateT s m a : Type
:= Mk_StateT (runStateT : s -> m (a * s)%type) : StateT s m a.
Definition State s :=
(StateT s Data.Functor.Identity.Identity)%type.
Arguments Mk_StateT {_} {_} {_} _.
Definition runStateT {s} {m} {a} (arg_0__ : StateT s m a) :=
let 'Mk_StateT runStateT := arg_0__ in
runStateT.
(* Converted value declarations: *)
Definition withStateT {s} {m} {a} : (s -> s) -> StateT s m a -> StateT s m a :=
fun f m => Mk_StateT (runStateT m GHC.Base.∘ f).
Definition withState {s} {a} : (s -> s) -> State s a -> State s a :=
withStateT.
Definition state {m} {s} {a} `{(GHC.Base.Monad m)}
: (s -> (a * s)%type) -> StateT s m a :=
fun f => Mk_StateT (GHC.Base.return_ GHC.Base.∘ f).
Definition runState {s} {a} : State s a -> s -> (a * s)%type :=
fun m => Data.Functor.Identity.runIdentity GHC.Base.∘ runStateT m.
Definition put {m} {s} `{(GHC.Base.Monad m)} : s -> StateT s m unit :=
fun s => state (fun arg_0__ => pair tt s).
Definition modify {m} {s} `{(GHC.Base.Monad m)} : (s -> s) -> StateT s m unit :=
fun f => state (fun s => pair tt (f s)).
Definition mapStateT {m} {a} {s} {n} {b}
: (m (a * s)%type -> n (b * s)%type) -> StateT s m a -> StateT s n b :=
fun f m => Mk_StateT (f GHC.Base.∘ runStateT m).
Definition mapState {a} {s} {b}
: ((a * s)%type -> (b * s)%type) -> State s a -> State s b :=
fun f =>
mapStateT (Data.Functor.Identity.Mk_Identity GHC.Base.∘
(f GHC.Base.∘ Data.Functor.Identity.runIdentity)).
Definition liftPass {m} {w} {a} {s} `{(GHC.Base.Monad m)}
: Control.Monad.Signatures.Pass w m (a * s)%type ->
Control.Monad.Signatures.Pass w (StateT s m) a :=
fun pass m =>
Mk_StateT (fun s =>
pass (let cont_0__ arg_1__ :=
let 'pair (pair a f) s' := arg_1__ in
GHC.Base.return_ (pair (pair a s') f) in
runStateT m s GHC.Base.>>= cont_0__)).
Definition liftListen {m} {w} {a} {s} `{(GHC.Base.Monad m)}
: Control.Monad.Signatures.Listen w m (a * s)%type ->
Control.Monad.Signatures.Listen w (StateT s m) a :=
fun listen m =>
Mk_StateT (fun s =>
let cont_0__ arg_1__ :=
let 'pair (pair a s') w := arg_1__ in
GHC.Base.return_ (pair (pair a w) s') in
listen (runStateT m s) GHC.Base.>>= cont_0__).
Definition liftCallCC' {m} {a} {s} {b}
: Control.Monad.Signatures.CallCC m (a * s)%type (b * s)%type ->
Control.Monad.Signatures.CallCC (StateT s m) a b :=
fun callCC f =>
Mk_StateT (fun s =>
callCC (fun c =>
runStateT (f (fun a => Mk_StateT (fun s' => c (pair a s')))) s)).
Definition liftCallCC {m} {a} {s} {b}
: Control.Monad.Signatures.CallCC m (a * s)%type (b * s)%type ->
Control.Monad.Signatures.CallCC (StateT s m) a b :=
fun callCC f =>
Mk_StateT (fun s =>
callCC (fun c =>
runStateT (f (fun a => Mk_StateT (fun arg_0__ => c (pair a s)))) s)).
Definition gets {m} {s} {a} `{(GHC.Base.Monad m)} : (s -> a) -> StateT s m a :=
fun f => state (fun s => pair (f s) s).
Definition get {m} {s} `{(GHC.Base.Monad m)} : StateT s m s :=
state (fun s => pair s s).
Local Definition Monad__StateT_op_zgzgze__ {inst_m} {inst_s} `{(GHC.Base.Monad
inst_m)}
: forall {a} {b},
(StateT inst_s inst_m) a ->
(a -> (StateT inst_s inst_m) b) -> (StateT inst_s inst_m) b :=
fun {a} {b} =>
fun m k =>
Mk_StateT (fun s =>
let cont_0__ arg_1__ := let 'pair a s' := arg_1__ in runStateT (k a) s' in
runStateT m s GHC.Base.>>= cont_0__).
Local Definition Monad__StateT_op_zgzg__ {inst_m} {inst_s} `{(GHC.Base.Monad
inst_m)}
: forall {a} {b},
(StateT inst_s inst_m) a ->
(StateT inst_s inst_m) b -> (StateT inst_s inst_m) b :=
fun {a} {b} => fun m k => Monad__StateT_op_zgzgze__ m (fun arg_0__ => k).
Local Definition Applicative__StateT_op_zlztzg__ {inst_m} {inst_s}
`{GHC.Base.Functor inst_m} `{GHC.Base.Monad inst_m}
: forall {a} {b},
(StateT inst_s inst_m) (a -> b) ->
(StateT inst_s inst_m) a -> (StateT inst_s inst_m) b :=
fun {a} {b} =>
fun arg_0__ arg_1__ =>
match arg_0__, arg_1__ with
| Mk_StateT mf, Mk_StateT mx =>
Mk_StateT (fun s =>
let cont_2__ arg_3__ :=
let 'pair f s' := arg_3__ in
let cont_4__ arg_5__ :=
let 'pair x s'' := arg_5__ in
GHC.Base.return_ (pair (f x) s'') in
mx s' GHC.Base.>>= cont_4__ in
mf s GHC.Base.>>= cont_2__)
end.
Local Definition Functor__StateT_fmap {inst_m} {inst_s} `{(GHC.Base.Functor
inst_m)}
: forall {a} {b},
(a -> b) -> (StateT inst_s inst_m) a -> (StateT inst_s inst_m) b :=
fun {a} {b} =>
fun f m =>
Mk_StateT (fun s =>
GHC.Base.fmap (fun '(pair a s') => pair (f a) s') (runStateT m s)).
Local Definition Functor__StateT_op_zlzd__ {inst_m} {inst_s} `{(GHC.Base.Functor
inst_m)}
: forall {a} {b}, a -> (StateT inst_s inst_m) b -> (StateT inst_s inst_m) a :=
fun {a} {b} => Functor__StateT_fmap GHC.Base.∘ GHC.Base.const.
Program Instance Functor__StateT {m} {s} `{(GHC.Base.Functor m)}
: GHC.Base.Functor (StateT s m) :=
fun _ k__ =>
k__ {| GHC.Base.fmap__ := fun {a} {b} => Functor__StateT_fmap ;
GHC.Base.op_zlzd____ := fun {a} {b} => Functor__StateT_op_zlzd__ |}.
Local Definition Applicative__StateT_liftA2 {inst_m} {inst_s} `{GHC.Base.Functor
inst_m} `{GHC.Base.Monad inst_m}
: forall {a} {b} {c},
(a -> b -> c) ->
(StateT inst_s inst_m) a ->
(StateT inst_s inst_m) b -> (StateT inst_s inst_m) c :=
fun {a} {b} {c} =>
fun f x => Applicative__StateT_op_zlztzg__ (GHC.Base.fmap f x).
Local Definition Applicative__StateT_pure {inst_m} {inst_s} `{GHC.Base.Functor
inst_m} `{GHC.Base.Monad inst_m}
: forall {a}, a -> (StateT inst_s inst_m) a :=
fun {a} => fun a => Mk_StateT (fun s => GHC.Base.return_ (pair a s)).
Definition Applicative__StateT_op_ztzg__ {inst_m} {inst_s} `{_
: GHC.Base.Functor inst_m} `{_ : GHC.Base.Monad inst_m}
: forall {a} {b},
StateT inst_s inst_m a -> StateT inst_s inst_m b -> StateT inst_s inst_m b :=
fun {a} {b} =>
fun m k =>
Applicative__StateT_op_zlztzg__ (Applicative__StateT_op_zlztzg__
(Applicative__StateT_pure (fun x y => x)) k) m.
Program Instance Applicative__StateT {m} {s} `{GHC.Base.Functor m}
`{GHC.Base.Monad m}
: GHC.Base.Applicative (StateT s m) :=
fun _ k__ =>
k__ {| GHC.Base.liftA2__ := fun {a} {b} {c} => Applicative__StateT_liftA2 ;
GHC.Base.op_zlztzg____ := fun {a} {b} => Applicative__StateT_op_zlztzg__ ;
GHC.Base.op_ztzg____ := fun {a} {b} => Applicative__StateT_op_ztzg__ ;
GHC.Base.pure__ := fun {a} => Applicative__StateT_pure |}.
Local Definition Monad__StateT_return_ {inst_m} {inst_s} `{(GHC.Base.Monad
inst_m)}
: forall {a}, a -> (StateT inst_s inst_m) a :=
fun {a} => GHC.Base.pure.
Program Instance Monad__StateT {m} {s} `{(GHC.Base.Monad m)}
: GHC.Base.Monad (StateT s m) :=
fun _ k__ =>
k__ {| GHC.Base.op_zgzg____ := fun {a} {b} => Monad__StateT_op_zgzg__ ;
GHC.Base.op_zgzgze____ := fun {a} {b} => Monad__StateT_op_zgzgze__ ;
GHC.Base.return___ := fun {a} => Monad__StateT_return_ |}.
Definition modify' {m} {s} `{(GHC.Base.Monad m)}
: (s -> s) -> StateT s m unit :=
fun f => get GHC.Base.>>= (fun s => put (f s)).
Definition execStateT {m} {s} {a} `{(GHC.Base.Monad m)}
: StateT s m a -> s -> m s :=
fun m s =>
let cont_0__ arg_1__ := let 'pair _ s' := arg_1__ in GHC.Base.return_ s' in
runStateT m s GHC.Base.>>= cont_0__.
Definition execState {s} {a} : State s a -> s -> s :=
fun m s => Data.Tuple.snd (runState m s).
Definition evalStateT {m} {s} {a} `{(GHC.Base.Monad m)}
: StateT s m a -> s -> m a :=
fun m s =>
let cont_0__ arg_1__ := let 'pair a _ := arg_1__ in GHC.Base.return_ a in
runStateT m s GHC.Base.>>= cont_0__.
Definition evalState {s} {a} : State s a -> s -> a :=
fun m s => Data.Tuple.fst (runState m s).
(* Skipping all instances of class `Control.Monad.IO.Class.MonadIO', including
`Control.Monad.Trans.State.Lazy.MonadIO__StateT' *)
Local Definition MonadTrans__StateT_lift {inst_s}
: forall {m} {a}, forall `{(GHC.Base.Monad m)}, m a -> (StateT inst_s) m a :=
fun {m} {a} `{(GHC.Base.Monad m)} =>
fun m =>
Mk_StateT (fun s => m GHC.Base.>>= (fun a => GHC.Base.return_ (pair a s))).
Program Instance MonadTrans__StateT {s}
: Control.Monad.Trans.Class.MonadTrans (StateT s) :=
fun _ k__ =>
k__ {| Control.Monad.Trans.Class.lift__ := fun {m} {a} `{(GHC.Base.Monad m)} =>
MonadTrans__StateT_lift |}.
(* Skipping all instances of class `Control.Monad.Fix.MonadFix', including
`Control.Monad.Trans.State.Lazy.MonadFix__StateT' *)
(* Skipping all instances of class `GHC.Base.MonadPlus', including
`Control.Monad.Trans.State.Lazy.MonadPlus__StateT' *)
Local Definition MonadFail__StateT_fail {inst_m} {inst_s}
`{(Control.Monad.Fail.MonadFail inst_m)}
: forall {a}, GHC.Base.String -> (StateT inst_s inst_m) a :=
fun {a} => fun str => Mk_StateT (fun arg_0__ => Control.Monad.Fail.fail str).
Program Instance MonadFail__StateT {m} {s} `{(Control.Monad.Fail.MonadFail m)}
: Control.Monad.Fail.MonadFail (StateT s m) :=
fun _ k__ =>
k__ {| Control.Monad.Fail.fail__ := fun {a} => MonadFail__StateT_fail |}.
(* Skipping all instances of class `GHC.Base.Alternative', including
`Control.Monad.Trans.State.Lazy.Alternative__StateT' *)
(* External variables:
op_zt__ pair tt unit Control.Monad.Fail.MonadFail Control.Monad.Fail.fail
Control.Monad.Fail.fail__ Control.Monad.Signatures.CallCC
Control.Monad.Signatures.Listen Control.Monad.Signatures.Pass
Control.Monad.Trans.Class.MonadTrans Control.Monad.Trans.Class.lift__
Data.Functor.Identity.Identity Data.Functor.Identity.Mk_Identity
Data.Functor.Identity.runIdentity Data.Tuple.fst Data.Tuple.snd
GHC.Base.Applicative GHC.Base.Functor GHC.Base.Monad GHC.Base.String
GHC.Base.const GHC.Base.fmap GHC.Base.fmap__ GHC.Base.liftA2__
GHC.Base.op_z2218U__ GHC.Base.op_zgzg____ GHC.Base.op_zgzgze__
GHC.Base.op_zgzgze____ GHC.Base.op_zlzd____ GHC.Base.op_zlztzg____
GHC.Base.op_ztzg____ GHC.Base.pure GHC.Base.pure__ GHC.Base.return_
GHC.Base.return___
*)
|
subroutine GLQGridCoord(latglq, longlq, lmax, nlat, nlong)
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
! Given a maximum spherical harmonic degree lmax, this routine
! will determine the latitude and longitude coordinates associated with
! grids that are used in the Gauss-Legendre quadratue spherical harmonic
! expansion routines. The coordinates are output in DEGREES.
!
! Calling Parameters
! IN
! lmax Maximum spherical harmonic degree of the expansion.
! OUT
! latglq Array of latitude points used in Gauss-Legendre grids, in degrees.
! longlq Array of longitude points used in Gauss-Legendre grids, in degrees.
! nlat, nlong Number of latidude and longitude points.
!
! Dependencies: NGLQSH, PreGLQ
!
! Written by Mark Wieczorek, 2004
! Completely rewritten June 6, 2006.
!
! Copyright (c) 2005-2006 Mark A. Wieczorek
! All rights reserved.
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
use SHTOOLS, only: NGLQSH, PreGLQ
implicit none
integer, intent(in) :: lmax
integer, intent(out) :: nlat, nlong
real*8, intent(out) :: latglq(:), longlq(:)
real*8 :: pi, upper, lower, zero(lmax+1), w(lmax+1)
integer :: i
if (size(latglq) < lmax+1) then
print*, "Error --- GLQGridCoord"
print*, "LATGLQ must be dimensioned as (LMAX+1) where LMAX is ", lmax
print*, "Input array is dimensioned as ", size(latglq)
stop
elseif (size(longlq) < 2*lmax+1) then
print*, "Error --- GLQGridCoord"
print*, "LONGLQ must be dimensioned as (2*LMAX+1) where LMAX is ", lmax
print*, "Input array is dimensioned as ", size(longlq)
stop
endif
pi = acos(-1.0d0)
nlat = NGLQSH(lmax)
nlong = 2*lmax +1
upper = 1.0d0
lower = -1.0d0
call PreGLQ(lower, upper, nlat, zero, w) ! Determine Gauss Points and Weights.
do i=1, nlong
longlq(i) = 360.0d0*(i-1)/nlong
enddo
do i=1, nlat
latglq(i) = asin(zero(i))*180.0d0/pi
enddo
end subroutine GLQGridCoord
|
# Atmospheric Radiation
____________
<a id='section1'></a>
## 1. Emission temperature and lapse rates
____________
Planetary energy balance is the foundation for all climate modeling. So far we have expressed this through a globally averaged budget
$$C \frac{d T_s}{dt} = (1-\alpha) Q - OLR$$
and we have written the OLR in terms of an emission temperature $T_e$ where by definition
$$ OLR = \sigma T_e^4 $$
Using values from the observed planetary energy budget, we found that $T_e = 255$ K
The emission temperature of the planet is thus about 33 K colder than the mean surface temperature (288 K).
### Where in the atmosphere do we find $T = T_e = 255$ K?
That's about -18ºC.
Let's plot **global, annual average observed air temperature** from NCEP reanalysis data.
```python
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import xarray as xr
```
```python
ncep_url = 'https://psl.noaa.gov/thredds/dodsC/Datasets/ncep.reanalysis.derived/'
ncep_air = xr.open_dataset( ncep_url + "pressure/air.mon.1981-2010.ltm.nc", use_cftime=True)
print( ncep_air)
```
<xarray.Dataset>
Dimensions: (lat: 73, level: 17, lon: 144, nbnds: 2, time: 12)
Coordinates:
* level (level) float32 1000.0 925.0 850.0 ... 30.0 20.0 10.0
* lon (lon) float32 0.0 2.5 5.0 7.5 ... 352.5 355.0 357.5
* time (time) object 0001-01-01 00:00:00 ... 0001-12-01 00:00:00
* lat (lat) float32 90.0 87.5 85.0 82.5 ... -85.0 -87.5 -90.0
Dimensions without coordinates: nbnds
Data variables:
climatology_bounds (time, nbnds) object ...
air (time, level, lat, lon) float32 ...
valid_yr_count (time, level, lat, lon) float32 ...
Attributes:
description: Data from NCEP initialized reanalysis (4...
platform: Model
Conventions: COARDS
not_missing_threshold_percent: minimum 3% values input to have non-missi...
history: Created 2011/07/12 by doMonthLTM\nConvert...
title: monthly ltm air from the NCEP Reanalysis
dataset_title: NCEP-NCAR Reanalysis 1
References: http://www.psl.noaa.gov/data/gridded/data...
```python
# Take global, annual average
coslat = np.cos(np.deg2rad(ncep_air.lat))
weight = coslat / coslat.mean(dim='lat')
Tglobal = (ncep_air.air * weight).mean(dim=('lat','lon','time'))
print(Tglobal)
```
<xarray.DataArray (level: 17)>
array([ 15.179084 , 11.207003 , 7.8383274 , 0.21994135,
-6.4483433 , -14.888848 , -25.570469 , -39.36969 ,
-46.797905 , -53.652245 , -60.56356 , -67.006065 ,
-65.53293 , -61.48664 , -55.853584 , -51.593952 ,
-43.21999 ], dtype=float32)
Coordinates:
* level (level) float32 1000.0 925.0 850.0 700.0 ... 50.0 30.0 20.0 10.0
```python
# a "quick and dirty" visualization of the data
Tglobal.plot()
```
Let's make a better plot.
Here we're going to use a package called `metpy` to automate plotting this temperature profile in a way that's more familiar to meteorologists: a so-called skew-T plot. The National Weather Service has a nice breakdown of the [skew-T log-P diagram](https://www.weather.gov/jetstream/skewt).
```python
from metpy.plots import SkewT
```
Cannot import USCOUNTIES and USSTATES without Cartopy installed.
```python
fig = plt.figure(figsize=(9, 9))
skew = SkewT(fig, rotation=30)
skew.plot(Tglobal.level, Tglobal, color='black', linestyle='-', linewidth=2, label='Observations')
skew.ax.set_ylim(1050, 10)
skew.ax.set_xlim(-75, 45)
# Add the relevant special lines
skew.plot_dry_adiabats(linewidth=0.5)
skew.plot_moist_adiabats(linewidth=0.5)
#skew.plot_mixing_lines()
skew.ax.legend()
skew.ax.set_title('Global, annual mean sounding from NCEP Reanalysis',
fontsize = 16)
```
Note that surface temperature in global mean is indeed about 288 K or 15ºC as we keep saying.
So where do we find temperature $T_e=255$ K or -18ºC?
Actually in mid-troposphere, near 500 hPa or about 5 km height.
We can infer that much of the outgoing longwave radiation actually originates far above the surface.
Recall that our observed global energy budget diagram shows 217 out of 239 W m$^{-2}$ total OLR emitted by the atmosphere and clouds, only 22 W m$^{-2}$ directly from the surface.
This is due to the **greenhouse effect**.
So far we have dealt with the greenhouse in a very artificial way in our energy balance model by simply assuming
$$ \text{OLR} = \tau \sigma T_s^4 $$
i.e., the OLR is reduced by a constant factor from the value it would have if the Earth emitted as a blackbody at the surface temperature.
Now it's time to start thinking a bit more about how the radiative transfer process actually occurs in the atmosphere, and how to model it.
____________
<a id='section2'></a>
## 2. Solar Radiation
____________
Let's plot a spectrum of solar radiation.
For Python details, see the code in the notebook.
```python
# Using pre-defined code for the Planck function from the climlab package
from climlab.utils.thermo import Planck_wavelength
```
```python
# approximate emission temperature of the sun in Kelvin
Tsun = 5780.
# boundaries of visible region in nanometers
UVbound = 390.
IRbound = 700.
# array of wavelengths
wavelength_nm = np.linspace(10., 3500., 400)
to_meters = 1E-9 # conversion factor
```
```python
label_size = 16
fig, ax = plt.subplots(figsize=(14,7))
ax.plot(wavelength_nm,
Planck_wavelength(wavelength_nm * to_meters, Tsun))
ax.grid()
ax.set_xlabel('Wavelength (nm)', fontsize=label_size)
ax.set_ylabel('Spectral radiance (W sr$^{-1}$ m$^{-3}$)', fontsize=label_size)
# Mask out points outside of this range
wavelength_vis = np.ma.masked_outside(wavelength_nm, UVbound, IRbound)
# Shade the visible region
ax.fill_between(wavelength_vis, Planck_wavelength(wavelength_vis * to_meters, Tsun))
title = 'Blackbody emission curve for the sun (T = {:.0f} K)'.format(Tsun)
ax.set_title(title, fontsize=label_size);
ax.text(280, 0.8E13, 'Ultraviolet', rotation='vertical', fontsize=12)
ax.text(500, 0.8E13, 'Visible', rotation='vertical', fontsize=16, color='w')
ax.text(800, 0.8E13, 'Infrared', rotation='vertical', fontsize=12);
```
- Spectrum peaks in the visible range
- Most energy at these wavelengths
- No coincidence that our eyes are sensitive to this range of wavelengths!
- Infrared radiation has a long wavelength and ultraviolet radiation has a short wavelength
The shape of the spectrum is a fundamental characteristic of radiative emissions.
Theory and experiments tell us that both the total flux of emitted radiation, and the wavelength of maximum emission, depend only on the temperature of the source!
The theoretical spectrum was worked out by Max Planck and is therefore known as the “Planck” spectrum (or simply blackbody spectrum).
```python
fig, ax = plt.subplots(figsize=(14,7))
wavelength_um = wavelength_nm / 1000
for T in [24000,12000,6000,3000]:
ax.plot(wavelength_um,
(Planck_wavelength(wavelength_nm * to_meters, T) / T**4),
label=str(T) + ' K')
ax.legend(fontsize=label_size)
ax.set_xlabel('Wavelength (um)', fontsize=label_size)
ax.set_ylabel('Normalized spectral radiance (W sr$^{-1}$ m$^{-2}$ K$^{-4}$)', fontsize=label_size)
ax.set_title("Normalized blackbody emission spectra $T^{-4} B_{\lambda}$ for different temperatures");
```
Going from cool to warm:
- total emission increases
- maximum emission occurs at shorter wavelengths.
The **integral of these curves over all wavelengths** gives us our familiar $\sigma T^4$
Mathematically it turns out that
$$ λ_{max} T = \text{constant} $$
(known as Wien’s displacement law).
By fitting the observed solar emission to a blackbody curve, we can deduce that the emission temperature of the sun is about 6000 K.
Knowing this, and knowing that the solar spectrum peaks at 0.6 micrometers, we can calculate the wavelength of maximum terrestrial radiation as
\begin{align}
\lambda_{max,Earth}T_{Earth} &= \lambda_{max,sun}T_{sun} \\
\lambda_{max,Earth} &= 0.6 ~ \mu m \frac{6000}{255} \\
&= 14 ~ \mu m
\end{align}
This is in the far-infrared part of the spectrum.
____________
<a id='section3'></a>
## 3. Terrestrial Radiation and absorption spectra
____________
Now let's look at normalized blackbody curves for Sun and Earth:
```python
fig, ax = plt.subplots(figsize=(14,7))
wavelength_um = np.linspace(0.1, 200, 10000)
wavelength_meters = wavelength_um / 1E6
for T in [6000, 255]:
ax.semilogx(wavelength_um,
(Planck_wavelength(wavelength_meters, T) / T**4 * wavelength_meters),
label=str(T) + ' K')
ax.legend(fontsize=label_size)
ax.set_xlabel('Wavelength (um)', fontsize=label_size)
ax.set_ylabel('Normalized spectral radiance (W sr$^{-1}$ m$^{-2}$ K$^{-4}$)', fontsize=label_size)
ax.set_title("Normalized blackbody emission spectra $T^{-4} \lambda B_{\lambda}$ for the sun ($T_e = 6000$ K) and Earth ($T_e = 255$ K)",
fontsize=label_size);
```
There is essentially no overlap between the two spectra.
**This is the fundamental reason we can discuss the solar “shortwave” and terrestrial “longwave” radiation as two distinct phenomena.**
In reality all radiation exists on a continuum of different wavelengths. But in climate science we can get a long way by thinking in terms of a very simple “two-stream” approximation (short and longwave). We’ve already been doing this throughout the course so far!
### Atmospheric absorption spectra
Now look at the atmospheric **absorption spectra**.
(fraction of radiation at each wavelength that is absorbed on a single vertical path through the atmosphere)
*Figure reproduced from Marshall and Plumb (2008): Atmosphere, Ocean, and Climate Dynamics*
- Atmosphere is almost completely transparent in the visible range, right at the peak of the solar spectrum
- Atmosphere is very opaque in the UV
- Opacity across the IR spectrum is highly variable!
- Look at the gases associated with various absorption features:
- Main players include H$_2$O, CO$_2$, N$_2$O, O$_2$.
- Compare to major constituents of atmosphere, in decreasing order:
- 78% N$_2$
- 21% O$_2$
- 1% Ar
- H$_2$O (variable)
- The dominant constituent gases N$_2$ and O$_2$ are nearly completely transparent across the entire spectrum (there are O$_2$ absorption features in far UV, but little energy at these wavelengths).
- The greenhouse effect mostly involves trace constituents:
- O$_3$ = 500 ppb
- N$_2$O = 310 ppb
- CO$_2$ = 400 ppm (but rapidly increasing!)
- CH$_4$ = 1.7 ppm
- Note that most of these are tri-atomic molecules! There are fundamental reasons for this: these molecules have modes of rotational and vibration that are easily excited at IR wavelengths. See courses in atmospheric science and radiative transfer!
____________
## Credits
This notebook is part of [The Climate Laboratory](https://brian-rose.github.io/ClimateLaboratoryBook), an open-source textbook developed and maintained by [Brian E. J. Rose](http://www.atmos.albany.edu/facstaff/brose/index.html), University at Albany. It has been modified by [Nicole Feldl](http://nicolefeldl.com), UC Santa Cruz.
It is licensed for free and open consumption under the
[Creative Commons Attribution 4.0 International (CC BY 4.0)](https://creativecommons.org/licenses/by/4.0/) license.
Development of these notes and the [climlab software](https://github.com/brian-rose/climlab) is partially supported by the National Science Foundation under award AGS-1455071 to Brian Rose. Any opinions, findings, conclusions or recommendations expressed here are mine and do not necessarily reflect the views of the National Science Foundation.
____________
|
lemma not_bounded_UNIV[simp]: "\<not> bounded (UNIV :: 'a::{real_normed_vector, perfect_space} set)" |
Require Import CertiGraph.graph.SpaceAdjMatGraph3.
Require Import CertiGraph.dijkstra.dijkstra_env.
(* A separate file with the underlying PQ spec-ed out *)
Require Export CertiGraph.binheap.binary_heap_malloc_spec.
Require Export CertiGraph.binheap.spec_binary_heap_pro.
(* Dijkstra-specific imports *)
Require Import CertiGraph.dijkstra.MathDijkGraph.
Require Export CertiGraph.dijkstra.dijkstra_spec_pure.
(* The first moment we become implementation-specific *)
Require Export CertiGraph.dijkstra.dijkstra3.
Require Import CertiGraph.dijkstra.dijkstra_constants.
Local Open Scope Z_scope.
Section DijkstraSpec.
Context {Z_EqDec : EquivDec.EqDec Z eq}.
Instance CompSpecs : compspecs. Proof. make_compspecs prog. Defined.
Definition Vprog : varspecs. mk_varspecs prog. Defined.
Global Existing Instance CompSpecs.
Definition getCell_spec :=
DECLARE _getCell
WITH sh: rshare,
g: @DijkGG size inf,
graph_ptr: pointer_val,
addresses: list val,
u: V,
i : V
PRE [tptr (tarray tint size), tint, tint]
PROP (0 <= i < size;
0 <= u < size)
PARAMS (pointer_val_val graph_ptr;
Vint (Int.repr u);
Vint (Int.repr i))
GLOBALS ()
SEP (@SpaceAdjMatGraph size CompSpecs sh id g (pointer_val_val graph_ptr))
POST [tint]
PROP ()
RETURN (Vint (Int.repr (Znth i (Znth u (@graph_to_mat size g id)))))
SEP (@SpaceAdjMatGraph size CompSpecs sh id g (pointer_val_val graph_ptr)).
Definition dijkstra_spec :=
DECLARE _dijkstra
WITH sh: rshare,
g: DijkGG,
graph_ptr : pointer_val,
addresses : list val,
dist_ptr : pointer_val,
prev_ptr : pointer_val,
src : V
PRE [tptr (tarray tint size), tint, tptr tint, tptr tint]
PROP (vvalid g src;
12 * size <= Int.max_unsigned;
connected_dir g src)
PARAMS (pointer_val_val graph_ptr;
Vint (Int.repr src);
pointer_val_val dist_ptr;
pointer_val_val prev_ptr)
GLOBALS ()
SEP (@SpaceAdjMatGraph size CompSpecs sh id g (pointer_val_val graph_ptr);
data_at_ Tsh (tarray tint size) (pointer_val_val dist_ptr);
data_at_ Tsh (tarray tint size) (pointer_val_val prev_ptr))
POST [tvoid]
EX prev: list V,
EX dist: list V,
PROP (forall dst,
vvalid g dst ->
@inv_popped size inf g src (VList g) prev dist dst)
LOCAL ()
SEP (@SpaceAdjMatGraph size CompSpecs sh id g (pointer_val_val graph_ptr);
data_at Tsh (tarray tint size) (map Vint (map Int.repr prev)) (pointer_val_val prev_ptr);
data_at Tsh (tarray tint size) (map Vint (map Int.repr dist)) (pointer_val_val dist_ptr)).
Definition Gprog : funspecs :=
ltac:(with_library prog [
getCell_spec;
dijkstra_spec;
mallocN_spec;
freeN_spec;
pq_remove_min_nc_spec;
pq_insert_nc_spec;
pq_size_spec;
pq_make_spec;
pq_edit_priority_spec;
pq_free_spec]).
End DijkstraSpec.
|
Paul Thomas Anderson ( born June 26 , 1970 ) also known as P.T. Anderson , is an American film director , screenwriter and producer . Interested in film @-@ making at a young age , Anderson was encouraged by his father Ernie Anderson ( a disc jockey , and television and radio announcer / voiceover artist ) to become a filmmaker .
|
[STATEMENT]
lemma numbering_translation:
assumes "recfn 2 psi"
obtains c where
"recfn 1 c"
"total c"
"\<forall>i x. eval psi [i, x] = eval r_phi [the (eval c [i]), x]"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>c. \<lbrakk>recfn 1 c; Partial_Recursive.total c; \<forall>i x. eval psi [i, x] = eval r_phi [the (eval c [i]), x]\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. (\<And>c. \<lbrakk>recfn 1 c; Partial_Recursive.total c; \<forall>i x. eval psi [i, x] = eval r_phi [the (eval c [i]), x]\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
let ?p = "encode psi"
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. (\<And>c. \<lbrakk>recfn 1 c; Partial_Recursive.total c; \<forall>i x. eval psi [i, x] = eval r_phi [the (eval c [i]), x]\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
define c where "c = Cn 1 (r_smn 1 1) [r_const ?p, Id 1 0]"
[PROOF STATE]
proof (state)
this:
c = Cn 1 (r_smn 1 1) [r_const (encode psi), recf.Id 1 0]
goal (1 subgoal):
1. (\<And>c. \<lbrakk>recfn 1 c; Partial_Recursive.total c; \<forall>i x. eval psi [i, x] = eval r_phi [the (eval c [i]), x]\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
c = Cn 1 (r_smn 1 1) [r_const (encode psi), recf.Id 1 0]
[PROOF STEP]
have "prim_recfn 1 c"
[PROOF STATE]
proof (prove)
using this:
c = Cn 1 (r_smn 1 1) [r_const (encode psi), recf.Id 1 0]
goal (1 subgoal):
1. prim_recfn 1 c
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
prim_recfn 1 c
goal (1 subgoal):
1. (\<And>c. \<lbrakk>recfn 1 c; Partial_Recursive.total c; \<forall>i x. eval psi [i, x] = eval r_phi [the (eval c [i]), x]\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
prim_recfn 1 c
goal (1 subgoal):
1. (\<And>c. \<lbrakk>recfn 1 c; Partial_Recursive.total c; \<forall>i x. eval psi [i, x] = eval r_phi [the (eval c [i]), x]\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
from this
[PROOF STATE]
proof (chain)
picking this:
prim_recfn 1 c
[PROOF STEP]
have "total c"
[PROOF STATE]
proof (prove)
using this:
prim_recfn 1 c
goal (1 subgoal):
1. Partial_Recursive.total c
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
Partial_Recursive.total c
goal (1 subgoal):
1. (\<And>c. \<lbrakk>recfn 1 c; Partial_Recursive.total c; \<forall>i x. eval psi [i, x] = eval r_phi [the (eval c [i]), x]\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
Partial_Recursive.total c
goal (1 subgoal):
1. (\<And>c. \<lbrakk>recfn 1 c; Partial_Recursive.total c; \<forall>i x. eval psi [i, x] = eval r_phi [the (eval c [i]), x]\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
have "eval r_phi [the (eval c [i]), x] = eval psi [i, x]" for i x
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. eval r_phi [the (eval c [i]), x] = eval psi [i, x]
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. eval r_phi [the (eval c [i]), x] = eval psi [i, x]
[PROOF STEP]
have "eval c [i] = eval (r_smn 1 1) [?p, i]"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. eval c [i] = eval (r_smn 1 1) [encode psi, i]
[PROOF STEP]
using c_def
[PROOF STATE]
proof (prove)
using this:
c = Cn 1 (r_smn 1 1) [r_const (encode psi), recf.Id 1 0]
goal (1 subgoal):
1. eval c [i] = eval (r_smn 1 1) [encode psi, i]
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
eval c [i] = eval (r_smn 1 1) [encode psi, i]
goal (1 subgoal):
1. eval r_phi [the (eval c [i]), x] = eval psi [i, x]
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
eval c [i] = eval (r_smn 1 1) [encode psi, i]
[PROOF STEP]
have "eval (r_universal 1) [the (eval c [i]), x] =
eval (r_universal 1) [the (eval (r_smn 1 1) [?p, i]), x]"
[PROOF STATE]
proof (prove)
using this:
eval c [i] = eval (r_smn 1 1) [encode psi, i]
goal (1 subgoal):
1. eval (r_universal 1) [the (eval c [i]), x] = eval (r_universal 1) [the (eval (r_smn 1 1) [encode psi, i]), x]
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
eval (r_universal 1) [the (eval c [i]), x] = eval (r_universal 1) [the (eval (r_smn 1 1) [encode psi, i]), x]
goal (1 subgoal):
1. eval r_phi [the (eval c [i]), x] = eval psi [i, x]
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
eval (r_universal 1) [the (eval c [i]), x] = eval (r_universal 1) [the (eval (r_smn 1 1) [encode psi, i]), x]
goal (1 subgoal):
1. eval r_phi [the (eval c [i]), x] = eval psi [i, x]
[PROOF STEP]
have "... = eval (r_universal (1 + 1)) (?p # [i] @ [x])"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. eval (r_universal 1) [the (eval (r_smn 1 1) [encode psi, i]), x] = eval (r_universal (1 + 1)) (encode psi # [i] @ [x])
[PROOF STEP]
using smn_lemma[of 1 "[i]" 1 "[x]" ?p]
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>0 < 1; length [i] = 1; length [x] = 1\<rbrakk> \<Longrightarrow> eval (r_universal (1 + 1)) (encode psi # [i] @ [x]) = eval (r_universal 1) [the (eval (r_smn 1 1) [encode psi, i]), x]
goal (1 subgoal):
1. eval (r_universal 1) [the (eval (r_smn 1 1) [encode psi, i]), x] = eval (r_universal (1 + 1)) (encode psi # [i] @ [x])
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
eval (r_universal 1) [the (eval (r_smn 1 1) [encode psi, i]), x] = eval (r_universal (1 + 1)) (encode psi # [i] @ [x])
goal (1 subgoal):
1. eval r_phi [the (eval c [i]), x] = eval psi [i, x]
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
eval (r_universal 1) [the (eval (r_smn 1 1) [encode psi, i]), x] = eval (r_universal (1 + 1)) (encode psi # [i] @ [x])
goal (1 subgoal):
1. eval r_phi [the (eval c [i]), x] = eval psi [i, x]
[PROOF STEP]
have "... = eval (r_universal 2) [?p, i, x]"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. eval (r_universal (1 + 1)) (encode psi # [i] @ [x]) = eval (r_universal 2) [encode psi, i, x]
[PROOF STEP]
by (metis append_eq_Cons_conv nat_1_add_1)
[PROOF STATE]
proof (state)
this:
eval (r_universal (1 + 1)) (encode psi # [i] @ [x]) = eval (r_universal 2) [encode psi, i, x]
goal (1 subgoal):
1. eval r_phi [the (eval c [i]), x] = eval psi [i, x]
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
eval (r_universal (1 + 1)) (encode psi # [i] @ [x]) = eval (r_universal 2) [encode psi, i, x]
goal (1 subgoal):
1. eval r_phi [the (eval c [i]), x] = eval psi [i, x]
[PROOF STEP]
have "... = eval psi [i, x]"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. eval (r_universal 2) [encode psi, i, x] = eval psi [i, x]
[PROOF STEP]
using r_universal[OF assms, of "[i, x]"]
[PROOF STATE]
proof (prove)
using this:
length [i, x] = 2 \<Longrightarrow> eval (r_universal 2) [encode psi, i, x] = eval psi [i, x]
goal (1 subgoal):
1. eval (r_universal 2) [encode psi, i, x] = eval psi [i, x]
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
eval (r_universal 2) [encode psi, i, x] = eval psi [i, x]
goal (1 subgoal):
1. eval r_phi [the (eval c [i]), x] = eval psi [i, x]
[PROOF STEP]
finally
[PROOF STATE]
proof (chain)
picking this:
eval (r_universal 1) [the (eval c [i]), x] = eval psi [i, x]
[PROOF STEP]
have "eval (r_universal 1) [the (eval c [i]), x] = eval psi [i, x]"
[PROOF STATE]
proof (prove)
using this:
eval (r_universal 1) [the (eval c [i]), x] = eval psi [i, x]
goal (1 subgoal):
1. eval (r_universal 1) [the (eval c [i]), x] = eval psi [i, x]
[PROOF STEP]
.
[PROOF STATE]
proof (state)
this:
eval (r_universal 1) [the (eval c [i]), x] = eval psi [i, x]
goal (1 subgoal):
1. eval r_phi [the (eval c [i]), x] = eval psi [i, x]
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
eval (r_universal 1) [the (eval c [i]), x] = eval psi [i, x]
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
eval (r_universal 1) [the (eval c [i]), x] = eval psi [i, x]
goal (1 subgoal):
1. eval r_phi [the (eval c [i]), x] = eval psi [i, x]
[PROOF STEP]
using r_phi_def
[PROOF STATE]
proof (prove)
using this:
eval (r_universal 1) [the (eval c [i]), x] = eval psi [i, x]
r_phi \<equiv> r_universal 1
goal (1 subgoal):
1. eval r_phi [the (eval c [i]), x] = eval psi [i, x]
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
eval r_phi [the (eval c [i]), x] = eval psi [i, x]
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
eval r_phi [the (eval c [?i]), ?x] = eval psi [?i, ?x]
goal (1 subgoal):
1. (\<And>c. \<lbrakk>recfn 1 c; Partial_Recursive.total c; \<forall>i x. eval psi [i, x] = eval r_phi [the (eval c [i]), x]\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
prim_recfn 1 c
Partial_Recursive.total c
eval r_phi [the (eval c [?i]), ?x] = eval psi [?i, ?x]
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
prim_recfn 1 c
Partial_Recursive.total c
eval r_phi [the (eval c [?i]), ?x] = eval psi [?i, ?x]
goal (1 subgoal):
1. thesis
[PROOF STEP]
using that
[PROOF STATE]
proof (prove)
using this:
prim_recfn 1 c
Partial_Recursive.total c
eval r_phi [the (eval c [?i]), ?x] = eval psi [?i, ?x]
\<lbrakk>recfn 1 ?c; Partial_Recursive.total ?c; \<forall>i x. eval psi [i, x] = eval r_phi [the (eval ?c [i]), x]\<rbrakk> \<Longrightarrow> thesis
goal (1 subgoal):
1. thesis
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
thesis
goal:
No subgoals!
[PROOF STEP]
qed |
If we append $n$ zeros to the end of a polynomial, the polynomial does not change. |
import Revise
import GLRenderer
import PoseComposition
import Rotations
import FileIO
R = Rotations
P = PoseComposition
GL = GLRenderer
obj_path = joinpath(@__DIR__, "035_power_drill/textured_simple.obj")
texture_path = joinpath(@__DIR__, "035_power_drill/texture_map.png")
camera_intrinsics = GL.CameraIntrinsics(
640, 480,
1000.0, 1000.0,
320.0, 240.0,
0.01, 5.0
)
camera_intrinsics = GL.scale_down_camera(camera_intrinsics, 4)
renderer = GL.setup_renderer(camera_intrinsics, GL.DepthMode())
mesh_data = GL.get_mesh_data_from_obj_file(obj_path)
GL.load_object!(renderer, mesh_data)
depth_image = GL.gl_render(renderer, [1], [P.Pose([0.0, 0.0, 1.0], R.RotXYZ(0.1, 0.4, 0.9))], P.IDENTITY_POSE)
times = [
let
r = rand() * 2*π
t = @elapsed GL.gl_render(renderer, [1], [P.Pose([0.0, 0.0, 1.0], R.RotXYZ(0.1, 0.4, r))], P.IDENTITY_POSE)
t
end
for _ in 1:1000
]
avg_time = sum(times)/length(times)
@show avg_time
FileIO.save("imgs/speed_test_img.png", GL.view_depth_image(depth_image))
|
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2014 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
//#include "KernelExecutor.h"
//#include <wx/wfstream.h>
//#include <wx/txtstrm.h>
//#include <boost/chrono.hpp>
//
//using namespace boost::chrono;
//
//KernelExecutor::KernelExecutor()
// : m_vd(0),
// m_vd_r(0),
// m_duplicate(true)
//{
//}
//
//KernelExecutor::~KernelExecutor()
//{
//}
//
//void KernelExecutor::SetCode(wxString &code)
//{
// m_code = code;
//}
//
//void KernelExecutor::LoadCode(wxString &filename)
//{
// if (!wxFileExists(filename))
// {
// m_message = "Kernel file " +
// filename + " doesn't exist.\n";
// return;
// }
// wxFileInputStream input(filename);
// wxTextInputStream cl_file(input);
// if (!input.IsOk())
// {
// m_message = "Kernel file " +
// filename + " reading failed.\n";
// return;
// }
// m_code = "";
// while (!input.Eof())
// {
// m_code += cl_file.ReadLine();
// m_code += "\n";
// }
// m_message = "Kernel file " +
// filename + " read.\n";
//}
//
//void KernelExecutor::SetVolume(VolumeData *vd)
//{
// m_vd = vd;
//}
//
//void KernelExecutor::SetDuplicate(bool dup)
//{
// m_duplicate = dup;
//}
//
//VolumeData* KernelExecutor::GetVolume()
//{
// return m_vd;
//}
//
//VolumeData* KernelExecutor::GetResult()
//{
// return m_vd_r;
//}
//
//void KernelExecutor::DeleteResult()
//{
// if (m_vd_r)
// delete m_vd_r;
// m_vd_r = 0;
//}
//
//bool KernelExecutor::GetMessage(wxString &msg)
//{
// if (m_message == "")
// return false;
// else
// {
// msg = m_message;
// return true;
// }
//}
//
//bool KernelExecutor::Execute()
//{
//// if (m_code == "")
//// {
//// m_message = "No OpenCL code to execute.\n";
//// return false;
//// }
////
////#ifdef _DARWIN
//// CGLContextObj ctx = CGLGetCurrentContext();
//// if (ctx != KernelProgram::gl_context_)
//// CGLSetCurrentContext(KernelProgram::gl_context_);
////#endif
////
//// //get volume currently selected
//// if (!m_vd)
//// {
//// m_message = "No volume selected. Select a volume first.\n";
//// return false;
//// }
//// VolumeRenderer* vr = m_vd->GetVR();
//// if (!vr)
//// {
//// m_message = "Volume corrupted.\n";
//// return false;
//// }
//// Texture* tex =m_vd->GetTexture();
//// if (!tex)
//// {
//// m_message = "Volume corrupted.\n";
//// return false;
//// }
////
//// int res_x, res_y, res_z;
//// m_vd->GetResolution(res_x, res_y, res_z);
////
//// //get bricks
//// Ray view_ray(Point(0.802, 0.267, 0.534), Vector(0.802, 0.267, 0.534));
//// tex->set_sort_bricks();
//// vector<TextureBrick*> *bricks = tex->get_sorted_bricks(view_ray);
//// if (!bricks || bricks->size() == 0)
//// {
//// m_message = "Volume empty.\n";
//// return false;
//// }
////
//// m_message = "";
//// //execute for each brick
//// TextureBrick *b, *b_r;
//// vector<TextureBrick*> *bricks_r;
//// void *result;
////
//// if (m_duplicate)
//// {
//// //result
//// double spc_x, spc_y, spc_z;
//// m_vd->GetSpacings(spc_x, spc_y, spc_z);
//// m_vd_r = new VolumeData();
//// m_vd_r->AddEmptyData(8,
//// res_x, res_y, res_z,
//// spc_x, spc_y, spc_z);
//// m_vd_r->SetSpcFromFile(true);
//// wxString name = m_vd->GetName();
//// m_vd_r->SetName(name + "_CL");
//// Texture* tex_r = m_vd_r->GetTexture();
//// if (!tex_r)
//// return false;
//// Nrrd* nrrd_r = tex_r->get_nrrd(0);
//// if (!nrrd_r)
//// return false;
//// result = nrrd_r->data;
//// if (!result)
//// return false;
////
//// tex_r->set_sort_bricks();
//// bricks_r = tex_r->get_sorted_bricks(view_ray);
//// if (!bricks_r || bricks_r->size() == 0)
//// return false;
////
//// if (m_vd)
//// {
//// //clipping planes
//// vector<Plane*> *planes = m_vd->GetVR() ? m_vd->GetVR()->get_planes() : 0;
//// if (planes && m_vd_r->GetVR())
//// m_vd_r->GetVR()->set_planes(planes);
//// //transfer function
//// m_vd_r->Set3DGamma(m_vd->Get3DGamma());
//// m_vd_r->SetBoundary(m_vd->GetBoundary());
//// m_vd_r->SetOffset(m_vd->GetOffset());
//// m_vd_r->SetLeftThresh(m_vd->GetLeftThresh());
//// m_vd_r->SetRightThresh(m_vd->GetRightThresh());
//// FLIVR::Color col = m_vd->GetColor();
//// m_vd_r->SetColor(col);
//// m_vd_r->SetAlpha(m_vd->GetAlpha());
//// //shading
//// m_vd_r->SetShading(m_vd->GetShading());
//// double amb, diff, spec, shine;
//// m_vd->GetMaterial(amb, diff, spec, shine);
//// m_vd_r->SetMaterial(amb, diff, spec, shine);
//// //shadow
//// m_vd_r->SetShadow(m_vd->GetShadow());
//// double shadow;
//// m_vd->GetShadowParams(shadow);
//// m_vd_r->SetShadowParams(shadow);
//// //sample rate
//// m_vd_r->SetSampleRate(m_vd->GetSampleRate());
//// //2d adjusts
//// col = m_vd->GetGamma();
//// m_vd_r->SetGamma(col);
//// col = m_vd->GetBrightness();
//// m_vd_r->SetBrightness(col);
//// col = m_vd->GetHdr();
//// m_vd_r->SetHdr(col);
//// m_vd_r->SetSyncR(m_vd->GetSyncR());
//// m_vd_r->SetSyncG(m_vd->GetSyncG());
//// m_vd_r->SetSyncB(m_vd->GetSyncB());
//// }
//// }
//// else
//// result = tex->get_nrrd(0)->data;
////
//// bool kernel_exe = true;
//// for (unsigned int i = 0; i<bricks->size(); ++i)
//// {
//// b = (*bricks)[i];
//// if (m_duplicate) b_r = (*bricks_r)[i];
//// GLint data_id = vr->load_brick(0, 0, bricks, i);
//// KernelProgram* kernel = VolumeRenderer::vol_kernel_factory_.kernel(m_code.ToStdString());
//// if (kernel)
//// {
//// m_message += "OpenCL kernel created.\n";
//// if (bricks->size() == 1)
//// kernel_exe = ExecuteKernel(kernel, data_id, result, res_x, res_y, res_z);
//// else
//// {
//// int brick_x = b->nx();
//// int brick_y = b->ny();
//// int brick_z = b->nz();
//// unsigned char* bresult = new unsigned char[brick_x*brick_y*brick_z];
//// kernel_exe = ExecuteKernel(kernel, data_id, bresult, brick_x, brick_y, brick_z);
//// if (!kernel_exe)
//// break;
//// //copy data back
//// unsigned char* ptr_br = bresult;
//// unsigned char* ptr_z;
//// if (m_duplicate)
//// ptr_z = (unsigned char*)(b_r->tex_data(0));
//// else
//// ptr_z = (unsigned char*)(b->tex_data(0));
//// unsigned char* ptr_y;
//// for (int bk = 0; bk<brick_z; ++bk)
//// {
//// ptr_y = ptr_z;
//// for (int bj = 0; bj<brick_y; ++bj)
//// {
//// memcpy(ptr_y, ptr_br, brick_x);
//// ptr_y += res_x;
//// ptr_br += brick_x;
//// }
//// ptr_z += res_x*res_y;
//// }
//// delete[]bresult;
//// }
//// }
//// else
//// {
//// m_message += "Fail to create OpenCL kernel.\n";
//// kernel_exe = false;
//// break;
//// }
//// //this is a problem needs to be solved
//// VolumeRenderer::vol_kernel_factory_.clean();
//// }
////
//// if (!kernel_exe)
//// {
//// if (m_duplicate && m_vd_r)
//// delete m_vd_r;
//// m_vd_r = 0;
//// return false;
//// }
////
//// //update
//// if (!m_duplicate)
//// m_vd->GetVR()->clear_tex_pool();
////
// return true;
//}
//
//bool KernelExecutor::ExecuteKernel(KernelProgram* kernel,
// GLuint data_id, void* result,
// size_t brick_x, size_t brick_y,
// size_t brick_z)
//{
// if (!kernel)
// return false;
//
// if (!kernel->valid())
// {
// string name = "kernel_main";
// if (kernel->create(name))
// m_message += "Kernel program compiled successfully on " +
// kernel->get_device_name() + ".\n";
// else
// {
// m_message += "Kernel program failed to compile on " +
// kernel->get_device_name() + ".\n";
// m_message += kernel->getInfo() + "\n";
// return false;
// }
// }
// //textures
// kernel->setKernelArgTex3D(0, CL_MEM_READ_ONLY, data_id);
// size_t result_size = brick_x*brick_y*brick_z*sizeof(unsigned char);
// kernel->setKernelArgBuf(1, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, result_size, result);
// kernel->setKernelArgConst(2, sizeof(unsigned int), (void*)(&brick_x));
// kernel->setKernelArgConst(3, sizeof(unsigned int), (void*)(&brick_y));
// kernel->setKernelArgConst(4, sizeof(unsigned int), (void*)(&brick_z));
// //execute
// size_t global_size[3] = { brick_x, brick_y, brick_z };
// size_t local_size[3] = { 1, 1, 1 };
// high_resolution_clock::time_point t1 = high_resolution_clock::now();
// kernel->execute(3, global_size, local_size);
// high_resolution_clock::time_point t2 = high_resolution_clock::now();
// duration<double> time_span = duration_cast<duration<double>>(t2 - t1);
// wxString stime = wxString::Format("%.4f", time_span.count());
// m_message += "OpenCL time on " +
// kernel->get_device_name() +
// ": " + stime + " sec.\n";
// kernel->readBuffer(1, result);
//
// return true;
//}
|
import networkx as nx
from data_pipeline import read_and_process_data, convert_network_to_newick_format
from lineage_solver.lineage_solver import solve_lineage_instance
from lineage_solver.solution_evaluation_metrics import cci_score
string_sample_values = read_and_process_data("ivlt_data/IVLT-2B_ALL.alleleTable.txt", '7.0')
score = cci_score(string_sample_values.values())
print("CCI Score" + str(score))
network = solve_lineage_instance(string_sample_values.values(), method='greedy')
string_to_sample = dict((string, sample) for sample, string in string_sample_values.items())
network = nx.relabel_nodes(network,string_to_sample)
print(convert_network_to_newick_format(network))
|
MODULE m_slabdim
USE m_juDFT
CONTAINS
SUBROUTINE slab_dim(atoms,nsld)
!***********************************************************************
! This subroutine calculates the number of layers in the slab
!
! Yury Koroteev 2003-09-30
!***********************************************************************
! ABBREVIATIONS
!
! natd : in, the number of atoms in the film
! pos(3,natd) : in, the coordinates of atoms in the film
! ntypd,ntype : in, the number of mt-sphere types
! neq(ntypd) : in, the number of mt-spheres of the same type
!-----------------------------------------------------------------------
! nsld : out, the number of layers in the film
!-----------------------------------------------------------------------
! znz(nsl) : work, the z-ordinate of mt-spheres in
! the nsl-layer
!-----------------------------------------------------------------------
!
USE m_types_setup
IMPLICIT NONE
TYPE(t_atoms),INTENT(IN) :: atoms
! ..
! ..Scalar Argument
INTEGER, INTENT (OUT) :: nsld
! ..
! ..Array Arguments
! ..
! ..Local Scalars
INTEGER iz,i,j,na,nz
REAL zs
! ..
! ..Local Arrays
REAL znz(atoms%nat)
! ..
! ----------------------------------------------
REAL,PARAMETER:: epsz=1.e-3
! ----------------------------------------------
!
! ---> Calculate the number of the film layers (nsld)
!
znz(1) = atoms%pos(3,1)
nz = 1
na = 0
DO i=1,atoms%ntype
equivAtomsLoop: DO j=1,atoms%neq(i)
na = na + 1
zs = atoms%pos(3,na)
DO iz=1,nz
IF(ABS(zs-znz(iz)).LT.epsz) CYCLE equivAtomsLoop
END DO
nz = nz+1
znz(nz) = zs
END DO equivAtomsLoop
END DO
nsld = nz
IF(nsld>atoms%nat) CALL juDFT_error("nsld.GT.atoms%nat ",calledby="slab_dim")
!
END SUBROUTINE slab_dim
END MODULE m_slabdim
|
module Math.HiddenMarkovModel.Named (
T(..),
Discrete,
Gaussian,
fromModelAndNames,
toCSV,
fromCSV,
) where
import qualified Math.HiddenMarkovModel.Distribution as Distr
import qualified Math.HiddenMarkovModel.Private as HMM
import qualified Math.HiddenMarkovModel.CSV as HMMCSV
import Math.HiddenMarkovModel.Distribution (State(..))
import Math.HiddenMarkovModel.Utility (attachOnes)
import qualified Numeric.LinearAlgebra.Algorithms as Algo
import qualified Data.Packed.Vector as Vector
import qualified Text.CSV.Lazy.String as CSV
import Text.Printf (printf)
import qualified Control.Monad.Exception.Synchronous as ME
import qualified Control.Monad.Trans.State as MS
import Control.DeepSeq (NFData, rnf)
import Foreign.Storable (Storable)
import qualified Data.Map as Map
import qualified Data.List as List
import Data.Tuple.HT (swap)
import Data.Map (Map)
{- |
A Hidden Markov Model with names for each state.
Although 'nameFromStateMap' and 'stateFromNameMap' are exported
you must be careful to keep them consistent when you alter them.
-}
data T distr prob =
Cons {
model :: HMM.T distr prob,
nameFromStateMap :: Map State String,
stateFromNameMap :: Map String State
}
deriving (Show, Read)
type Discrete prob symbol = T (Distr.Discrete prob symbol) prob
type Gaussian a = T (Distr.Gaussian a) a
instance
(NFData distr, NFData prob, Storable prob) =>
NFData (T distr prob) where
rnf hmm = rnf (model hmm, nameFromStateMap hmm, stateFromNameMap hmm)
fromModelAndNames :: HMM.T distr prob -> [String] -> T distr prob
fromModelAndNames md names =
let m = Map.fromList $ zip [State 0 ..] names
in Cons {
model = md,
nameFromStateMap = m,
stateFromNameMap = inverseMap m
}
inverseMap :: Map State String -> Map String State
inverseMap =
Map.fromListWith (error "duplicate label") .
map swap . Map.toList
toCSV ::
(Distr.CSV distr, Algo.Field prob, Show prob) =>
T distr prob -> String
toCSV hmm =
CSV.ppCSVTable $ snd $ CSV.toCSVTable $ HMMCSV.padTable "" $
Map.elems (nameFromStateMap hmm) : HMM.toCells (model hmm)
fromCSV ::
(Distr.CSV distr, Algo.Field prob, Read prob) =>
String -> ME.Exceptional String (T distr prob)
fromCSV =
MS.evalStateT parseCSV . map HMMCSV.fixShortRow . CSV.parseCSV
parseCSV ::
(Distr.CSV distr, Algo.Field prob, Read prob) =>
HMMCSV.CSVParser (T distr prob)
parseCSV = do
names <- HMMCSV.parseStringList =<< HMMCSV.getRow
let duplicateNames =
Map.keys $ Map.filter (> (1::Int)) $
Map.fromListWith (+) $ attachOnes names
in HMMCSV.assert (null duplicateNames) $
"duplicate names: " ++ List.intercalate ", " duplicateNames
md <- HMM.parseCSV
let n = length names
m = Vector.dim (HMM.initial md)
in HMMCSV.assert (n == m) $
printf "got %d state names for %d state" n m
return $ fromModelAndNames md names
|
State Before: n : ℕ
⊢ choose n n = 1 State After: no goals Tactic: induction n <;> simp [*, choose, choose_eq_zero_of_lt (lt_succ_self _)] |
/* specfunc/elementary.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* 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; either version 2 of the License, or (at
* your option) any later version.
*
* 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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* Author: G. Jungman */
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include "gsl_sf_elementary.h"
#include "error.h"
#include "check.h"
int
gsl_sf_multiply_e(const double x, const double y, gsl_sf_result * result)
{
const double ax = fabs(x);
const double ay = fabs(y);
if(x == 0.0 || y == 0.0) {
/* It is necessary to eliminate this immediately.
*/
result->val = 0.0;
result->err = 0.0;
return GSL_SUCCESS;
}
else if((ax <= 1.0 && ay >= 1.0) || (ay <= 1.0 && ax >= 1.0)) {
/* Straddling 1.0 is always safe.
*/
result->val = x*y;
result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return GSL_SUCCESS;
}
else {
const double f = 1.0 - 2.0 * GSL_DBL_EPSILON;
const double min = GSL_MIN_DBL(fabs(x), fabs(y));
const double max = GSL_MAX_DBL(fabs(x), fabs(y));
if(max < 0.9 * GSL_SQRT_DBL_MAX || min < (f * DBL_MAX)/max) {
result->val = GSL_COERCE_DBL(x*y);
result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);
CHECK_UNDERFLOW(result);
return GSL_SUCCESS;
}
else {
OVERFLOW_ERROR(result);
}
}
}
int
gsl_sf_multiply_err_e(const double x, const double dx,
const double y, const double dy,
gsl_sf_result * result)
{
int status = gsl_sf_multiply_e(x, y, result);
result->err += fabs(dx*y) + fabs(dy*x);
return status;
}
/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/
#include "eval.h"
double gsl_sf_multiply(const double x, const double y)
{
EVAL_RESULT(gsl_sf_multiply_e(x, y, &result));
}
|
theory Transition
imports Main "./Definitions" "./Log"
begin
datatype message_payload
= append_entry
(* leaderId *) node
(* leaderCommit *) log_index
(* leaderLog *) log
| request_vote
(* candidateid *) node
(* lastLogIndex *) log_index
(* lastLogTerm *) election_term
| append_entry_response
(* success *) bool
| request_vote_response
(* voteGranted *) bool
primrec is_response where
"is_response (append_entry _ _ _) = False"
| "is_response (request_vote _ _ _) = False"
| "is_response (append_entry_response _) = True"
| "is_response (request_vote_response _) = True"
fun is_request where
"is_request r = (\<not> is_response r)"
datatype message
= message (sender: node) (receiver: node) (payload: message_payload) (sender_term: election_term)
fun payload_respond_to where
"payload_respond_to (append_entry_response _) (append_entry _ _ _) = True"
| "payload_respond_to (request_vote_response _) (request_vote _ _ _) = True"
| "payload_respond_to _ _ = False"
definition respond_to where
"respond_to resp req \<equiv>
(is_response (payload resp)
\<and> is_request (payload req)
\<and> sender req = receiver resp
\<and> sender resp = receiver req
\<and> payload_respond_to (payload resp) (payload req)
\<and> sender_term resp = sender_term req)"
datatype node_state = follower | candidate | leader
record server_state =
state :: node_state
(* Persistent state *)
currentTerm :: election_term
votedFor :: "node option"
log :: log
(* Volatile state *)
commitIndex :: nat
lastApplied :: nat
(* Volatile state on leaders *)
nextIndex :: "log_index list"
matchIndex :: "log_index list"
definition initial_server_state where
"initial_server_state n = \<lparr>
state = follower,
currentTerm = election_term 0,
votedFor = None,
log = [],
commitIndex = 0,
lastApplied = 0,
nextIndex = repeat (log_index 0) n,
matchIndex = repeat (log_index 0) n
\<rparr>"
definition ExReqProps where
"ExReqProps resp P req \<equiv> P req \<and> respond_to resp req"
definition ExReq where
"ExReq resp P \<equiv> Ex (ExReqProps resp P)"
definition majority where
"majority n t \<equiv> 2 * card t > n"
lemma majority_pigeonhole: "\<lbrakk> finite u; card u = n; x \<subseteq> u; y \<subseteq> u; majority n x; majority n y \<rbrakk> \<Longrightarrow> x \<inter> y \<noteq> {}"
proof-
assume "finite u" "card u = n" "x \<subseteq> u" "y \<subseteq> u" "majority n x" "majority n y"
have "2 * card x > n"
using \<open>majority n x\<close> majority_def by blast
moreover have "2 * card y > n"
using \<open>majority n y\<close> majority_def by auto
ultimately have "card x + card y > n"
by simp
{ assume "x \<inter> y = {}"
have "card (x \<union> y) = card x + card y"
by (meson \<open>finite u\<close> \<open>x \<inter> y = {}\<close> \<open>x \<subseteq> u\<close> \<open>y \<subseteq> u\<close> card_Un_disjoint finite_subset)
also have "\<dots> > n"
by (simp add: \<open>n < card x + card y\<close>)
finally have "card (x \<union> y) > n"
by simp
have "x \<union> y \<subseteq> u"
by (simp add: \<open>x \<subseteq> u\<close> \<open>y \<subseteq> u\<close>)
have False
by (metis \<open>card u = n\<close> \<open>finite u\<close> \<open>n < card (x \<union> y)\<close> \<open>x \<union> y \<subseteq> u\<close> card_mono not_le)
}
thus "x \<inter> y \<noteq> {}"
by auto
qed
(* Assumption: all RequestVote messages to followers are sent at once. Is it appropriate to assume this? *)
definition TR_condition_start_election where
"TR_condition_start_election \<sigma> \<sigma>' ms ms' target \<equiv>
let (index, term) = get_last_log_info (log (\<sigma>' ! target)) in
target < length \<sigma>
\<and> \<sigma>' = update target ((\<sigma> ! target) \<lparr>
currentTerm := increment_election_term (currentTerm (\<sigma> ! target)),
votedFor := Some (node target)
\<rparr>) \<sigma>
\<and> ms' = ms \<union> {message (node target) (node i) (request_vote (node target) index term) (currentTerm (\<sigma>' ! target)) | i. i \<in> {0..length \<sigma> - 1} \<and> i \<noteq> target}"
definition TR_condition_request_vote_resp where
"TR_condition_request_vote_resp \<sigma> \<sigma>' ms ms' m r s t vg \<equiv>
let resp = message (node m) (node r) (request_vote_response vg) t in
(ExReq resp (\<lambda>req. \<exists>candidateId lastLogIndex lastLogTerm. payload req = request_vote candidateId lastLogIndex lastLogTerm
\<and> req \<in> ms
\<and> vg = (if sender_term req < currentTerm (\<sigma> ! r) then False
else (votedFor (\<sigma> ! r) = None \<or> votedFor (\<sigma> ! r) = Some candidateId) \<and> log_up_to_date (log (\<sigma> ! r)) lastLogIndex lastLogTerm)
\<and> (votedFor (\<sigma> ! m) = Some s \<or> votedFor (\<sigma> ! m) = None)))
\<and> m < length \<sigma>
\<and> r < length \<sigma>
\<and> \<sigma>' = update m ((\<sigma> ! m) \<lparr> votedFor := Some s \<rparr>) \<sigma>
\<and> ms' = ms \<union> {resp}"
definition TR_condition_promote_to_leader where
"TR_condition_promote_to_leader \<sigma> \<sigma>' ms ms' target \<equiv>
majority (length \<sigma>) {s. \<exists>m \<in> ms. m = message s (node target) (request_vote_response True) (currentTerm (\<sigma> ! target))}
\<and> target < length \<sigma>
\<and> \<sigma>' = update target ((\<sigma> ! target) \<lparr> state := leader \<rparr>) \<sigma>
\<and> ms' = ms"
definition TR_condition_append_entry where
"TR_condition_append_entry \<sigma> \<sigma>' ms ms' s r \<equiv>
let m = message (node s) (node r) (append_entry (node s) (log_index (length (log (\<sigma> ! s)) - 1)) (log (\<sigma> ! s))) (currentTerm (\<sigma> ! s)) in
state (\<sigma> ! s) = leader
\<and> s < length \<sigma>
\<and> r < length \<sigma>
\<and> \<sigma>' = \<sigma>
\<and> ms' = ms \<union> {m}"
(*
This algorithm for AppendEntry is different from the original paper;
leader is supposed to send all logs in the state for the simplicity (no need to calculate diffs for merging and leader retries)
*)
definition TR_condition_append_entry_resp where
"TR_condition_append_entry_resp \<sigma> \<sigma>' ms ms' leadersLog prevLogTerm prevLogIndex t success r s \<equiv>
let resp = message (node s) (node r) (append_entry_response success) t in
ExReq resp (\<lambda>req. \<exists>leaderId leaderCommit. payload req = append_entry leaderId leaderCommit leadersLog
\<and> req \<in> ms
\<and> success = (if sender_term req < currentTerm (\<sigma> ! r) then False
else if \<not> log_up_to_date (log (\<sigma> ! r)) prevLogIndex prevLogTerm then False
else True))
\<and> s < length \<sigma>
\<and> r < length \<sigma>
\<and> \<sigma>' = update s ((\<sigma> ! s) \<lparr> log := leadersLog \<rparr>) \<sigma>
\<and> ms' = ms \<union> {resp}"
inductive transition :: "server_state list \<times> message set \<Rightarrow> server_state list \<times> message set \<Rightarrow> bool" (infix "\<rightarrow>" 50) where
TR_start_election: "TR_condition_start_election \<sigma> \<sigma>' ms ms' target \<Longrightarrow> transition (\<sigma>, ms) (\<sigma>', ms')"
| TR_request_vote_resp: "TR_condition_request_vote_resp \<sigma> \<sigma>' ms ms' m r s t vg \<Longrightarrow> transition (\<sigma>, ms) (\<sigma>', ms')"
| TR_promote_to_leader: "TR_condition_promote_to_leader \<sigma> \<sigma>' ms ms' target \<Longrightarrow> transition (\<sigma>, ms) (\<sigma>', ms')"
| TR_append_entry: "TR_condition_append_entry \<sigma> \<sigma>' ms ms' s r \<Longrightarrow> transition (\<sigma>, ms) (\<sigma>', ms')"
| TR_append_entry_resp: "TR_condition_append_entry_resp \<sigma> \<sigma>' ms ms' leadersLog prevLogTerm prevLogIndex t success r s \<Longrightarrow> transition (\<sigma>, ms) (\<sigma>', ms')"
lemma leader_promote_inversion_for_transition:
"\<lbrakk> i < length \<sigma>; transition (\<sigma>, ms) (\<sigma>', ms'); state (\<sigma> ! i) \<noteq> leader; state (\<sigma>' ! i) = leader \<rbrakk> \<Longrightarrow> majority (length \<sigma>) {s. \<exists>m \<in> ms. m = message s (node i) (request_vote_response True) (currentTerm (\<sigma> ! i))}"
apply (cases rule: transition.cases)
apply simp_all
proof-
fix \<sigma>'' \<sigma>''' msa ms'a target
show "i < length \<sigma> \<Longrightarrow>
(\<sigma>, ms) \<rightarrow> (\<sigma>', ms') \<Longrightarrow>
state (\<sigma> ! i) \<noteq> leader \<Longrightarrow>
state (\<sigma>' ! i) = leader \<Longrightarrow>
(\<sigma>, ms) = (\<sigma>'', msa) \<Longrightarrow>
(\<sigma>', ms') = (\<sigma>''', ms'a) \<Longrightarrow>
TR_condition_start_election \<sigma>'' \<sigma>''' msa ms'a target \<Longrightarrow>
majority (length \<sigma>) {s. message s (node i) (request_vote_response True) (currentTerm (\<sigma> ! i)) \<in> ms}"
apply (simp add: TR_condition_start_election_def)
apply (cases "\<sigma>'' ! target")
apply simp
by (metis select_convs(1) update_nth_nonupdated update_nth_updated)
next
fix \<sigma>'' \<sigma>''' msa ms'a m r s t vg
show "i < length \<sigma> \<Longrightarrow>
(\<sigma>, ms) \<rightarrow> (\<sigma>', ms') \<Longrightarrow>
state (\<sigma> ! i) \<noteq> leader \<Longrightarrow>
state (\<sigma>' ! i) = leader \<Longrightarrow>
(\<sigma>, ms) = (\<sigma>'', msa) \<Longrightarrow>
(\<sigma>', ms') = (\<sigma>''', ms'a) \<Longrightarrow>
TR_condition_request_vote_resp \<sigma>'' \<sigma>''' msa ms'a m r s t vg \<Longrightarrow>
majority (length \<sigma>) {s. message s (node i) (request_vote_response True) (currentTerm (\<sigma> ! i)) \<in> ms}"
apply (simp add: TR_condition_request_vote_resp_def)
apply (cases "\<sigma>'' ! m")
apply simp
by (metis select_convs(1) update_nth_nonupdated update_nth_updated)
next
fix \<sigma>'' \<sigma>''' msa ms'a target
show "i < length \<sigma> \<Longrightarrow>
(\<sigma>, ms) \<rightarrow> (\<sigma>', ms') \<Longrightarrow>
state (\<sigma> ! i) \<noteq> leader \<Longrightarrow>
state (\<sigma>' ! i) = leader \<Longrightarrow>
(\<sigma>, ms) = (\<sigma>'', msa) \<Longrightarrow>
(\<sigma>', ms') = (\<sigma>''', ms'a) \<Longrightarrow>
TR_condition_promote_to_leader \<sigma>'' \<sigma>''' msa ms'a target \<Longrightarrow>
majority (length \<sigma>) {s. message s (node i) (request_vote_response True) (currentTerm (\<sigma> ! i)) \<in> ms}"
apply (simp add: TR_condition_promote_to_leader_def)
apply (cases "\<sigma>'' ! target")
apply simp
by (metis select_convs(2) update_nth_nonupdated)
next
fix \<sigma>'' \<sigma>''' msa ms'a s r
show "i < length \<sigma> \<Longrightarrow>
(\<sigma>, ms) \<rightarrow> (\<sigma>', ms') \<Longrightarrow>
state (\<sigma> ! i) \<noteq> leader \<Longrightarrow>
state (\<sigma>' ! i) = leader \<Longrightarrow>
(\<sigma>, ms) = (\<sigma>'', msa) \<Longrightarrow>
(\<sigma>', ms') = (\<sigma>''', ms'a) \<Longrightarrow>
TR_condition_append_entry \<sigma>'' \<sigma>''' msa ms'a s r \<Longrightarrow>
majority (length \<sigma>) {s. message s (node i) (request_vote_response True) (currentTerm (\<sigma> ! i)) \<in> ms}"
apply (simp add: TR_condition_append_entry_def)
done
next
fix \<sigma>'' \<sigma>''' msa ms'a leadersLog prevLogTerm prevLogIndex t success r s
show "i < length \<sigma> \<Longrightarrow>
(\<sigma>, ms) \<rightarrow> (\<sigma>', ms') \<Longrightarrow>
state (\<sigma> ! i) \<noteq> leader \<Longrightarrow>
state (\<sigma>' ! i) = leader \<Longrightarrow>
(\<sigma>, ms) = (\<sigma>'', msa) \<Longrightarrow>
(\<sigma>', ms') = (\<sigma>''', ms'a) \<Longrightarrow>
TR_condition_append_entry_resp \<sigma>'' \<sigma>''' msa ms'a leadersLog prevLogTerm prevLogIndex t success r s \<Longrightarrow>
majority (length \<sigma>) {s. message s (node i) (request_vote_response True) (currentTerm (\<sigma> ! i)) \<in> ms}"
apply (simp add: TR_condition_append_entry_resp_def)
apply (cases "\<sigma>''' ! s")
by (metis (no_types, lifting) select_convs(1) surjective update_convs(4) update_nth_nonupdated update_nth_updated)
qed
lemma state_length_invariant_for_transition: "transition (\<sigma>, m) (\<sigma>', m') \<Longrightarrow> length \<sigma> = length \<sigma>'"
apply (cases rule: transition.cases)
apply simp_all
apply (simp add: TR_condition_start_election_def)
apply (simp add: TR_condition_request_vote_resp_def)
apply (metis update_length)
apply (simp add: TR_condition_promote_to_leader_def)
apply (simp add: TR_condition_append_entry_def)
apply (simp add: TR_condition_append_entry_resp_def)
by (metis update_length)
lemma transition_message_monotonicity: "(\<sigma>, m) \<rightarrow> (\<sigma>', m') \<Longrightarrow> m \<subseteq> m'"
proof-
assume hyp: "transition (\<sigma>,m) (\<sigma>',m')"
have "(\<lambda>(_, m). \<lambda>(_, m'). m \<subseteq> m') (\<sigma>,m) (\<sigma>', m')"
apply (induct rule: transition.induct [OF hyp])
apply (auto simp add: TR_condition_append_entry_def TR_condition_start_election_def TR_condition_promote_to_leader_def TR_condition_append_entry_resp_def TR_condition_request_vote_resp_def)
apply (metis insertCI)
apply (metis insertCI)
done
thus "m \<subseteq> m'"
by simp
qed
lemma transition_message_preserves_finite: "\<lbrakk> (\<sigma>,m) \<rightarrow> (\<sigma>',m'); finite m \<rbrakk> \<Longrightarrow> finite m'"
apply (cases rule: transition.cases)
apply simp_all
apply (simp add: TR_condition_start_election_def)
apply auto[1]
apply (simp add: TR_condition_request_vote_resp_def)
apply (metis finite_insert)
apply (simp add: TR_condition_promote_to_leader_def)
apply (simp add: TR_condition_append_entry_def)
apply (simp add: TR_condition_append_entry_resp_def)
by (metis finite_insert)
lemma transition_currentTerm_monotonicity: "\<lbrakk> i < length \<sigma>; (\<sigma>,m) \<rightarrow> (\<sigma>',m') \<rbrakk> \<Longrightarrow> currentTerm (\<sigma> ! i) \<le> currentTerm (\<sigma>' ! i)"
apply (cases rule: transition.cases)
apply simp_all
proof-
fix \<sigma>'' \<sigma>''' ms ms' target
show "i < length \<sigma> \<Longrightarrow>
(\<sigma>, m) \<rightarrow> (\<sigma>', m') \<Longrightarrow>
(\<sigma>, m) = (\<sigma>'', ms) \<Longrightarrow> (\<sigma>', m') = (\<sigma>''', ms') \<Longrightarrow> TR_condition_start_election \<sigma>'' \<sigma>''' ms ms' target \<Longrightarrow> currentTerm (\<sigma> ! i) \<le> currentTerm (\<sigma>' ! i)"
apply (simp add: TR_condition_start_election_def)
apply (cases "i = target")
apply simp
apply (cases "\<sigma>'' ! target")
apply simp
apply (simp add: increment_election_term_greater update_nth_updated)
by (simp add: less_eq_election_term_def update_nth_nonupdated)
next
fix \<sigma>'' \<sigma>''' ms ms' ma r s t vg
show "i < length \<sigma> \<Longrightarrow>
(\<sigma>, m) \<rightarrow> (\<sigma>', m') \<Longrightarrow>
(\<sigma>, m) = (\<sigma>'', ms) \<Longrightarrow>
(\<sigma>', m') = (\<sigma>''', ms') \<Longrightarrow> TR_condition_request_vote_resp \<sigma>'' \<sigma>''' ms ms' ma r s t vg \<Longrightarrow> currentTerm (\<sigma> ! i) \<le> currentTerm (\<sigma>' ! i)"
apply (simp add: TR_condition_request_vote_resp_def)
by (metis eq_iff less_eq_election_term_def select_convs(2) simps(12) surjective update_nth_nonupdated update_nth_updated)
next
fix \<sigma>'' \<sigma>''' ms ms' target
show "i < length \<sigma> \<Longrightarrow>
(\<sigma>, m) \<rightarrow> (\<sigma>', m') \<Longrightarrow>
(\<sigma>, m) = (\<sigma>'', ms) \<Longrightarrow> (\<sigma>', m') = (\<sigma>''', ms') \<Longrightarrow> TR_condition_promote_to_leader \<sigma>'' \<sigma>''' ms ms' target \<Longrightarrow> currentTerm (\<sigma> ! i) \<le> currentTerm (\<sigma>' ! i)"
apply (simp add: TR_condition_promote_to_leader_def)
by (metis eq_iff less_eq_election_term_def select_convs(2) surjective update_convs(1) update_nth_nonupdated update_nth_updated)
next
fix \<sigma>'' \<sigma>''' ms ms' s r
show "i < length \<sigma> \<Longrightarrow>
(\<sigma>, m) \<rightarrow> (\<sigma>', m') \<Longrightarrow>
(\<sigma>, m) = (\<sigma>'', ms) \<Longrightarrow> (\<sigma>', m') = (\<sigma>''', ms') \<Longrightarrow> TR_condition_append_entry \<sigma>'' \<sigma>''' ms ms' s r \<Longrightarrow> currentTerm (\<sigma> ! i) \<le> currentTerm (\<sigma>' ! i)"
apply (simp add: TR_condition_append_entry_def)
using less_eq_election_term_def by presburger
next
fix \<sigma>'' \<sigma>''' ms ms' leadersLog prevLogTerm prevLogIndex t success r s
show "i < length \<sigma> \<Longrightarrow>
(\<sigma>, m) \<rightarrow> (\<sigma>', m') \<Longrightarrow>
(\<sigma>, m) = (\<sigma>'', ms) \<Longrightarrow>
(\<sigma>', m') = (\<sigma>''', ms') \<Longrightarrow>
TR_condition_append_entry_resp \<sigma>'' \<sigma>''' ms ms' leadersLog prevLogTerm prevLogIndex t success r s \<Longrightarrow> currentTerm (\<sigma> ! i) \<le> currentTerm (\<sigma>' ! i)"
apply (simp add: TR_condition_append_entry_resp_def)
by (metis (mono_tags, lifting) eq_iff less_eq_election_term_def select_convs(2) surjective update_convs(4) update_nth_nonupdated update_nth_updated)
qed
definition transitions (infix "\<rightarrow>*" 50) where
"transitions \<equiv> rtranclp transition"
lemma transitions_one: "a \<rightarrow> b \<Longrightarrow> a \<rightarrow>* b"
by (simp add: transitions_def)
lemma transisions_trans [trans]: "a \<rightarrow>* b \<Longrightarrow> b \<rightarrow>* c \<Longrightarrow> a \<rightarrow>* c"
using transitions_def
by (metis rtranclp_trans)
end
|
(* Title: HOL/Library/DAList_Multiset.thy
Author: Lukas Bulwahn, TU Muenchen
*)
section \<open>Multisets partially implemented by association lists\<close>
theory DAList_Multiset
imports Multiset DAList
begin
text \<open>Delete prexisting code equations\<close>
lemma [code, code del]: "{#} = {#}" ..
lemma [code, code del]: "Multiset.is_empty = Multiset.is_empty" ..
lemma [code, code del]: "add_mset = add_mset" ..
lemma [code, code del]: "plus = (plus :: 'a multiset \<Rightarrow> _)" ..
lemma [code, code del]: "minus = (minus :: 'a multiset \<Rightarrow> _)" ..
lemma [code, code del]: "inf_subset_mset = (inf_subset_mset :: 'a multiset \<Rightarrow> _)" ..
lemma [code, code del]: "sup_subset_mset = (sup_subset_mset :: 'a multiset \<Rightarrow> _)" ..
lemma [code, code del]: "image_mset = image_mset" ..
lemma [code, code del]: "filter_mset = filter_mset" ..
lemma [code, code del]: "count = count" ..
lemma [code, code del]: "size = (size :: _ multiset \<Rightarrow> nat)" ..
lemma [code, code del]: "sum_mset = sum_mset" ..
lemma [code, code del]: "prod_mset = prod_mset" ..
lemma [code, code del]: "set_mset = set_mset" ..
lemma [code, code del]: "sorted_list_of_multiset = sorted_list_of_multiset" ..
lemma [code, code del]: "subset_mset = subset_mset" ..
lemma [code, code del]: "subseteq_mset = subseteq_mset" ..
lemma [code, code del]: "equal_multiset_inst.equal_multiset = equal_multiset_inst.equal_multiset" ..
text \<open>Raw operations on lists\<close>
definition join_raw ::
"('key \<Rightarrow> 'val \<times> 'val \<Rightarrow> 'val) \<Rightarrow>
('key \<times> 'val) list \<Rightarrow> ('key \<times> 'val) list \<Rightarrow> ('key \<times> 'val) list"
where "join_raw f xs ys = foldr (\<lambda>(k, v). map_default k v (\<lambda>v'. f k (v', v))) ys xs"
lemma join_raw_Nil [simp]: "join_raw f xs [] = xs"
by (simp add: join_raw_def)
lemma join_raw_Cons [simp]:
"join_raw f xs ((k, v) # ys) = map_default k v (\<lambda>v'. f k (v', v)) (join_raw f xs ys)"
by (simp add: join_raw_def)
lemma map_of_join_raw:
assumes "distinct (map fst ys)"
shows "map_of (join_raw f xs ys) x =
(case map_of xs x of
None \<Rightarrow> map_of ys x
| Some v \<Rightarrow> (case map_of ys x of None \<Rightarrow> Some v | Some v' \<Rightarrow> Some (f x (v, v'))))"
using assms
apply (induct ys)
apply (auto simp add: map_of_map_default split: option.split)
apply (metis map_of_eq_None_iff option.simps(2) weak_map_of_SomeI)
apply (metis Some_eq_map_of_iff map_of_eq_None_iff option.simps(2))
done
lemma distinct_join_raw:
assumes "distinct (map fst xs)"
shows "distinct (map fst (join_raw f xs ys))"
using assms
proof (induct ys)
case Nil
then show ?case by simp
next
case (Cons y ys)
then show ?case by (cases y) (simp add: distinct_map_default)
qed
definition "subtract_entries_raw xs ys = foldr (\<lambda>(k, v). AList.map_entry k (\<lambda>v'. v' - v)) ys xs"
lemma map_of_subtract_entries_raw:
assumes "distinct (map fst ys)"
shows "map_of (subtract_entries_raw xs ys) x =
(case map_of xs x of
None \<Rightarrow> None
| Some v \<Rightarrow> (case map_of ys x of None \<Rightarrow> Some v | Some v' \<Rightarrow> Some (v - v')))"
using assms
unfolding subtract_entries_raw_def
apply (induct ys)
apply auto
apply (simp split: option.split)
apply (simp add: map_of_map_entry)
apply (auto split: option.split)
apply (metis map_of_eq_None_iff option.simps(3) option.simps(4))
apply (metis map_of_eq_None_iff option.simps(4) option.simps(5))
done
lemma distinct_subtract_entries_raw:
assumes "distinct (map fst xs)"
shows "distinct (map fst (subtract_entries_raw xs ys))"
using assms
unfolding subtract_entries_raw_def
by (induct ys) (auto simp add: distinct_map_entry)
text \<open>Operations on alists with distinct keys\<close>
lift_definition join :: "('a \<Rightarrow> 'b \<times> 'b \<Rightarrow> 'b) \<Rightarrow> ('a, 'b) alist \<Rightarrow> ('a, 'b) alist \<Rightarrow> ('a, 'b) alist"
is join_raw
by (simp add: distinct_join_raw)
lift_definition subtract_entries :: "('a, ('b :: minus)) alist \<Rightarrow> ('a, 'b) alist \<Rightarrow> ('a, 'b) alist"
is subtract_entries_raw
by (simp add: distinct_subtract_entries_raw)
text \<open>Implementing multisets by means of association lists\<close>
definition count_of :: "('a \<times> nat) list \<Rightarrow> 'a \<Rightarrow> nat"
where "count_of xs x = (case map_of xs x of None \<Rightarrow> 0 | Some n \<Rightarrow> n)"
lemma count_of_multiset: "count_of xs \<in> multiset"
proof -
let ?A = "{x::'a. 0 < (case map_of xs x of None \<Rightarrow> 0::nat | Some n \<Rightarrow> n)}"
have "?A \<subseteq> dom (map_of xs)"
proof
fix x
assume "x \<in> ?A"
then have "0 < (case map_of xs x of None \<Rightarrow> 0::nat | Some n \<Rightarrow> n)"
by simp
then have "map_of xs x \<noteq> None"
by (cases "map_of xs x") auto
then show "x \<in> dom (map_of xs)"
by auto
qed
with finite_dom_map_of [of xs] have "finite ?A"
by (auto intro: finite_subset)
then show ?thesis
by (simp add: count_of_def fun_eq_iff multiset_def)
qed
lemma count_simps [simp]:
"count_of [] = (\<lambda>_. 0)"
"count_of ((x, n) # xs) = (\<lambda>y. if x = y then n else count_of xs y)"
by (simp_all add: count_of_def fun_eq_iff)
lemma count_of_empty: "x \<notin> fst ` set xs \<Longrightarrow> count_of xs x = 0"
by (induct xs) (simp_all add: count_of_def)
lemma count_of_filter: "count_of (List.filter (P \<circ> fst) xs) x = (if P x then count_of xs x else 0)"
by (induct xs) auto
lemma count_of_map_default [simp]:
"count_of (map_default x b (\<lambda>x. x + b) xs) y =
(if x = y then count_of xs x + b else count_of xs y)"
unfolding count_of_def by (simp add: map_of_map_default split: option.split)
lemma count_of_join_raw:
"distinct (map fst ys) \<Longrightarrow>
count_of xs x + count_of ys x = count_of (join_raw (\<lambda>x (x, y). x + y) xs ys) x"
unfolding count_of_def by (simp add: map_of_join_raw split: option.split)
lemma count_of_subtract_entries_raw:
"distinct (map fst ys) \<Longrightarrow>
count_of xs x - count_of ys x = count_of (subtract_entries_raw xs ys) x"
unfolding count_of_def by (simp add: map_of_subtract_entries_raw split: option.split)
text \<open>Code equations for multiset operations\<close>
definition Bag :: "('a, nat) alist \<Rightarrow> 'a multiset"
where "Bag xs = Abs_multiset (count_of (DAList.impl_of xs))"
code_datatype Bag
lemma count_Bag [simp, code]: "count (Bag xs) = count_of (DAList.impl_of xs)"
by (simp add: Bag_def count_of_multiset)
lemma Mempty_Bag [code]: "{#} = Bag (DAList.empty)"
by (simp add: multiset_eq_iff alist.Alist_inverse DAList.empty_def)
lift_definition is_empty_Bag_impl :: "('a, nat) alist \<Rightarrow> bool" is
"\<lambda>xs. list_all (\<lambda>x. snd x = 0) xs" .
lemma is_empty_Bag [code]: "Multiset.is_empty (Bag xs) \<longleftrightarrow> is_empty_Bag_impl xs"
proof -
have "Multiset.is_empty (Bag xs) \<longleftrightarrow> (\<forall>x. count (Bag xs) x = 0)"
unfolding Multiset.is_empty_def multiset_eq_iff by simp
also have "\<dots> \<longleftrightarrow> (\<forall>x\<in>fst ` set (alist.impl_of xs). count (Bag xs) x = 0)"
proof (intro iffI allI ballI)
fix x assume A: "\<forall>x\<in>fst ` set (alist.impl_of xs). count (Bag xs) x = 0"
thus "count (Bag xs) x = 0"
proof (cases "x \<in> fst ` set (alist.impl_of xs)")
case False
thus ?thesis by (force simp: count_of_def split: option.splits)
qed (insert A, auto)
qed simp_all
also have "\<dots> \<longleftrightarrow> list_all (\<lambda>x. snd x = 0) (alist.impl_of xs)"
by (auto simp: count_of_def list_all_def)
finally show ?thesis by (simp add: is_empty_Bag_impl.rep_eq)
qed
lemma union_Bag [code]: "Bag xs + Bag ys = Bag (join (\<lambda>x (n1, n2). n1 + n2) xs ys)"
by (rule multiset_eqI)
(simp add: count_of_join_raw alist.Alist_inverse distinct_join_raw join_def)
lemma add_mset_Bag [code]: "add_mset x (Bag xs) =
Bag (join (\<lambda>x (n1, n2). n1 + n2) (DAList.update x 1 DAList.empty) xs)"
unfolding add_mset_add_single[of x "Bag xs"] union_Bag[symmetric]
by (simp add: multiset_eq_iff update.rep_eq empty.rep_eq)
lemma minus_Bag [code]: "Bag xs - Bag ys = Bag (subtract_entries xs ys)"
by (rule multiset_eqI)
(simp add: count_of_subtract_entries_raw alist.Alist_inverse
distinct_subtract_entries_raw subtract_entries_def)
lemma filter_Bag [code]: "filter_mset P (Bag xs) = Bag (DAList.filter (P \<circ> fst) xs)"
by (rule multiset_eqI) (simp add: count_of_filter DAList.filter.rep_eq)
lemma mset_eq [code]: "HOL.equal (m1::'a::equal multiset) m2 \<longleftrightarrow> m1 \<le># m2 \<and> m2 \<le># m1"
by (metis equal_multiset_def subset_mset.eq_iff)
text \<open>By default the code for \<open><\<close> is @{prop"xs < ys \<longleftrightarrow> xs \<le> ys \<and> \<not> xs = ys"}.
With equality implemented by \<open>\<le>\<close>, this leads to three calls of \<open>\<le>\<close>.
Here is a more efficient version:\<close>
lemma mset_less[code]: "xs <# (ys :: 'a multiset) \<longleftrightarrow> xs \<le># ys \<and> \<not> ys \<le># xs"
by (rule subset_mset.less_le_not_le)
lemma mset_less_eq_Bag0:
"Bag xs \<le># A \<longleftrightarrow> (\<forall>(x, n) \<in> set (DAList.impl_of xs). count_of (DAList.impl_of xs) x \<le> count A x)"
(is "?lhs \<longleftrightarrow> ?rhs")
proof
assume ?lhs
then show ?rhs by (auto simp add: subseteq_mset_def)
next
assume ?rhs
show ?lhs
proof (rule mset_subset_eqI)
fix x
from \<open>?rhs\<close> have "count_of (DAList.impl_of xs) x \<le> count A x"
by (cases "x \<in> fst ` set (DAList.impl_of xs)") (auto simp add: count_of_empty)
then show "count (Bag xs) x \<le> count A x" by (simp add: subset_mset_def)
qed
qed
lemma mset_less_eq_Bag [code]:
"Bag xs \<le># (A :: 'a multiset) \<longleftrightarrow> (\<forall>(x, n) \<in> set (DAList.impl_of xs). n \<le> count A x)"
proof -
{
fix x n
assume "(x,n) \<in> set (DAList.impl_of xs)"
then have "count_of (DAList.impl_of xs) x = n"
proof transfer
fix x n
fix xs :: "('a \<times> nat) list"
show "(distinct \<circ> map fst) xs \<Longrightarrow> (x, n) \<in> set xs \<Longrightarrow> count_of xs x = n"
proof (induct xs)
case Nil
then show ?case by simp
next
case (Cons ym ys)
obtain y m where ym: "ym = (y,m)" by force
note Cons = Cons[unfolded ym]
show ?case
proof (cases "x = y")
case False
with Cons show ?thesis
unfolding ym by auto
next
case True
with Cons(2-3) have "m = n" by force
with True show ?thesis
unfolding ym by auto
qed
qed
qed
}
then show ?thesis
unfolding mset_less_eq_Bag0 by auto
qed
declare multiset_inter_def [code]
declare sup_subset_mset_def [code]
declare mset.simps [code]
fun fold_impl :: "('a \<Rightarrow> nat \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'b \<Rightarrow> ('a \<times> nat) list \<Rightarrow> 'b"
where
"fold_impl fn e ((a,n) # ms) = (fold_impl fn ((fn a n) e) ms)"
| "fold_impl fn e [] = e"
context
begin
qualified definition fold :: "('a \<Rightarrow> nat \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'b \<Rightarrow> ('a, nat) alist \<Rightarrow> 'b"
where "fold f e al = fold_impl f e (DAList.impl_of al)"
end
context comp_fun_commute
begin
lemma DAList_Multiset_fold:
assumes fn: "\<And>a n x. fn a n x = (f a ^^ n) x"
shows "fold_mset f e (Bag al) = DAList_Multiset.fold fn e al"
unfolding DAList_Multiset.fold_def
proof (induct al)
fix ys
let ?inv = "{xs :: ('a \<times> nat) list. (distinct \<circ> map fst) xs}"
note cs[simp del] = count_simps
have count[simp]: "\<And>x. count (Abs_multiset (count_of x)) = count_of x"
by (rule Abs_multiset_inverse[OF count_of_multiset])
assume ys: "ys \<in> ?inv"
then show "fold_mset f e (Bag (Alist ys)) = fold_impl fn e (DAList.impl_of (Alist ys))"
unfolding Bag_def unfolding Alist_inverse[OF ys]
proof (induct ys arbitrary: e rule: list.induct)
case Nil
show ?case
by (rule trans[OF arg_cong[of _ "{#}" "fold_mset f e", OF multiset_eqI]])
(auto, simp add: cs)
next
case (Cons pair ys e)
obtain a n where pair: "pair = (a,n)"
by force
from fn[of a n] have [simp]: "fn a n = (f a ^^ n)"
by auto
have inv: "ys \<in> ?inv"
using Cons(2) by auto
note IH = Cons(1)[OF inv]
define Ys where "Ys = Abs_multiset (count_of ys)"
have id: "Abs_multiset (count_of ((a, n) # ys)) = ((op + {# a #}) ^^ n) Ys"
unfolding Ys_def
proof (rule multiset_eqI, unfold count)
fix c
show "count_of ((a, n) # ys) c =
count ((op + {#a#} ^^ n) (Abs_multiset (count_of ys))) c" (is "?l = ?r")
proof (cases "c = a")
case False
then show ?thesis
unfolding cs by (induct n) auto
next
case True
then have "?l = n" by (simp add: cs)
also have "n = ?r" unfolding True
proof (induct n)
case 0
from Cons(2)[unfolded pair] have "a \<notin> fst ` set ys" by auto
then show ?case by (induct ys) (simp, auto simp: cs)
next
case Suc
then show ?case by simp
qed
finally show ?thesis .
qed
qed
show ?case
unfolding pair
apply (simp add: IH[symmetric])
unfolding id Ys_def[symmetric]
apply (induct n)
apply (auto simp: fold_mset_fun_left_comm[symmetric])
done
qed
qed
end
context
begin
private lift_definition single_alist_entry :: "'a \<Rightarrow> 'b \<Rightarrow> ('a, 'b) alist" is "\<lambda>a b. [(a, b)]"
by auto
lemma image_mset_Bag [code]:
"image_mset f (Bag ms) =
DAList_Multiset.fold (\<lambda>a n m. Bag (single_alist_entry (f a) n) + m) {#} ms"
unfolding image_mset_def
proof (rule comp_fun_commute.DAList_Multiset_fold, unfold_locales, (auto simp: ac_simps)[1])
fix a n m
show "Bag (single_alist_entry (f a) n) + m = ((add_mset \<circ> f) a ^^ n) m" (is "?l = ?r")
proof (rule multiset_eqI)
fix x
have "count ?r x = (if x = f a then n + count m x else count m x)"
by (induct n) auto
also have "\<dots> = count ?l x"
by (simp add: single_alist_entry.rep_eq)
finally show "count ?l x = count ?r x" ..
qed
qed
end
(* we cannot use (\<lambda>a n. op + (a * n)) for folding, since * is not defined
in comm_monoid_add *)
lemma sum_mset_Bag[code]: "sum_mset (Bag ms) = DAList_Multiset.fold (\<lambda>a n. ((op + a) ^^ n)) 0 ms"
unfolding sum_mset.eq_fold
apply (rule comp_fun_commute.DAList_Multiset_fold)
apply unfold_locales
apply (auto simp: ac_simps)
done
(* we cannot use (\<lambda>a n. op * (a ^ n)) for folding, since ^ is not defined
in comm_monoid_mult *)
lemma prod_mset_Bag[code]: "prod_mset (Bag ms) = DAList_Multiset.fold (\<lambda>a n. ((op * a) ^^ n)) 1 ms"
unfolding prod_mset.eq_fold
apply (rule comp_fun_commute.DAList_Multiset_fold)
apply unfold_locales
apply (auto simp: ac_simps)
done
lemma size_fold: "size A = fold_mset (\<lambda>_. Suc) 0 A" (is "_ = fold_mset ?f _ _")
proof -
interpret comp_fun_commute ?f by standard auto
show ?thesis by (induct A) auto
qed
lemma size_Bag[code]: "size (Bag ms) = DAList_Multiset.fold (\<lambda>a n. op + n) 0 ms"
unfolding size_fold
proof (rule comp_fun_commute.DAList_Multiset_fold, unfold_locales, simp)
fix a n x
show "n + x = (Suc ^^ n) x"
by (induct n) auto
qed
lemma set_mset_fold: "set_mset A = fold_mset insert {} A" (is "_ = fold_mset ?f _ _")
proof -
interpret comp_fun_commute ?f by standard auto
show ?thesis by (induct A) auto
qed
lemma set_mset_Bag[code]:
"set_mset (Bag ms) = DAList_Multiset.fold (\<lambda>a n. (if n = 0 then (\<lambda>m. m) else insert a)) {} ms"
unfolding set_mset_fold
proof (rule comp_fun_commute.DAList_Multiset_fold, unfold_locales, (auto simp: ac_simps)[1])
fix a n x
show "(if n = 0 then \<lambda>m. m else insert a) x = (insert a ^^ n) x" (is "?l n = ?r n")
proof (cases n)
case 0
then show ?thesis by simp
next
case (Suc m)
then have "?l n = insert a x" by simp
moreover have "?r n = insert a x" unfolding Suc by (induct m) auto
ultimately show ?thesis by auto
qed
qed
instantiation multiset :: (exhaustive) exhaustive
begin
definition exhaustive_multiset ::
"('a multiset \<Rightarrow> (bool \<times> term list) option) \<Rightarrow> natural \<Rightarrow> (bool \<times> term list) option"
where "exhaustive_multiset f i = Quickcheck_Exhaustive.exhaustive (\<lambda>xs. f (Bag xs)) i"
instance ..
end
end
|
{-# LANGUAGE RecordWildCards #-}
module Statistics.BBVI.StepSize
( KucP(..)
, rhoKuc
, defaultKucP
, Rho
)
where
import qualified Data.Vector as V
import Statistics.BBVI.Propagator ( DistCell(..)
, Gradient
, Memory
)
-- | step size is a vector the same length as n parameters in
-- the distribution
type Rho = V.Vector Double
-- | calculates a step size following Kucukelbir et al 2017
rhoKuc
:: KucP -- ^ parameters
-> Gradient -- ^ gradient at time t
-> DistCell a -- ^ distribution cell (needed for memory data
-- e.g. \( s_{t-1} \) in Kucukelbir et al 2017)
-> (Memory, Rho) -- ^ change in memory, stepsize
rhoKuc KucP {..} gra (Node time memory _dist) =
( deltaM
, V.zipWith
(\ds s ->
eta
* (fromIntegral time)
** (negate 0.5 + eps)
* (1.0 / (tau + sqrt (s + ds)))
)
deltaM
memory
)
where
deltaM = V.zipWith (\g s -> alpha * g ^ (2 :: Int) - alpha * s) gra memory
rhoKuc _kp _gra (U{}) = error "called step size cell on an update cell!"
-- | parameters for 'rhoKuc'
data KucP = KucP
{ alpha :: Double
, eta :: Double
, tau :: Double
, eps :: Double
} deriving (Show, Eq, Ord, Read)
-- | default parameters for 'rhoKuc.' eta is what you probably want to
-- tune: kucukelbir et al try 0.01 0.1 1 10 100
defaultKucP :: KucP
defaultKucP = KucP { alpha = 0.1, eta = 0.1, tau = 1.0, eps = 1e-16 }
|
/*
* VGMTrans (c) 2002-2019
* Licensed under the zlib license,
* refer to the included LICENSE.txt file
*/
#pragma once
#include <string>
#include <sstream>
#include <cassert>
#include <cmath>
#include <cstring>
#include <iomanip>
#include <climits>
#include <algorithm>
#include <vector>
#include <gsl-lite.hpp>
#include "helper.h"
#define VERSION "1.0.3"
/* Type aliases to save some typing */
using size_t = std::size_t;
using s8 = std::int8_t;
using s16 = std::int16_t;
using s32 = std::int32_t;
using s64 = std::int64_t;
using sptr = std::intptr_t;
using u8 = std::uint8_t;
using u16 = std::uint16_t;
using u32 = std::uint32_t;
using u64 = std::uint64_t;
using uptr = std::uintptr_t;
std::string removeExtFromPath(const std::string &s);
std::string StringToUpper(std::string myString);
std::string StringToLower(std::string myString);
uint32_t StringToHex(const std::string &str);
std::string ConvertToSafeFileName(const std::string &str);
inline int CountBytesOfVal(uint8_t *buf, uint32_t numBytes, uint8_t val) {
int count = 0;
for (uint32_t i = 0; i < numBytes; i++)
if (buf[i] == val)
count++;
return count;
}
struct SizeOffsetPair {
uint32_t size;
uint32_t offset;
SizeOffsetPair() : size(0), offset(0) {}
SizeOffsetPair(uint32_t offset_, uint32_t size_) : size(size_), offset(offset_) {}
};
char *GetFileWithBase(const char *f, const char *newfile);
std::vector<char> zdecompress(gsl::span<const char> data);
std::vector<char> zdecompress(std::vector<char> &data);
|
################################################################################
# Assign Model and Target Parameter
_modelProb = ModelWrapper(ProbModel(), val_dist)
_syms = [
keys(_modelProb.val),
keys(_modelProb.val)[1],
keys(_modelProb.val)[end],
(:d_a1, :d_a2, :d_a3, :d_a5, :d_a6, :d_a7, :d_a8),
]
_targets = [Tagged(_modelProb, _syms[iter]) for iter in eachindex(_syms)]
_params = [sample(_modelProb, _targets[iter]) for iter in eachindex(_syms)]
@testset "Tagged - Model parameter" begin
## Assign Sub Model
for iter in eachindex(_syms)
_sym = _syms[iter]
_target = _targets[iter]
_param = _params[iter]
_model_temp = ModelWrapper(subset(val_dist, _sym))
## Compute logdensities and check length
@test length(_model_temp) == length(_target)
@test abs(log_prior(_model_temp, _target) - log_prior(_model_temp)) <= _TOL
@test abs(log_abs_det_jac(_model_temp, _target) - log_abs_det_jac(_model_temp)) <=
_TOL
## Type Check - Unflatten/Constrain
theta_unconstrained_vec = randn(length(_target))
theta_constrained = unflatten_constrain(_model_temp, theta_unconstrained_vec)
theta_constrained2 = unflatten_constrain(
_model_temp, _target, theta_unconstrained_vec
)
@test typeof(theta_constrained) == typeof(_model_temp.val)
@test typeof(theta_constrained2) == typeof(_model_temp.val)
_θ1 = flatten(_model_temp.info.reconstruct, theta_constrained)
_θ2 = flatten(_target.info.reconstruct, theta_constrained2)
@test sum(abs.(_θ1 - _θ2)) ≈ 0 atol = _TOL
## Utility functions
log_prior(_target, _model_temp.val)
θ_flat = flatten(_model_temp, _target)
unflatten(_model_temp, _target, θ_flat)
unflatten!(_model_temp, _target, θ_flat)
θ_flat_unconstrained = unconstrain_flatten(_model_temp, _target)
unflatten_constrain!(_model_temp, _target, θ_flat_unconstrained)
log_prior_with_transform(_model_temp, _target)
subset(_model_temp, _target)
ModelWrappers.length(_target)
ModelWrappers.paramnames(_target)
fill(_model_temp, _target, _model_temp.val)
fill!(_model_temp, _target, _model_temp.val)
_model_temp.val
sample(_RNG, _model_temp, _target)
sample(_model_temp, _target)
sample!(_RNG, _model_temp, _target)
sample!(_model_temp, _target)
end
end
|
Require Export RecTypes.SpecTypes.
Require Export RecTypes.InstTy.
Require Export RecTypes.LemmasTypes.
Require Import StlcIso.SpecEvaluation.
Require Import StlcIso.SpecSyntax.
Require Import StlcIso.SpecTyping.
Require Import StlcIso.LemmasTyping.
Require Import StlcIso.LemmasEvaluation.
Require Import StlcIso.CanForm.
Require Import StlcIso.Fix.
Require Import StlcIso.Size.
Require Import StlcIso.TypeSafety.
Require Import StlcFix.SpecEvaluation.
Require Import StlcFix.SpecSyntax.
Require Import StlcFix.SpecTyping.
Require Import StlcFix.SpecAnnot.
Require Import StlcFix.LemmasTyping.
Require Import StlcFix.LemmasEvaluation.
Require Import StlcFix.CanForm.
Require Import StlcFix.Size.
Require Import StlcFix.StlcOmega.
Require Import StlcFix.TypeSafety.
Require Import Common.Relations.
Module F.
Include StlcFix.SpecEvaluation.
Include StlcFix.SpecSyntax.
Include StlcFix.SpecTyping.
Include StlcFix.SpecAnnot.
Include StlcFix.LemmasTyping.
Include StlcFix.LemmasEvaluation.
Include StlcFix.CanForm.
Include StlcFix.Size.
Include StlcFix.TypeSafety.
End F.
Module I.
Include RecTypes.SpecTypes.
Include RecTypes.InstTy.
Include RecTypes.LemmasTypes.
Include StlcIso.SpecEvaluation.
Include StlcIso.SpecSyntax.
Include StlcIso.SpecTyping.
Include StlcIso.LemmasTyping.
Include StlcIso.LemmasEvaluation.
Include StlcIso.CanForm.
Include StlcIso.Fix.
Include StlcIso.Size.
Include StlcIso.TypeSafety.
End I.
Definition UValFI' := fun (S : I.Ty -> F.Ty) (τ : I.Ty) =>
let τl := match τ with
| I.tunit => F.tunit
| I.tbool => F.tbool
| I.tarr τ1 τ2 as τ => F.tarr (S τ1) (S τ2)
| I.tprod τ1 τ2 as τ => F.tprod (S τ1) (S τ2)
| I.tsum τ1 τ2 =>
let σ1 := S τ1 in
let σ2 := S τ2 in
F.tsum σ1 σ2
| I.trec τ => S τ[beta1 (I.trec τ)]
| I.tvar i => F.tunit
end
in F.tsum τl F.tunit.
Arguments UValFI'/ S τ.
Fixpoint UValFI (n : nat) (τ : I.Ty) {struct n} : F.Ty :=
match n with
| 0 => F.tunit
| S n => UValFI' (UValFI n) τ
end.
Arguments UValFI !n !τ.
Definition unkUVal (n : nat) : F.Tm :=
match n with
| 0 => F.unit
| _ => F.inr F.unit
end.
Definition unkUValA (n : nat) (τ : I.Ty) : F.TmA :=
match n with
| 0 => F.a_unit
| (S n) => F.a_inr (match τ with
| I.tunit => F.tunit
| I.tbool => F.tbool
| I.tarr τ1 τ2 as τ => F.tarr (UValFI n τ1) (UValFI n τ2)
| I.tprod τ1 τ2 as τ => F.tprod (UValFI n τ1) (UValFI n τ2)
| I.tsum τ1 τ2 =>
let σ1 := UValFI n τ1 in
let σ2 := UValFI n τ2 in
F.tsum σ1 σ2
| I.trec τ => UValFI n τ[beta1 (I.trec τ)]
| I.tvar i => F.tunit
end) F.tunit F.a_unit
end.
Lemma unkUVal_unkUValA {n τ} : unkUVal n = eraseAnnot (unkUValA n τ).
Proof.
destruct n;
now cbn.
Qed.
Lemma unkUVal_Value (n : nat) : F.Value (unkUVal n).
Proof.
case n; simpl; trivial.
Qed.
Lemma unkUValT {Γ n τ} : F.Typing Γ (unkUVal n) (UValFI n τ).
Proof.
induction n;
eauto using F.Typing.
Qed.
Lemma unkUValAT {Γ n τ} : F.AnnotTyping Γ (unkUValA n τ) (UValFI n τ).
Proof.
induction n;
eauto using F.AnnotTyping.
Qed.
#[export]
Hint Resolve unkUValT : uval_typing.
#[export]
Hint Resolve unkUValAT : uval_typing.
(* Definition constr_uvalfi {Γ} (n : nat) (τ : I.Ty) (t : F.Tm) {P : ClosedTy τ} {Q : F.Typing Γ t (@UValFI n τ P)} : F.Tm := *)
(* F.inl t. *)
(* Definition inUnit_pctx (n : nat) := pinr (pinl phole). *)
(* Definition inUnit (n : nat) (t : Tm) := pctx_app t (inUnit_pctx n). *)
(* Arguments inUnit_pctx / n. *)
(* Lemma inUnit_Value {n v} : Value v → Value (inUnit n v). *)
(* Proof. *)
(* simpl; trivial. *)
(* Qed. *)
(* Lemma inUnit_pctx_T {Γ n} : ⟪Unit_pctx n : Γ , tunit → Γ , UVal (S n) ⟫. *)
(* Proof. *)
(* unfold inUnit_pctx. crushTyping. *)
(* Qed. *)
Lemma inUnitT {Γ n t} : ⟪ Γ ⊢ t : F.tunit ⟫ → ⟪ Γ ⊢ F.inl t : UValFI (S n) I.tunit ⟫.
Proof.
intuition.
Qed.
(* Arguments inUnit n t : simpl never. *)
Definition inBool_pctx (n : nat) : PCtx := pinl phole.
Definition inBool (n : nat) (t : Tm): Tm := pctx_app t (inBool_pctx n).
Arguments inBool_pctx /n.
Lemma inBool_pctx_T {Γ n} : ⟪ ⊢ inBool_pctx n : Γ , tbool → Γ , UValFI (S n) I.tbool ⟫.
Proof.
unfold inBool_pctx. unfold UValFI. crushTyping.
Qed.
Lemma inBoolT {Γ n t} : ⟪ Γ ⊢ t : tbool ⟫ → ⟪ Γ ⊢ inBool n t : UValFI (S n) I.tbool ⟫.
Proof.
unfold inBool. eauto using inBool_pctx_T with typing.
Qed.
Lemma inBool_Value {n v} : Value v → Value (inBool n v).
Proof.
simpl; trivial.
Qed.
Definition inProd_pctx (n : nat) : PCtx := pinl phole.
Definition inProd (n : nat) (t : Tm) : Tm := pctx_app t (inProd_pctx n).
Lemma inProd_pctx_T {Γ n τ₁ τ₂} : ⟪ ⊢ inProd_pctx n : Γ , UValFI n τ₁ × UValFI n τ₂ → Γ , UValFI (S n) (I.tprod τ₁ τ₂)⟫.
Proof.
unfold inProd_pctx. crushTyping.
Qed.
Lemma inProd_T {Γ n t τ₁ τ₂} : ⟪ Γ ⊢ t : UValFI n τ₁ × UValFI n τ₂ ⟫ → ⟪ Γ ⊢ inProd n t : UValFI (S n) (I.tprod τ₁ τ₂) ⟫.
Proof.
unfold inProd. eauto using inProd_pctx_T with typing.
Qed.
Lemma inProd_Value {n v} : Value v → Value (inProd n v).
Proof.
simpl; trivial.
Qed.
(* Definition inArr_pctx (n : nat) : PCtx := pinr (pinr (pinr (pinr (pinl phole)))). *)
(* Definition inArr (n : nat) (t : Tm) : Tm := pctx_app t (inArr_pctx n). *)
(* Arguments inArr_pctx / n. *)
(* Lemma inArr_pctx_T {Γ n} : ⟪ ⊢ inArr_pctx n : Γ , UValFI n ⇒ UValFI n → Γ , UValFI (S n) ⟫. *)
(* Proof. *)
(* unfold inArr_pctx. crushTyping. *)
(* Qed. *)
Lemma inArr_T {Γ n t τ τ'} : ⟪ Γ ⊢ t : F.tarr (UValFI n τ) (UValFI n τ') ⟫ → ⟪ Γ ⊢ F.inl t : UValFI (S n) (I.tarr τ τ') ⟫.
Proof.
intuition.
Qed.
(* Lemma inArr_Value {n v} : Value v → Value (inArr n v). *)
(* Proof. *)
(* simpl; trivial. *)
(* Qed. *)
(* Definition inSum_pctx (n : nat) : PCtx := pinr (pinr (pinr (pinr (pinr phole)))). *)
(* Definition inSum (n : nat) (t : Tm) : Tm := pctx_app t (inSum_pctx n). *)
(* Lemma inSum_pctx_T {Γ n} : ⟪ ⊢ inSum_pctx n : Γ , UVal n ⊎ UVal n → Γ , UVal (S n) ⟫. *)
(* Proof. *)
(* unfold inSum_pctx. crushTyping. *)
(* Qed. *)
Lemma inSum_T {Γ n t τ τ'} : ⟪ Γ ⊢ t : F.tsum (UValFI n τ) (UValFI n τ') ⟫ → ⟪ Γ ⊢ F.inl t : UValFI (S n) (I.tsum τ τ') ⟫.
Proof.
intuition.
Qed.
(* Lemma inSum_Value {n v} : Value v → Value (inSum n v). *)
(* Proof. *)
(* simpl; trivial. *)
(* Qed. *)
(* (t : F.Tm) {P : F.Typing t (UValFI n I.tunit)} : F.Tm := *)
Definition case_uvalfi_unit (n : nat) : F.Tm :=
let τ := UValFI (S n) I.tunit in
let t := F.caseof (F.var 0) (F.var 0) (F.Om F.tunit) in
F.abs τ t.
Definition case_uvalfi_arr (n : nat) (τ1 τ2 : I.Ty) : F.Tm :=
let τ := @UValFI (S n) (I.tarr τ1 τ2) in
let τ' := F.tarr (UValFI n τ1) (UValFI n τ2) in
let t := F.caseof (F.var 0) (F.var 0) (F.Om τ') in
F.abs τ t.
Lemma uvalfi_expand_arr {n τ1 τ2} :
UValFI (S n) (I.tarr τ1 τ2) = F.tsum (F.tarr (UValFI n τ1) (UValFI n τ2)) F.tunit.
Proof.
reflexivity.
Qed.
Lemma case_uval_arr_typing {Γ n τ1 τ2} :
let τ := I.tarr τ1 τ2 in
let uval_dest := case_uvalfi_arr n τ1 τ2 in
let arg_type := UValFI (S n) τ in
let ret_type := F.tarr (UValFI n τ1) (UValFI n τ2) in
let type := F.tarr arg_type ret_type in
F.Typing Γ uval_dest type.
Proof.
intros.
unfold uval_dest.
unfold type.
unfold arg_type.
unfold ret_type.
(* unfold uval_dest, arg_type, ret_type, type, case_uvalfi_arr. *)
(* crushTyping. *)
constructor.
unfold τ.
apply (@F.WtCaseof (F.evar Γ arg_type) (F.var 0) (F.var 0) (F.Om ret_type) ret_type F.tunit ret_type).
unfold arg_type.
unfold ret_type.
constructor.
simpl.
constructor.
constructor.
constructor.
apply wtOm_tau.
Qed.
Definition case_uvalfi_tsum (n : nat) (τ1 τ2 : I.Ty) : F.Tm :=
let τ := UValFI (S n) (I.tsum τ1 τ2) in
let τ' := F.tsum (UValFI n τ1) (@UValFI n τ2) in
let t := F.caseof (F.var 0) (F.var 0) (F.Om τ') in
F.abs τ t.
Definition case_uvalfi_trec (n : nat) (τb : I.Ty) : F.Tm :=
let τ_rec := I.trec τb in
let τ := UValFI (S n) τ_rec in
let τ' := UValFI n τb[beta1 τ_rec] in
let t := F.caseof (F.var 0) (F.var 0) (F.Om τ') in
F.abs τ t.
Definition caseV0 (case₁ : F.Tm) (case₂ : F.Tm) : F.Tm :=
F.caseof (F.var 0) (case₁ [wkm↑]) (case₂[wkm↑]).
Lemma caseV0_T {Γ : F.Env} {τ₁ τ₂ τ : F.Ty} {case₁ case₂ : F.Tm} :
F.Typing (F.evar Γ τ₁) case₁ τ →
F.Typing (F.evar Γ τ₂) case₂ τ →
F.Typing (F.evar Γ (F.tsum τ₁ τ₂)) (caseV0 case₁ case₂) τ.
Proof.
unfold caseV0.
F.crushTyping.
Qed.
#[export]
Hint Resolve caseV0_T : uval_typing.
Definition caseUVal_pctx (τ : F.Ty) := F.pcaseof₁ F.phole (F.var 0) (stlcOmega τ).
Definition caseUVal_pctxA (τ : F.Ty) := F.a_pcaseof₁ τ F.tunit τ F.a_phole (F.a_var 0) (stlcOmegaA τ).
Definition caseUnit_pctx := caseUVal_pctx F.tunit.
Definition caseUnit_pctxA (n : nat) := caseUVal_pctxA F.tunit.
Definition caseBool_pctx := caseUVal_pctx F.tbool.
Definition caseBool_pctxA (n : nat) := caseUVal_pctxA F.tbool.
Definition caseProd_pctx (n : nat) (τ1 τ2 : I.Ty) := caseUVal_pctx (F.tprod (UValFI n τ1) (UValFI n τ2)).
Definition caseProd_pctxA (n : nat) (τ1 τ2 : I.Ty) := caseUVal_pctxA (F.tprod (UValFI n τ1) (UValFI n τ2)).
Definition caseSum_pctx (n : nat) (τ1 τ2 : I.Ty) := caseUVal_pctx (F.tsum (UValFI n τ1) (UValFI n τ2)).
Definition caseSum_pctxA (n : nat) (τ1 τ2 : I.Ty) := caseUVal_pctxA (F.tsum (UValFI n τ1) (UValFI n τ2)).
Definition caseArr_pctx (n : nat) (τ1 τ2 : I.Ty) := caseUVal_pctx (F.tarr (UValFI n τ1) (UValFI n τ2)).
Definition caseArr_pctxA (n : nat) (τ1 τ2 : I.Ty) := caseUVal_pctxA (F.tarr (UValFI n τ1) (UValFI n τ2)).
Definition caseRec_pctx (n : nat) (τ : I.Ty) := caseUVal_pctx (UValFI n τ[beta1 (I.trec τ)]).
Definition caseRec_pctxA (n : nat) (τ : I.Ty) := caseUVal_pctxA (UValFI n τ[beta1 (I.trec τ)]).
Definition caseUVal (τ : F.Ty) (t : F.Tm) := F.pctx_app t (caseUVal_pctx τ).
Definition caseUValA (τ : F.Ty) (t : F.TmA) := F.pctxA_app t (caseUVal_pctxA τ).
(* Definition caseUValIso (n : nat) (τ : I.Ty) (t : F.Tm) := caseUVal (UValFI n τ) t. *)
(* Definition caseUValIsoA (n : nat) (τ' τ : I.Ty) (t : F.Tm) := caseUVal (UValFI n τ) t. *)
Arguments caseUVal_pctx τ : simpl never.
Arguments caseUVal τ t : simpl never.
Definition caseUnit t := F.pctx_app t caseUnit_pctx.
Definition caseUnitA n t := F.pctxA_app t (caseUnit_pctxA n).
Definition caseBool t := F.pctx_app t caseBool_pctx.
Definition caseBoolA n t := F.pctxA_app t (caseBool_pctxA n).
Definition caseSum n t τ1 τ2 := F.pctx_app t (caseSum_pctx n τ1 τ2).
Definition caseSumA n t τ1 τ2 := F.pctxA_app t (caseSum_pctxA n τ1 τ2).
Definition caseProd n t τ1 τ2 := F.pctx_app t (caseProd_pctx n τ1 τ2).
Definition caseProdA n t τ1 τ2 := F.pctxA_app t (caseProd_pctxA n τ1 τ2).
Definition caseArr n t τ1 τ2 := F.pctx_app t (caseArr_pctx n τ1 τ2).
Definition caseArrA n t τ1 τ2 := F.pctxA_app t (caseArr_pctxA n τ1 τ2).
Definition caseRec n t τ := F.pctx_app t (caseRec_pctx n τ).
Definition caseRecA n t τ := F.pctxA_app t (caseRec_pctxA n τ).
Lemma caseUnit_pctx_T {Γ n} :
⟪ ⊢ caseUnit_pctx : Γ, UValFI (S n) I.tunit → Γ, F.tunit ⟫.
Proof.
unfold caseUnit_pctx, caseUVal_pctx.
eauto with typing uval_typing.
Qed.
Lemma caseUnit_pctxA_T {Γ n} :
⟪ a⊢ caseUnit_pctxA n : Γ, UValFI (S n) I.tunit → Γ, F.tunit ⟫.
Proof.
unfold caseUnit_pctxA, caseUVal_pctxA.
cbn.
repeat constructor.
Qed.
Lemma caseUnit_T {Γ n t} :
⟪ Γ ⊢ t : UValFI (S n) I.tunit ⟫ →
⟪ Γ ⊢ caseUnit t : F.tunit ⟫.
Proof.
unfold caseUnit; eauto using caseUnit_pctx_T with typing uval_typing.
Qed.
Lemma caseUnitA_T {Γ n t} :
⟪ Γ a⊢ t : UValFI (S n) I.tunit ⟫ →
⟪ Γ a⊢ caseUnitA n t : F.tunit ⟫.
Proof.
unfold caseUnitA; eauto using caseUnit_pctxA_T with typing uval_typing.
Qed.
Lemma caseUnit_pctx_ectx : ECtx caseUnit_pctx.
Proof. simpl; trivial. Qed.
Lemma caseBool_pctx_T {Γ n} :
⟪ ⊢ caseBool_pctx : Γ, UValFI (S n) I.tbool → Γ, F.tbool ⟫.
Proof.
unfold caseBool_pctx, caseUVal_pctx.
eauto with typing uval_typing.
Qed.
Lemma caseBool_pctxA_T {Γ n} :
⟪ a⊢ caseBool_pctxA n : Γ, UValFI (S n) I.tbool → Γ, F.tbool ⟫.
Proof.
unfold caseBool_pctxA, caseUVal_pctxA.
cbn.
repeat constructor.
Qed.
Lemma caseBool_T {Γ n t} :
⟪ Γ ⊢ t : UValFI (S n) I.tbool ⟫ →
⟪ Γ ⊢ caseBool t : F.tbool ⟫.
Proof.
unfold caseBool; eauto using caseBool_pctx_T with typing uval_typing.
Qed.
Lemma caseBoolA_T {Γ n t} :
⟪ Γ a⊢ t : UValFI (S n) I.tbool ⟫ →
⟪ Γ a⊢ caseBoolA n t : F.tbool ⟫.
Proof.
unfold caseBoolA; eauto using caseBool_pctxA_T with typing uval_typing.
Qed.
Lemma caseBool_pctx_ectx : ECtx caseBool_pctx.
Proof. simpl; trivial. Qed.
Lemma caseSum_pctx_T {Γ n τ1 τ2} :
⟪ ⊢ caseSum_pctx n τ1 τ2 : Γ, UValFI (S n) (I.tsum τ1 τ2) → Γ, F.tsum (UValFI n τ1) (UValFI n τ2) ⟫.
Proof.
unfold caseSum_pctx, caseUVal_pctx.
eauto with typing uval_typing.
Qed.
Lemma caseSum_pctxA_T {Γ n τ1 τ2} :
⟪ a⊢ caseSum_pctxA n τ1 τ2 : Γ, UValFI (S n) (I.tsum τ1 τ2) → Γ, F.tsum (UValFI n τ1) (UValFI n τ2) ⟫.
Proof.
unfold caseSum_pctxA, caseUVal_pctxA.
repeat constructor.
Qed.
Lemma caseSum_T {Γ n t τ1 τ2} :
⟪ Γ ⊢ t : UValFI (S n) (I.tsum τ1 τ2) ⟫ →
⟪ Γ ⊢ caseSum n t τ1 τ2 : F.tsum (UValFI n τ1) (UValFI n τ2) ⟫.
Proof.
unfold caseSum; eauto using caseSum_pctx_T with typing uval_typing.
Qed.
Lemma caseSumA_T {Γ n t τ1 τ2} :
⟪ Γ a⊢ t : UValFI (S n) (I.tsum τ1 τ2) ⟫ →
⟪ Γ a⊢ caseSumA n t τ1 τ2 : F.tsum (UValFI n τ1) (UValFI n τ2) ⟫.
Proof.
unfold caseSumA; eauto using caseSum_pctxA_T with typing uval_typing.
Qed.
Lemma caseSum_pctx_ectx {n τ τ'} : ECtx (caseSum_pctx n τ τ').
Proof. simpl; trivial. Qed.
Lemma eraseAnnot_caseSumA {n t τ₁ τ₂} :
eraseAnnot (caseSumA n t τ₁ τ₂) = caseSum n (eraseAnnot t) τ₁ τ₂.
Proof.
now cbn.
Qed.
Lemma caseProd_pctx_T {Γ n τ1 τ2} :
⟪ ⊢ caseProd_pctx n τ1 τ2 : Γ, UValFI (S n) (I.tprod τ1 τ2) → Γ, F.tprod (UValFI n τ1) (UValFI n τ2) ⟫.
Proof.
unfold caseProd_pctx, caseUVal_pctx.
eauto with typing uval_typing.
Qed.
Lemma caseProd_pctxA_T {Γ n τ1 τ2} :
⟪ a⊢ caseProd_pctxA n τ1 τ2 : Γ, UValFI (S n) (I.tprod τ1 τ2) → Γ, F.tprod (UValFI n τ1) (UValFI n τ2) ⟫.
Proof.
unfold caseProd_pctxA, caseUVal_pctxA.
repeat constructor.
Qed.
Lemma caseProd_T {Γ n t τ1 τ2} :
⟪ Γ ⊢ t : UValFI (S n) (I.tprod τ1 τ2) ⟫ →
⟪ Γ ⊢ caseProd n t τ1 τ2 : F.tprod (UValFI n τ1) (UValFI n τ2) ⟫.
Proof.
unfold caseProd; eauto using caseProd_pctx_T with typing uval_typing.
Qed.
Lemma caseProdA_T {Γ n t τ1 τ2} :
⟪ Γ a⊢ t : UValFI (S n) (I.tprod τ1 τ2) ⟫ →
⟪ Γ a⊢ caseProdA n t τ1 τ2 : F.tprod (UValFI n τ1) (UValFI n τ2) ⟫.
Proof.
unfold caseProdA; eauto using caseProd_pctxA_T with typing uval_typing.
Qed.
Lemma caseProd_pctx_ectx {n τ τ'} : ECtx (caseProd_pctx n τ τ').
Proof. simpl; trivial. Qed.
Lemma eraseAnnot_caseProdA {n t τ₁ τ₂} :
eraseAnnot (caseProdA n t τ₁ τ₂) = caseProd n (eraseAnnot t) τ₁ τ₂.
Proof.
now cbn.
Qed.
Lemma caseArr_pctx_T {Γ n τ1 τ2} :
⟪ ⊢ caseArr_pctx n τ1 τ2 : Γ, UValFI (S n) (I.tarr τ1 τ2) → Γ, F.tarr (UValFI n τ1) (UValFI n τ2) ⟫.
Proof.
unfold caseArr_pctx, caseUVal_pctx.
eauto with typing uval_typing.
Qed.
Lemma caseArr_pctxA_T {Γ n τ1 τ2} :
⟪ a⊢ caseArr_pctxA n τ1 τ2 : Γ, UValFI (S n) (I.tarr τ1 τ2) → Γ, F.tarr (UValFI n τ1) (UValFI n τ2) ⟫.
Proof.
unfold caseArr_pctxA, caseUVal_pctxA.
repeat constructor.
Qed.
Lemma caseArr_T {Γ n t τ1 τ2} :
⟪ Γ ⊢ t : UValFI (S n) (I.tarr τ1 τ2) ⟫ →
⟪ Γ ⊢ caseArr n t τ1 τ2 : F.tarr (UValFI n τ1) (UValFI n τ2) ⟫.
Proof.
unfold caseArr; eauto using caseArr_pctx_T with typing uval_typing.
Qed.
Lemma caseArrA_T {Γ n t τ1 τ2} :
⟪ Γ a⊢ t : UValFI (S n) (I.tarr τ1 τ2) ⟫ →
⟪ Γ a⊢ caseArrA n t τ1 τ2 : F.tarr (UValFI n τ1) (UValFI n τ2) ⟫.
Proof.
unfold caseArrA; eauto using caseArr_pctxA_T with typing uval_typing.
Qed.
Lemma caseArr_pctx_ectx {n τ τ'} : ECtx (caseArr_pctx n τ τ').
Proof. simpl; trivial. Qed.
Lemma eraseAnnot_caseArrA {n t τ₁ τ₂} :
eraseAnnot (caseArrA n t τ₁ τ₂) = caseArr n (eraseAnnot t) τ₁ τ₂.
Proof.
now cbn.
Qed.
Lemma caseRec_pctx_T {Γ n τ} :
⟪ ⊢ caseRec_pctx n τ : Γ, UValFI (S n) (I.trec τ) → Γ, UValFI n τ[beta1 (I.trec τ)] ⟫.
Proof.
unfold caseRec_pctx, caseUVal_pctx.
eauto with typing uval_typing.
Qed.
Lemma caseRec_T {Γ n t τ} :
⟪ Γ ⊢ t : UValFI (S n) (I.trec τ) ⟫ →
⟪ Γ ⊢ caseRec n t τ : UValFI n τ[beta1 (I.trec τ)] ⟫.
Proof.
unfold caseRec; eauto using caseRec_pctx_T with typing uval_typing.
Qed.
Lemma caseRec_pctxA_T {Γ n τ} :
⟪ a⊢ caseRec_pctxA n τ : Γ, UValFI (S n) (I.trec τ) → Γ, UValFI n τ[beta1 (I.trec τ)] ⟫.
Proof.
unfold caseRec_pctxA, caseUVal_pctxA.
repeat constructor.
Qed.
Lemma caseRecA_T {Γ n t τ} :
⟪ Γ a⊢ t : UValFI (S n) (I.trec τ) ⟫ →
⟪ Γ a⊢ caseRecA n t τ : UValFI n τ[beta1 (I.trec τ)] ⟫.
Proof.
unfold caseRecA; eauto using caseRec_pctxA_T with typing uval_typing.
Qed.
Lemma caseRec_pctx_ectx {n τ} : ECtx (caseRec_pctx n τ).
Proof. simpl; trivial. Qed.
Lemma eraseAnnot_caseRecA {n t τ} :
eraseAnnot (caseRecA n t τ) = caseRec n (eraseAnnot t) τ.
Proof.
now cbn.
Qed.
#[export]
Hint Resolve caseUnit_T : uval_typing.
#[export]
Hint Resolve caseSum_T : uval_typing.
#[export]
Hint Resolve caseArr_T : uval_typing.
#[export]
Hint Resolve caseRec_T : uval_typing.
#[export]
Hint Resolve caseUnitA_T : uval_typing.
#[export]
Hint Resolve caseSumA_T : uval_typing.
#[export]
Hint Resolve caseArrA_T : uval_typing.
#[export]
Hint Resolve caseRecA_T : uval_typing.
(* Lemma caseUVal_eval_bool {n tunk tcunit tcbool tcprod tcsum tcarr v} : *)
(* Value v → *)
(* caseUVal (inBool n v) tunk tcunit tcbool tcprod tcsum tcarr -->* tcbool [beta1 v]. *)
(* Proof. *)
(* intros vv. *)
(* unfold caseUVal, inBool; simpl. *)
(* crushEvalsInCaseUVal. *)
(* Qed. *)
(* Lemma caseUVal_pctx_T {Γ n tunk tcunit tcbool tcprod tcsum tcarr τ} : *)
(* ⟪ Γ ⊢ tunk : τ ⟫ → *)
(* ⟪ Γ ▻ tunit ⊢ tcunit : τ ⟫ → *)
(* ⟪ Γ ▻ tbool ⊢ tcbool : τ ⟫ → *)
(* (* ⟪ Γ ▻ (UVal n × UVal n) ⊢ tcprod : τ ⟫ → *) *)
(* ⟪ Γ ▻ (UVal n ⊎ UVal n) ⊢ tcsum : τ ⟫ → *)
(* ⟪ Γ ▻ (UVal n ⇒ UVal n) ⊢ tcarr : τ ⟫ → *)
(* ⟪ ⊢ caseUVal_pctx tunk tcunit tcbool tcprod tcsum tcarr : Γ , UVal (S n) → Γ , τ ⟫. *)
(* Proof. *)
(* unfold caseUVal_pctx. *)
(* crushTyping. *)
(* eauto with typing uval_typing. *)
(* Qed. *)
(* Lemma caseUVal_T {Γ n tscrut tunk tcunit tcbool tcprod tcsum tcarr τ} : *)
(* ⟪ Γ ⊢ tscrut : UVal (S n) ⟫ → *)
(* ⟪ Γ ⊢ tunk : τ ⟫ → *)
(* ⟪ Γ ▻ tunit ⊢ tcunit : τ ⟫ → *)
(* ⟪ Γ ▻ tbool ⊢ tcbool : τ ⟫ → *)
(* ⟪ Γ ▻ (UVal n × UVal n) ⊢ tcprod : τ ⟫ → *)
(* ⟪ Γ ▻ (UVal n ⊎ UVal n) ⊢ tcsum : τ ⟫ → *)
(* ⟪ Γ ▻ (UVal n ⇒ UVal n) ⊢ tcarr : τ ⟫ → *)
(* ⟪ Γ ⊢ caseUVal tscrut tunk tcunit tcbool tcprod tcsum tcarr : τ ⟫. *)
(* Proof. *)
(* unfold caseUVal. *)
(* eauto using caseUVal_pctx_T with typing. *)
(* Qed. *)
Arguments UValFI n : simpl never.
#[export]
Hint Resolve unkUValT : uval_typing.
#[export]
Hint Resolve inUnitT : uval_typing.
#[export]
Hint Resolve inBoolT : uval_typing.
#[export]
Hint Resolve inProd_T : uval_typing.
#[export]
Hint Resolve inSum_T : uval_typing.
#[export]
Hint Resolve inArr_T : uval_typing.
(* #[export]
Hint Resolve inUnit_pctx_T : uval_typing. *)
(* #[export]
Hint Resolve inBool_pctx_T : uval_typing. *)
(* #[export]
Hint Resolve inProd_pctx_T : uval_typing. *)
(* #[export]
Hint Resolve inSum_pctx_T : uval_typing. *)
(* #[export]
Hint Resolve inArr_pctx_T : uval_typing. *)
(* #[export]
Hint Resolve caseUVal_pctx_T : uval_typing. *)
(* #[export]
Hint Resolve caseUVal_T : uval_typing. *)
Local Ltac crush :=
repeat (subst*;
repeat rewrite
(* ?protect_wkm_beta1, ?protect_wkm2_beta1, *)
(* ?confine_wkm_beta1, ?confine_wkm2_beta1, *)
?apply_wkm_beta1_up_cancel;
(* ?apply_up_def_S; *)
repeat crushDbLemmasMatchH;
repeat crushDbSyntaxMatchH;
repeat crushStlcSyntaxMatchH;
repeat crushTypingMatchH2;
repeat crushTypingMatchH;
repeat match goal with
[ |- _ ∧ _ ] => split
end;
trivial;
eauto with ws typing uval_typing eval
).
Lemma caseV0_eval_inl {v case₁ case₂ : F.Tm}:
F.Value v →
F.eval (caseV0 case₁ case₂)[beta1 (F.inl v)] (case₁ [beta1 v]).
Proof.
intros vv.
unfold caseV0; apply F.eval₀_to_eval; crush.
change ((F.caseof (F.var 0) case₁[wkm↑] case₂ [wkm↑])[beta1 (F.inl v)]) with
(F.caseof (F.inl v) (case₁[wkm↑][(beta1 (F.inl v))↑]) (case₂[wkm↑][(beta1 (F.inl v))↑])).
crush.
Qed.
Lemma caseV0_eval_inr {v case₁ case₂ : F.Tm}:
F.Value v →
F.eval (caseV0 case₁ case₂)[beta1 (F.inr v)] (case₂ [beta1 v]).
Proof.
intros vv.
unfold caseV0; apply F.eval₀_to_eval; crush.
change ((F.caseof (F.var 0) case₁[wkm↑] case₂ [wkm↑])[beta1 (F.inr v)]) with
(F.caseof (F.inr v) (case₁[wkm↑][(beta1 (F.inr v))↑]) (case₂[wkm↑][(beta1 (F.inr v))↑])).
crush.
Qed.
Lemma caseV0_eval {v τ₁ τ₂ case₁ case₂}:
F.Value v → F.Typing F.empty v (F.tsum τ₁ τ₂) →
(exists v', v = F.inl v' ∧ F.eval (caseV0 case₁ case₂)[beta1 v] case₁[beta1 v']) ∨
(exists v', v = F.inr v' ∧ F.eval (caseV0 case₁ case₂)[beta1 v] case₂[beta1 v']).
Proof.
intros vv ty.
F.stlcCanForm; [left|right]; exists x;
crush; eauto using caseV0_eval_inl, caseV0_eval_inr.
Qed.
Local Ltac crushEvalsInCaseUVal :=
repeat
(match goal with
[ |- (F.evalStar (F.caseof (F.inl _) _ _) _) ] => (eapply (evalStepStar _); [eapply F.eval₀_to_eval; crush|])
| [ |- (F.evalStar (F.caseof (F.inr _) _ _) _) ] => (eapply (evalStepStar _); [eapply F.eval₀_to_eval; crush|])
| [ |- (F.evalStar ((caseV0 _ _) [beta1 (F.inl _)]) _) ] => (eapply (evalStepStar _); [eapply caseV0_eval_inl; crush|])
| [ |- (F.evalStar ((caseV0 _ _) [beta1 (F.inr _)]) _) ] => (eapply (evalStepStar _); [eapply caseV0_eval_inr; crush|])
| [ |- (F.evalStar ?t ?t) ] => eauto with *
end;
try rewrite -> apply_wkm_beta1_cancel
).
Lemma caseUVal_eval_unk_diverges {n τ} :
not (F.Terminating (caseUVal τ (unkUVal (S n)))).
Proof.
unfold caseUVal, unkUVal; simpl.
eapply F.divergence_closed_under_eval.
apply F.eval₀_to_eval.
apply F.eval_case_inr.
simpl; trivial.
apply stlcOmega_div.
Qed.
Lemma caseUnit_eval_unk_diverges {n} :
(caseUnit (unkUVal (S n)))⇑.
Proof.
unfold caseUnit, unkUVal; simpl.
eapply F.divergence_closed_under_eval.
apply F.eval₀_to_eval.
apply F.eval_case_inr.
simpl; trivial.
apply stlcOmega_div.
Qed.
Lemma caseArr_eval_unk_diverges {n τ1 τ2} :
(caseArr n (unkUVal (S n)) τ1 τ2)⇑.
Proof.
unfold caseArr, unkUVal; simpl.
eapply F.divergence_closed_under_eval.
apply F.eval₀_to_eval.
apply F.eval_case_inr.
simpl; trivial.
apply stlcOmega_div.
Qed.
Lemma caseSum_eval_unk_diverges {n τ1 τ2} :
(caseSum n (unkUVal (S n)) τ1 τ2)⇑.
Proof.
unfold caseSum, unkUVal; simpl.
eapply F.divergence_closed_under_eval.
apply F.eval₀_to_eval.
apply F.eval_case_inr.
simpl; trivial.
apply stlcOmega_div.
Qed.
Lemma caseRec_eval_unk_diverges {n τ} :
(caseRec n (unkUVal (S n)) τ)⇑.
Proof.
unfold caseRec, unkUVal; simpl.
eapply F.divergence_closed_under_eval.
apply F.eval₀_to_eval.
apply F.eval_case_inr.
simpl; trivial.
apply stlcOmega_div.
Qed.
Lemma caseUVal_eval_left {v τ}:
Value v →
caseUVal τ (F.inl v) -->* v.
Proof.
intro vv.
unfold caseUVal; simpl.
eapply (evalStepStar _).
apply eval₀_to_eval.
apply eval_case_inl.
simpl; trivial.
eauto with eval.
Qed.
Lemma canonUValS_Unit {n v} :
F.Value v →
⟪ F.empty ⊢ v : UValFI (S n) I.tunit ⟫ →
(v = F.inl F.unit) ∨ (v = F.inr F.unit).
Proof.
unfold UValFI.
intros.
destruct (F.can_form_tsum H H0) as [(? & ? & ?) | (? & ? & ?)];
[left | right];
assert (F.Value x) by (
subst;
cbn in H;
assumption);
pose proof (F.can_form_tunit H3 H2);
rewrite H4 in H1;
assumption.
Qed.
Lemma canonUValS_Bool {n v} :
F.Value v →
⟪ F.empty ⊢ v : UValFI (S n) I.tbool ⟫ →
(v = F.inl F.true) ∨ (v = F.inl F.false) ∨ (v = F.inr F.unit).
Proof.
unfold UValFI.
intros.
destruct (F.can_form_tsum H H0) as [(? & ? & ?) | (? & ? & ?)];
subst; cbn in H; F.stlcCanForm.
- now left.
- now right; left.
- now right; right.
Qed.
Lemma canonUValS_Arr {n v τ τ'} :
F.Value v →
⟪ F.empty ⊢ v : UValFI (S n) (I.tarr τ τ') ⟫ →
(exists v', F.Value v' ∧ (v = F.inl v') ∧ ⟪ F.empty ⊢ v' : F.tarr (UValFI n τ) (UValFI n τ')⟫) ∨ (v = F.inr F.unit).
Proof.
unfold UValFI.
intros vv ty.
destruct (F.can_form_tsum vv ty) as [(? & ? & ?) | (? & ? & ?)];
[left | right].
exists x.
split.
subst.
cbn in vv.
assumption.
split.
assumption.
assumption.
assert (F.Value x) by (
subst;
cbn in vv;
assumption
).
pose proof (F.can_form_tunit H1 H0).
rewrite H2 in H.
assumption.
Qed.
Lemma canonUValS_Sum {n v τ τ'} :
F.Value v →
⟪ F.empty ⊢ v : UValFI (S n) (I.tsum τ τ') ⟫ →
(exists v', F.Value v' ∧ (v = F.inl v') ∧ ⟪ F.empty ⊢ v' : F.tsum (UValFI n τ) (UValFI n τ')⟫) ∨ (v = F.inr F.unit).
Proof.
unfold UValFI.
intros vv ty.
destruct (F.can_form_tsum vv ty) as [(? & ? & ?) | (? & ? & ?)];
[left | right].
exists x.
split.
subst.
cbn in vv.
assumption.
split.
assumption.
assumption.
assert (F.Value x) by (
subst;
cbn in vv;
assumption
).
pose proof (F.can_form_tunit H1 H0).
rewrite H2 in H.
assumption.
Qed.
Lemma canonUValS_Prod {n v τ τ'} :
F.Value v →
⟪ F.empty ⊢ v : UValFI (S n) (I.tprod τ τ') ⟫ →
(exists v', F.Value v' ∧ (v = F.inl v') ∧ ⟪ F.empty ⊢ v' : F.tprod (UValFI n τ) (UValFI n τ')⟫) ∨
(v = F.inr F.unit).
Proof.
unfold UValFI.
intros vv ty.
cbn in *.
stlcCanForm.
- left. exists (F.pair x0 x1).
crush.
- now right.
Qed.
Lemma canonUValS_Rec {n v τ} :
F.Value v →
⟪ F.empty ⊢ v : UValFI (S n) (I.trec τ) ⟫ →
(exists v', F.Value v' ∧ (v = F.inl v') ∧ ⟪ F.empty ⊢ v' : UValFI n τ[beta1 (I.trec τ)] ⟫) ∨ (v = F.inr F.unit).
Proof.
unfold UValFI.
intros vv ty.
destruct (F.can_form_tsum vv ty) as [(? & ? & ?) | (? & ? & ?)];
[left | right].
exists x.
split.
subst.
cbn in vv.
assumption.
split.
assumption.
assumption.
assert (F.Value x) by (
subst;
cbn in vv;
assumption
).
pose proof (F.can_form_tunit H1 H0).
rewrite H2 in H.
assumption.
Qed.
(* Lemma canonUVal_Arr {n v τ τ'} : *)
(* F.Value v → *)
(* ⟪ F.empty ⊢ v : UValFI n (I.tarr τ τ') ⟫ → *)
(* (v = F.unit) ∨ (exists v', F.Value v' ∧ (v = F.inl v') ∧ ⟪ F.empty ⊢ v' : F.tarr (UValFI n τ) (UValFI n τ')⟫) ∨ (v = F.inr F.unit). *)
(* Proof. *)
(* intros. *)
(* destruct n as [? | ?]. *)
(* left. *)
(* unfold UValFI in H0. *)
(* F.stlcCanForm. *)
(* reflexivity. *)
(* right. *)
(* apply (canonUValS_Arr H). *)
(* NOTE: for compatibility lemmas, we might need a UVal context and accompanying lemmas *)
(* Lemma canonUValS {n v} : *)
(* ⟪ empty ⊢ v : UVal (S n) ⟫ → Value v → *)
(* (v = unkUVal (S n)) ∨ *)
(* (∃ v', v = inUnit n v' ∧ Value v' ∧ ⟪ empty ⊢ v' : tunit ⟫) ∨ *)
(* (∃ v', v = inBool n v' ∧ Value v' ∧ ⟪ empty ⊢ v' : tbool ⟫) ∨ *)
(* (∃ v', v = inProd n v' ∧ Value v' ∧ ⟪ empty ⊢ v' : UVal n × UVal n ⟫) ∨ *)
(* (∃ v', v = inSum n v' ∧ Value v' ∧ ⟪ empty ⊢ v' : UVal n ⊎ UVal n ⟫) ∨ *)
(* (∃ v', v = inArr n v' ∧ Value v' ∧ ⟪ empty ⊢ v' : UVal n ⇒ UVal n ⟫). *)
(* Proof. *)
(* intros ty vv. *)
(* unfold UVal in ty; simpl. *)
(* (* Apply canonical form lemmas but only as far as we need. *) *)
(* stlcCanForm1; *)
(* [left|right;stlcCanForm1; *)
(* [left|right;stlcCanForm1; *)
(* [left|right;stlcCanForm1; *)
(* [left|right;stlcCanForm1; *)
(* [right|left]]]]]. *)
(* - stlcCanForm; crush. *)
(* - exists x0; crush. *)
(* - exists x; crush. *)
(* - exists x0; crush. *)
(* - exists x; crush. *)
(* - exists x; crush. *)
(* Qed. *)
(* Lemma canonUVal {n v} : *)
(* ⟪ empty ⊢ v : UVal n ⟫ → Value v → *)
(* (v = unkUVal n) ∨ *)
(* ∃ n', n = S n' ∧ *)
(* ((∃ v', v = inUnit n' v' ∧ Value v' ∧ ⟪ empty ⊢ v' : tunit ⟫) ∨ *)
(* (∃ v', v = inBool n' v' ∧ Value v' ∧ ⟪ empty ⊢ v' : tbool ⟫) ∨ *)
(* (∃ v', v = inProd n' v' ∧ Value v' ∧ ⟪ empty ⊢ v' : UVal n' × UVal n' ⟫) ∨ *)
(* (∃ v', v = inSum n' v' ∧ Value v' ∧ ⟪ empty ⊢ v' : UVal n' ⊎ UVal n' ⟫) ∨ *)
(* (∃ v', v = inArr n' v' ∧ Value v' ∧ ⟪ empty ⊢ v' : UVal n' ⇒ UVal n' ⟫)). *)
(* Proof. *)
(* intros ty vv. *)
(* destruct n. *)
(* - left. unfold UVal, unkUVal in *. stlcCanForm. trivial. *)
(* - destruct (canonUValS ty vv) as [? | ?]. *)
(* + left; crush. *)
(* + right; crush. *)
(* Qed. *)
(* Ltac canonUVal := *)
(* match goal with *)
(* [ H : Value ?v, H' : ⟪ empty ⊢ ?v : UVal 0 ⟫ |- _ ] => *)
(* (unfold UVal in H'; stlcCanForm; subst) *)
(* | [ H : Value ?v, H' : ⟪ empty ⊢ ?v : UVal (S _) ⟫ |- _ ] => *)
(* (destruct (canonUValS H' H) as *)
(* [?| [(? & ? & ? & ?) *)
(* |[(? & ? & ? & ?) *)
(* |[(? & ? & ? & ?) *)
(* |[(? & ? & ? & ?) *)
(* |(? & ? & ? & ?)]]]]]; subst) *)
(* | [ H : Value ?v, H' : ⟪ empty ⊢ ?v : UVal (S _ + _) ⟫ |- _ ] => *)
(* (destruct (canonUValS H' H) as *)
(* [?| [(? & ? & ? & ?) *)
(* |[(? & ? & ? & ?) *)
(* |[(? & ? & ? & ?) *)
(* |[(? & ? & ? & ?) *)
(* |(? & ? & ? & ?)]]]]]; subst) *)
(* | [ H : Value ?v, H' : ⟪ empty ⊢ ?v : UVal _ ⟫ |- _ ] => *)
(* (destruct (canonUVal H' H) as *)
(* [?| (? & ? & [(? & ? & ? & ?) *)
(* |[(? & ? & ? & ?) *)
(* |[(? & ? & ? & ?) *)
(* |[(? & ? & ? & ?) *)
(* |(? & ? & ? & ?)]]]])]; subst) *)
(* end. *)
(* Lemma caseUVal_eval_unk {n : nat} {tunk tcunit tcbool tcprod tcsum tcarr : F.Tm} : *)
(* F.evalStar (caseUVal (F.inr F.unit) tunk tcunit tcbool tcprod tcsum tcarr) tunk. *)
(* Proof. *)
(* unfold caseUVal, unkUVal; simpl. *)
(* (* why doesn't crush do the following? *) *)
(* assert (Value (inl unit)) by (simpl; trivial). *)
(* crushEvalsInCaseUVal. *)
(* eauto with *. *)
(* Qed. *)
(* Lemma caseUVal_eval_unit {n tunk tcunit tcbool tcprod tcsum tcarr v} : *)
(* Value v → *)
(* caseUVal (inUnit n v) tunk tcunit tcbool tcprod tcsum tcarr -->* tcunit [beta1 v]. *)
(* Proof. *)
(* intros vv. *)
(* unfold caseUVal, inUnit; simpl. *)
(* crushEvalsInCaseUVal. *)
(* Qed. *)
(* Lemma caseUVal_eval_bool {n tunk tcunit tcbool tcprod tcsum tcarr v} : *)
(* Value v → *)
(* caseUVal (inBool n v) tunk tcunit tcbool tcprod tcsum tcarr -->* tcbool [beta1 v]. *)
(* Proof. *)
(* intros vv. *)
(* unfold caseUVal, inBool; simpl. *)
(* crushEvalsInCaseUVal. *)
(* Qed. *)
(* Lemma caseUVal_eval_prod {n tunk tcunit tcbool tcprod tcsum tcarr v} : *)
(* Value v → *)
(* caseUVal (inProd n v) tunk tcunit tcbool tcprod tcsum tcarr -->* tcprod [beta1 v]. *)
(* Proof. *)
(* intros vv. *)
(* unfold caseUVal, inProd; simpl. *)
(* crushEvalsInCaseUVal. *)
(* Qed. *)
(* Lemma caseUVal_eval_sum {n tunk tcunit tcbool tcprod tcsum tcarr v} : *)
(* Value v → *)
(* caseUVal (inSum n v) tunk tcunit tcbool tcprod tcsum tcarr -->* tcsum [beta1 v]. *)
(* Proof. *)
(* intros vv. *)
(* unfold caseUVal, inSum; simpl. *)
(* crushEvalsInCaseUVal. *)
(* Qed. *)
(* Lemma caseUVal_eval_arr {n tunk tcunit tcbool tcprod tcsum tcarr v} : *)
(* Value v → *)
(* caseUVal (inArr n v) tunk tcunit tcbool tcprod tcsum tcarr -->* tcarr [beta1 v]. *)
(* Proof. *)
(* intros vv. *)
(* unfold caseUVal, inArr; simpl. *)
(* crushEvalsInCaseUVal. *)
(* Qed. *)
(* Lemma caseUVal_sub {t tunk tcunit tcbool tcprod tcsum tcarr} γ : *)
(* (caseUVal t tunk tcunit tcbool tcprod tcsum tcarr)[γ] = *)
(* caseUVal (t[γ]) (tunk[γ]) (tcunit[γ↑]) (tcbool[γ↑]) (tcprod[γ↑]) (tcsum[γ↑]) (tcarr[γ↑]). *)
(* Proof. *)
(* unfold caseUVal, caseUVal_pctx, caseV0. cbn. *)
(* crush; *)
(* rewrite <- ?apply_wkm_comm, <- ?(apply_wkm_up_comm); *)
(* reflexivity. *)
(* Qed. *)
(* Arguments caseUVal tscrut tunk tcunit tcbool tcprod tcsum tcarr : simpl never. *)
(* Arguments caseUVal_pctx tunk tcunit tcbool tcprod tcsum tcarr : simpl never. *)
(* Lemma caseUVal_pctx_ECtx {tunk tcunit tcbool tcprod tcsum tcarr} : *)
(* ECtx (caseUVal_pctx tunk tcunit tcbool tcprod tcsum tcarr). *)
(* Proof. *)
(* simpl; trivial. *)
(* Qed. *)
(* Definition caseUVal (n : nat) (tscrut tunk tcunit tcbool tcprod tcsum tcarr : Tm) := *)
(* Definition caseUnit_pctx := caseUVal_pctx (stlcOmega tunit) (var 0) (stlcOmega tunit) (stlcOmega tunit) (stlcOmega tunit) (stlcOmega tunit). *)
(* Definition caseBool_pctx := caseUVal_pctx (stlcOmega tbool) (stlcOmega tbool) (var 0) (stlcOmega tbool) (stlcOmega tbool) (stlcOmega tbool). *)
(* Definition caseProd_pctx n := caseUVal_pctx (stlcOmega (UVal n × UVal n)) (stlcOmega (UVal n × UVal n)) (stlcOmega (UVal n × UVal n)) (var 0) (stlcOmega (UVal n × UVal n)) (stlcOmega (UVal n × UVal n)). *)
(* Definition caseSum_pctx n := caseUVal_pctx (stlcOmega (UVal n ⊎ UVal n)) (stlcOmega (UVal n ⊎ UVal n)) (stlcOmega (UVal n ⊎ UVal n)) (stlcOmega (UVal n ⊎ UVal n)) (var 0) (stlcOmega (UVal n ⊎ UVal n)). *)
(* Definition caseArr_pctx n := caseUVal_pctx (stlcOmega (UVal n ⇒ UVal n)) (stlcOmega (UVal n ⇒ UVal n)) (stlcOmega (UVal n ⇒ UVal n)) (stlcOmega (UVal n ⇒ UVal n)) (stlcOmega (UVal n ⇒ UVal n)) (var 0). *)
(* Definition caseUnit t := pctx_app t caseUnit_pctx. *)
(* Definition caseBool t := pctx_app t caseBool_pctx. *)
(* Definition caseProd n t := pctx_app t (caseProd_pctx n). *)
(* Definition caseSum n t := pctx_app t (caseSum_pctx n). *)
(* Definition caseArr n t := pctx_app t (caseArr_pctx n). *)
(* Lemma caseUnit_pctx_ECtx : ECtx caseUnit_pctx. *)
(* Proof. *)
(* simpl; trivial. *)
(* Qed. *)
(* Lemma caseBool_pctx_ECtx : ECtx caseBool_pctx. *)
(* Proof. *)
(* simpl; trivial. *)
(* Qed. *)
(* Lemma caseProd_pctx_ECtx {n}: ECtx (caseProd_pctx n). *)
(* Proof. *)
(* simpl; trivial. *)
(* Qed. *)
(* Lemma caseSum_pctx_ECtx {n}: ECtx (caseSum_pctx n). *)
(* Proof. *)
(* simpl; trivial. *)
(* Qed. *)
(* Lemma caseArr_pctx_ECtx {n}: ECtx (caseArr_pctx n). *)
(* Proof. *)
(* simpl; trivial. *)
(* Qed. *)
Lemma caseUnit_sub {t γ} :
(caseUnit t) [γ] = caseUnit (t [γ]).
Proof.
unfold caseUnit; crush.
Qed.
(* Lemma caseBool_sub {t γ} : *)
(* caseBool t [γ] = caseBool (t [γ]). *)
(* Proof. *)
(* unfold caseBool; crush. *)
(* Qed. *)
(* Lemma caseProd_sub {n t γ} : *)
(* caseProd n t [γ] = caseProd n (t [γ]). *)
(* Proof. *)
(* unfold caseProd; crush. *)
(* Qed. *)
Lemma caseSum_sub {n t τ τ' γ} :
(caseSum n t τ τ') [γ] = caseSum n (t [γ]) τ τ'.
Proof.
unfold caseSum; crush.
Qed.
Lemma caseArr_sub {n t τ τ' γ} :
(caseArr n t τ τ') [γ] = caseArr n (t [γ]) τ τ'.
Proof.
unfold caseArr; crush.
Qed.
Lemma caseRec_sub {n t τ γ} :
(caseRec n t τ) [γ] = caseRec n (t [γ]) τ.
Proof.
unfold caseRec; crush.
Qed.
Arguments caseUnit t : simpl never.
Arguments caseSum n t τ1 τ2 : simpl never.
Arguments caseArr n t τ1 τ2 : simpl never.
Arguments caseRec n t τ : simpl never.
Arguments caseUnitA n t : simpl never.
Arguments caseSumA n t τ1 τ2 : simpl never.
Arguments caseArrA n t τ1 τ2 : simpl never.
Arguments caseRecA n t τ : simpl never.
(* Lemma caseUnit_pctx_T {Γ n} : *)
(* ⟪ ⊢ caseUnit_pctx : Γ , UVal (S n) → Γ , tunit ⟫. *)
(* Proof. *)
(* unfold caseUnit_pctx. *)
(* eauto with typing uval_typing. *)
(* Qed. *)
(* Lemma caseUnit_T {Γ n t} : *)
(* ⟪ Γ ⊢ t : UVal (S n) ⟫ → ⟪ Γ ⊢ caseUnit t : tunit ⟫. *)
(* Proof. *)
(* unfold caseUnit. *)
(* eauto using caseUnit_pctx_T with typing. *)
(* Qed. *)
(* Lemma caseBool_pctx_T {Γ n} : *)
(* ⟪ ⊢ caseBool_pctx : Γ , UVal (S n) → Γ , tbool ⟫. *)
(* Proof. *)
(* unfold caseBool_pctx. *)
(* eauto with typing uval_typing. *)
(* Qed. *)
(* Lemma caseBool_T {Γ n t} : *)
(* ⟪ Γ ⊢ t : UVal (S n) ⟫ → ⟪ Γ ⊢ caseBool t : tbool ⟫. *)
(* Proof. *)
(* unfold caseBool. *)
(* eauto using caseBool_pctx_T with typing. *)
(* Qed. *)
(* Lemma caseProd_pctx_T {Γ n} : *)
(* ⟪ ⊢ caseProd_pctx n : Γ , UVal (S n) → Γ , UVal n × UVal n ⟫. *)
(* Proof. *)
(* unfold caseProd_pctx. *)
(* eauto with typing uval_typing. *)
(* Qed. *)
(* Lemma caseProd_T {Γ n t} : *)
(* ⟪ Γ ⊢ t : UVal (S n) ⟫ → ⟪ Γ ⊢ caseProd n t : UVal n × UVal n ⟫. *)
(* Proof. *)
(* unfold caseProd. *)
(* eauto using caseProd_pctx_T with typing. *)
(* Qed. *)
(* Lemma caseSum_pctx_T {Γ n} : *)
(* ⟪ ⊢ caseSum_pctx n : Γ , UVal (S n) → Γ , UVal n ⊎ UVal n ⟫. *)
(* Proof. *)
(* unfold caseSum_pctx. *)
(* eauto with typing uval_typing. *)
(* Qed. *)
(* Lemma caseSum_T {Γ n t} : *)
(* ⟪ Γ ⊢ t : UVal (S n) ⟫ → ⟪ Γ ⊢ caseSum n t : UVal n ⊎ UVal n ⟫. *)
(* Proof. *)
(* unfold caseSum. *)
(* eauto using caseSum_pctx_T with typing. *)
(* Qed. *)
(* Lemma caseArr_pctx_T {Γ n} : *)
(* ⟪ ⊢ caseArr_pctx n : Γ , UVal (S n) → Γ , UVal n ⇒ UVal n ⟫. *)
(* Proof. *)
(* unfold caseArr_pctx. *)
(* eauto with typing uval_typing. *)
(* Qed. *)
(* Lemma caseArr_T {Γ n t} : *)
(* ⟪ Γ ⊢ t : UVal (S n) ⟫ → ⟪ Γ ⊢ caseArr n t : UVal n ⇒ UVal n ⟫. *)
(* Proof. *)
(* unfold caseArr. *)
(* eauto using caseArr_pctx_T with typing. *)
(* Qed. *)
|
#ifndef __ARNOLDI_Implicit_restart_Arnoldi_H__
#define __ARNOLDI_Implicit_restart_Arnoldi_H__
#include "Macros.h"
#include "timer.h"
#include "cuda_supp.h"
#include "memory_operations.h"
#include "Arnoldi_Driver.h"
#include "Select_Shifts.h"
#include "QR_Shifts.h"
#include "Matrix_Vector_emulator.h"
#include "file_operations.h"
//to set number of threads in openblas
#include <cblas.h>
extern "C" int openblas_get_num_threads(void);
extern "C" void openblas_set_num_threads(int);
real Implicit_restart_Arnoldi_GPU_data(cublasHandle_t handle, bool verbose, int N, user_map_vector Axb, void *user_struct, char which[2], int k, int m, complex real* eigenvaluesA, real tol, int max_iter, real *eigenvectors_real=NULL, real *eigenvectors_imag=NULL, int BLASTreads=1);
real Implicit_restart_Arnoldi_GPU_data_Matrix_Exponent(cublasHandle_t handle, bool verbose, int N, user_map_vector Axb_exponent_invert, void *user_struct_exponent_invert, user_map_vector Axb, void *user_struct, char which[2], char which_exponent[2], int k, int m, complex real* eigenvaluesA, real tol, int max_iter, bool is_rotated, real *eigenvectors_real_d=NULL, real *eigenvectors_imag_d=NULL, int BLASThreads=1);
#endif |
(* Positive paradox of material implication*)
theory Week1
imports Main
begin
(*If-Introduction*)
print_statement impI (*thm impI*)
lemma "A \<longrightarrow> A"
proof (rule impI)
assume A (*assuming the antecedent*)
then show A.
qed
(*Paradox of Material Implication*)
lemma positive_paradox : "A \<longrightarrow> (B \<longrightarrow> A)"
proof (rule impI)
assume A
show "B \<longrightarrow> A"
proof (rule impI)
assume B (*irrelevant*)
from `A` show A. (* 'from `A`' can be abb. as 'then' *)
qed
qed
(*2.1 Exercise*)
lemma "A \<longrightarrow> B \<longrightarrow> B"
proof(rule impI)
assume A (*irrelevant*)
show "B \<longrightarrow> B"
proof (rule impI)
assume B
then show B.(* 'thus' is an abb. for 'then show' *)
qed
qed
(*Modus Ponens*)
lemma "A \<longrightarrow> (A \<longrightarrow> B) \<longrightarrow> B"
proof(rule impI)
assume A
show "(A \<longrightarrow> B) \<longrightarrow> B"
proof
assume "(A \<longrightarrow> B)"
then show B using `A` by (rule mp)
qed
qed
(*3.1 Exercise*)
print_statement mp
lemma contraction: "(A \<longrightarrow> A \<longrightarrow> B) \<longrightarrow> (A \<longrightarrow> B)"
proof (rule impI)
assume "(A \<longrightarrow> A \<longrightarrow> B)"
show "(A \<longrightarrow> B)"
proof (rule impI)
assume A
with `A \<longrightarrow> A \<longrightarrow> B` have "(A \<longrightarrow> B)" by (rule mp) (*get the consequent () for further use*)
thus B using `A` by (rule mp)
qed
qed
(* EXERCISES *)
(*1*)
lemma mingle: "A \<longrightarrow> A \<longrightarrow> A"
proof (rule impI)
assume A
show "A \<longrightarrow> A"
proof
assume A
from `A` show A. (*A from line 2 used.*)
(* To use A from line 5, type `thus A.`
In either case, one of the A's will be unused, hence not sound.*)
qed
qed
(*2*)
lemma prefixing: "(A \<longrightarrow> B) \<longrightarrow> (C \<longrightarrow> A) \<longrightarrow> (C \<longrightarrow> B)"
proof (rule impI)
assume "(A \<longrightarrow> B)"
show "(C \<longrightarrow> A) \<longrightarrow> (C \<longrightarrow> B)"
proof (rule impI)
assume "(C \<longrightarrow> A)"
show "C \<longrightarrow> B"
proof
assume C
with `(A \<longrightarrow> B)` and `(C \<longrightarrow> A)` have "(C \<longrightarrow> B)" by blast
thus B using `C` by blast
qed
qed
qed
(*3*)
(*NOTE: Solution can be implemented using the method above as well*)
lemma suffixing: "(A \<longrightarrow> B) \<longrightarrow> (B \<longrightarrow> C) \<longrightarrow> (A \<longrightarrow> C)"
proof (rule impI)
assume "(A \<longrightarrow> B)"
show "(B \<longrightarrow> C) \<longrightarrow> (A \<longrightarrow> C)"
proof (rule impI)
assume "(B \<longrightarrow> C)"
show "A \<longrightarrow> C"
proof
assume A
with `(A \<longrightarrow> B)` have B by (rule mp)
with `(B \<longrightarrow> C)` show C by (rule mp)
qed
qed
qed
(*4*)
lemma "(A\<longrightarrow> B\<longrightarrow> C)\<longrightarrow> (B\<longrightarrow> A\<longrightarrow> C)"
proof
assume "(A\<longrightarrow> B\<longrightarrow> C)"
show "(B\<longrightarrow> A\<longrightarrow> C)"
proof
assume B
show "(A\<longrightarrow> C)"
proof
assume A
with `(A\<longrightarrow> B\<longrightarrow> C)` have "(B\<longrightarrow> C)" by blast (*rule mp*)
then show C using `B` by blast (*rule mp*)
qed
qed
qed
(*5*)
lemma hypothetical_syllogism: "(A \<longrightarrow> B) \<longrightarrow> (B \<longrightarrow> C) \<longrightarrow> (A \<longrightarrow> C)"
proof (rule Week1.suffixing)
qed
(*Not mentioned*)
lemma "(A\<longrightarrow> B)\<longrightarrow> A\<longrightarrow> C\<longrightarrow> B"
proof(rule impI)
assume "A \<longrightarrow> B"
show "A\<longrightarrow> C\<longrightarrow> B"
proof (rule impI)
assume A
show "C\<longrightarrow> B"
proof (rule impI)
assume C
from `A \<longrightarrow> B` have B using `A` by (rule mp)
from `B` show B.
qed
qed
qed
lemma "(A \<longrightarrow> B \<longrightarrow> C) \<longrightarrow> (A \<longrightarrow> B) \<longrightarrow> (A \<longrightarrow> C)"
proof (rule impI)
assume "A\<longrightarrow> B \<longrightarrow> C"
show "(A \<longrightarrow> B) \<longrightarrow> (A \<longrightarrow> C)"
proof (rule impI)
assume "A \<longrightarrow> B"
show "A \<longrightarrow> C"
proof (rule impI)
assume A
from `A \<longrightarrow> B` have B using `A` by (rule mp)
from `A\<longrightarrow> B \<longrightarrow>C` have "B\<longrightarrow> C" using `A` by (rule mp)
thus C using `B` by (rule mp)
qed
qed
qed
end
|
[STATEMENT]
lemma Mem_SUCC_E:
assumes "insert (u IN t) H \<turnstile> C" "insert (u EQ t) H \<turnstile> C" shows "insert (u IN SUCC t) H \<turnstile> C"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. insert (u IN SUCC t) H \<turnstile> C
[PROOF STEP]
by (metis assms Mem_Eats_E SUCC_def) |
(* Title: ZF/Perm.thy
Author: Lawrence C Paulson, Cambridge University Computer Laboratory
Copyright 1991 University of Cambridge
The theory underlying permutation groups
-- Composition of relations, the identity relation
-- Injections, surjections, bijections
-- Lemmas for the Schroeder-Bernstein Theorem
*)
section\<open>Injections, Surjections, Bijections, Composition\<close>
theory Perm imports func begin
definition
(*composition of relations and functions; NOT Suppes's relative product*)
comp :: "[i,i]=>i" (infixr "O" 60) where
"r O s == {xz \<in> domain(s)*range(r) .
\<exists>x y z. xz=<x,z> & <x,y>:s & <y,z>:r}"
definition
(*the identity function for A*)
id :: "i=>i" where
"id(A) == (\<lambda>x\<in>A. x)"
definition
(*one-to-one functions from A to B*)
inj :: "[i,i]=>i" where
"inj(A,B) == { f \<in> A->B. \<forall>w\<in>A. \<forall>x\<in>A. f`w=f`x \<longrightarrow> w=x}"
definition
(*onto functions from A to B*)
surj :: "[i,i]=>i" where
"surj(A,B) == { f \<in> A->B . \<forall>y\<in>B. \<exists>x\<in>A. f`x=y}"
definition
(*one-to-one and onto functions*)
bij :: "[i,i]=>i" where
"bij(A,B) == inj(A,B) \<inter> surj(A,B)"
subsection\<open>Surjective Function Space\<close>
lemma surj_is_fun: "f \<in> surj(A,B) ==> f \<in> A->B"
apply (unfold surj_def)
apply (erule CollectD1)
done
lemma fun_is_surj: "f \<in> Pi(A,B) ==> f \<in> surj(A,range(f))"
apply (unfold surj_def)
apply (blast intro: apply_equality range_of_fun domain_type)
done
lemma surj_range: "f \<in> surj(A,B) ==> range(f)=B"
apply (unfold surj_def)
apply (best intro: apply_Pair elim: range_type)
done
text\<open>A function with a right inverse is a surjection\<close>
lemma f_imp_surjective:
"[| f \<in> A->B; !!y. y \<in> B ==> d(y): A; !!y. y \<in> B ==> f`d(y) = y |]
==> f \<in> surj(A,B)"
by (simp add: surj_def, blast)
lemma lam_surjective:
"[| !!x. x \<in> A ==> c(x): B;
!!y. y \<in> B ==> d(y): A;
!!y. y \<in> B ==> c(d(y)) = y
|] ==> (\<lambda>x\<in>A. c(x)) \<in> surj(A,B)"
apply (rule_tac d = d in f_imp_surjective)
apply (simp_all add: lam_type)
done
text\<open>Cantor's theorem revisited\<close>
lemma cantor_surj: "f \<notin> surj(A,Pow(A))"
apply (unfold surj_def, safe)
apply (cut_tac cantor)
apply (best del: subsetI)
done
subsection\<open>Injective Function Space\<close>
lemma inj_is_fun: "f \<in> inj(A,B) ==> f \<in> A->B"
apply (unfold inj_def)
apply (erule CollectD1)
done
text\<open>Good for dealing with sets of pairs, but a bit ugly in use [used in AC]\<close>
lemma inj_equality:
"[| <a,b>:f; <c,b>:f; f \<in> inj(A,B) |] ==> a=c"
apply (unfold inj_def)
apply (blast dest: Pair_mem_PiD)
done
lemma inj_apply_equality: "[| f \<in> inj(A,B); f`a=f`b; a \<in> A; b \<in> A |] ==> a=b"
by (unfold inj_def, blast)
text\<open>A function with a left inverse is an injection\<close>
lemma f_imp_injective: "[| f \<in> A->B; \<forall>x\<in>A. d(f`x)=x |] ==> f \<in> inj(A,B)"
apply (simp (no_asm_simp) add: inj_def)
apply (blast intro: subst_context [THEN box_equals])
done
lemma lam_injective:
"[| !!x. x \<in> A ==> c(x): B;
!!x. x \<in> A ==> d(c(x)) = x |]
==> (\<lambda>x\<in>A. c(x)) \<in> inj(A,B)"
apply (rule_tac d = d in f_imp_injective)
apply (simp_all add: lam_type)
done
subsection\<open>Bijections\<close>
lemma bij_is_inj: "f \<in> bij(A,B) ==> f \<in> inj(A,B)"
apply (unfold bij_def)
apply (erule IntD1)
done
lemma bij_is_surj: "f \<in> bij(A,B) ==> f \<in> surj(A,B)"
apply (unfold bij_def)
apply (erule IntD2)
done
lemma bij_is_fun: "f \<in> bij(A,B) ==> f \<in> A->B"
by (rule bij_is_inj [THEN inj_is_fun])
lemma lam_bijective:
"[| !!x. x \<in> A ==> c(x): B;
!!y. y \<in> B ==> d(y): A;
!!x. x \<in> A ==> d(c(x)) = x;
!!y. y \<in> B ==> c(d(y)) = y
|] ==> (\<lambda>x\<in>A. c(x)) \<in> bij(A,B)"
apply (unfold bij_def)
apply (blast intro!: lam_injective lam_surjective)
done
lemma RepFun_bijective: "(\<forall>y\<in>x. \<exists>!y'. f(y') = f(y))
==> (\<lambda>z\<in>{f(y). y \<in> x}. THE y. f(y) = z) \<in> bij({f(y). y \<in> x}, x)"
apply (rule_tac d = f in lam_bijective)
apply (auto simp add: the_equality2)
done
subsection\<open>Identity Function\<close>
lemma idI [intro!]: "a \<in> A ==> <a,a> \<in> id(A)"
apply (unfold id_def)
apply (erule lamI)
done
lemma idE [elim!]: "[| p \<in> id(A); !!x.[| x \<in> A; p=<x,x> |] ==> P |] ==> P"
by (simp add: id_def lam_def, blast)
lemma id_type: "id(A) \<in> A->A"
apply (unfold id_def)
apply (rule lam_type, assumption)
done
lemma id_conv [simp]: "x \<in> A ==> id(A)`x = x"
apply (unfold id_def)
apply (simp (no_asm_simp))
done
lemma id_mono: "A<=B ==> id(A) \<subseteq> id(B)"
apply (unfold id_def)
apply (erule lam_mono)
done
lemma id_subset_inj: "A<=B ==> id(A): inj(A,B)"
apply (simp add: inj_def id_def)
apply (blast intro: lam_type)
done
lemmas id_inj = subset_refl [THEN id_subset_inj]
lemma id_surj: "id(A): surj(A,A)"
apply (unfold id_def surj_def)
apply (simp (no_asm_simp))
done
lemma id_bij: "id(A): bij(A,A)"
apply (unfold bij_def)
apply (blast intro: id_inj id_surj)
done
lemma subset_iff_id: "A \<subseteq> B \<longleftrightarrow> id(A) \<in> A->B"
apply (unfold id_def)
apply (force intro!: lam_type dest: apply_type)
done
text\<open>@{term id} as the identity relation\<close>
lemma id_iff [simp]: "<x,y> \<in> id(A) \<longleftrightarrow> x=y & y \<in> A"
by auto
subsection\<open>Converse of a Function\<close>
lemma inj_converse_fun: "f \<in> inj(A,B) ==> converse(f) \<in> range(f)->A"
apply (unfold inj_def)
apply (simp (no_asm_simp) add: Pi_iff function_def)
apply (erule CollectE)
apply (simp (no_asm_simp) add: apply_iff)
apply (blast dest: fun_is_rel)
done
text\<open>Equations for converse(f)\<close>
text\<open>The premises are equivalent to saying that f is injective...\<close>
lemma left_inverse_lemma:
"[| f \<in> A->B; converse(f): C->A; a \<in> A |] ==> converse(f)`(f`a) = a"
by (blast intro: apply_Pair apply_equality converseI)
lemma left_inverse [simp]: "[| f \<in> inj(A,B); a \<in> A |] ==> converse(f)`(f`a) = a"
by (blast intro: left_inverse_lemma inj_converse_fun inj_is_fun)
lemma left_inverse_eq:
"[|f \<in> inj(A,B); f ` x = y; x \<in> A|] ==> converse(f) ` y = x"
by auto
lemmas left_inverse_bij = bij_is_inj [THEN left_inverse]
lemma right_inverse_lemma:
"[| f \<in> A->B; converse(f): C->A; b \<in> C |] ==> f`(converse(f)`b) = b"
by (rule apply_Pair [THEN converseD [THEN apply_equality]], auto)
(*Should the premises be f \<in> surj(A,B), b \<in> B for symmetry with left_inverse?
No: they would not imply that converse(f) was a function! *)
lemma right_inverse [simp]:
"[| f \<in> inj(A,B); b \<in> range(f) |] ==> f`(converse(f)`b) = b"
by (blast intro: right_inverse_lemma inj_converse_fun inj_is_fun)
lemma right_inverse_bij: "[| f \<in> bij(A,B); b \<in> B |] ==> f`(converse(f)`b) = b"
by (force simp add: bij_def surj_range)
subsection\<open>Converses of Injections, Surjections, Bijections\<close>
lemma inj_converse_inj: "f \<in> inj(A,B) ==> converse(f): inj(range(f), A)"
apply (rule f_imp_injective)
apply (erule inj_converse_fun, clarify)
apply (rule right_inverse)
apply assumption
apply blast
done
lemma inj_converse_surj: "f \<in> inj(A,B) ==> converse(f): surj(range(f), A)"
by (blast intro: f_imp_surjective inj_converse_fun left_inverse inj_is_fun
range_of_fun [THEN apply_type])
text\<open>Adding this as an intro! rule seems to cause looping\<close>
lemma bij_converse_bij [TC]: "f \<in> bij(A,B) ==> converse(f): bij(B,A)"
apply (unfold bij_def)
apply (fast elim: surj_range [THEN subst] inj_converse_inj inj_converse_surj)
done
subsection\<open>Composition of Two Relations\<close>
text\<open>The inductive definition package could derive these theorems for @{term"r O s"}\<close>
lemma compI [intro]: "[| <a,b>:s; <b,c>:r |] ==> <a,c> \<in> r O s"
by (unfold comp_def, blast)
lemma compE [elim!]:
"[| xz \<in> r O s;
!!x y z. [| xz=<x,z>; <x,y>:s; <y,z>:r |] ==> P |]
==> P"
by (unfold comp_def, blast)
lemma compEpair:
"[| <a,c> \<in> r O s;
!!y. [| <a,y>:s; <y,c>:r |] ==> P |]
==> P"
by (erule compE, simp)
lemma converse_comp: "converse(R O S) = converse(S) O converse(R)"
by blast
subsection\<open>Domain and Range -- see Suppes, Section 3.1\<close>
text\<open>Boyer et al., Set Theory in First-Order Logic, JAR 2 (1986), 287-327\<close>
lemma range_comp: "range(r O s) \<subseteq> range(r)"
by blast
lemma range_comp_eq: "domain(r) \<subseteq> range(s) ==> range(r O s) = range(r)"
by (rule range_comp [THEN equalityI], blast)
lemma domain_comp: "domain(r O s) \<subseteq> domain(s)"
by blast
lemma domain_comp_eq: "range(s) \<subseteq> domain(r) ==> domain(r O s) = domain(s)"
by (rule domain_comp [THEN equalityI], blast)
lemma image_comp: "(r O s)``A = r``(s``A)"
by blast
lemma inj_inj_range: "f \<in> inj(A,B) ==> f \<in> inj(A,range(f))"
by (auto simp add: inj_def Pi_iff function_def)
lemma inj_bij_range: "f \<in> inj(A,B) ==> f \<in> bij(A,range(f))"
by (auto simp add: bij_def intro: inj_inj_range inj_is_fun fun_is_surj)
subsection\<open>Other Results\<close>
lemma comp_mono: "[| r'<=r; s'<=s |] ==> (r' O s') \<subseteq> (r O s)"
by blast
text\<open>composition preserves relations\<close>
lemma comp_rel: "[| s<=A*B; r<=B*C |] ==> (r O s) \<subseteq> A*C"
by blast
text\<open>associative law for composition\<close>
lemma comp_assoc: "(r O s) O t = r O (s O t)"
by blast
(*left identity of composition; provable inclusions are
id(A) O r \<subseteq> r
and [| r<=A*B; B<=C |] ==> r \<subseteq> id(C) O r *)
lemma left_comp_id: "r<=A*B ==> id(B) O r = r"
by blast
(*right identity of composition; provable inclusions are
r O id(A) \<subseteq> r
and [| r<=A*B; A<=C |] ==> r \<subseteq> r O id(C) *)
lemma right_comp_id: "r<=A*B ==> r O id(A) = r"
by blast
subsection\<open>Composition Preserves Functions, Injections, and Surjections\<close>
lemma comp_function: "[| function(g); function(f) |] ==> function(f O g)"
by (unfold function_def, blast)
text\<open>Don't think the premises can be weakened much\<close>
lemma comp_fun: "[| g \<in> A->B; f \<in> B->C |] ==> (f O g) \<in> A->C"
apply (auto simp add: Pi_def comp_function Pow_iff comp_rel)
apply (subst range_rel_subset [THEN domain_comp_eq], auto)
done
(*Thanks to the new definition of "apply", the premise f \<in> B->C is gone!*)
lemma comp_fun_apply [simp]:
"[| g \<in> A->B; a \<in> A |] ==> (f O g)`a = f`(g`a)"
apply (frule apply_Pair, assumption)
apply (simp add: apply_def image_comp)
apply (blast dest: apply_equality)
done
text\<open>Simplifies compositions of lambda-abstractions\<close>
lemma comp_lam:
"[| !!x. x \<in> A ==> b(x): B |]
==> (\<lambda>y\<in>B. c(y)) O (\<lambda>x\<in>A. b(x)) = (\<lambda>x\<in>A. c(b(x)))"
apply (subgoal_tac "(\<lambda>x\<in>A. b(x)) \<in> A -> B")
apply (rule fun_extension)
apply (blast intro: comp_fun lam_funtype)
apply (rule lam_funtype)
apply simp
apply (simp add: lam_type)
done
lemma comp_inj:
"[| g \<in> inj(A,B); f \<in> inj(B,C) |] ==> (f O g) \<in> inj(A,C)"
apply (frule inj_is_fun [of g])
apply (frule inj_is_fun [of f])
apply (rule_tac d = "%y. converse (g) ` (converse (f) ` y)" in f_imp_injective)
apply (blast intro: comp_fun, simp)
done
lemma comp_surj:
"[| g \<in> surj(A,B); f \<in> surj(B,C) |] ==> (f O g) \<in> surj(A,C)"
apply (unfold surj_def)
apply (blast intro!: comp_fun comp_fun_apply)
done
lemma comp_bij:
"[| g \<in> bij(A,B); f \<in> bij(B,C) |] ==> (f O g) \<in> bij(A,C)"
apply (unfold bij_def)
apply (blast intro: comp_inj comp_surj)
done
subsection\<open>Dual Properties of @{term inj} and @{term surj}\<close>
text\<open>Useful for proofs from
D Pastre. Automatic theorem proving in set theory.
Artificial Intelligence, 10:1--27, 1978.\<close>
lemma comp_mem_injD1:
"[| (f O g): inj(A,C); g \<in> A->B; f \<in> B->C |] ==> g \<in> inj(A,B)"
by (unfold inj_def, force)
lemma comp_mem_injD2:
"[| (f O g): inj(A,C); g \<in> surj(A,B); f \<in> B->C |] ==> f \<in> inj(B,C)"
apply (unfold inj_def surj_def, safe)
apply (rule_tac x1 = x in bspec [THEN bexE])
apply (erule_tac [3] x1 = w in bspec [THEN bexE], assumption+, safe)
apply (rule_tac t = "op ` (g) " in subst_context)
apply (erule asm_rl bspec [THEN bspec, THEN mp])+
apply (simp (no_asm_simp))
done
lemma comp_mem_surjD1:
"[| (f O g): surj(A,C); g \<in> A->B; f \<in> B->C |] ==> f \<in> surj(B,C)"
apply (unfold surj_def)
apply (blast intro!: comp_fun_apply [symmetric] apply_funtype)
done
lemma comp_mem_surjD2:
"[| (f O g): surj(A,C); g \<in> A->B; f \<in> inj(B,C) |] ==> g \<in> surj(A,B)"
apply (unfold inj_def surj_def, safe)
apply (drule_tac x = "f`y" in bspec, auto)
apply (blast intro: apply_funtype)
done
subsubsection\<open>Inverses of Composition\<close>
text\<open>left inverse of composition; one inclusion is
@{term "f \<in> A->B ==> id(A) \<subseteq> converse(f) O f"}\<close>
lemma left_comp_inverse: "f \<in> inj(A,B) ==> converse(f) O f = id(A)"
apply (unfold inj_def, clarify)
apply (rule equalityI)
apply (auto simp add: apply_iff, blast)
done
text\<open>right inverse of composition; one inclusion is
@{term "f \<in> A->B ==> f O converse(f) \<subseteq> id(B)"}\<close>
lemma right_comp_inverse:
"f \<in> surj(A,B) ==> f O converse(f) = id(B)"
apply (simp add: surj_def, clarify)
apply (rule equalityI)
apply (best elim: domain_type range_type dest: apply_equality2)
apply (blast intro: apply_Pair)
done
subsubsection\<open>Proving that a Function is a Bijection\<close>
lemma comp_eq_id_iff:
"[| f \<in> A->B; g \<in> B->A |] ==> f O g = id(B) \<longleftrightarrow> (\<forall>y\<in>B. f`(g`y)=y)"
apply (unfold id_def, safe)
apply (drule_tac t = "%h. h`y " in subst_context)
apply simp
apply (rule fun_extension)
apply (blast intro: comp_fun lam_type)
apply auto
done
lemma fg_imp_bijective:
"[| f \<in> A->B; g \<in> B->A; f O g = id(B); g O f = id(A) |] ==> f \<in> bij(A,B)"
apply (unfold bij_def)
apply (simp add: comp_eq_id_iff)
apply (blast intro: f_imp_injective f_imp_surjective apply_funtype)
done
lemma nilpotent_imp_bijective: "[| f \<in> A->A; f O f = id(A) |] ==> f \<in> bij(A,A)"
by (blast intro: fg_imp_bijective)
lemma invertible_imp_bijective:
"[| converse(f): B->A; f \<in> A->B |] ==> f \<in> bij(A,B)"
by (simp add: fg_imp_bijective comp_eq_id_iff
left_inverse_lemma right_inverse_lemma)
subsubsection\<open>Unions of Functions\<close>
text\<open>See similar theorems in func.thy\<close>
text\<open>Theorem by KG, proof by LCP\<close>
lemma inj_disjoint_Un:
"[| f \<in> inj(A,B); g \<in> inj(C,D); B \<inter> D = 0 |]
==> (\<lambda>a\<in>A \<union> C. if a \<in> A then f`a else g`a) \<in> inj(A \<union> C, B \<union> D)"
apply (rule_tac d = "%z. if z \<in> B then converse (f) `z else converse (g) `z"
in lam_injective)
apply (auto simp add: inj_is_fun [THEN apply_type])
done
lemma surj_disjoint_Un:
"[| f \<in> surj(A,B); g \<in> surj(C,D); A \<inter> C = 0 |]
==> (f \<union> g) \<in> surj(A \<union> C, B \<union> D)"
apply (simp add: surj_def fun_disjoint_Un)
apply (blast dest!: domain_of_fun
intro!: fun_disjoint_apply1 fun_disjoint_apply2)
done
text\<open>A simple, high-level proof; the version for injections follows from it,
using @{term "f \<in> inj(A,B) \<longleftrightarrow> f \<in> bij(A,range(f))"}\<close>
lemma bij_disjoint_Un:
"[| f \<in> bij(A,B); g \<in> bij(C,D); A \<inter> C = 0; B \<inter> D = 0 |]
==> (f \<union> g) \<in> bij(A \<union> C, B \<union> D)"
apply (rule invertible_imp_bijective)
apply (subst converse_Un)
apply (auto intro: fun_disjoint_Un bij_is_fun bij_converse_bij)
done
subsubsection\<open>Restrictions as Surjections and Bijections\<close>
lemma surj_image:
"f \<in> Pi(A,B) ==> f \<in> surj(A, f``A)"
apply (simp add: surj_def)
apply (blast intro: apply_equality apply_Pair Pi_type)
done
lemma surj_image_eq: "f \<in> surj(A, B) ==> f``A = B"
by (auto simp add: surj_def image_fun) (blast dest: apply_type)
lemma restrict_image [simp]: "restrict(f,A) `` B = f `` (A \<inter> B)"
by (auto simp add: restrict_def)
lemma restrict_inj:
"[| f \<in> inj(A,B); C<=A |] ==> restrict(f,C): inj(C,B)"
apply (unfold inj_def)
apply (safe elim!: restrict_type2, auto)
done
lemma restrict_surj: "[| f \<in> Pi(A,B); C<=A |] ==> restrict(f,C): surj(C, f``C)"
apply (insert restrict_type2 [THEN surj_image])
apply (simp add: restrict_image)
done
lemma restrict_bij:
"[| f \<in> inj(A,B); C<=A |] ==> restrict(f,C): bij(C, f``C)"
apply (simp add: inj_def bij_def)
apply (blast intro: restrict_surj surj_is_fun)
done
subsubsection\<open>Lemmas for Ramsey's Theorem\<close>
lemma inj_weaken_type: "[| f \<in> inj(A,B); B<=D |] ==> f \<in> inj(A,D)"
apply (unfold inj_def)
apply (blast intro: fun_weaken_type)
done
lemma inj_succ_restrict:
"[| f \<in> inj(succ(m), A) |] ==> restrict(f,m) \<in> inj(m, A-{f`m})"
apply (rule restrict_bij [THEN bij_is_inj, THEN inj_weaken_type], assumption, blast)
apply (unfold inj_def)
apply (fast elim: range_type mem_irrefl dest: apply_equality)
done
lemma inj_extend:
"[| f \<in> inj(A,B); a\<notin>A; b\<notin>B |]
==> cons(<a,b>,f) \<in> inj(cons(a,A), cons(b,B))"
apply (unfold inj_def)
apply (force intro: apply_type simp add: fun_extend)
done
end
|
#ifndef RANDOM_H
#define RANDOM_H
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
extern gsl_rng *rng_state;
void rand_init(int);
int rand_store(void*);
void rand_load(void*, int);
#define SQRT2INV 0.70710678118654752440084436210
#define rand_uniform() gsl_rng_uniform_pos(rng_state)
#define rand_gaussian() gsl_ran_gaussian_ziggurat(rng_state, SQRT2INV)
#define rand_z2() ((rand_uniform() < 0.5) ? SQRT2INV : -SQRT2INV)
#endif
|
\section{Cognitive and Environmental State-Change}
\p{Last section I hinted that I consider meanings somehow
bound up with state-changes. This point seems obvious
when we openly express state-change desires, like for
the window to be closed, but of course a lot of
discourse is more about establishing facts or
syncing concepts. Compare between:
\begin{sentenceList}\sentenceItem{} \label{itm:store} Remember that wine we tasted on the Niagara
Peninsula last summer? Can you find it in our
local liquor store?
\sentenceItem{} \label{itm:varietal} Remember that wine we tasted on the Niagara
Peninsula last summer? What varietal was that again?
\end{sentenceList}
The first sentence in each pair attempts to
establish a common frame of reference between
addresser and addressee \mdash{} it does not, in and
of itself, request any practical (extramental) action.
The second sentence in (\ref{itm:store}) \i{can} be read as
requesting the addressee buy a bottle, though an alternate
interpretation is to learn for \i{future reference}
whether someone \i{could} buy that bottle. The
second sentence in (\ref{itm:varietal}) carries no directive
implicature at all, at least with any directness;
it asks for more information.
}
\p{Despite these variations, it seems reasonable to say that
language is always performed in an overarching setting
where concrete (extralinguistic) activity
will \i{evetually} take place. If in (\ref{itm:varietal}) I intend
to recommend that grape variety to a friend, I may not be
making a direct request of him, but I \i{am}
proposing an eventual action that he
might take. If in (\ref{itm:store}) I am not issuing a directive, I
am however establishing (and reserving the future possibility)
that such a directive would be reasonable. As a result, some
extralinguistic state change seems to be lurking
behind the linguistic content: I want my friend
to go from having never tasted that varietal
to having tasted it.
Or I want to go from not having a bottle of that
wine to having one. Or, if I do not
want these things at the moment, I want
to confirm intellectually that these wishes are
plausible. We seem to use language to
set up the interpersonal understandings needed
to \i{eventually} engage in (usually collective)
practical activity, which means effectuating some
(extralinguistic) change.
}
\p{Having said that, most expressions are not direct
requests or suggestions of the \q{close the window}
or \q{let's get some wine} varity. We may have a
\i{holistic} sense that meanings orbit around
extralinguistic and extramental state-change,
but at the level of particular sentences most
changes that occur, or are proposed, tend to be
changes in our conceptualization of situations.
Nevertheless, we can pursue a semantic theory
based on state-change if we stipulate that \mdash{} even if
many changes which occur in the course of
linguistic activity do not have immediate,
apparent physical effects \mdash{} there are still
multiple kinds of changes that can occur. Dialogs
themselves change: the first sentences in
(\ref{itm:store}) and (\ref{itm:varietal})
modify the discursive frame so that, for example,
a particular wine becoms available as the anaphoric
target for \q{that} and \q{that wine} \mdash{} and also,
metonymically, \q{that varietal}, \q{that grape},
\q{that winery}. Conceptual frames can change:
if we are discussing a visit to Ontario and
I mention one specific winery, one effect is to
(insofar as the conversation follows my lead)
refigure our joint framing to something
narrower and more granular that the prior frame (but
still contained in it; I am not changing the subject
entirly). We can pull a frame out as well as in
\mdash{} e.g., switch from talking about one winery visit to
the whole trip, or one Leafs game to the entire season.
Moreover, our beliefs can change/evolve: if you tell me
the wine was Cabernet Franc, I have that piece of
info in my arsenal that I did not have before.
}
\p{We are now in position to develop a theory that
linguistic manings are grounded in state-changes,
assuming that the \q{register} where the changes occur can
vary over several cognitive and extramental options:
actual change in our environment (the window closed,
milk in the coffee, the bottle opened); changes to the
dialog structure (for anaphoric references, pronoun
resolution, metalinguistic cues like \q{can you say that
again}, etc.), changes to conceptual framings
(zoom in, zoom out, add detail), changes to beliefs.
Each of these kinds of changes deserve their own analysis,
but we can imagine the totality of such analyses
forming a robust semantic theory.
}
\p{During the course of a conversation \mdash{} and indeed
of any structured cognitive activity \mdash{} we
maintain conceptual frames representing relevant
information, what other people know or believe,
what are our goals and plans (individually and
collectively), and so forth. We update
these frames periodically, and use language to
compel others to modify their frams in
ways that we can (to some approximation) anticipate
and encode in linguistic structure.
}
\p{In the simplest case, we can effectuate changes in
others' frames by making assertions they are likely
to believe to be true (assuming they deem us
reliable). In general, it is impossible
to extricate the explicit content of the relevant
speech-acts from the relevant cognitive, linguistic, and
real-world situational contexts:
\begin{sentenceList}\sentenceItem{} That wine was a Cabernet Franc.
\sentenceItem{} Those dogs are my neighbor's.
They are very sweet.
\end{sentenceList}
Although there is a determinate propositional content being
asserted and although there is no propositional attitude
other than bald assertion to complicate the pragmatics,
still the actual words depend on addressees drawing from
the dialogic conext in accord with how I expect them to
(as manifest in open-ended expressions like \q{that wine},
\q{those dogs}, \q{they}). Moreover, the
open-ended components can refer outward in different
\q{registers}: in \q{that wine} I may be
referencing a concept previously established in
the conversation, while \q{those dogs} may refer to
pets we saw or heard but had not previously
talked about. Of course, the scenarios
could be reversed: I could introduce \q{that wine}
into the conversation by gesturing to a bottle
you had not noticed before, and refer via
\q{those dogs} to animals you have never seen or heard but
had talked about, or heard talk about, in the recent past.
}
\p{Surface-level language is not always clear as to whether
referring expressions are to work \q{deictically}
(drawing content from the ambient context,
signified by gestures, rather than from any
linguistic meaning proper), \q{discursively}
(referring within chains of dialog, e.g.
anaphora), or \q{descriptively} (using
purely semantic means to establish a designation,
like \q{my next-door neighbor's dogs} or
\q{Inniskillin Cabernet Franc Icewine 2015}.
}
\p{Let's agree to call the set of entities sufficiently
relevant to a discourse or conversation context the \q{ledger}.
By \q{sufficiently relevant} I mean whatever is already
established in a discourse so it can be referenced with something
less that full definite description (and without the aid
of extralinguistic gastures). I assume that gestures
and/or descriptions are communicative acts which \q{add}
to the ledger. The purely linguistic case \mdash{} let's say,
\q{descriptive additions} \mdash{} can themselves be distinguished
by their level of grounding in the current context.
A description can be \q{definitive} in a specific situation without
being a \q{definite description} in Russell's sense
(see \q{that wine we tasted last summer}).
}
\p{So, descriptive additions to the ledger are one kind of
semantic side-effect: we can change the ledger via
language acts. I will similarly dub another facet of
cognitive-linguistic frames as a \q{lens}: the idea
that in conversation we can \q{zoom} attention
in and out and move it around in time. \q{That wine we
tasted last summer in Ontario} both modifies
the ledger (adding a new referent for convenient
designation) and might alter the lens:
potentially compelling subsequent
conversation to focus on that time and/or place.
Finally, I will identify a class of frame-modifications
which do directly involve propositional content:
the capacity for language to promote shared beliefs
between people whose cognitive frames are in
the proper resonance, by adding dtails to conceptual
pictures already established: \q{those dogs are Staffordshires},
\q{that wine is Cabernet Franc}, \q{we have almond milk}, etc.
}
\p{For sake of discussion, I will call this latter part of the \q{active}
cognitive frame, for some discussion
\mdash{} the part concerning shared beliefes or asserted facts \mdash{}
the \q{doxa inventory}.
This \q{database}-like repository stands alongside the
\q{ledger} and \q{lens} to track propositional content
asserted, collectively established, or already
considered as background knowledge, \visavis{} some
discourse. Manipulations of the lens and ledger allow
spakers to designate (using referential cues
that could be ambiguous out-of-context)
propositional contents which they
wish to add to the \q{doxa inventory}. I'll also say
that modifying this inventory \i{can} be done through
language, but participants in a discourse are entitled
to assume that everyone formulates certain beliefs
which are observationally obvious, and can therefore
be linguistically presupposed rather than reported
(the likes of that a traffic light
is red, or a train has pulled into a station, or
that it's raining).
}
\p{So, I will assume that the machinery of frames is cognitive,
not just linguistic. We have analogous faculties for
\q{refocusing } attentions and adding conceptual details
via interaction with our environment, both alone and with others,
and both via language and via other means. Some
aspects of \i{linguistic} cognitive framing \mdash{} like
the \q{ledger} of referents previously established in a
conversation \mdash{} may be of a purely linguistic character,
but these are the exception rather than the rule.
In the typical case we have a latent ability to
direct attention and form beliefs by
direct observation or by accepting others' reports as
proxies for direct observation.
}
\p{When we are told that two dogs are male, for instance,
we may not perceptually encounter the dogs but we understand what
sorts of preceptual disclosures could
serve as motivation for someone believing that idea. We therefore
assume that such belief was initially warranted by
observation and subsequently got passed through a chain
of language-acts whose warrants are rooted in the perceived
credibility of the speaker. Internal to this
process is our prior knowledge of the parameters for judging
statements like \q{this dog is male} observationally.
}
\p{True, sometimes such observational warrants are less on
display. If I had never heard of Staffordshires, I
would be fuzzier about observational warrants and could end
up in conversations like:
\begin{sentenceList}\sentenceItem{} Those dogs are Staffordshires.
\sentenceItem{} What's a Staffordshire?
\sentenceItem{} It's a breed of dog.
\end{sentenceList}
\noindent{}Here I still don't really have a picture of what it is
like to tell observationally that a dog is a Staffordshire.
There may not be any visual cues \mdash{} at least none I
know of \mdash{} which announce to the world that a dog
is a Staffordshire (compared to those announcing that it is male,
say). But insofar as I am acquainted
with the concept \i{dog breed}, I also understand
the general pattern of these observations. For instance
I may know breeds like poodles or huskies and be able to
identify \i{these} by distinctive visual cues. I also
understand that dogs' parentage is often documented, allowing
informed parties to know their breeds via those of their
forebearers. That is, I am familiar with
how beliefs about breeds are formed based on
observation rather than just accepting others'
reports, so I know the extralinguistic epistemology
anchoring chains of linguistic reports in this area
to originating observations \mdash{} even if
I cannot in this case initiate such a chain myself.
}
\p{My overall point is that language enables us to formulate beliefs
based on the beliefs of others, but this is possible because
we also realize what itis like to formulate \i{our own}
beliefs, and envision that sort of practice at the
origin of reports that later get circulated via language.
If we can't sufficiently picture the originating
observations, we don't feel like we are grasping
the linguistic simulacrum of those reports with enough
substance. If I never learn what Stafforshire is,
an assertion that some dogs are Staffordshires
has no real meaning for me \mdash{} even if I trust the asserter
and do indeed thereby believe that the dogs are Staffordshires.
Notice that merely knowing Staffordshire is a breed of
dog does not expand my conceptual repertiore very much
\mdash{} it does not tell me how to recognize a Staffordshire
or what I can do with the knowledge
that a dog is one (it cannot, for instance, help
me anticipate his behavior). Nevertheless even (only) knowing
that Staffordshire is a breed of
dog seems to fundamentally change the status
of sentences like \q{those dogs are Staffordshires}
for me: I do not \i{have} the conceptual machinery
to exploit that knowledge, but I undersatnd
what \i{sort} of machinery is involved.
}
\p{In short, the \i{linguistic} meaning of concepts is tightly bound
to how concepts factor in perceptual observations anterior
to linguistic articulation. As a result,
during any episode wherein conversants use language to
compel others' beliefs, an intrinsic dimension of the
unfolding conversation is that people will form
their own (extralinguistic) beliefs \mdash{} and can also
imagine themselves in the role of originating the
reports they hear via language, whether or not they
can actually test out the reports by their own
observations.
}
\p{This extralinguistic epistemic
capacity is clearly exploited by the form of language itself.
If a tasting organizer hands me a glass and says
\q{This is Syrah}, she clearly expects me to infer that I
should take the glass from her and taste the wine (and
know that the glase contains wine, etc.). These conventions
may be \i{mediated} by language \mdash{} we are more likely to
understand \q{unspoken} norms by asking questions, until we gain
enough literacy in the relevant practical domain to
understand unspoken cues and assumptions. But many situational
assumptions are extralinguistic because
they are (by convention) not explicitly stated,
even if they accompany content that \i{is} explicitly stated.
\q{This is Syrah} acccompanied by the gesture of handing
me a glass is an indirect invitation for me to drink it
(compare to \q{Please hold this for a second?} or
\q{Please hand this to the man behind you?}).
}
\p{I bring to every linguistic situation a
capacity to make extralinguistc observations, and
to understand every utterance in the context of hypothetical
extralinguistc observations from which is originates.
My conversation peers can use language to trigger
these extralinguistic observations. Sometimes the
\q{gap} \mdash{} the conceptual slot which
extralinguistic reasoning is expected to fill
\mdash{} is direcly expressed, as in \q{See the
dog over there?}. But elsewhere the
\q{extralinguistic implicature} is more indirect,
as in \q{This is Syrah} and my expected belief that
I should take and taste from the glass. But in any
case the phenomenon of triggering these
extralinguistic observation is
one form of linguistic \q{side effect}, initiating a
change in my overall conceptualization of a situation by
compeling me to augment beliefs with new observations.
}
\p{All told, then, the language which is presented to me has the effect
of initiating changes in what I believe
\mdash{} partly via signifyimg propositional
content that I could take on faith, but partly
also via directing my attention and my interpretive
dispositions to guide me towards extralinguistic
observations. If this gloss is credible, it
remains to be discussed whether side-effects like
these are just side-effects of linguistic meaning,
or are in some sense \i{constitutive} of
meaning. I can understand the intuitive appeal
of the former idea, but I think the latter
may be closer to the truth. I will discuss
these alternatives in the next two subsections.
}
|
lemma pointwise_minimal_pointwise_maximal: fixes s :: "(nat \<Rightarrow> nat) set" assumes "finite s" and "s \<noteq> {}" and "\<forall>x\<in>s. \<forall>y\<in>s. x \<le> y \<or> y \<le> x" shows "\<exists>a\<in>s. \<forall>x\<in>s. a \<le> x" and "\<exists>a\<in>s. \<forall>x\<in>s. x \<le> a" |
" Baby Boy "
|
import Issue2447.M
import Issue2447.Parse-error
|
import combinatorics.simple_graph.basic
import combinatorics.simple_graph.subgraph
import data.finset.basic
import data.finset.card
import data.fintype.basic
import data.fintype.card
import data.finset.powerset
import simple_graph_aux
import complete_graph_aux
import coercions_aux
import induced_subgraph
universe u
variables {V : Type u} [fintype V] [decidable_eq V]
variables (G : simple_graph V) [decidable_rel G.adj]
variables {k : ℕ}
variable R : ↥(finset.powerset_len k (finset.univ : finset V))
variable red_edges : (finset ↥G.edge_finset)
variable red_edges_by_R :
finset ↥(G.edge_finset \ ((G.induced_subgraph R).edge_finset)) ×
finset ↥((G.induced_subgraph R).edge_finset)
-- trivial helper lemma
lemma card_R : (R : finset V).card = k :=
begin
cases R with R R_in,
change R.card = k,
rw finset.mem_powerset_len at R_in,
rw R_in.right,
end
def red_edges_by_R_coe :
( finset ↥(G.edge_finset \ ((G.induced_subgraph R).edge_finset)) ×
finset ↥((G.induced_subgraph R).edge_finset) ) →
(finset ↥G.edge_finset) := λ c,
↑(⟨finset.map (function.embedding.subtype _) c.fst ∪
finset.map (function.embedding.subtype _) c.snd,
begin
rw finset.union_subset_iff,
split,
{ rw finset.subset_iff,
intro x,
intro x_in,
have x_in' := finset.property_of_mem_map_subtype c.fst x_in,
rw finset.mem_sdiff at x_in',
exact x_in'.left,},
{ rw finset.subset_iff,
intro x,
intro x_in,
have x_in' := finset.property_of_mem_map_subtype c.snd x_in,
apply finset.mem_of_subset,
exact (G.induced_subgraph R).edge_finset_subset,
exact x_in', },
end⟩ : {s // s ⊆ G.edge_finset})
instance red_edges_by_R_has_coe : has_coe
( finset ↥(G.edge_finset \ ((G.induced_subgraph R).edge_finset)) ×
finset ↥((G.induced_subgraph R).edge_finset))
(finset ↥G.edge_finset)
:= ⟨red_edges_by_R_coe G R⟩
theorem red_edges_by_R_coe_inj :
function.injective (red_edges_by_R_coe G R) :=
begin
unfold function.injective,
unfold red_edges_by_R_coe,
change (coe : {s // s ⊆ G.edge_finset} → finset ↥(G.edge_finset))
with subset_subtype.finset_subtype.coe,
intros c₁ c₂,
intro h_union,
rw function.injective.eq_iff subset_subtype.finset_subtype.coe_injective
at h_union,
rw subtype.mk_eq_mk at h_union,
rw prod.ext_iff,
split,
{ rw finset.ext_iff,
intro e,
split,
{ intro e_in₁,
have e_coe_in₁ := finset.mem_map_of_mem
(function.embedding.subtype _) e_in₁,
rw function.embedding.coe_subtype _ at e_coe_in₁,
have e_coe_in_union :
↑e ∈ finset.map (function.embedding.subtype _) c₁.fst ∪
finset.map (function.embedding.subtype _) c₁.snd,
{ rw finset.mem_union,
left,
exact e_coe_in₁, },
rw h_union at e_coe_in_union,
have e_coe_in₂ :
↑e ∈ finset.map (function.embedding.subtype _) c₂.fst,
{ rw finset.mem_union at e_coe_in_union,
cases e_coe_in_union with e_coe_in₂ e_coe_in_false,
{ exact e_coe_in₂, },
{ exfalso,
have e_in_R :=
finset.property_of_mem_map_subtype _ e_coe_in_false,
have e_not_in_R := e.property,
rw finset.mem_sdiff at e_not_in_R,
exact e_not_in_R.right e_in_R, }, },
simp only [finset.mem_sdiff, simple_graph.mem_edge_finset,
simple_graph.complete_graph_eq_top, coe_coe, finset.mem_map,
function.embedding.coe_subtype, exists_prop, subtype.exists,
subtype.coe_mk, exists_and_distrib_right, exists_eq_right,
finset.mk_coe] at e_coe_in₂,
exact e_coe_in₂.right, },
{ intro e_in₂,
have e_coe_in₂ := finset.mem_map_of_mem
(function.embedding.subtype _) e_in₂,
rw function.embedding.coe_subtype _ at e_coe_in₂,
have e_coe_in_union :
↑e ∈ finset.map (function.embedding.subtype _) c₂.fst ∪
finset.map (function.embedding.subtype _) c₂.snd,
{ rw finset.mem_union,
left,
exact e_coe_in₂, },
rw ← h_union at e_coe_in_union,
have e_coe_in₁ :
↑e ∈ finset.map (function.embedding.subtype _) c₁.fst,
{ rw finset.mem_union at e_coe_in_union,
cases e_coe_in_union with e_coe_in₁ e_coe_in_false,
{ exact e_coe_in₁, },
{ exfalso,
have e_in_R :=
finset.property_of_mem_map_subtype _ e_coe_in_false,
have e_not_in_R := e.property,
rw finset.mem_sdiff at e_not_in_R,
exact e_not_in_R.right e_in_R,}, },
simp only [finset.mem_sdiff, simple_graph.mem_edge_finset,
simple_graph.complete_graph_eq_top, coe_coe, finset.mem_map,
function.embedding.coe_subtype, exists_prop, subtype.exists,
subtype.coe_mk, exists_and_distrib_right, exists_eq_right,
finset.mk_coe] at e_coe_in₁,
exact e_coe_in₁.right, }, },
{ rw finset.ext_iff,
intro e,
split,
{ intro e_in₁,
have e_coe_in₁ := finset.mem_map_of_mem
(function.embedding.subtype _) e_in₁,
rw function.embedding.coe_subtype at e_coe_in₁,
have e_coe_in_union :
↑e ∈ finset.map (function.embedding.subtype _) c₁.fst ∪
finset.map (function.embedding.subtype _) c₁.snd,
{ rw finset.mem_union,
right,
exact e_coe_in₁, },
rw h_union at e_coe_in_union,
have e_coe_in₂ :
↑e ∈ finset.map (function.embedding.subtype _) c₂.snd,
{ rw finset.mem_union at e_coe_in_union,
cases e_coe_in_union with e_coe_in_false e_coe_in₂,
{ exfalso,
have e_not_in_R :=
finset.property_of_mem_map_subtype _ e_coe_in_false,
rw finset.mem_sdiff at e_not_in_R,
have e_in_R := e.property,
exact e_not_in_R.right e_in_R, },
{ exact e_coe_in₂, }, },
simp only [coe_coe, finset.mem_map, function.embedding.coe_subtype,
exists_prop, subtype.exists, subtype.coe_mk,
exists_and_distrib_right, exists_eq_right, finset.mk_coe]
at e_coe_in₂,
exact e_coe_in₂.right, },
{ intro e_in₂,
have e_coe_in₂ := finset.mem_map_of_mem
(function.embedding.subtype _) e_in₂,
rw function.embedding.coe_subtype at e_coe_in₂,
have e_coe_in_union :
↑e ∈ finset.map (function.embedding.subtype _) c₂.fst ∪
finset.map (function.embedding.subtype _) c₂.snd,
{ rw finset.mem_union,
right,
exact e_coe_in₂, },
rw ← h_union at e_coe_in_union,
have e_coe_in₁ :
↑e ∈ finset.map (function.embedding.subtype _) c₁.snd,
{ rw finset.mem_union at e_coe_in_union,
cases e_coe_in_union with e_coe_in_false e_coe_in₁,
{ exfalso,
have e_not_in_R :=
finset.property_of_mem_map_subtype _ e_coe_in_false,
rw finset.mem_sdiff at e_not_in_R,
have e_in_R := e.property,
exact e_not_in_R.right e_in_R, },
{ exact e_coe_in₁, }, },
simp only [coe_coe, finset.mem_map, function.embedding.coe_subtype,
exists_prop, subtype.exists, subtype.coe_mk,
exists_and_distrib_right, exists_eq_right, finset.mk_coe]
at e_coe_in₁,
exact e_coe_in₁.right, }, },
end
def A : Prop :=
∀ (e₁ : ↥((G.induced_subgraph R).edge_finset))
(e₂ : ↥((G.induced_subgraph R).edge_finset)),
( set.inclusion (G.induced_subgraph R).edge_finset_subset e₁ ∈ red_edges ∧
set.inclusion (G.induced_subgraph R).edge_finset_subset e₂ ∈ red_edges ) ∨
( set.inclusion (G.induced_subgraph R).edge_finset_subset e₁ ∉ red_edges ∧
set.inclusion (G.induced_subgraph R).edge_finset_subset e₂ ∉ red_edges )
instance A_decidable : decidable_pred (A G R) :=
begin
unfold decidable_pred,
intro red_edges,
unfold A,
refine fintype.decidable_forall_fintype,
end
def finset_univ_two_colouring : finset (finset ↥(G.edge_finset)) :=
finset.univ
def two_colourings_sat_A_R : finset (finset ↥(G.edge_finset)) :=
finset.filter (A G R) (finset_univ_two_colouring G)
def empty_univ_col_R :
finset (finset ↥(G.edge_finset \ ((G.induced_subgraph R).edge_finset)) ×
finset ↥((G.induced_subgraph R).edge_finset)) :=
finset.product finset.univ {∅, finset.univ}
theorem all_red_colourings_sat_A_R :
two_colourings_sat_A_R (complete_graph V) R =
finset.map
⟨red_edges_by_R_coe (complete_graph V) R, red_edges_by_R_coe_inj _ _⟩
(empty_univ_col_R (complete_graph V) R) :=
begin
unfold two_colourings_sat_A_R,
unfold finset_univ_two_colouring,
unfold empty_univ_col_R,
unfold red_edges_by_R_coe,
change (coe :
{s // s ⊆ (complete_graph V).edge_finset} →
finset ↥((complete_graph V).edge_finset))
with subset_subtype.finset_subtype.coe,
rw finset.ext_iff,
intro c,
simp only [finset.mem_filter, finset.mem_univ, true_and, finset.mem_map,
finset.mem_product, finset.mem_insert, finset.mem_singleton,
function.embedding.coe_fn_mk, exists_prop, prod.exists],
split,
{ intro hA,
generalize h_cR :
simple_graph.induced_subgraph.edge_subtype_finset
(complete_graph V) R (finset.map (function.embedding.subtype _) c)
= cR,
generalize h_cRc :
simple_graph.induced_subgraph.edge_complement_subtype_finset
(complete_graph V) R (finset.map (function.embedding.subtype _) c)
= cRc,
use cRc,
use cR,
rw ← @finset.map_inj _ _
(function.embedding.subtype (∈ (complete_graph V).edge_finset)) _ _,
rw subset_subtype.coe_type,
have h_union :
finset.map (function.embedding.subtype _) cRc ∪
finset.map (function.embedding.subtype _) cR =
finset.map (function.embedding.subtype _) c,
{ rw ← h_cR,
rw ← h_cRc,
unfold simple_graph.induced_subgraph.edge_complement_subtype_finset,
unfold simple_graph.induced_subgraph.edge_subtype_finset,
rw finset.subtype_map,
rw finset.subtype_map,
simp_rw [finset.mem_sdiff],
rw finset.union_comm,
rw finset.filter_and,
rw finset.union_distrib_left,
rw finset.filter_union_filter_neg_eq
(∈ ((complete_graph V).induced_subgraph ↑R).edge_finset)
(finset.map (function.embedding.subtype _) c),
have h_eq_c :
finset.filter
(∈ (complete_graph V).edge_finset)
(finset.map (function.embedding.subtype _) c) =
(finset.map (function.embedding.subtype _) c),
{ rw finset.filter_eq_self,
intro x,
intro x_in,
have := finset.property_of_mem_map_subtype _ x_in,
exact this, },
rw h_eq_c,
rw finset.union_comm,
exact finset.union_inter_cancel_left, },
cases finset.eq_empty_or_nonempty cR with cR_empty cR_nonempty,
{ clear hA,
split,
{ left,
exact cR_empty,},
{ exact h_union, }, },
{ split,
{ clear h_union,
right,
unfold finset.nonempty at cR_nonempty,
cases cR_nonempty with e₁ e₁_in,
apply finset.ext,
intro e₂,
split,
{ revert e₂,
exact cR.subset_univ, },
{ intro e₂_in,
specialize hA e₁ e₂,
cases hA with h_red h_blue,
{ rw ← h_cR,
unfold simple_graph.induced_subgraph.edge_subtype_finset,
simp only [simple_graph.mem_edge_finset,
simple_graph.complete_graph_eq_top, finset.mem_subtype,
finset.mem_map, function.embedding.coe_subtype,
exists_prop, subtype.exists, subtype.coe_mk,
exists_and_distrib_right, exists_eq_right],
have e₂_in_set : ↑e₂ ∈ (complete_graph V).edge_set,
{ have e₂_in_finset := finset.mem_of_subset
((complete_graph V).induced_subgraph R).edge_finset_subset
e₂.property,
unfold simple_graph.edge_finset at e₂_in_finset,
rw set.mem_to_finset at e₂_in_finset,
exact e₂_in_finset, },
use e₂_in_set,
exact h_red.right, },
{ exfalso,
have e₁_not_in := h_blue.left,
rw ← h_cR at e₁_in,
unfold simple_graph.induced_subgraph.edge_subtype_finset
at e₁_in,
simp only [simple_graph.mem_edge_finset,
simple_graph.complete_graph_eq_top, finset.mem_subtype,
finset.mem_map, function.embedding.coe_subtype, exists_prop,
subtype.exists, subtype.coe_mk, exists_and_distrib_right,
exists_eq_right] at e₁_in,
cases e₁_in with _ e₁_in,
exact h_blue.left e₁_in, }, }, },
{ exact h_union, }, }, },
{ rintro ⟨cRc, cR, hcR, h_union⟩,
cases hcR with cR_empty cR_univ,
{ intros e₁ e₂,
right,
rw ← h_union,
clear h_union,
rw cR_empty,
clear cR_empty,
simp only [finset.map_empty, finset.union_empty],
unfold subset_subtype.finset_subtype.coe,
split,
{ by_contra,
simp only [finset.univ_eq_attach, finset.mem_map,
finset.mem_attach, function.embedding.coe_fn_mk,
exists_true_left] at h,
unfold set.inclusion at h,
rcases h with ⟨⟨a, a_in⟩, h_eq⟩,
rw subtype.mk_eq_mk at h_eq,
change a = e₁.val at h_eq,
rw h_eq at a_in,
have e_in := finset.property_of_mem_map_subtype cRc a_in,
rw finset.mem_sdiff at e_in,
exact e_in.right e₁.property, },
{ by_contra,
simp only [finset.univ_eq_attach, finset.mem_map,
finset.mem_attach, function.embedding.coe_fn_mk,
exists_true_left] at h,
unfold set.inclusion at h,
rcases h with ⟨⟨a, a_in⟩, h_eq⟩,
rw subtype.mk_eq_mk at h_eq,
change a = e₂.val at h_eq,
rw h_eq at a_in,
have e_in := finset.property_of_mem_map_subtype cRc a_in,
rw finset.mem_sdiff at e_in,
exact e_in.right e₂.property, }, },
{ intros e₁ e₂,
left,
rw ← h_union,
clear h_union,
rw cR_univ,
clear cR_univ,
unfold subset_subtype.finset_subtype.coe,
simp only [finset.univ_eq_attach, finset.mem_map, finset.mem_attach,
function.embedding.coe_fn_mk, exists_true_left],
split,
{ use e₁,
{ rw set.mem_def,
rw ← finset.mem_def,
rw finset.mem_union,
right,
change (function.embedding.subtype _) e₁ ∈ finset.map
(function.embedding.subtype _) finset.univ,
rw finset.mem_map' (function.embedding.subtype _),
exact finset.mem_univ e₁, },
refl, },
{ use e₂,
{ rw set.mem_def,
rw ← finset.mem_def,
rw finset.mem_union,
right,
change (function.embedding.subtype _) e₂ ∈ finset.map
(function.embedding.subtype _) finset.univ,
rw finset.mem_map' (function.embedding.subtype _),
exact finset.mem_univ e₂, },
refl, }, }, },
end
theorem card_red_colourings_sat_A_R (hk : k ≥ 2) :
(two_colourings_sat_A_R (complete_graph V) R).card =
2 ^ ((fintype.card V).choose 2 - k.choose 2 + 1) :=
begin
rw all_red_colourings_sat_A_R,
unfold empty_univ_col_R,
rw finset.card_map,
rw finset.card_product,
rw finset.card_univ,
rw fintype.card_finset,
rw fintype.card_coe,
rw finset.card_sdiff
(((complete_graph V).induced_subgraph R).edge_finset_subset),
rw complete_graph.induced_subgraph.card_edge_finset,
change (↑R : set V) with (↑(↑R : finset V) : set V),
simp_rw finset.coe_sort_coe,
rw fintype.card_coe,
rw complete_graph.card_edge_finset,
rw finset.card_doubleton,
rw pow_succ',
rw card_R,
symmetry,
apply finset.nonempty.ne_empty,
rw finset.univ_nonempty_iff,
rw finset.nonempty_coe_sort,
unfold simple_graph.subgraph.edge_finset,
rw ← finset.coe_nonempty,
exact complete_graph.induced_subgraph_size.edge_finset_nonempty R hk,
end
variable (k)
def finset_univ_prod_R_colouring :
finset (finset.powerset_len k (finset.univ : finset V) ×
finset ↥G.edge_finset) := finset.univ
theorem finset_univ_prod_R_colouring_eq_prod_univ :
finset_univ_prod_R_colouring G k =
finset.product finset.univ finset.univ :=
begin
unfold finset_univ_prod_R_colouring,
exact finset.univ_product_univ,
end
theorem finset_univ_prod_R_colouring_eq_bUnion :
finset_univ_prod_R_colouring G k = finset.univ.bUnion
(λ R, finset.map ⟨prod.mk R, prod.mk.inj_left R⟩ finset.univ) :=
begin
simp_rw [finset.map_eq_image],
rw finset_univ_prod_R_colouring_eq_prod_univ,
exact finset.product_eq_bUnion finset.univ finset.univ,
end
def finset_univ_prod_R_colouring_sat_A_R :
finset (finset.powerset_len k (finset.univ : finset V) ×
finset ↥G.edge_finset) :=
finset.filter (λ Rc, A G Rc.fst Rc.snd) (finset_univ_prod_R_colouring G k)
lemma function.uncurry.comp_prod_mk_eq_self
{α : Type*} {β : Type*} {γ : Type*} (f : α → β → γ) (a : α) :
(function.uncurry f) ∘ (prod.mk a) = f a := by unfold function.uncurry
theorem finset_univ_prod_R_colouring_sat_A_R_eq_bUnion_filter :
finset_univ_prod_R_colouring_sat_A_R G k =
finset.univ.bUnion (λ R, finset.map
⟨prod.mk R, prod.mk.inj_left R⟩
(two_colourings_sat_A_R G R)) :=
begin
unfold finset_univ_prod_R_colouring_sat_A_R,
rw finset_univ_prod_R_colouring_eq_bUnion,
rw finset.filter_bUnion,
apply congr_arg,
apply funext,
intro R,
unfold two_colourings_sat_A_R,
rw finset.map_filter,
apply congr_arg,
rw function.embedding.coe_fn_mk,
change (λ Rc :
↥(finset.powerset_len k finset.univ) × finset ↥(G.edge_finset),
A G Rc.fst Rc.snd) with function.uncurry (A G),
simp_rw [function.uncurry.comp_prod_mk_eq_self],
unfold finset_univ_two_colouring,
end
theorem card_finset_univ_prod_R_colouring_sat_A_R {k} (hk : k ≥ 2) :
(finset_univ_prod_R_colouring_sat_A_R (complete_graph V) k).card =
(fintype.card V).choose k * 2 ^ ((fintype.card V).choose 2 -
k.choose 2 + 1) :=
begin
rw finset_univ_prod_R_colouring_sat_A_R_eq_bUnion_filter,
rw finset.card_bUnion,
rw finset.sum_const_nat,
swap 3,
{ exact 2 ^ ((fintype.card V).choose 2 - k.choose 2 + 1) },
{ rw finset.card_univ,
rw fintype.card_coe,
rw finset.card_powerset_len,
rw finset.card_univ, },
{ intros R R_in,
rw finset.card_map,
rw card_red_colourings_sat_A_R,
exact hk, },
intros R R_in R' R'_in R_ne_R',
rw finset.disjoint_iff_ne,
rintros ⟨R₁, c⟩ Rc_in ⟨R'₁, c'⟩ R'c'_in,
simp only [finset.mem_map, function.embedding.coe_fn_mk,
prod.mk.inj_iff, exists_prop, exists_eq_right_right] at Rc_in R'c'_in,
rw ← Rc_in.right,
rw ← R'c'_in.right,
rw ne.def,
rw prod.mk.inj_iff,
exact not_and_of_not_left _ R_ne_R',
end
def finset_univ_colouring_sat_A : finset (finset ↥G.edge_finset) :=
finset.image prod.snd (@finset_univ_prod_R_colouring_sat_A_R _ _ _ G _ k)
theorem finset_univ_prod_R_colouring_sat_A_R_ssubset_univ {k}
( h : ((fintype.card V).choose k) * 2 ^
((fintype.card V).choose 2 - k.choose 2 + 1) <
2 ^ (fintype.card V).choose 2) (hk : k ≥ 2) :
finset_univ_colouring_sat_A (complete_graph V) k ⊂
(finset_univ_two_colouring (complete_graph V)) :=
begin
unfold finset_univ_two_colouring,
rw finset.ssubset_iff_subset_ne,
split,
{ exact finset.subset_univ _, },
{ rw ← finset.card_lt_iff_ne_univ,
calc (finset_univ_colouring_sat_A (complete_graph V) k).card ≤
(finset_univ_prod_R_colouring_sat_A_R (complete_graph V) k).card :
finset.card_image_le
... = (fintype.card V).choose k * 2 ^
((fintype.card V).choose 2 - k.choose 2 + 1) :
card_finset_univ_prod_R_colouring_sat_A_R hk
... < 2 ^ (fintype.card V).choose 2 : h
... = finset.univ.card :
begin
rw finset.card_univ,
rw fintype.card_finset,
rw fintype.card_coe,
rw complete_graph.card_edge_finset
end, },
end
theorem ramsey_lower_bound {k}
( h : ((fintype.card V).choose k) * 2 ^
((fintype.card V).choose 2 - k.choose 2 + 1) <
2 ^ (fintype.card V).choose 2) (hk : k ≥ 2) :
∃ c : finset ↥((complete_graph V).edge_finset),
¬∃ R' : ↥(finset.powerset_len k (finset.univ : finset V)),
A (complete_graph V) R' c :=
begin
rcases
finset.exists_of_ssubset
(finset_univ_prod_R_colouring_sat_A_R_ssubset_univ h hk)
with ⟨c, c_in, c_not_in⟩,
use c,
convert_to ¬∃ R',
(R', c) ∈ (finset_univ_prod_R_colouring_sat_A_R (complete_graph V) k),
{ unfold finset_univ_prod_R_colouring_sat_A_R,
simp_rw finset.mem_filter,
unfold finset_univ_prod_R_colouring,
simp_rw [eq_true_intro (finset.mem_univ _)],
simp_rw [true_and], },
unfold finset_univ_colouring_sat_A at c_not_in,
rw finset.mem_image at c_not_in,
rw not_exists at c_not_in,
rw not_exists,
intro R,
specialize c_not_in (R, c),
rw not_exists at c_not_in,
rw eq_self_iff_true at c_not_in,
rw not_true at c_not_in,
rw imp_false at c_not_in,
exact c_not_in,
end |
If $S$ is compact and $T$ is closed, then the set $\{x + y \mid x \in S, y \in T\}$ is closed. |
(** Mathematical model of the causal memory implementation
from "Causal memory: definitions, implementation, and programming"
(https://link.springer.com/article/10.1007/BF01784241).*)
From aneris.aneris_lang Require Import lang resources.
From stdpp Require Import gmap.
From aneris.prelude Require Import misc.
From aneris.examples.ccddb.spec Require Import base.
From aneris.examples.ccddb.model Require Export model_lsec.
Section Local_history_valid.
Context `{!anerisG Mdl Σ, !DB_params}.
Definition DBM_lhst_ext (s : gset apply_event) :=
∀ e e', e ∈ s → e' ∈ s → ae_time e = ae_time e' → e = e'.
Definition DBM_lhst_times (s : gset apply_event) :=
∀ e, e ∈ s → length e.(ae_time) = length DB_addresses.
Definition DBM_lhst_origs (i : nat) (s : gset apply_event) :=
(∀ e, e ∈ s → e.(ae_orig) < length DB_addresses).
Definition DBM_lhst_lsec_valid (i : nat) (s : gset apply_event) :=
(∀ j, j < length DB_addresses → DBM_lsec_valid i j s).
Definition DBM_lhst_seqids (s : gset apply_event) :=
∀ e, e ∈ s → e.(ae_seqid) <= size s.
Definition DBM_lhst_keys (s : gset apply_event) :=
∀ e, e ∈ s → e.(ae_key) ∈ DB_keys.
Record DBM_lhst_valid (i : nat) (s : gset apply_event) : Prop := {
DBM_LHV_bound_at: i < length DB_addresses;
DBM_LHV_times: DBM_lhst_times s;
DBM_LHV_ext: DBM_lhst_ext s;
DBM_LHV_origs: DBM_lhst_origs i s;
DBM_LHV_keys: DBM_lhst_keys s;
DBM_LHV_secs_valid: DBM_lhst_lsec_valid i s;
DBM_LHV_seqids: DBM_lhst_seqids s;
}.
Global Arguments DBM_LHV_bound_at {_ _} _.
Global Arguments DBM_LHV_times {_ _} _.
Global Arguments DBM_LHV_ext {_ _} _.
Global Arguments DBM_LHV_origs {_ _} _.
Global Arguments DBM_LHV_secs_valid {_ _} _.
Global Arguments DBM_LHV_seqids {_ _} _.
Global Arguments DBM_LHV_keys {_ _} _.
Lemma in_lhs_time_component e k i s :
DBM_lhst_valid i s →
k < length DB_addresses →
e ∈ s →
is_Some (e.(ae_time) !! k).
Proof.
intros ???; eapply lookup_lt_is_Some_2; erewrite DBM_LHV_times; eauto.
Qed.
Lemma DBM_lsec_empty i s:
DBM_lhst_valid i s →
∀ j', j' < length DB_addresses →
DBM_lsec j' s = ∅ ↔ ∀ e, e ∈ s → e.(ae_time) !! j' = Some 0.
Proof.
intros Hvli j' Hj'lt.
split.
- intros Hjs e Hes.
pose proof (in_lsec_orig e s Hes) as Hesec.
pose proof (DBM_LHV_origs Hvli e Hes) as Heorig.
destruct (lookup_lt_is_Some_2 (ae_time e) j') as [k Hk].
{ rewrite (DBM_LHV_times Hvli) //. }
rewrite Hk.
destruct (decide (j' = e.(ae_orig))) as [->|].
{ by rewrite Hjs in Hesec. }
pose proof (DBM_LHV_secs_valid Hvli e.(ae_orig) Heorig) as Hesecvl.
destruct (decide (i = e.(ae_orig))) as [->|].
{ pose proof (DBM_LSV_caus_refl Hesecvl j' e Hj'lt) as Hvlrefl.
rewrite Hk /= in Hvlrefl.
rewrite DBM_lsec_latest_in_frame_empty in Hvlrefl; last done.
apply Hvlrefl; auto. }
pose proof (DBM_LSV_caus Hesecvl j' e Hj'lt) as Hvlirrefl.
rewrite Hk /= in Hvlirrefl.
rewrite DBM_lsec_latest_in_frame_empty in Hvlirrefl; last done.
f_equal; symmetry; apply le_n_0_eq.
apply Hvlirrefl; auto.
- destruct (decide (DBM_lsec j' s = ∅)) as [|Hne]; first done.
apply set_choose_L in Hne as [x Hx].
pose proof (DBM_LHV_secs_valid Hvli j' Hj'lt) as Hesecvl.
intros He.
pose proof (in_lsec_in_lhst _ _ _ Hx) as Hxs.
apply He in Hxs.
destruct (DBM_LSV_strongly_complete (DBM_LHV_times Hvli) Hj'lt Hesecvl 0)
as [_ []]; eauto with lia.
Qed.
Definition lsec_sup (j : nat) (s: gset apply_event) : nat :=
nat_sup (omap (λ e, e.(ae_time) !! j) (elements (DBM_lsec j s))).
Lemma lsec_sup_empty j : lsec_sup j ∅ = 0.
Proof. by rewrite /lsec_sup DBM_lsec_of_empty elements_empty /=. Qed.
Lemma elem_of_lsec_lsec_sup_length e i j s :
DBM_lhst_valid i s →
j < length DB_addresses →
e ∈ DBM_lsec j s → length (elements (DBM_lsec j s)) = lsec_sup j s.
Proof.
intros Hvl Hj He.
assert (∃ e', e' ∈ DBM_lsec j s ∧
(e'.(ae_time) !! j = Some (lsec_sup j s))) as
(e' & He'1 & He'2).
{ assert
(lsec_sup j s ∈ (omap (λ e, e.(ae_time) !! j)
(elements (DBM_lsec j s)))) as Hsup.
{ edestruct (in_lhs_time_component e j) as [p Hp];
eauto using in_lsec_in_lhst.
eapply (nat_sup_elem_of p).
apply elem_of_list_omap.
by exists e; split; first apply elem_of_elements. }
apply elem_of_list_omap in Hsup as (?&?%elem_of_elements&?); eauto. }
apply Nat.le_antisymm.
- edestruct le_lt_dec as [Hle|Hlt]; first exact Hle.
destruct (DBM_LSV_comp (DBM_LHV_secs_valid Hvl j Hj) (S (lsec_sup j s))) as
(e'' & He''1 & He''2); first lia.
assert (S (lsec_sup j s) ≤ lsec_sup j s); last lia.
apply nat_sup_UB.
apply elem_of_list_omap.
by eexists; split; first apply elem_of_elements.
- apply (DBM_LSV_strongly_complete
(DBM_LHV_times Hvl) Hj (DBM_LHV_secs_valid Hvl j Hj)); eauto.
Qed.
Lemma lsec_lsup_length i j s :
DBM_lhst_valid i s →
j < length DB_addresses →
length (elements (DBM_lsec j s)) = lsec_sup j s.
Proof.
intros Hvl Hj.
destruct (decide (DBM_lsec j s ≡ ∅)) as [Hempty| Hex].
- rewrite /lsec_sup. simplify_eq. rewrite Hempty. set_solver.
- apply set_choose in Hex as (e' & He').
eapply (elem_of_lsec_lsec_sup_length e'); eauto.
Qed.
Lemma DBM_lsec_causality_lemma i s e p q r :
r < length DB_addresses →
DBM_lhst_valid i s →
e ∈ s →
0 < p →
p ≤ q →
e.(ae_time) !! r = Some q →
∃ e', e' ∈ DBM_lsec r s ∧ e'.(ae_time) !! r = Some p.
Proof.
intros Hr His He Hp Hpq Herq.
destruct (decide (r = e.(ae_orig))) as [Heq|Hreor].
{ apply (DBM_LSV_comp (DBM_LHV_secs_valid His r Hr)).
split; first lia.
apply (Nat.le_trans _ q); first done.
apply (DBM_LSV_strongly_complete
(DBM_LHV_times His) Hr (DBM_LHV_secs_valid His r Hr)).
exists e; split; last done.
by rewrite Heq; apply in_lsec_orig. }
assert (DBM_lsec r s ≠ ∅) as Hrs.
{ rewrite (DBM_lsec_empty i); auto.
intros Hz.
specialize (Hz e He); rewrite Herq in Hz; simplify_eq; lia. }
assert (∃ e' p', e' ∈ DBM_lsec r s ∧ e'.(ae_time) !! r = Some p')
as (e' & p' & He' & Hp').
{ apply set_choose_L in Hrs as (e' & He').
edestruct (in_lhs_time_component e') as [p' Hp'];
eauto using in_lsec_in_lhst. }
assert (1 ≤ p').
{ eapply DBM_LSV_strongly_complete; [|done| |by eauto].
- by eapply DBM_LHV_times; eauto.
- by eapply DBM_LHV_secs_valid; eauto. }
assert (p' ≤ lsec_sup r s).
{ apply nat_sup_UB.
apply elem_of_list_omap.
exists e'; split; first apply elem_of_elements; eauto. }
destruct (decide (p <= lsec_sup r s)).
- assert (1 ≤ p ∧ p <= strings.length (elements (DBM_lsec r s)))
as Hpbounds.
{ split; first lia.
erewrite elem_of_lsec_lsec_sup_length; eauto with lia. }
apply (DBM_LSV_comp (DBM_LHV_secs_valid His r Hr)); eauto.
- assert (lsec_sup r s < p) as HpSup by lia.
assert (q <= lsec_sup r s); last lia.
pose proof (DBM_LHV_origs His e He) as Helsec.
pose proof (DBM_LSV_caus (DBM_LHV_secs_valid His e.(ae_orig) Helsec)
r e Hr Hreor) as Hq.
rewrite Herq /= in Hq.
etrans; first by apply Hq, in_lsec_orig.
apply nat_sup_mono.
intros a; rewrite !elem_of_list_omap;
intros (?&[? ?]%elem_of_list_filter&?); eauto.
Qed.
Lemma empty_lhst_valid i :
i < length DB_addresses →
DBM_lhst_valid i ∅.
Proof.
split; [done|done|done|done|done| |done].
intros ? ?; apply sections_empty_valid; done.
Qed.
Definition Observe_lhst (s : gset apply_event) : apply_event :=
sup ae_seqid lt (ApplyEvent "" #() inhabitant 0 0) (elements s).
Lemma Observe_lhst_max_seqid s e :
(∀ e', e' ∈ s → e' ≠ e → e'.(ae_seqid) < e.(ae_seqid)) →
e ∈ s →
e.(ae_seqid) > 0 →
Observe_lhst s = e.
Proof.
intros Hs Hes Heseq.
assert (e.(ae_seqid) ≤ (Observe_lhst s).(ae_seqid)) as Hseqids.
{ apply (sup_UB ae_seqid lt le); last set_solver; eauto with lia. }
assert (Observe_lhst s = (ApplyEvent "" #() inhabitant 0 0) ∨
Observe_lhst s ∈ s) as Hobs.
{ rewrite -elem_of_elements.
apply find_one_maximal_eq_or_elem_of. }
destruct Hobs as [Hobs| Hobs].
- rewrite Hobs in Hseqids; simpl in *; lia.
- destruct (decide (Observe_lhst s = e)) as [|Hneq]; first done.
specialize (Hs _ Hobs Hneq); lia.
Qed.
Lemma valid_lhst_restrict_key_out i s k :
DBM_lhst_valid i s → k ∉ DB_keys → restrict_key k s = ∅.
Proof.
intros Hvl Hk.
apply set_eq; intros a; split; last done.
apply elem_of_subseteq; intros x.
rewrite elem_of_filter.
intros [<- Hx%(DBM_LHV_keys Hvl)]; done.
Qed.
End Local_history_valid.
|
classdef nme_gen_acp < mp.nme_gen_ac & mp.form_acp
% MATPOWER
% Copyright (c) 2019-2020, Power Systems Engineering Research Center (PSERC)
% by Ray Zimmerman, PSERC Cornell
%
% This file is part of MATPOWER.
% Covered by the 3-clause BSD License (see LICENSE file for details).
% See https://matpower.org for more info.
% properties
% end %% properties
% methods
% end %% methods
end %% classdef
|
# Solving Stiff Equations
### Chris Rackauckas
This tutorial is for getting into the extra features for solving stiff ordinary
differential equations in an efficient manner. Solving stiff ordinary
differential equations requires specializing the linear solver on properties of
the Jacobian in order to cut down on the O(n^3) linear solve and the O(n^2)
back-solves. Note that these same functions and controls also extend to stiff
SDEs, DDEs, DAEs, etc.
## Code Optimization for Differential Equations
### Writing Efficient Code
For a detailed tutorial on how to optimize one's DifferentialEquations.jl code,
please see the
[Optimizing DiffEq Code tutorial](http://tutorials.juliadiffeq.org/html/introduction/03-optimizing_diffeq_code.html).
### Choosing a Good Solver
Choosing a good solver is required for getting top notch speed. General
recommendations can be found on the solver page (for example, the
[ODE Solver Recommendations](https://docs.juliadiffeq.org/latest/solvers/ode_solve)).
The current recommendations can be simplified to a Rosenbrock method
(`Rosenbrock23` or `Rodas5`) for smaller (<50 ODEs) problems, ESDIRK methods
for slightly larger (`TRBDF2` or `KenCarp4` for <2000 ODEs), and Sundials
`CVODE_BDF` for even larger problems. `lsoda` from
[LSODA.jl](https://github.com/rveltz/LSODA.jl) is generally worth a try.
More details on the solver to choose can be found by benchmarking. See the
[DiffEqBenchmarks](https://github.com/JuliaDiffEq/DiffEqBenchmarks.jl) to
compare many solvers on many problems.
### Check Out the Speed FAQ
See [this FAQ](http://docs.juliadiffeq.org/latest/basics/faq.html#Performance-1)
for information on common pitfalls and how to improve performance.
### Setting Up Your Julia Installation for Speed
Julia uses an underlying BLAS implementation for its matrix multiplications
and factorizations. This library is automatically multithreaded and accelerates
the internal linear algebra of DifferentialEquations.jl. However, for optimality,
you should make sure that the number of BLAS threads that you are using matches
the number of physical cores and not the number of logical cores. See
[this issue for more details](https://github.com/JuliaLang/julia/issues/33409).
To check the number of BLAS threads, use:
```julia
ccall((:openblas_get_num_threads64_, Base.libblas_name), Cint, ())
```
8
If I want to set this directly to 4 threads, I would use:
```julia
using LinearAlgebra
LinearAlgebra.BLAS.set_num_threads(4)
```
Additionally, in some cases Intel's MKL might be a faster BLAS than the standard
BLAS that ships with Julia (OpenBLAS). To switch your BLAS implementation, you
can use [MKL.jl](https://github.com/JuliaComputing/MKL.jl) which will accelerate
the linear algebra routines. Please see the package for the limitations.
### Use Accelerator Hardware
When possible, use GPUs. If your ODE system is small and you need to solve it
with very many different parameters, see the
[ensembles interface](https://docs.juliadiffeq.org/latest/features/ensemble)
and [DiffEqGPU.jl](https://github.com/JuliaDiffEq/DiffEqGPU.jl). If your problem
is large, consider using a [CuArray](https://github.com/JuliaGPU/CuArrays.jl)
for the state to allow for GPU-parallelism of the internal linear algebra.
## Speeding Up Jacobian Calculations
When one is using an implicit or semi-implicit differential equation solver,
the Jacobian must be built at many iterations and this can be one of the most
expensive steps. There are two pieces that must be optimized in order to reach
maximal efficiency when solving stiff equations: the sparsity pattern and the
construction of the Jacobian. The construction is filling the matrix
`J` with values, while the sparsity pattern is what `J` to use.
The sparsity pattern is given by a prototype matrix, the `jac_prototype`, which
will be copied to be used as `J`. The default is for `J` to be a `Matrix`,
i.e. a dense matrix. However, if you know the sparsity of your problem, then
you can pass a different matrix type. For example, a `SparseMatrixCSC` will
give a sparse matrix. Additionally, structured matrix types like `Tridiagonal`,
`BandedMatrix` (from
[BandedMatrices.jl](https://github.com/JuliaMatrices/BandedMatrices.jl)),
`BlockBandedMatrix` (from
[BlockBandedMatrices.jl](https://github.com/JuliaMatrices/BlockBandedMatrices.jl)),
and more can be given. DifferentialEquations.jl will internally use this matrix
type, making the factorizations faster by utilizing the specialized forms.
For the construction, there are 3 ways to fill `J`:
- The default, which uses normal finite/automatic differentiation
- A function `jac(J,u,p,t)` which directly computes the values of `J`
- A `colorvec` which defines a sparse differentiation scheme.
We will now showcase how to make use of this functionality with growing complexity.
### Declaring Jacobian Functions
Let's solve the Rosenbrock equations:
$$\begin{align}
dy_1 &= -0.04y₁ + 10^4 y_2 y_3 \\
dy_2 &= 0.04 y_1 - 10^4 y_2 y_3 - 3*10^7 y_{2}^2 \\
dy_3 &= 3*10^7 y_{3}^2 \\
\end{align}$$
In order to reduce the Jacobian construction cost, one can describe a Jacobian
function by using the `jac` argument for the `ODEFunction`. First, let's do
a standard `ODEProblem`:
```julia
using DifferentialEquations
function rober(du,u,p,t)
y₁,y₂,y₃ = u
k₁,k₂,k₃ = p
du[1] = -k₁*y₁+k₃*y₂*y₃
du[2] = k₁*y₁-k₂*y₂^2-k₃*y₂*y₃
du[3] = k₂*y₂^2
nothing
end
prob = ODEProblem(rober,[1.0,0.0,0.0],(0.0,1e5),(0.04,3e7,1e4))
sol = solve(prob,Rosenbrock23())
using Plots
plot(sol, xscale=:log10, tspan=(1e-6, 1e5), layout=(3,1))
```
```julia
using BenchmarkTools
@btime solve(prob)
```
Now we want to add the Jacobian. First we have to derive the Jacobian
$\frac{df_i}{du_j}$ which is `J[i,j]`. From this we get:
```julia
function rober_jac(J,u,p,t)
y₁,y₂,y₃ = u
k₁,k₂,k₃ = p
J[1,1] = k₁ * -1
J[2,1] = k₁
J[3,1] = 0
J[1,2] = y₃ * k₃
J[2,2] = y₂ * k₂ * -2 + y₃ * k₃ * -1
J[3,2] = y₂ * 2 * k₂
J[1,3] = k₃ * y₂
J[2,3] = k₃ * y₂ * -1
J[3,3] = 0
nothing
end
f = ODEFunction(rober, jac=rober_jac)
prob_jac = ODEProblem(f,[1.0,0.0,0.0],(0.0,1e5),(0.04,3e7,1e4))
@btime solve(prob_jac)
```
### Automatic Derivation of Jacobian Functions
But that was hard! If you want to take the symbolic Jacobian of numerical
code, we can make use of [ModelingToolkit.jl](https://github.com/JuliaDiffEq/ModelingToolkit.jl)
to symbolicify the numerical code and do the symbolic calculation and return
the Julia code for this.
```julia
using ModelingToolkit
de = modelingtoolkitize(prob)
ModelingToolkit.generate_jacobian(de...)[2] # Second is in-place
```
which outputs:
```julia
:((##MTIIPVar#376, u, p, t)->begin
#= C:\Users\accou\.julia\packages\ModelingToolkit\czHtj\src\utils.jl:65 =#
#= C:\Users\accou\.julia\packages\ModelingToolkit\czHtj\src\utils.jl:66 =#
let (x₁, x₂, x₃, α₁, α₂, α₃) = (u[1], u[2], u[3], p[1], p[2], p[3])
##MTIIPVar#376[1] = α₁ * -1
##MTIIPVar#376[2] = α₁
##MTIIPVar#376[3] = 0
##MTIIPVar#376[4] = x₃ * α₃
##MTIIPVar#376[5] = x₂ * α₂ * -2 + x₃ * α₃ * -1
##MTIIPVar#376[6] = x₂ * 2 * α₂
##MTIIPVar#376[7] = α₃ * x₂
##MTIIPVar#376[8] = α₃ * x₂ * -1
##MTIIPVar#376[9] = 0
end
#= C:\Users\accou\.julia\packages\ModelingToolkit\czHtj\src\utils.jl:67 =#
nothing
end)
```
Now let's use that to give the analytical solution Jacobian:
```julia
jac = eval(ModelingToolkit.generate_jacobian(de...)[2])
f = ODEFunction(rober, jac=jac)
prob_jac = ODEProblem(f,[1.0,0.0,0.0],(0.0,1e5),(0.04,3e7,1e4))
```
### Declaring a Sparse Jacobian
Jacobian sparsity is declared by the `jac_prototype` argument in the `ODEFunction`.
Note that you should only do this if the sparsity is high, for example, 0.1%
of the matrix is non-zeros, otherwise the overhead of sparse matrices can be higher
than the gains from sparse differentiation!
But as a demonstration, let's build a sparse matrix for the Rober problem. We
can do this by gathering the `I` and `J` pairs for the non-zero components, like:
```julia
I = [1,2,1,2,3,1,2]
J = [1,1,2,2,2,3,3]
using SparseArrays
jac_prototype = sparse(I,J,1.0)
```
Now this is the sparse matrix prototype that we want to use in our solver, which
we then pass like:
```julia
f = ODEFunction(rober, jac=jac, jac_prototype=jac_prototype)
prob_jac = ODEProblem(f,[1.0,0.0,0.0],(0.0,1e5),(0.04,3e7,1e4))
```
### Automatic Sparsity Detection
One of the useful companion tools for DifferentialEquations.jl is
[SparsityDetection.jl](https://github.com/JuliaDiffEq/SparsityDetection.jl).
This allows for automatic declaration of Jacobian sparsity types. To see this
in action, let's look at the 2-dimensional Brusselator equation:
```julia
const N = 32
const xyd_brusselator = range(0,stop=1,length=N)
brusselator_f(x, y, t) = (((x-0.3)^2 + (y-0.6)^2) <= 0.1^2) * (t >= 1.1) * 5.
limit(a, N) = a == N+1 ? 1 : a == 0 ? N : a
function brusselator_2d_loop(du, u, p, t)
A, B, alpha, dx = p
alpha = alpha/dx^2
@inbounds for I in CartesianIndices((N, N))
i, j = Tuple(I)
x, y = xyd_brusselator[I[1]], xyd_brusselator[I[2]]
ip1, im1, jp1, jm1 = limit(i+1, N), limit(i-1, N), limit(j+1, N), limit(j-1, N)
du[i,j,1] = alpha*(u[im1,j,1] + u[ip1,j,1] + u[i,jp1,1] + u[i,jm1,1] - 4u[i,j,1]) +
B + u[i,j,1]^2*u[i,j,2] - (A + 1)*u[i,j,1] + brusselator_f(x, y, t)
du[i,j,2] = alpha*(u[im1,j,2] + u[ip1,j,2] + u[i,jp1,2] + u[i,jm1,2] - 4u[i,j,2]) +
A*u[i,j,1] - u[i,j,1]^2*u[i,j,2]
end
end
p = (3.4, 1., 10., step(xyd_brusselator))
```
Given this setup, we can give and example `input` and `output` and call `sparsity!`
on our function with the example arguments and it will kick out a sparse matrix
with our pattern, that we can turn into our `jac_prototype`.
```julia
using SparsityDetection, SparseArrays
input = rand(32,32,2)
output = similar(input)
sparsity_pattern = sparsity!(brusselator_2d_loop,output,input,p,0.0)
jac_sparsity = Float64.(sparse(sparsity_pattern))
```
Let's double check what our sparsity pattern looks like:
```julia
using Plots
spy(jac_sparsity,markersize=1,colorbar=false,color=:deep)
```
That's neat, and would be tedius to build by hand! Now we just pass it to the
`ODEFunction` like as before:
```julia
f = ODEFunction(brusselator_2d_loop;jac_prototype=jac_sparsity)
```
Build the `ODEProblem`:
```julia
function init_brusselator_2d(xyd)
N = length(xyd)
u = zeros(N, N, 2)
for I in CartesianIndices((N, N))
x = xyd[I[1]]
y = xyd[I[2]]
u[I,1] = 22*(y*(1-y))^(3/2)
u[I,2] = 27*(x*(1-x))^(3/2)
end
u
end
u0 = init_brusselator_2d(xyd_brusselator)
prob_ode_brusselator_2d = ODEProblem(brusselator_2d_loop,
u0,(0.,11.5),p)
prob_ode_brusselator_2d_sparse = ODEProblem(f,
u0,(0.,11.5),p)
```
Now let's see how the version with sparsity compares to the version without:
```julia
@btime solve(prob_ode_brusselator_2d,save_everystep=false)
@btime solve(prob_ode_brusselator_2d_sparse,save_everystep=false)
```
### Declaring Color Vectors for Fast Construction
If you cannot directly define a Jacobian function, you can use the `colorvec`
to speed up the Jacobian construction. What the `colorvec` does is allows for
calculating multiple columns of a Jacobian simultaniously by using the sparsity
pattern. An explanation of matrix coloring can be found in the
[MIT 18.337 Lecture Notes](https://mitmath.github.io/18337/lecture9/stiff_odes).
To perform general matrix coloring, we can use
[SparseDiffTools.jl](https://github.com/JuliaDiffEq/SparseDiffTools.jl). For
example, for the Brusselator equation:
```julia
using SparseDiffTools
colorvec = matrix_colors(jac_sparsity)
@show maximum(colorvec)
```
This means that we can now calculate the Jacobian in 12 function calls. This is
a nice reduction from 2048 using only automated tooling! To now make use of this
inside of the ODE solver, you simply need to declare the colorvec:
```julia
f = ODEFunction(brusselator_2d_loop;jac_prototype=jac_sparsity,
colorvec=colorvec)
prob_ode_brusselator_2d_sparse = ODEProblem(f,
init_brusselator_2d(xyd_brusselator),
(0.,11.5),p)
@btime solve(prob_ode_brusselator_2d_sparse,save_everystep=false)
```
Notice the massive speed enhancement!
## Defining Linear Solver Routines and Jacobian-Free Newton-Krylov
A completely different way to optimize the linear solvers for large sparse
matrices is to use a Krylov subpsace method. This requires choosing a linear
solver for changing to a Krylov method. Optionally, one can use a Jacobian-free
operator to reduce the memory requirements.
### Declaring a Jacobian-Free Newton-Krylov Implementation
To swap the linear solver out, we use the `linsolve` command and choose the
GMRES linear solver.
```julia
@btime solve(prob_ode_brusselator_2d,TRBDF2(linsolve=LinSolveGMRES()),save_everystep=false)
@btime solve(prob_ode_brusselator_2d_sparse,TRBDF2(linsolve=LinSolveGMRES()),save_everystep=false)
```
For more information on linear solver choices, see the
[linear solver documentation](https://docs.juliadiffeq.org/latest/features/linear_nonlinear).
On this problem, handling the sparsity correctly seemed to give much more of a
speedup than going to a Krylov approach, but that can be dependent on the problem
(and whether a good preconditioner is found).
We can also enhance this by using a Jacobian-Free implementation of `f'(x)*v`.
To define the Jacobian-Free operator, we can use
[DiffEqOperators.jl](https://github.com/JuliaDiffEq/DiffEqOperators.jl) to generate
an operator `JacVecOperator` such that `Jv*v` performs `f'(x)*v` without building
the Jacobian matrix.
```julia
using DiffEqOperators
Jv = JacVecOperator(brusselator_2d_loop,u0,p,0.0)
```
and then we can use this by making it our `jac_prototype`:
```julia
f = ODEFunction(brusselator_2d_loop;jac_prototype=Jv)
prob_ode_brusselator_2d_jacfree = ODEProblem(f,u0,(0.,11.5),p)
@btime solve(prob_ode_brusselator_2d_jacfree,TRBDF2(linsolve=LinSolveGMRES()),save_everystep=false)
```
### Adding a Preconditioner
The [linear solver documentation](https://docs.juliadiffeq.org/latest/features/linear_nonlinear/#iterativesolvers-jl-1)
shows how you can add a preconditioner to the GMRES. For example, you can
use packages like [AlgebraicMultigrid.jl](https://github.com/JuliaLinearAlgebra/AlgebraicMultigrid.jl)
to add an algebraic multigrid (AMG) or [IncompleteLU.jl](https://github.com/haampie/IncompleteLU.jl)
for an incomplete LU-factorization (iLU).
```julia
using AlgebraicMultigrid
pc = aspreconditioner(ruge_stuben(jac_sparsity))
@btime solve(prob_ode_brusselator_2d_jacfree,TRBDF2(linsolve=LinSolveGMRES(Pl=pc)),save_everystep=false)
```
## Using Structured Matrix Types
If your sparsity pattern follows a specific structure, for example a banded
matrix, then you can declare `jac_prototype` to be of that structure and then
additional optimizations will come for free. Note that in this case, it is
not necessary to provide a `colorvec` since the color vector will be analytically
derived from the structure of the matrix.
The matrices which are allowed are those which satisfy the
[ArrayInterface.jl](https://github.com/JuliaDiffEq/ArrayInterface.jl) interface
for automatically-colorable matrices. These include:
- Bidiagonal
- Tridiagonal
- SymTridiagonal
- BandedMatrix ([BandedMatrices.jl](https://github.com/JuliaMatrices/BandedMatrices.jl))
- BlockBandedMatrix ([BlockBandedMatrices.jl](https://github.com/JuliaMatrices/BlockBandedMatrices.jl))
Matrices which do not satisfy this interface can still be used, but the matrix
coloring will not be automatic, and an appropriate linear solver may need to
be given (otherwise it will default to attempting an LU-decomposition).
## Sundials-Specific Handling
While much of the setup makes the transition to using Sundials automatic, there
are some differences between the pure Julia implementations and the Sundials
implementations which must be taken note of. These are all detailed in the
[Sundials solver documentation](https://docs.juliadiffeq.org/latest/solvers/ode_solve/#ode_solve_sundials-1),
but here we will highlight the main details which one should make note of.
Defining a sparse matrix and a Jacobian for Sundials works just like any other
package. The core difference is in the choice of the linear solver. With Sundials,
the linear solver choice is done with a Symbol in the `linear_solver` from a
preset list. Particular choices of note are `:Band` for a banded matrix and
`:GMRES` for using GMRES. If you are using Sundials, `:GMRES` will not require
defining the JacVecOperator, and instead will always make use of a Jacobian-Free
Newton Krylov (with numerical differentiation). Thus on this problem we could do:
```julia
using Sundials
# Sparse Version
@btime solve(prob_ode_brusselator_2d_sparse,CVODE_BDF(),save_everystep=false)
# GMRES Version: Doesn't require any extra stuff!
@btime solve(prob_ode_brusselator_2d,CVODE_BDF(linear_solver=:GMRES),save_everystep=false)
```
Details for setting up a preconditioner with Sundials can be found at the
[Sundials solver page](https://docs.juliadiffeq.org/latest/solvers/ode_solve/#ode_solve_sundials-1).
## Handling Mass Matrices
Instead of just defining an ODE as $u' = f(u,p,t)$, it can be common to express
the differential equation in the form with a mass matrix:
$$Mu' = f(u,p,t)$$
where $M$ is known as the mass matrix. Let's solve the Robertson equation.
At the top we wrote this equation as:
$$\begin{align}
dy_1 &= -0.04y₁ + 10^4 y_2 y_3 \\
dy_2 &= 0.04 y_1 - 10^4 y_2 y_3 - 3*10^7 y_{2}^2 \\
dy_3 &= 3*10^7 y_{3}^2 \\
\end{align}$$
But we can instead write this with a conservation relation:
$$\begin{align}
dy_1 &= -0.04y₁ + 10^4 y_2 y_3 \\
dy_2 &= 0.04 y_1 - 10^4 y_2 y_3 - 3*10^7 y_{2}^2 \\
1 &= y_{1} + y_{2} + y_{3} \\
\end{align}$$
In this form, we can write this as a mass matrix ODE where $M$ is singular
(this is another form of a differential-algebraic equation (DAE)). Here, the
last row of `M` is just zero. We can implement this form as:
```julia
using DifferentialEquations
function rober(du,u,p,t)
y₁,y₂,y₃ = u
k₁,k₂,k₃ = p
du[1] = -k₁*y₁+k₃*y₂*y₃
du[2] = k₁*y₁-k₂*y₂^2-k₃*y₂*y₃
du[3] = y₁ + y₂ + y₃ - 1
nothing
end
M = [1. 0 0
0 1. 0
0 0 0]
f = ODEFunction(rober,mass_matrix=M)
prob_mm = ODEProblem(f,[1.0,0.0,0.0],(0.0,1e5),(0.04,3e7,1e4))
sol = solve(prob_mm,Rodas5())
plot(sol, xscale=:log10, tspan=(1e-6, 1e5), layout=(3,1))
```
Note that if your mass matrix is singular, i.e. your system is a DAE, then you
need to make sure you choose
[a solver that is compatible with DAEs](https://docs.juliadiffeq.org/latest/solvers/dae_solve/#dae_solve_full-1)
|
import Data.Vect
MkBig : Nat -> Type
MkBig Z = Int
MkBig (S k) = ((n ** Vect n Int), MkBig k)
bigEx : (n : Nat) -> MkBig n
bigEx Z = 94
bigEx (S k) = ((2 ** [0,0]), bigEx k)
data VWrap : Type -> Type where
MkVWrap : (0 n : Nat) -> Vect n a -> VWrap a
export
MkBig' : Nat -> Type
MkBig' Z = Int
MkBig' (S k) = (VWrap Int, MkBig' k)
namespace Foo
public
export
bigEx' : (n : Nat) -> MkBig' n
bigEx' Z = 94
bigEx' (S k) = (MkVWrap 1 [0], bigEx' k)
eqBigs : bigEx 1000000 = bigEx 1000000
eqBigs = Refl
eqBigs' : bigEx' 800000 = bigEx' 800000
eqBigs' = Refl
|
rebol []
dat-io: make stream-io []
to-timestamp: func[date [date!] /local time][
time: any [date/time 0:0:0]
first parse form ((date - 1-1-1970) * 86400)
+ (time/hour * 3600)
+ (time/minute * 60)
+ time/second
- to integer! (any [date/zone 0])
"."
]
make-id: has [date time][
date: now
time: any [date/time 0:0:0]
join enbase/base head reverse int-to-ui32 ((date - 1-1-1970) * 86400)
+ (time/hour * 3600)
+ (time/minute * 60)
+ time/second
- to integer! (any [date/zone 0])
16
["-" enbase/base head reverse int-to-ui32 num-imported: num-imported + 1 16]
]
import-media-img: func[
"Imports media item into DAT file"
source-file
/dom "updates DOMDocument.xml file as well"
/as dat-file
/smoothing smVal
/local node imgFormat width height ARGB buf name tmp
][
if verbose > 0 [print ["IMPORTING DOMBitmapItem::" mold source-file]]
source-file: to-rebol-file source-file
if #"/" <> first source-file [insert source-file what-dir]
unless as [dat-file: rejoin [%My " 1 " checksum source-file %.dat]]
with ctx-imagick [
start
unless zero? MagickReadImage *wand to-local-file source-file [
either find ["JPG" "JPEG"] imgFormat: MagickGetImageFormat *wand [
write/binary xfl-source-dir/bin/:dat-file read/binary source-file
][
;img: imageCore/load source-file
;ARGB: img/bARGB
;width: img/size/x
;height: img/size/y
width: MagickGetImageWidth *wand
height: MagickGetImageHeight *wand
ARGB: make binary! (width * height * 4)
insert/dup ARGB #{00} (width * height * 4)
try MagickExportImagePixels *wand 0 0 width height "ARGB" 1 address? ARGB
premultiply ARGB
comment {
while [not tail? ARGB][
a: ARGB/1
ARGB: next ARGB
ARGB: change ARGB to char! ((a * ARGB/1) / 255)
ARGB: change ARGB to char! ((a * ARGB/1) / 255)
ARGB: change ARGB to char! ((a * ARGB/1) / 255)
]
ARGB: head ARGB
}
;write/binary probe to-file join source-file %.argb argb
with dat-io [
clearOutBuffer
writeBytes #{0305}
writeUI16 width * 4
writeUI16 width
writeUI16 height
writeBytes #{00000000}
writeUI32 width * 20
writeBytes #{00000000}
writeUI32 height * 20
writeBytes #{01}
writeBytes #{010200}
ARGB: zlib/compress/level ARGB 1 ;;head clear skip tail compress ARGB -4
writeBytes copy/part ARGB 2
remove/part ARGB 2
while [not empty? ARGB][
buf: copy/part ARGB 2048
remove/part ARGB 2048
writeUI16 length? buf
writeBytes buf
]
writeBytes #{0000}
write/binary xfl-target-dir/bin/:dat-file head outBuffer
]
if dom [
name: encode-entities decode-filename form last split-path source-file
if find name #"." [name: head clear find/last name #"."]
unless find Media name [
;print "---"
insert/only Media-content node: reduce [
"DOMBitmapItem" tmp: reduce [
"name" name
"itemID" make-id
"sourceExternalFilepath" join ".\LIBRARY\" [name "." imgFormat]
"externalFileSize" mold size? source-file
"sourceLastImported" to-timestamp now
"href" join ".\LIBRARY\" [name "." imgFormat]
"bitmapDataHRef" to-string dat-file
"allowSmoothing" either any [smVal = true smVal = "true"] ["true"]["false"]
"frameRight" 20 * width
"frameBottom" 20 * height
]
]
append tmp either imgFormat = "JPG" [
["isJPEG" "true"]
][
["useImportedJPEGData" "false" "compressionType" "lossless" "originalCompressionType" "lossless"]
]
new-line/all tmp false
new-line/all Media-content true
;probe Media-content
;ask "-imp-done-"
]
]
]
]
end
]
node
]
export-media-item: func[
"Exports media item from dat file to the Library folder"
item
/into-file item-file
/overwrite
/local len-decompressed width height argb chunk-length *pixel ext-file errmsg dat-id a
][
if verbose > 0 [print ["EXPORTING MediaItem::" mold item-file]]
if verbose > 1 [probe item]
unless into-file [
item-file: join "./LIBRARY/" last parse/all any [
select item "sourceExternalFilepath"
item/("href")
] "/\"
]
unless find ["png" "jpg"] last parse item-file "." [append item-file %.png]
item/("sourceExternalFilepath"): item/("href"): item-file
if all [
exists? xfl-source-dir/bin/(item/("bitmapDataHRef"))
any [
(
ext-file: join xfl-target-dir to-rebol-file item-file
overwrite
)
not exists? ext-file
]
][
with dat-io [
setStreamBuffer read/binary xfl-source-dir/bin/(item/("bitmapDataHRef"))
switch/default dat-id: readBytes 2 [;bitmap identifier?
#{FFD8} [;jpeg
if verbose > 1 [print ["as JPEG"]]
inBuffer: head inBuffer
with ctx-imagick [
start
unless all [
MagickReadImageBlob *wand address? inBuffer length? inBuffer
not zero? MagickWriteImages *wand to-local-file ext-file
][
errmsg: reform [
Exception/Severity "="
ptr-to-string desc: MagickGetException *wand Exception
]
MagickRelinquishMemory desc
end
make error! errmsg
]
end
]
;write/binary ext-file head inBuffer
]
#{0303} [;???
print ["Exporting unknown IMG?" item-file]
probe len-decompressed: readUI16
width: readUI16
height: readUI16
print ["size:" as-pair width height]
probe readBytes 4
probe readUI32 4
probe readBytes 4
probe readUI32 4
probe readBytes 1
;probe xx: readBytes 17 ;???
argb: none
probe readRest
ask ""
]
#{0305} [;raw image
if verbose > 1 [print ["as RAW"]]
len-decompressed: readUI16
width: readUI16
height: readUI16
if verbose > 1 [print ["size:" as-pair width height]]
readBytes 17 ;???
argb: none
switch/default readBytes 1 [
#{00} [
argb: readRest
]
#{01} [
argb: make binary! (width * height * 4)
while [0 < chunk-length: readUI16][
insert tail argb readBytes chunk-length
]
argb: as-binary zlib/decompress/l argb (width * height * 4)
]
][
ask "!!! UNKNOWN DAT IMG STRUCT !!!"
]
if argb [
if (length? argb) <> (width * height * 4) [
ask ["Inbalid ARGB length?" (length? argb) "<>" (width * height * 4)]
]
demultiply argb
with ctx-imagick [
start
*pixel: NewPixelWand
unless all [
not zero? MagickNewImage *wand width height *pixel
not zero? MagickSetImageBackgroundColor *wand *pixel
not zero? MagickImportImagePixels *wand 0 0 width height "ARGB" 1 address? ARGB
not zero? MagickSetImageDepth *wand 8
not zero? MagickWriteImages *wand to-local-file ext-file
][
errmsg: reform [
Exception/Severity "="
ptr-to-string desc: MagickGetException *wand Exception
]
MagickRelinquishMemory desc
end
make error! errmsg
]
if *pixel [
ClearPixelWand *pixel
DestroyPixelWand *pixel
]
end
]
]
]
][
print ["UNKNOWN DAT TYPE:" dat-id (item/("bitmapDataHRef"))]
]
]
]
if verbose > 1 [probe ext-file]
either all [
not none? ext-file
exists? ext-file: to-rebol-file ext-file
][
ext-file
][ none]
]
export-media: func[
"Exports images from dat files to the Library folder"
/local
][
foreach [name item] media [
export-media-item item
]
]
export-sound: func[
item
/local dat-file sz wav0file sampleRate SignificantBitsPerSample NumChannels BlockAlign
][
probe item
probe dat-file: join xfl-source-dir [%bin/ item/("soundDataHRef")]
probe sz: size? dat-file
wav-file: join xfl-target-dir [%LIBRARY/ item/("name")]
unless parse item/("format") [
copy tmp some ch_digits "kHz" (
unless sampleRate: select [
"8" 8000
"11" 11025
"16" 16000
"22" 22050
"32" 32000
"44" 44100
"48" 48000
"96" 96000
"192" 192000
] tmp [
ask ["!!! Unknown sampleRate:" mold item/("format")]
]
)
SP
copy SignificantBitsPerSample some ch_digits "bit" (
SignificantBitsPerSample: to-integer SignificantBitsPerSample
)
SP
[
"stereo" (NumChannels: 2) |
"mono" (NumChannels: 1)
]
to end
][
ask ["!!! UNKNOWN SoundItem format" mold item/("format")]
]
BlockAlign: SignificantBitsPerSample / 8 * NumChannels
if "wav" <> last parse wav-file "." [append wav-file %.wav]
with dat-io [
clearOutBuffer
writeBytes "RIFF"
writeUI32 (sz + 36)
writeBytes "WAVE"
writebytes "fmt "
writeUI32 16 ;chunk size!
writeUI16 1 ;Compression code, 1 = PCM
writeUI16 2 ;Num channels
writeUI32 sampleRate
writeUI32 sampleRate * BlockAlign ;176400 ;bytes per sec
writeUI16 BlockAlign
writeUI16 SignificantBitsPerSample
writeBytes "data"
writeUI32 sz
write/binary wav-file head outBuffer
write/binary/append wav-file read/binary dat-file
]
]
|
Any two subspaces of Euclidean spaces of the same dimension are homeomorphic. |
import implementation.model.predicate
import implementation.model.sys_state
import implementation.spec.main
import implementation.proof.misc
import implementation.proof.proposer
-- This file contains proofs about voters (or what can be associated with
-- them in our co-located Paxos implementation).
--
-- NOTE(gnanabit): comments are omitted for facts that are "obvious" or not
-- particularly revealing about paxos.
variables {pid_t : Type} [linear_order pid_t] [fintype pid_t] {value_t : Type}
{is_quorum : finset pid_t → Prop} [decidable_pred is_quorum]
[quorum_assumption is_quorum] {vals : pid_t → value_t}
-- A server's ballot is always larger than or equal to the ballot in the
-- proposal it has stored in `accepted` (if such a proposal exists).
--
-- Similarly, the ballot in a p1b is always larger than the proposal stored in
-- the p1b.
lemma current_ge_accepted_ballot : predicate.invariant
(λ (s : sys_state pid_t (server pid_t value_t is_quorum vals) (message pid_t value_t)),
(∀ (p : pid_t) (prop : proposal pid_t value_t),
(s.procs p).accepted = some prop → prop.bal ≤ (s.procs p).curr) ∧
(∀ (p : pid_t) (e ∈ s.network p) (b : ballot pid_t) (prop : proposal pid_t value_t),
(envelope.msg e) = message.p1b b (option.some prop) → prop.bal ≤ b)) :=
begin
suffices : predicate.inductive_invariant _,
by { exact predicate.ind_inv_is_inv this },
split,
{ intros s hs,
split;
intro p;
specialize hs p;
unfold protocol.init at hs;
injection hs with start_proc start_network,
{ rw ← start_proc,
intro prop,
trivial },
rw ← start_network,
intros e he b prop contradicts_he,
cases he,
{ rw he at contradicts_he, injection contradicts_he },
rw set.mem_singleton_iff at he,
rw he at contradicts_he, injection contradicts_he },
intros u v,
rintros ⟨servers_satisfy, promises_satisfy⟩,
intro u_pn_v,
have to_split := u_pn_v,
rcases to_split with ⟨receiver, sender, e, he, deliverable, proc_change, ntwk_change, same⟩,
split;
intro p;
cases decidable.em (p = receiver),
{ clear same,
intro prop,
rw h, clear h p,
rw proc_change,
have delta := state_change receiver (u.procs receiver) e.msg sender,
cases delta,
{ rw delta, exact servers_satisfy receiver prop },
cases e,
cases e_msg,
case p1a : b {
cases delta with new_ballot_larger b_is_new_ballot,
rw b_is_new_ballot,
intro hyp,
apply le_of_lt,
calc prop.bal ≤ (u.procs receiver).curr : servers_satisfy receiver prop hyp
... < b : new_ballot_larger
},
case p1b : b p_or {
cases delta,
{ cases delta with new_ballot_larger b_is_new_ballot,
rw b_is_new_ballot,
intro hyp,
apply le_of_lt,
calc prop.bal ≤ (u.procs receiver).curr : servers_satisfy receiver prop hyp
... < b : new_ballot_larger },
cases delta,
{ rw delta.right.right.right.right,
intro hyp,
have key : prop.bal = (u.procs receiver).curr,
by {
injection hyp with key,
rw ← key
},
rw key },
rw delta.right.right.right.right.right,
intro hyp,
cases proposal.merge_is_one_of (u.procs receiver).accepted p_or,
{ rw h at hyp,
exact servers_satisfy receiver prop hyp },
rw h at hyp,
rw delta.left,
apply promises_satisfy sender {msg := message.p1b b p_or, sent_to := e_sent_to} he b prop,
rw ← hyp
},
case p2a : p {
cases delta with new_ballot_larger b_is_new_ballot,
rw b_is_new_ballot,
intro hyp,
have key : p = prop, by { injection hyp },
rw key
},
case p2b : b acc {
cases delta with new_ballot_larger b_is_new_ballot,
rw b_is_new_ballot,
intro hyp,
apply le_of_lt,
calc prop.bal ≤ (u.procs receiver).curr : servers_satisfy receiver prop hyp
... < b : new_ballot_larger
},
case preempt : {
cases delta with ballot_not_from_self ballot_is_next,
rw ballot_is_next,
intro hyp,
apply le_of_lt,
calc prop.bal ≤ (u.procs receiver).curr : servers_satisfy receiver prop hyp
... < ballot.next receiver (u.procs receiver).curr : ballot.next_larger receiver (u.procs receiver).curr,
}},
{ rw same.left p h, exact servers_satisfy p },
{ rw h, clear h p,
intros e' he' b prop e'_msg_eq,
rw ntwk_change at he',
cases he',
{ exact promises_satisfy receiver e' he' b prop e'_msg_eq },
rcases p1b_emitted e'_msg_eq he' with ⟨b', e_msg_is, accepted_unchanged, b_is_max⟩,
calc prop.bal ≤ (u.procs receiver).curr : servers_satisfy receiver prop accepted_unchanged
... ≤ b : by { rw ← b_is_max,
exact le_max_left (u.procs receiver).curr b'} },
rw same.right p h, exact promises_satisfy p
end
-- Any stored proposal has been proposed in some p2a (a stored proposal is one in either a p1b
-- or in a server's `accepted` field).
lemma accepted_means_issued : predicate.invariant
(λ (s : sys_state pid_t (server pid_t value_t is_quorum vals) (message pid_t value_t)),
(∀ (p : pid_t) (prop : proposal pid_t value_t),
(s.procs p).accepted = some prop → proposed s prop.bal prop.val) ∧
(∀ (p : pid_t) (e ∈ s.network p) (b : ballot pid_t) (prop : proposal pid_t value_t),
(envelope.msg e) = message.p1b b (option.some prop) → proposed s prop.bal prop.val))
:=
begin
suffices : predicate.inductive_invariant _,
by { exact predicate.ind_inv_is_inv this },
split,
{ intros s hs,
split;
intro p;
specialize hs p;
unfold protocol.init at hs;
injection hs with start_proc start_network,
{ rw ← start_proc,
intro prop,
trivial },
rw ← start_network,
intros e he b prop contradicts_he,
cases he,
{ rw he at contradicts_he, injection contradicts_he },
rw set.mem_singleton_iff at he,
rw he at contradicts_he, injection contradicts_he },
intros u v,
rintros ⟨accepted_satisfies, promises_satisfy⟩,
intro u_pn_v,
have to_split := u_pn_v,
rcases to_split with ⟨receiver, sender, e, he, deliverable, proc_change, ntwk_change, same⟩,
split;
intro p;
cases decidable.em (p = receiver),
{ rw h,
clear h p,
rw proc_change,
intros prop h_prop,
suffices key : proposed u prop.bal prop.val ∨
(∃ e' ∈ (protocol.handler receiver (u.procs receiver) e.msg sender).snd,
envelope.msg e' = message.p2a prop),
by {
cases key,
{ exact proposed_stable prop.bal prop.val u v key u_pn_v },
{ rcases key with ⟨e', he', e'_msg_is⟩,
use [receiver, e'],
split,
{ rw ntwk_change, right, exact he' },
rw e'_msg_is, cases prop, refl },
},
have acc_unchanged_enough : (protocol.handler receiver (u.procs receiver) e.msg sender).fst.accepted = (u.procs receiver).accepted → proposed u prop.bal prop.val ∨
(∃ e' ∈ (protocol.handler receiver (u.procs receiver) e.msg sender).snd,
envelope.msg e' = message.p2a prop), by {
intro hyp, left, rw hyp at h_prop, exact accepted_satisfies receiver prop h_prop
},
have key := state_change receiver (u.procs receiver) e.msg sender,
cases key,
{ left, rw key at h_prop, exact accepted_satisfies receiver prop h_prop },
cases e,
cases e_msg,
case p1a : b { apply acc_unchanged_enough, rw key.right },
case p1b : b p_or {
cases key,
{ apply acc_unchanged_enough, rw key.right },
cases key,
{ right,
clear acc_unchanged_enough,
rcases key with ⟨same_bal, bal_from_self, u_no_qrm, v_has_qrm, state_change⟩,
have prop_eq: { proposal . bal := (u.procs receiver).curr,
val := proposal.value_or_default
(proposal.merge (u.procs receiver).accepted p_or)
(vals receiver)} = prop, by {
rw state_change at h_prop, injection h_prop
},
use {envelope . msg := message.p2a prop,
sent_to := target.exclude receiver},
split,
{ rw ← prop_eq,
unfold protocol.handler server.handle_p1b,
rw if_neg (show ¬(u.procs receiver).curr < b, by { rw same_bal, exact lt_irrefl b }),
rw if_neg (show ¬(u.procs receiver).curr.address ≠ receiver,
by { rw decidable.not_not, rw same_bal, exact bal_from_self }),
rw if_neg (show ¬(u.procs receiver).curr > b, by { rw same_bal, exact lt_irrefl b }),
rw if_neg (show ¬(is_quorum (u.procs receiver).followers ∨
sender ∈ (u.procs receiver).followers),
by {
rw not_or_distrib,
split,
{ exact u_no_qrm },
intro cond,
have fact : (u.procs receiver).followers ∪ {sender} = (u.procs receiver).followers,
by {
rw finset.union_eq_left_iff_subset,
rw finset.singleton_subset_iff,
exact cond
},
apply u_no_qrm,
rw ← fact,
exact v_has_qrm
}),
rw if_pos v_has_qrm,
left, refl },
refl },
rw key.right.right.right.right.right at h_prop,
clear key acc_unchanged_enough,
left,
cases proposal.merge_is_one_of (u.procs receiver).accepted p_or;
rw h at h_prop,
{ exact accepted_satisfies receiver prop h_prop },
apply promises_satisfy sender {msg := message.p1b b p_or, sent_to := e_sent_to} he b prop,
rw ← h_prop
},
case p2a : p {
clear acc_unchanged_enough,
rw key.right at h_prop, clear key,
left,
have key : prop = p, by { injection h_prop with fact, exact eq.symm fact },
rw key,
use [sender, {msg := message.p2a p, sent_to := e_sent_to}, he],
cases p, refl
},
case p2b : b acc { apply acc_unchanged_enough, rw key.right },
case preempt : { apply acc_unchanged_enough, rw key.right },
},
{ rw same.left p h,
have ind_hyp := accepted_satisfies p,
intros prop key,
exact proposed_stable prop.bal prop.val u v (accepted_satisfies p prop key) u_pn_v },
{ rw h, clear same h p,
rw ntwk_change, clear ntwk_change proc_change,
intros e' he' b p e'_is_1b,
cases he',
{ exact proposed_stable p.bal p.val u v
(promises_satisfy receiver e' he' b p e'_is_1b) u_pn_v },
rcases p1b_emitted e'_is_1b he' with ⟨b', e_msg_is, accepted_unchanged, b_is_max⟩,
exact proposed_stable p.bal p.val u v
(accepted_satisfies receiver p accepted_unchanged) u_pn_v },
rw same.right p h,
intros e' he' b prop e'_is_promise,
have ind_hyp := promises_satisfy p e' he' b prop e'_is_promise,
exact proposed_stable prop.bal prop.val u v ind_hyp u_pn_v
end
-- The ballot in a server's `accepted` field only ever increases. That is, if at
-- some point a server has accepted a proposal, then it will always have a
-- proposal in `accepted` and moreover the proposal ballot will be at least as
-- large as what's currently stored.
lemma accepted_ballot_nondecreasing {p : pid_t} {prop_u : proposal pid_t value_t}
(u v : sys_state pid_t (server pid_t value_t is_quorum vals) (message pid_t value_t))
(u_r : u.reachable) (h_uv : u.possible_next v)
(h_u : (u.procs p).accepted = some prop_u) :
∃ (prop_v : proposal pid_t value_t), (v.procs p).accepted = some prop_v ∧ prop_u.bal ≤ prop_v.bal :=
begin
rcases h_uv with ⟨receiver, sender, e, he, deliverable, proc_change, ntwk_change, same⟩,
cases decidable.em (p = receiver),
swap,
{ exact ⟨prop_u, by { rw same.left p h, exact h_u }, by refl⟩ },
rw h at h_u ⊢,
clear h p,
rw proc_change,
have key := state_change receiver (u.procs receiver) e.msg sender,
cases key,
{ exact ⟨prop_u, by { rw key, exact h_u }, by refl⟩ },
cases e.msg,
case p1a : b {
rw key.right,
exact ⟨prop_u, h_u, by refl⟩
},
case p1b : b p_or {
cases key,
{ rw key.right,
exact ⟨prop_u, h_u, by refl⟩ },
cases key,
{ rw key.right.right.right.right,
use { bal := (u.procs receiver).curr,
val := proposal.value_or_default (proposal.merge (u.procs receiver).accepted p_or)
(vals receiver) },
exact ⟨by refl, (current_ge_accepted_ballot u u_r).left receiver prop_u h_u⟩ },
rw key.right.right.right.right.right,
rw h_u,
exact proposal.merge_ballot_ge_left prop_u p_or
},
case p2a : pr {
cases key with pr_bal_ge_curr update_w_pr,
exact ⟨pr, by { rw update_w_pr }, by { exact le_trans
((current_ge_accepted_ballot u u_r).left receiver prop_u h_u)
pr_bal_ge_curr }⟩,
},
case p2b : b accepted {
rw key.right,
exact ⟨prop_u, h_u, by refl⟩
},
case preempt : {
rw key.right,
exact ⟨prop_u, h_u, by refl⟩
}
end
-- If a server issued a p1b promising not to accept anything with ballot less
-- than b, then its `curr` ballot will always be at least b.
lemma ballot_ge_any_promised (voter : pid_t)
(b_promised : ballot pid_t) (p_or : option (proposal pid_t value_t)) : predicate.invariant
(λ (s : sys_state pid_t (server pid_t value_t is_quorum vals) (message pid_t value_t)),
(∃ e ∈ s.network voter, envelope.msg e = message.p1b b_promised p_or) →
(s.procs voter).curr ≥ b_promised) :=
begin
suffices : predicate.inductive_invariant _,
by { exact predicate.ind_inv_is_inv this},
split,
{ intros s hs,
rintros ⟨e, he, e_is_promise⟩,
specialize hs voter,
injection hs with __ key, clear_, rw ← key at he,
cases he,
{ rw he at e_is_promise, injection e_is_promise },
rw set.mem_singleton_iff at he,
rw he at e_is_promise, injection e_is_promise },
intros u v hu u_pn_v,
rintros ⟨e, he, e_is_promise⟩,
rcases (show _, by exact u_pn_v) with ⟨receiver, sender, e', he', deliverable, proc_change, ntwk_change, rest_same⟩,
cases decidable.em (voter = receiver),
swap,
{ rw rest_same.left voter h,
rw rest_same.right voter h at he,
exact hu ⟨e, he, e_is_promise⟩ },
clear rest_same,
rw ← h at proc_change ntwk_change deliverable, clear h receiver,
rw ntwk_change at he,
cases he,
{ apply le_trans (hu ⟨e, he, e_is_promise⟩),
exact ballot_nondecreasing voter u_pn_v },
rcases p1b_emitted e_is_promise he with ⟨b', e'_is, accepted_is, is_max⟩,
rw e'_is at proc_change, rw proc_change,
unfold protocol.handler server.handle_p1a,
cases decidable.em ((u.procs voter).curr < b'),
{ rw if_pos h,
unfold max max_default at is_max,
rw if_neg (not_le_of_gt h) at is_max,
rw is_max, exact le_refl _ },
rw if_neg h,
unfold max max_default at is_max,
rw if_pos (le_of_not_gt h) at is_max,
rw is_max,
exact le_refl _
end
def voted_ballot
(s : sys_state pid_t (server pid_t value_t is_quorum vals) (message pid_t value_t))
(voter : pid_t) (b : ballot pid_t) :=
∃ e ∈ s.network voter, (envelope.msg e) = message.p2b b tt
lemma voted_imp_proposed (voter : pid_t) (b : ballot pid_t) : predicate.invariant
(λ (s : sys_state pid_t (server pid_t value_t is_quorum vals) (message pid_t value_t)),
voted_ballot s voter b → ∃ v, proposed s b v) :=
begin
suffices : predicate.inductive_invariant _,
by { exact predicate.ind_inv_is_inv this },
split,
{ intros s hs, rintros ⟨ev, h_ev, ev_vote⟩,
specialize hs voter,
injection hs with __ key, clear_,
rw ← key at h_ev,
cases h_ev,
{ rw h_ev at ev_vote, injection ev_vote },
rw set.mem_singleton_iff at h_ev,
rw h_ev at ev_vote, injection ev_vote },
intros u w hu u_pn_w,
rcases (show _, by exact u_pn_w) with ⟨receiver, sender, e, he, deliverable, proc_change, ntwk_change, proc_same, ntwk_same⟩, clear deliverable proc_same,
intro h_voted,
unfold voted_ballot at h_voted,
cases decidable.em (voter = receiver),
swap,
{ rw ntwk_same voter h at h_voted,
rcases hu h_voted with ⟨v, proposed_at_u⟩,
exact ⟨v, proposed_stable b v u w proposed_at_u u_pn_w⟩ },
clear ntwk_same,
rw ← h at ntwk_change proc_change, clear h receiver,
rw ntwk_change at h_voted,
rcases h_voted with ⟨e', he', e'_msg_is_vote⟩,
cases he',
{ rcases hu ⟨e', he', e'_msg_is_vote⟩ with ⟨v, proposed_at_u⟩,
exact ⟨v, proposed_stable b v u w proposed_at_u u_pn_w⟩ },
have event := p2b_emitted e'_msg_is_vote he',
cases event,
{ rcases event with ⟨p_or, e_msg_is, bal_from_self, u_no_qrm, v_has_qrm, rest⟩,
have ntwk_delta_eq : (protocol.handler voter (u.procs voter) e.msg sender).snd = {{msg := message.p2a
{bal := (u.procs voter).curr,
val := proposal.value_or_default (proposal.merge (u.procs voter).accepted p_or) (vals voter)},
sent_to := target.exclude voter},
{msg := message.p2b (u.procs voter).curr tt, sent_to := target.just voter}},
by {
rw e_msg_is,
unfold protocol.handler server.handle_p1b,
rw if_neg (lt_irrefl _),
rw if_neg (show ¬(u.procs voter).curr.address ≠ voter,
by { rw decidable.not_not, exact bal_from_self }),
rw if_neg (lt_irrefl _),
rw if_neg (show ¬(is_quorum (u.procs voter).followers ∨
sender ∈ (u.procs voter).followers),
by {
rw not_or_distrib,
split,
{ exact u_no_qrm },
intro cond,
have fact : (u.procs voter).followers ∪ {sender} = (u.procs voter).followers,
by {
rw finset.union_eq_left_iff_subset,
rw finset.singleton_subset_iff,
exact cond
},
apply u_no_qrm,
rw ← fact,
exact v_has_qrm
}),
rw if_pos v_has_qrm },
use proposal.value_or_default (proposal.merge (u.procs voter).accepted p_or) (vals voter),
use voter,
use {msg := message.p2a
{bal := (u.procs voter).curr,
val := proposal.value_or_default (proposal.merge (u.procs voter).accepted p_or) (vals voter)},
sent_to := target.exclude voter},
split,
{ rw ntwk_change, right,
rw ntwk_delta_eq, left, refl },
suffices : (u.procs voter).curr = b, by { rw this },
rw rest at e'_msg_is_vote, injection e'_msg_is_vote },
rcases event with ⟨⟨p_bal, p_val⟩, e_msg_is, p_bal_larger⟩,
use [p_val, sender, e, sys_state.ntwk_subset he u_pn_w],
rw e_msg_is,
suffices : p_bal = b, by { rw this },
rw e_msg_is at he',
unfold protocol.handler server.handle_p2a at he',
rw if_pos p_bal_larger at he',
rw set.mem_singleton_iff at he',
rw he' at e'_msg_is_vote,
injection e'_msg_is_vote
end
-- In a same vein to `ballot_ge_any_promised`, if a server voted for a ballot b,
-- then it will always have a proposal stored where the proposal's ballot is at
-- least b.
lemma accepted_ge_any_voted (voter : pid_t) (b : ballot pid_t): predicate.invariant
(λ (s : sys_state pid_t (server pid_t value_t is_quorum vals) (message pid_t value_t)),
voted_ballot s voter b →
∃ p, (s.procs voter).accepted = some p ∧ p.bal ≥ b) :=
begin
rw predicate.use_any_invariant,
split,
{ intros s hs,
rintros ⟨e, he, e_is_vote⟩,
specialize hs voter,
unfold protocol.init at hs,
injection hs with __ network, clear_,
rw ← network at he,
cases he,
{ rw he at e_is_vote, injection e_is_vote },
rw set.mem_singleton_iff at he,
rw he at e_is_vote, injection e_is_vote },
intros u v u_r hu u_pn_v v_r,
rcases (show _, by exact u_pn_v) with ⟨receiver, sender, e', he', deliverable, proc_change, ntwk_change, rest_same⟩,
rintros ⟨ev, h_ev, ev_vote⟩,
cases decidable.em (voter = receiver),
swap,
{ rw rest_same.left voter h,
rw rest_same.right voter h at h_ev,
exact hu ⟨ev, h_ev, ev_vote⟩ },
rw ← h at proc_change ntwk_change deliverable,
clear rest_same h receiver,
rw ntwk_change at h_ev,
cases h_ev,
{ rcases hu ⟨ev, h_ev, ev_vote⟩ with ⟨p, hp, p_ge_b⟩,
rcases accepted_ballot_nondecreasing u v u_r u_pn_v hp with ⟨prop_v, middle, right_for_trans⟩,
exact ⟨prop_v, middle, le_trans p_ge_b right_for_trans⟩ },
cases p2b_emitted ev_vote h_ev,
{ rcases h with ⟨p_or, e'_msg_is, active, no_start_quorum, end_w_quorum, ev_is⟩,
use {bal := (u.procs voter).curr,
val := proposal.value_or_default (proposal.merge (u.procs voter).accepted p_or) (vals voter)},
rw e'_msg_is at proc_change, clear e'_msg_is,
rw proc_change,
unfold protocol.handler server.handle_p1b,
rw if_neg (lt_irrefl _),
rw if_neg (decidable.not_not.mpr active),
rw if_neg (lt_irrefl _),
rw if_neg (show ¬(is_quorum (u.procs voter).followers ∨ sender ∈ (u.procs voter).followers),
by {
rw not_or_distrib,
split,
{ exact no_start_quorum },
intro cond,
have fact : (u.procs voter).followers ∪ {sender} = (u.procs voter).followers,
by {
rw finset.union_eq_left_iff_subset,
rw finset.singleton_subset_iff,
exact cond
},
apply no_start_quorum,
rw ← fact,
exact end_w_quorum
}),
rw if_pos end_w_quorum,
split,
{ refl },
apply ge_of_eq,
rw ev_is at ev_vote,
injection ev_vote },
rcases h with ⟨p, e'_msg_is, p_bal_larger⟩,
rw e'_msg_is at proc_change h_ev, clear e'_msg_is,
use p,
rw proc_change,
unfold protocol.handler server.handle_p2a,
rw if_pos p_bal_larger,
split,
{ refl },
unfold protocol.handler server.handle_p2a at h_ev,
rw if_pos p_bal_larger at h_ev,
rw set.mem_singleton_iff at h_ev,
rw h_ev at ev_vote,
injection ev_vote with key __,
exact ge_of_eq key
end
-- If a server sent a p1b with ballot b and wrote that no ballot was stored,
-- then it will never vote for any proposal with ballot less than b.
--
-- If a server sent a p1b with ballot b and wrote that its highest stored was
-- (some p), then it will never vote for any proposal with a ballot larger than
-- p.bal and less than b.
theorem none_voted_between_p1b : predicate.invariant
(λ (s : sys_state pid_t (server pid_t value_t is_quorum vals) (message pid_t value_t)),
∀ (voter : pid_t) (b_voted b_promised : ballot pid_t)
(p_or : option (proposal pid_t value_t)),
voted_ballot s voter b_voted →
(∃ e ∈ s.network voter, envelope.msg e = message.p1b b_promised p_or) →
b_voted ≥ b_promised ∨
∃ p, p_or = some p ∧ b_voted ≤ p.bal) :=
begin
suffices intros_before :
∀ (voter : pid_t) (b_voted b_promised : ballot pid_t) (p_or : option (proposal pid_t value_t)),
predicate.invariant
(λ (s : sys_state pid_t (server pid_t value_t is_quorum vals) (message pid_t value_t)),
voted_ballot s voter b_voted →
(∃ (e ∈ s.network voter), envelope.msg e = message.p1b b_promised p_or) →
(b_voted ≥ b_promised ∨
∃ p, p_or = some p ∧ b_voted ≤ p.bal)),
by { intros u u_r voter b_voted b_promised p_or,
exact intros_before voter b_voted b_promised p_or u u_r },
intros voter b_voted b_promised p_or,
rw predicate.use_any_invariant,
split,
{ intros s hs,
rintros ⟨e, he, e_is_vote⟩,
specialize hs voter,
unfold protocol.init at hs,
injection hs with __ network, clear_,
rw ← network at he,
cases he,
{ rw he at e_is_vote, injection e_is_vote },
rw set.mem_singleton_iff at he,
rw he at e_is_vote, injection e_is_vote },
intros u w u_r hu u_pn_w w_r,
rintros ⟨ev, h_ev, ev_vote⟩,
rintros ⟨ep, h_ep, ep_promise⟩,
rcases (by exact u_pn_w) with ⟨receiver, sender, e', he', deliverable, proc_change, ntwk_change, rest_same⟩,
cases decidable.em (voter = receiver),
swap,
{ rw rest_same.right voter h at h_ev h_ep,
exact hu ⟨ev, h_ev, ev_vote⟩ ⟨ep, h_ep, ep_promise⟩ },
clear rest_same,
rw ← h at proc_change ntwk_change deliverable, clear h receiver,
rw ntwk_change at h_ev h_ep,
cases h_ep; cases h_ev,
{ exact hu ⟨ev, h_ev, ev_vote⟩ ⟨ep, h_ep, ep_promise⟩ },
{ left,
have key := ballot_ge_any_promised voter b_promised p_or u u_r ⟨ep, h_ep, ep_promise⟩,
cases p2b_emitted ev_vote h_ev,
{ rcases h with ⟨p_or, _, _, _, _, ev_is⟩,
rw ev_is at ev_vote,
have fact : (u.procs voter).curr = b_voted, by { injection ev_vote },
rw fact at key, exact key },
rcases h with ⟨p, e'_is, p_larger⟩,
rw e'_is at h_ev,
unfold protocol.handler server.handle_p2a at h_ev,
rw if_pos p_larger at h_ev,
rw set.mem_singleton_iff at h_ev,
rw h_ev at ev_vote,
injection ev_vote with fact __, clear_,
rw ← fact,
exact le_trans key p_larger },
{ right,
rcases p1b_emitted ep_promise h_ep with ⟨b', _, key, _⟩,
rcases accepted_ge_any_voted voter b_voted u u_r ⟨ev, h_ev, ev_vote⟩ with ⟨p, fact, p_bal_ge⟩,
use p,
split,
{ rw ← key, exact fact },
exact p_bal_ge
},
rcases p1b_emitted ep_promise h_ep with ⟨b', e'_msg_is, _, _⟩,
rw e'_msg_is at h_ev,
unfold protocol.handler server.handle_p1a at h_ev,
cases decidable.em ((u.procs voter).curr < b'),
{ rw if_pos h at h_ev,
rw set.mem_singleton_iff at h_ev,
rw h_ev at ev_vote,
injection ev_vote },
rw if_neg h at h_ev,
rw set.mem_singleton_iff at h_ev,
rw h_ev at ev_vote,
injection ev_vote
end
|
Formal statement is: lemma continuous_on_homotopic_join_lemma: fixes q :: "[real,real] \<Rightarrow> 'a::topological_space" assumes p: "continuous_on ({0..1} \<times> {0..1}) (\<lambda>y. p (fst y) (snd y))" (is "continuous_on ?A ?p") and q: "continuous_on ({0..1} \<times> {0..1}) (\<lambda>y. q (fst y) (snd y))" (is "continuous_on ?A ?q") and pf: "\<And>t. t \<in> {0..1} \<Longrightarrow> pathfinish(p t) = pathstart(q t)" shows "continuous_on ({0..1} \<times> {0..1}) (\<lambda>y. (p(fst y) +++ q(fst y)) (snd y))" Informal statement is: Suppose $p$ and $q$ are continuous functions from $[0,1] \times [0,1]$ to a topological space $X$. If $p(t)$ and $q(t)$ are paths in $X$ such that $p(t)$ ends at the same point as $q(t)$ starts for each $t \in [0,1]$, then the function $y \mapsto (p(x) +++ q(x))(y)$ is continuous. |
module Language.LSP.CodeAction.GenerateDef
import Core.Context
import Core.Core
import Core.Env
import Core.Metadata
import Core.UnifyState
import Data.List
import Data.List1
import Data.String
import Idris.IDEMode.CaseSplit
import Idris.Pretty
import Idris.REPL
import Idris.REPL.Opts
import Idris.Resugar
import Idris.Syntax
import Language.JSON
import Language.LSP.CodeAction
import Language.LSP.Message
import Libraries.Data.List.Extra
import Libraries.Data.PosMap
import Libraries.Text.PrettyPrint.Prettyprinter
import Server.Configuration
import Server.Response
import Server.Utils
import System.File
import Server.Log
import System.Clock
import TTImp.Interactive.GenerateDef
import TTImp.TTImp
import TTImp.Interactive.ExprSearch
import Parser.Unlit
printClause : Ref Ctxt Defs
=> Ref Syn SyntaxInfo
=> Maybe String -> Nat -> ImpClause -> Core String
printClause l i (PatClause _ lhsraw rhsraw) = do
lhs <- pterm lhsraw
rhs <- pterm rhsraw
pure (relit l (pack (replicate i ' ') ++ show lhs ++ " = " ++ show rhs))
printClause l i (WithClause _ lhsraw wvraw prf flags csraw) = do
lhs <- pterm lhsraw
wval <- pterm wvraw
cs <- traverse (printClause l (i + 2)) csraw
pure (relit l ((pack (replicate i ' ')
++ show lhs
++ " with (" ++ show wval ++ ")"
++ maybe "" (\ nm => " proof " ++ show nm) prf
++ "\n"))
++ showSep "\n" cs)
printClause l i (ImpossibleClause _ lhsraw) = do
do lhs <- pterm lhsraw
pure (relit l (pack (replicate i ' ') ++ show lhs ++ " impossible"))
number : Nat -> List a -> List (Nat, a)
number n [] = []
number n (x :: xs) = (n,x) :: number (S n) xs
pred : Nat -> Nat
pred Z = Z
pred (S k) = k
-- This is needed as PosMap is not smart enough yet to track down
-- the non applied functions in the PosMap. This requires a change
-- in the compiler, for that reason the generateDef functionality
-- needs to have a backup strategy for names. If the PosMap
-- creation of the compiler changes probably this functions
-- will be rendered as reduntant one.
guessName : Ref MD Metadata
=> (Int, Int) -> Core (Maybe Name)
guessName (line, col) = do
meta <- get MD
let Nothing = findPointInTree (line, col) (nameLocMap meta)
| Just name => pure (Just name)
Nothing <- findTypeAt $ anyAt $ within (line, col)
| Just (name, _, _) => pure (Just name)
pure Nothing
export
generateDef : Ref LSPConf LSPConfiguration
=> Ref MD Metadata
=> Ref Ctxt Defs
=> Ref UST UState
=> Ref Syn SyntaxInfo
=> Ref ROpts REPLOpts
=> CodeActionParams -> Core (List CodeAction)
generateDef params = do
defs <- branch
let True = params.range.start.line == params.range.end.line
| _ => do
logString Debug "generateDef: start and end lines were different."
pure []
[] <- searchCache params.range GenerateDef
| actions => do logString Debug "generateDef: found cached action"
pure actions
let line = params.range.start.line
let col = params.range.start.character
defs <- get Ctxt
Just (_, n, _, _) <- findTyDeclAt (\p, n => onLine line p)
| Nothing => do logString Debug "generateDef: couldn't find type declaration at line \{show line}"
pure []
fuel <- gets LSPConf searchLimit
solutions <- case !(lookupDefExact n defs.gamma) of
Just None => do
catch (do searchdefs@((fc, _) :: _) <- makeDefN (\p, n => onLine line p) fuel n
| _ => pure []
let l : Nat = integerToNat $ cast $ startCol (toNonEmptyFC fc)
Just srcLine <- getSourceLine (line + 1)
| Nothing => do logString Error "generateDef: source line \{show line} not found"
pure []
let (markM, srcLineUnlit) = isLitLine srcLine
for searchdefs $ \(_, cs) => do
traverse (printClause markM l) cs)
(\case Timeout _ => pure []
err => do logString Debug "generateDef: unexpected error while searching"
throw err)
Just _ => do logString Debug "generateDef: there is already a definition for \{show n}"
pure []
Nothing => do logString Debug "generateDef: couldn't find type declaration at line \{show line}"
pure []
put Ctxt defs
let docURI = params.textDocument.uri
let rng = MkRange (MkPosition (line + 1) 0) (MkPosition (line + 1) 0) -- insert
actions <- for (number 1 solutions) $ \(i,funcDef) => do
let lastLine = fromMaybe "" (last' funcDef)
let edit = MkTextEdit rng (String.unlines funcDef ++ "\n") -- extra newline
let workspaceEdit = MkWorkspaceEdit
{ changes = Just (singleton docURI [edit])
, documentChanges = Nothing
, changeAnnotations = Nothing
}
pure $ MkCodeAction
{ title = "Generate definition #\{show i} as ~ \{strSubstr 0 50 lastLine} ..."
, kind = Just RefactorRewrite
, diagnostics = Just []
, isPreferred = Just False
, disabled = Nothing
, edit = Just workspaceEdit
, command = Nothing
, data_ = Nothing
}
-- TODO: retrieve the line length efficiently
modify LSPConf (record { cachedActions $= insert (MkRange (MkPosition line 0) (MkPosition line 1000), GenerateDef, actions) })
pure actions
|
/*
Copyright (c) 2013-2016, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_RESOLVER_INTERFACE_HPP_INCLUDE
#define TORRENT_RESOLVER_INTERFACE_HPP_INCLUDE
#include <vector>
#include "libtorrent/error_code.hpp"
#include "libtorrent/address.hpp"
#include "libtorrent/aux_/disable_warnings_push.hpp"
#include <boost/function.hpp>
#include "libtorrent/aux_/disable_warnings_pop.hpp"
namespace libtorrent
{
struct TORRENT_EXTRA_EXPORT resolver_interface
{
typedef boost::function<void(error_code const&, std::vector<address> const&)>
callback_t;
enum flags_t
{
// this flag will make async_resolve() always use the cache if we have an
// entry, regardless of how old it is. This is usefull when completing the
// lookup quickly is more important than accuracy
prefer_cache = 1,
// set this flag for lookups that are not critical during shutdown. i.e.
// for looking up tracker names _except_ when stopping a tracker.
abort_on_shutdown = 2
};
virtual void async_resolve(std::string const& host, int flags
, callback_t const& h) = 0;
virtual void abort() = 0;
protected:
~resolver_interface() {}
};
}
#endif
|
-- =====================================================================
-- § Resumen --
-- =====================================================================
-- En esta relación se demostrará que
-- + la imagen de un espacio compacto mediante una función continua es
-- compacta.
-- + Los subconjuntos cerrados de un espacio compacto son compactos.
--
-- Concretamente, lo que demostraremos es que
-- + Si `f : X → Y` es una función continua y `S : set X` es un conjunto
-- compacto (con la subtopología), entonces `f '' S` (la imagen de `S`
-- por `f`) es compacto (con la subtopología).
-- + Si `X` es unespacio topológico, `S` es un subconjunto compacto y
-- `C` es un subconjunto cerrado, entonces `S ∩ C` es un subconjunto
-- compacto.
--
-- Los resultados originales son los casos particulares cuando `S` es
-- `univ : set X`.
-- ---------------------------------------------------------------------
-- Ejercicio. Importar la teoría de las propiedades de los subconjuntos
-- de los espacios topológicos.
-- ---------------------------------------------------------------------
import topology.subset_properties
-- =====================================================================
-- § Introducción --
-- =====================================================================
-- ---------------------------------------------------------------------
-- Ejercicio. Declarar
-- + X e Y como variables sobre espacios topológicos.
-- + f como variable sobre las funciones de x en Y.
-- ---------------------------------------------------------------------
variables (X Y : Type) [topological_space X] [topological_space Y]
variable (f : X → Y)
-- ---------------------------------------------------------------------
-- Ejercicio. Abrir es espacion de nombre set (de los conjuntos).
-- ---------------------------------------------------------------------
open set
-- =====================================================================
-- § Subespacios compactos --
-- =====================================================================
-- ---------------------------------------------------------------------
-- Ejercicio. Demostrar que un subconjunto de un espacio topológico es
-- compacto si de todo recubrimiento abierto se puede extraer un
-- subrecubrimiento finito.
-- ---------------------------------------------------------------------
lemma compact_iff_finite_subcover'
{α : Type} [topological_space α]
{S : set α}
: is_compact S ↔
(∀ {ι : Type} (U : ι → set α),
(∀ i, is_open (U i))
→ S ⊆ (⋃ i, U i)
→ (∃ (t : set ι), t.finite ∧ S ⊆ (⋃ i ∈ t, U i))) :=
begin
rw compact_iff_finite_subcover,
split,
{ intros hs ι U hU hsU,
cases hs U hU hsU with F hF,
use [(↑F : set ι), finset.finite_to_set F],
exact hF },
{ intros hs ι U hU hsU,
rcases hs U hU hsU with ⟨F, hFfin, hF⟩,
use hFfin.to_finset,
convert hF,
ext,
simp }
end
-- =====================================================================
-- § La imagen continua de compactos es compacta --
-- =====================================================================
-- Nota: Lemas útiles sobre topología
-- + is_open_compl_iff
-- {α : Type u} [topological_space α]
-- {s : set α}
-- : is_open sᶜ ↔ is_closed s
-- + is_open_preimage
-- {α : Type u_1} [topological_space α]
-- {β : Type u_2} [topological_space β]
-- {f : α → β}
-- (hf : continuous f)
-- {s : set β}
-- (h : is_open s)
-- : is_open (f ⁻¹' s)
/-!
## Continuous image of compact is compact
I would start with `rw compact_iff_finite_subcover' at hS ⊢,`
The proof that I recommend formalising is this. Say `S` is a compact
subset of `X`, and `f : X → Y` is continuous. We want to prove that
every cover of `f '' S` by open subsets of `Y` has a finite subcover.
So let's cover `f '' S` with opens `U i : set Y`, for `i : ι` and `ι` an index type.
Pull these opens back to `V i : set X` and observe that they cover `S`.
Choose a finite subcover corresponding to some `F : set ι` such that `F` is finite
(Lean writes this `h : F.finite`) and then check that the corresponding cover
of `f '' S` by the `U i` with `i ∈ F` is a finite subcover.
Good luck! Please ask questions (or DM me on discord if you don't want to
ask publically). Also feel free to DM me if you manage to do it!
Useful theorems:
`continuous.is_open_preimage` -- preimage of an open set under a
continuous map is open.
`is_open_compl_iff` -- complement `Sᶜ` of `S` is open iff `S` is closed.
## Some useful tactics:
### `specialize`
`specialize` can be used with `_`. If you have a hypothesis
`hS : ∀ {ι : Type} (U : ι → set X), (∀ (i : ι), is_open (U i)) → ...`
and `U : ι → set X`, then
`specialize hS U` will change `hS` to
`hS : (∀ (i : ι), is_open (U i)) → ...`
But what if you now want to prove `∀ i, is_open (U i)` so you can feed it
into `hS` as an input? You can put
`specialize hS _`
and then that goal will pop out. Unfortunately it pops out _under_ the
current goal! You can swap two goals with the `swap` tactic though :-)
### `change`
If your goal is `⊢ P` and `P` is definitionally equal to `Q`, then you
can write `change Q` and the goal will change to `Q`. Sometimes useful
because rewriting works up to syntactic equality, which is stronger
than definitional equality.
### `rwa`
`rwa h` just means `rw h, assumption`
### `contradiction`
If you have `h1 : P` and `h2 : ¬ P` as hypotheses, then you can prove any goal with
the `contradiction` tactic, which just does `exfalso, apply h2, exact h1`.
### `set`
Note : The `set` tactic is totally unrelated to the `set X` type of subsets of `X`!
The `set` tactic can be used to define things. For example
`set T := f '' S with hT_def,` will define `T` to be `f '' S`
and will also define `hT_def : T = f '' S`.
-/
-- ---------------------------------------------------------------------
-- Ejercicio. Demostrar que si f es continua y S es compacto, entoces la
-- imagen de S por f es compacto.
-- ---------------------------------------------------------------------
-- La idea de la demostración es la siguiente: Sea `S` un subconjunto
-- compacto de `X` y `f : X → Y` continua. Dado `U i : set Y` un
-- recubrimiento abierto de `f '' S`, para cada `i` se define
-- `V i = f ⁻¹' (U i)`. Se rprueba que `V` es un recubriemiento abierto
-- de `S` y, como `S`es compacto, tiene un subrecubrimiento finito. La
-- imágenes de cada conjunto de dicho subrecubrimiento forman un
-- subrecubrimiento finito de `f '' S`.
lemma image_compact_of_compact
(hf : continuous f)
(S : set X)
(hS : is_compact S)
: is_compact (f '' S) :=
begin
rw compact_iff_finite_subcover' at *,
set T := f '' S with hT_def,
intros ι U hU hcoverU,
set V : ι → set X := λ i, f ⁻¹' (U i) with hV_def,
specialize hS V _,
swap,
{ intro i,
rw hV_def, dsimp only,
apply continuous.is_open_preimage hf _ (hU i), },
{ specialize hS _,
swap,
{ intros x hx,
have hfx : f x ∈ T,
{ rw hT_def,
rw mem_image,
use x,
use hx,},
{ specialize hcoverU hfx,
rw mem_Union at hcoverU ⊢,
exact hcoverU, }},
{ rcases hS with ⟨F, hFfinite, hF⟩,
use F,
use hFfinite,
rintros y ⟨x, hxs, rfl⟩,
rw subset_def at hF,
specialize hF x hxs,
rw mem_bUnion_iff at hF ⊢,
exact hF, }},
end
-- =====================================================================
-- § Subconjuntos cerrados de compactos --
-- =====================================================================
-- ---------------------------------------------------------------------
-- Ejercicio. Demostrar que si S es compacto y C es cerrado, entonces
-- `S ∩ C` es compacto.
-- ---------------------------------------------------------------------
lemma closed_of_compact
(S : set X)
(hS : is_compact S)
(C : set X)
(hC : is_closed C)
: is_compact (S ∩ C) :=
begin
rw compact_iff_finite_subcover' at *,
intros ι U hUopen hSCcover,
let V : option ι → set X := λ x, option.rec Cᶜ U x,
specialize hS V _,
swap,
{ intros i,
cases i with i,
{ change is_open Cᶜ,
rwa is_open_compl_iff },
{ change is_open (U i),
apply hUopen } },
specialize hS _,
swap,
{ intros x hxS,
by_cases hxC : x ∈ C,
{ rw subset_def at hSCcover,
specialize hSCcover x ⟨hxS, hxC⟩,
rw mem_Union at ⊢ hSCcover,
cases hSCcover with i hi,
use (some i),
exact hi },
{ rw mem_Union,
use none } },
rcases hS with ⟨F, hFfinite, hFcover⟩,
use (some : ι → option ι) ⁻¹' F,
split,
{ apply finite.preimage _ hFfinite,
intros i hi j hj,
exact option.some_inj.mp },
rintros x ⟨hxS, hxC⟩,
rw subset_def at hFcover,
specialize hFcover x hxS,
rw mem_bUnion_iff at hFcover ⊢,
rcases hFcover with ⟨i, hiF, hxi⟩,
cases i with i,
{ contradiction },
{ use [i, hiF, hxi] },
end
|
# Regressão linear 2: gradiente descendente
### Aprendizado e otimização
Dada uma função *target* desconhecida $f:\mathbb{R}^{d} \rightarrow \mathbb{R}$ e uma hipótese $h_{\mathbf{w}}:\mathbb{R}^{d} \rightarrow \mathbb{R}$ o erro de $h_{\mathbf{w}}$ é definido por:
\begin{equation}
E_{out}(h_{\mathbf{w}}) = \mathbb{E}_{\mathbf{x}\sim p_{data}}L(h(\mathbf{x}; \mathbf{w}), \; f(\mathbf{x}))
\end{equation}
em que $p_{data}$ é a distribuição geradora dos dados, $L$ é alguma função de perda (por exemplo, o quadrado da diferença) e $h(\mathbf{x}; \mathbf{w}) = h_{\mathbf{w}}(\mathbf{x})$. Se tivéssemos acesso a $p_{data}$ poderíamos calcular a função acima para qualquer $h_{\mathbf{w}}$ e escolher aquele com erro mínimo.
Como não temos acesso a $p_{data}$, define-se
\begin{equation}
E_{in}(h_{\mathbf{w}}) = J(\mathbf{w}) = \frac{1}{N}\sum_{i=1}^{N} L(h(\mathbf{x}_{i}; \mathbf{w}), \; y_{i})
\end{equation}
em que $N$ é o tamanho do dataset de treinamento e $y_{i} = f(\mathbf{x}_{i})$.
Como visto em aula, uma relação entre $E_{in}$ e $E_{out}$ pode ser estabelecida pela **Inequação de Hoeffding**.
Aqui estamos interessados em encontrar $h_{\mathbf{w}}$ com erro $J(\mathbf{w})$ mínimo. Isto corresponde a determinar o ponto mínimo da função $J(\mathbf{w})$. Por isso, vamos nos concentrar apenas em uma técnica de otimização para minimizar $E_{in}$.
### Gradiente ascendente e gradiente descendente
Dados $\mathbf{w}, \mathbf{u} \in \mathbb{R}^{d}$ e $J:\mathbb{R}^{d} \rightarrow \mathbb{R}$ tal que $||\mathbf{u}||_{2} = 1$ a taxa de variação de $J$ no ponto $\mathbf{w}$ em direção a $\mathbf{u}$ é chamada de **derivada direcional**, $D_{\mathbf{u}}J(\mathbf{w})$. Definindo $g(h) = J(\mathbf{w} + h\mathbf{u})$, podemos usar a regra da cadeia e a definição de produto escalar para mostrar que
\begin{equation}
D_{\mathbf{u}}J(\mathbf{w}) \;\;=\;\; \left. \frac{dg}{dh} \right|_{h=0} \;\;=\;\; \mathbf{u}^{T}\nabla_{\mathbf{w}}J(\mathbf{w})
\;\;=\;\; ||\mathbf{u}||_{2}||\nabla_{\mathbf{w}}J(\mathbf{w})||_{2}cos\theta \;\;=\;\; ||\nabla_{\mathbf{w}}J(\mathbf{w})||_{2}cos\theta
\end{equation}
em que $\theta$ é o ângulo entre $\mathbf{u}$ e $\nabla_{\mathbf{w}}J(\mathbf{w})$. Assim, pensando em $D_{\mathbf{u}}J(\mathbf{w})$ em termos do vetor $\mathbf{u}$ temos que: $D_{\mathbf{u}}J(\mathbf{w})$ tem o valor máximo quando $\mathbf{u}$ tem a mesma direção que $\nabla_{\mathbf{w}}J(\mathbf{w})$ ($\theta=0$); similarmente $D_{\mathbf{u}}J(\mathbf{w})$ tem o valor mínimo quando $\mathbf{u}$ tem a direção oposta a $\nabla_{\mathbf{w}}J(\mathbf{w})$ ($\theta=\pi$).
Desse modo podemos maximizar $J$ alterando $\mathbf{w}$ na direção de $\nabla_{\mathbf{w}}J(\mathbf{w})$ e podemos minimizar $J$ alterando $\mathbf{w}$ na direção de $-\nabla_{\mathbf{w}}J(\mathbf{w})$. Isso permite dois métodos bem simples de otimização:
**Gradiente Ascendente**
- $\mathbf{w}(0) = \mathbf{w}$
- for $t = 0, 1, 2, \dots$ do
* $\mathbf{w}(t+1) = \mathbf{w}(t) + \eta \nabla_{\mathbf{w}(t)}J(\mathbf{w}(t))$
**Gradiente Descendente**
- $\mathbf{w}(0) = \mathbf{w}$
- for $t = 0, 1, 2, \dots$ do
* $\mathbf{w}(t+1) = \mathbf{w}(t) - \eta \nabla_{\mathbf{w}(t)}J(\mathbf{w}(t))$
Em ambos os casos o parâmetro $\eta \in \mathbb{R}_{\geq}$ é chamado de **taxa de aprendizado** (*learning rate*); ele pondera o tamanho de cada atualização.
##### A seguir são apresentados uma sequência de exercícios que ilustram diferentes aspectos práticos na implementação do algoritmo *gradient descent*
Iremos considerar o problema de regressão linear.
```python
# all imports
import numpy as np
import time
from util import r_squared, randomize_in_place, get_housing_prices_data
from plots import simple_step_plot, plot_points_regression, plot_cost_function_curve
%matplotlib inline
```
##### Vamos usar o mesmo dataset de antes, mas agora vamos dividir os dados em treinamento, validação e teste.
Essa divisão é comumente realizada na prática: os dados de treinamento são usados na otimização da função custo $J$, os dados de validação são usados para aferir a qualidade da otimização, e os dados de teste são usados para aferir a qualidade da predição.
```python
X, y = get_housing_prices_data(N=350, verbose=False)
randomize_in_place(X, y)
train_X = X[0:250]
train_y = y[0:250]
valid_X = X[250:300]
valid_y = y[250:300]
test_X = X[300:]
test_y = y[300:]
print("\nDividindo os dados em treinamento, validação e teste")
print("\ntrain_X shape = {}".format(train_X.shape))
print("\ntrain_y shape = {}".format(train_y.shape))
print("\nvalid_X shape = {}".format(valid_X.shape))
print("\nvalid_y shape = {}".format(valid_y.shape))
print("\ntest_X shape = {}".format(test_X.shape))
print("\ntest_y shape = {}".format(test_y.shape))
```
```python
plot_points_regression(train_X,
train_y,
title='Training data',
xlabel="m\u00b2",
ylabel='$')
```
### Para minimizar a função de custo vamos ter que colocar os dados em uma outra escala
Um modo de fazer isso é o chamado [standard/z score](https://en.wikipedia.org/wiki/Standard_score).
Aplicamos a seguinte transformação:
\begin{equation}
\mathbf{X}^{\top}_{i} \leftarrow \frac{\mathbf{X}^{\top}_{i} - \mu_{i}}{\sigma_{i}}
\end{equation}
em que $\mathbf{X}^{T}_{i} \in \mathbb{R}^{N}$ ($i = 1, \dots, d$) é um vetor de features da design matrix $\mathbf{X}$, $\mu_{i}$ é a média de tal vetor, e $\sigma_{i}$ seu desvio padrão.
A importância de se fazer essa transformação é discutida mais ao final deste notebook.
##### **Exercício 1)**
Use a biblioteca numpy para implementar a função que altera os dados conforme a equação acima (essa função deve funcionar para uma design matrix $\mathbf{X}$ com um número arbitrário de features).
```python
def standardize(X):
"""
Returns standardized version of the ndarray 'X'.
:param X: input array
:type X: np.ndarray(shape=(N, d))
:return: standardized array
:rtype: np.ndarray(shape=(N, d))
"""
# YOUR CODE HERE:
raise NotImplementedError("falta completar a função standardize")
# END YOUR CODE
return X_out
```
**Teste exercício 1)**
```python
toy_X = np.array([[1100.3, 2.4, 34.34],
[2300.3, 1.4, 442.23]])
toy_y = np.array([[1000.2], [2000.5]])
toy_X_norm = standardize(toy_X)
toy_y_norm = standardize(toy_y)
xmean, xstd = np.mean(toy_X_norm), np.std(toy_X_norm)
ymean, ystd = np.mean(toy_y_norm), np.std(toy_y_norm)
assert -1 <= xmean < 0
assert 0 <= ymean < 1
assert 0.9 <= xstd <= 1
assert 0.9 <= ystd <= 1
```
```python
train_X_norm = standardize(train_X)
train_y_norm = standardize(train_y)
xmean, xstd = np.mean(train_X), np.std(train_X)
xmax, xmin = np.max(train_X), np.min(train_X)
ymean, ystd = np.mean(train_y), np.std(train_y)
ymax, ymin = np.max(train_y), np.min(train_y)
print("Dados originais\n")
print("X:\nmean {}, std {:.2f}, max {}, min {}".format(xmean,
xstd,
xmax,
xmin))
print("\ny:\nmean {}, std {:.2f}, max {}, min {}\n".format(ymean,
ystd,
ymax,
ymin))
xmean, xstd = np.mean(train_X_norm), np.std(train_X_norm)
xmax, xmin = np.max(train_X_norm), np.min(train_X_norm)
ymean, ystd = np.mean(train_y_norm), np.std(train_y_norm)
ymax, ymin = np.max(train_y_norm), np.min(train_y_norm)
print("Dados normalizados\n")
print("X:\nmean {}, std {:.2f}, max {}, min {}".format(xmean,
xstd,
xmax,
xmin))
print("\ny:\nmean {}, std {:.2f}, max {}, min {}\n".format(ymean,
ystd,
ymax,
ymin))
plot_points_regression(train_X_norm,
train_y_norm,
title='Training data (normalized)',
xlabel="m\u00b2",
ylabel='$')
```
##### Adicionando uma componente com apenas 1s como uma nova feature
Conforme já vimos, adicionar uma componente (coordenada artificial) constante 1 é conveniente. Isto é, em vez de $\mathbf{x} \in \mathbb{R}^d$ é conveniente considerarmos $(1,\mathbf{x}) \in \mathbb{R}^{d+1}$.
```python
def add_feature_ones(X):
"""
Returns the ndarray 'X' with the extra
feature column containing only 1s.
:param X: input array
:type X: np.ndarray(shape=(N, d))
:return: output array
:rtype: np.ndarray(shape=(N, d+1))
"""
return np.concatenate((np.ones((X.shape[0], 1)), X), axis=1)
train_X_1 = add_feature_ones(train_X_norm)
print("\ntrain_X shape = {}".format(train_X_1.shape))
```
##### Criando a predição da regressão linear e plotando uma predição arbitrária
```python
def linear_regression_prediction(X, w):
"""
Calculates the linear regression prediction.
:param X: design matrix
:type X: np.ndarray(shape=(N, d))
:param w: weights
:type w: np.array(shape=(d, 1))
:return: prediction
:rtype: np.array(shape=(N, 1))
"""
return X.dot(w)
w = np.array([[1.2], [2.3]])
prediction = linear_regression_prediction(train_X_1, w)
plot_points_regression(train_X_norm,
train_y_norm,
title='Training data (normalized)',
xlabel="m\u00b2",
ylabel='$',
prediction=prediction,
legend=True)
```
### Computando a função de custo
Usando o erro quadrárico médio, a função de custo $J(\mathbf{w})$ para a tarefa de regressão linear pode ser escrita de dois modos. A forma iterativa:
\begin{equation}
J(\mathbf{w}) = \frac{1}{N}\sum_{i=1}^{N}(\hat{y}_{i} - y_{i})^{2}
\end{equation}
e a forma vetorial:
\begin{equation}
J(\mathbf{w}) = \frac{1}{N}(\mathbf{X}\mathbf{w} - \mathbf{y})^{T}(\mathbf{X}\mathbf{w} - \mathbf{y})
\end{equation}
##### **Exercício 2)**
Use a biblioteca numpy para implementar a função de custo.
```python
def compute_cost(X, y, w):
"""
Calculates mean square error cost.
:param X: design matrix
:type X: np.ndarray(shape=(N, d))
:param y: regression targets
:type y: np.ndarray(shape=(N, 1))
:param w: weights
:type w: np.array(shape=(d, 1))
:return: cost
:rtype: float
"""
# YOUR CODE HERE:
raise NotImplementedError("falta completar a função compute_cost")
# END YOUR CODE
return J
```
**Teste exercício 2)**
```python
toy_w = np.array([[1], [1], [2]])
toy_X = np.array([[2, 3, 1],
[5, 1, 2]])
toy_y = np.array([[1], [1]])
assert compute_cost(toy_X, toy_y, toy_w) == 58.5
```
Podemos olhar a superficie de custo e ver onde se situa um valor $J(\mathbf{w})$.
```python
initial_w = np.array([[15], [-35.3]])
initial_J = compute_cost(train_X_1, train_y_norm, initial_w)
plot_cost_function_curve(train_X_1,
train_y_norm,
compute_cost,
title="Optimization landscape",
weights_list=[initial_w.flatten()],
cost_list=[initial_J])
```
### Calculando os gradientes
É fácil calcular a derivada parcial de $J(\mathbf{w})$ com relação a cada entrada $j$ de $\mathbf{w}$:
\begin{equation}
\frac{\partial J(\mathbf{w})}{\partial \mathbf{w}_{j}} = \frac{2}{N}\sum_{i=1}^{N} (\hat{y}_i - y_i) \mathbf{x}_{ij}
\end{equation}
Lembre que o gradiente de $J(\mathbf{w})$ com relação a $\mathbf{w}$ é:
\begin{equation}
\nabla_{\mathbf{w}}J(\mathbf{w}) = \begin{bmatrix}\frac{\partial J(\mathbf{w})}{\partial \mathbf{w}_{1}} \dots \frac{\partial J(\mathbf{w})}{\partial \mathbf{w}_{m}} \end{bmatrix}
\end{equation}
##### **Exercício 3)**
Use a biblioteca numpy para calcular $\nabla_{\mathbf{w}}J(\mathbf{w})$.
```python
def compute_wgrad(X, y, w):
"""
Calculates gradient of J(w) with respect to w.
:param X: design matrix
:type X: np.ndarray(shape=(N, d))
:param y: regression targets
:type y: np.ndarray(shape=(N, 1))
:param w: weights
:type w: np.array(shape=(d, 1))
:return: gradient
:rtype: np.array(shape=(d, 1))
"""
# YOUR CODE HERE:
raise NotImplementedError("falta completar a função compute_wgrad")
# END YOUR CODE
return grad
```
**Teste exercício 3)**
```python
def grad_check(X, y, w, h=1e-4):
"""
Check gradients for linear regression.
:param X: design matrix
:type X: np.ndarray(shape=(N, d))
:param y: regression targets
:type y: np.ndarray(shape=(N, 1))
:param w: weights
:type w: np.array(shape=(d, 1))
:param h: small variation
:type h: float
:return: gradient test
:rtype: boolean
"""
Jw = compute_cost(X, y, w)
grad = compute_wgrad(X, y, w)
passing = True
d = w.shape[0]
for i in range(d):
w_plus_h = np.array(w, copy=True)
w_plus_h[i] = w_plus_h[i] + h
Jw_plus_h = compute_cost(X, y, w_plus_h)
w_minus_h = np.array(w, copy=True)
w_minus_h[i] = w_minus_h[i] - h
Jw_minus_h = compute_cost(X, y, w_minus_h)
numgrad_i = (Jw_plus_h - Jw_minus_h) / (2 * h)
reldiff = abs(numgrad_i - grad[i]) / max(1, abs(numgrad_i), abs(grad[i]))
if reldiff > 1e-5:
passing = False
msg = """
Seu gradiente = {0}
Gradiente numérico = {1}""".format(grad[i], numgrad_i)
print(" " + str(i) + ": " + msg)
print(" Jw = {}".format(Jw))
print(" Jw_plus_h = {}".format(Jw_plus_h))
print(" Jw_minus_h = {}\n".format(Jw_minus_h))
if passing:
print("Gradiente passando!")
return passing
toy_w1 = np.array([[1.], [2.], [1.], [2.]])
toy_X1 = np.array([[2., 3., 1., 2.],
[5., 1., 1., 2.]])
toy_y1 = np.array([[1.], [-1.]])
toy_w2 = np.array([[-100.22], [20002.1], [102.5]])
toy_X2 = np.array([[2111.3, -2223., 404.0],
[5222., -22221., 3.3]])
toy_y2 = np.array([[122.], [221.]])
toy_w3 = np.array([[-10.22], [-3.1]])
toy_X3 = np.array([[1.3, -1.2],
[2.2, -2.1],
[-2.3, -5.5],
[3.2, 8.1],
[3.3, -1.1],
[-3.4, -2.22],
[2.23, -4.4],
[5.2, -2.3]])
toy_y3 = np.array([[10.3],
[23.3],
[10.1],
[-20.2],
[-10.2],
[20.2],
[-14.4],
[-30.3]])
assert grad_check(toy_X1, toy_y1, toy_w1)
assert grad_check(toy_X2, toy_y2, toy_w2)
assert grad_check(toy_X3, toy_y3, toy_w3)
```
### Batch gradient descent
A versão mais simples do algoritmo *gradient descent* faz uso de todas as observações do dataset de treinamento (esse algoritmo também é conhecido como *batch gradient descent* ou *vanilla gradient descent*).
**Batch gradient descent**
- $\mathbf{w}(0) = \mathbf{w}$
- for $t = 0, 1, 2, \dots$ do
* Compute the gradient $\nabla_{\mathbf{w}(t)}J(\mathbf{w}(t))$
* Apply update : $\mathbf{w}(t+1) = \mathbf{w}(t) - \eta \nabla_{\mathbf{w}(t)}J(\mathbf{w}(t))$
##### **Exercício 4)**
Implemente o algoritmo batch gradient descent com a taxa de apreendizado fixa para a regressão linear. A função abaixo deve retornar três coisas: o vetor de pesos $\mathbf{w}$, uma lista com cada peso obtido ao longo do treinamento, e uma lista com o custo de cada peso.
```python
def batch_gradient_descent(X, y, w, learning_rate, num_iters):
"""
Performs batch gradient descent optimization.
:param X: design matrix
:type X: np.ndarray(shape=(N, d))
:param y: regression targets
:type y: np.ndarray(shape=(N, 1))
:param w: weights
:type w: np.array(shape=(d, 1))
:param learning_rate: learning rate
:type learning_rate: float
:param num_iters: number of iterations
:type num_iters: int
:return: weights, weights history, cost history
:rtype: np.array(shape=(d, 1)), list, list
"""
weights_history = [w.flatten()]
cost_history = [compute_cost(X, y, w)]
# YOUR CODE HERE:
raise NotImplementedError("falta completar a função batch_gradient_descent")
# END YOUR CODE
return w, weights_history, cost_history
```
**Teste exercício 4)**
```python
learning_rate = 0.8
iterations = 20000
init = time.time()
w, weights_history, cost_history = batch_gradient_descent(train_X_1,
train_y_norm,
initial_w,
learning_rate,
iterations)
assert cost_history[-1] < cost_history[0]
assert type(w) == np.ndarray
assert len(weights_history) == len(cost_history)
init = time.time() - init
print("Tempo de treinamento = {:.8f}(s)".format(init))
print("Tem que ser em menos de 1 segundo ")
```
##### Agora podemos treinar o modelo
```python
learning_rate = 0.03
iterations = 400
w, weights_history, cost_history = batch_gradient_descent(train_X_1,
train_y_norm,
initial_w,
learning_rate,
iterations)
title = "Optimization landscape\nlearning rate = {} | iterations = {}".format(learning_rate,
iterations)
plot_cost_function_curve(train_X_1,
train_y_norm,
compute_cost,
title=title,
weights_list=weights_history,
cost_list=cost_history)
simple_step_plot([cost_history],
"loss",
'Training loss\nlearning rate = {} | iterations = {}'.format(learning_rate,
iterations))
```
### Hiper parâmetros (*hyperparameters*)
Hiper parâmetros são parâmetros que controlam o comportamento do algoritmo. Eles não são modificados pelo algoritmo de aprendizado. Escolhemos os hiper parâmetros de acordo com a performance deles no dataset de treinamento. Para evitar que o modelo decore o dataset de treinamento, pegamos uma parte desse dataset só para achar os melhores hiper parâmetros. Essa parte é chamada de **dataset de validação** (*validation set*).
```python
valid_X_norm = standardize(valid_X)
valid_y_norm = standardize(valid_y)
valid_X_1 = add_feature_ones(valid_X_norm)
hyper_params = [(0.001, 200),
(0.1, 10),
(0.9, 8),
(0.02, 600)]
all_costs = []
all_w = []
for param in hyper_params:
learning_rate = param[0]
iterations = param[1]
w, weights_history, cost_history = batch_gradient_descent(train_X_1,
train_y_norm,
initial_w,
learning_rate,
iterations)
all_costs.append(compute_cost(valid_X_1, valid_y_norm, w))
all_w.append(w)
title = "Optimization landscape\n"
title += "learning rate = {} | iterations = {}".format(learning_rate,
iterations)
plot_cost_function_curve(train_X_1,
train_y_norm,
compute_cost,
title=title,
weights_list=weights_history,
cost_list=cost_history)
best_result_i = np.argmin(all_costs)
best_w = all_w[best_result_i]
lowest_cost = all_costs[best_result_i]
best_params = hyper_params[best_result_i]
result_str = "Best hyperparameters\n"
result_str += "learning rate = {}".format(best_params[0])
result_str += " | iterations = {}\n".format(best_params[1])
result_str += "w = {}\n".format(best_w.flatten())
result_str += "lowest validation set cost = {}\n".format(lowest_cost)
print(result_str)
```
##### Com o modelo treinado e escolhidos os melhores hiper parâmetros, podemos avaliá-lo sobre o dataset de teste.
```python
test_X_norm = standardize(test_X)
test_y_norm = standardize(test_y)
test_X_1 = add_feature_ones(test_X_norm)
prediction = linear_regression_prediction(test_X_1, best_w)
prediction = (prediction * np.std(train_y)) + np.mean(train_y)
r_2 = r_squared(test_y, prediction)
plot_points_regression(test_X,
test_y,
title='Test data',
xlabel="m\u00b2",
ylabel='$',
prediction=prediction,
r_squared=r_2,
legend=True)
```
### Gradiente descendente estocástico
Nos casos em que $N$ é um número grande, computar $\nabla_{\mathbf{w}}J(\mathbf{w})$ a cada iteração se torna algo muito custoso. Uma estratégia para lidar com isso é **aproximar** $\nabla_{\mathbf{w}}J(\mathbf{w})$ usando o gradiente:
\begin{equation}
\hat{\nabla_{\mathbf{w}}J(\mathbf{w})} = \nabla_{\mathbf{w}}\frac{1}{m}\sum_{i=1}^{m} L(h(\mathbf{x}_{i}; \mathbf{w}), \; y_{i})
\end{equation}
em que $(\mathbf{x}_{1}, y_{1}), \dots ,(\mathbf{x}_{m}, y_{m})$ é uma amostragem aleatória dos dados de treinamento. A estocasticidade surge da escolha desses $m$ dados (para que $\hat{\nabla_{\mathbf{w}}J(\mathbf{w})}$ seja um estimador não enviesado de $\nabla_{\mathbf{w}}J(\mathbf{w})$ nós amostramos os $m$ dados a cada iteração). Normalmente usamos o nome **gradiente descendente estocástico** (*stochastic gradient descent* ou *online gradient descent*) quando $m=1$, e usamos o nome **minibatch stochastic gradient descent** quando $1 < m <N$ (nesse caso estamos usando apenas um pequeno lote dos dados, um *minibatch*). Usamos *batch* para referir a um *minibatch*, não confunda isso com *batch gradient descent*.
**Stochastic gradient descent (SGD)**
- $\mathbf{w}(0) = \mathbf{w}$
- for $t = 0, 1, 2, \dots$ do
* Sample a minibatch of $m$ examples from the training data.
* Compute the gradient estimate $\hat{\nabla_{\mathbf{w}(t)}J(\mathbf{w}(t))}$
* Apply update : $\mathbf{w}(t+1) = \mathbf{w}(t) - \eta \hat{\nabla_{\mathbf{w}(t)}J(\mathbf{w}(t))}$
##### **Exercício 5)**
Implemente o algoritmo stochastic gradient descent para a regressão linear com a taxa de apreendizado fixa. A saída da função é a mesma da função do exercício 4.
```python
def stochastic_gradient_descent(X, y, w, learning_rate, num_iters, batch_size):
"""
Performs stochastic gradient descent optimization
:param X: design matrix
:type X: np.ndarray(shape=(N, d))
:param y: regression targets
:type y: np.ndarray(shape=(N, 1))
:param w: weights
:type w: np.array(shape=(d, 1))
:param learning_rate: learning rate
:type learning_rate: float
:param num_iters: number of iterations
:type num_iters: int
:param batch_size: size of the minibatch
:type batch_size: int
:return: weights, weights history, cost history
:rtype: np.array(shape=(d, 1)), list, list
"""
# YOUR CODE HERE:
raise NotImplementedError("falta completar a função stochastic_gradient_descent")
# END YOUR CODE
return w, weights_history, cost_history
```
**Teste exercício 5)**
```python
init = time.time()
learning_rate = 0.8
iterations = 2000
batch_size = 36
w, weights_history, cost_history = stochastic_gradient_descent(train_X_1,
train_y_norm,
initial_w,
learning_rate,
iterations,
batch_size)
assert cost_history[-1] < cost_history[0]
assert type(w) == np.ndarray
assert len(weights_history) == len(cost_history)
init = time.time() - init
print("Tempo de treinamento = {:.8f}(s)".format(init))
print("Tem que ser em menos de 1.2 segundos")
```
###### Podemos experimentar com diferentes tamanhos de batch para ver que quanto maior o tamanho do batch (mais próximo de $N$) menor a variância.
```python
hyper_params = [(0.001, 1000, 1),
(0.001, 1000, 10),
(0.001, 1000, 36)]
all_costs = []
for param in hyper_params:
learning_rate = param[0]
iterations = param[1]
batch_size = param[2]
_, weights_history, cost_history = stochastic_gradient_descent(train_X_1,
train_y_norm,
initial_w,
learning_rate,
iterations,
batch_size)
all_costs.append(cost_history)
title = "Optimization landscape\n"
title += "learning rate = {}".format(learning_rate)
title += " | iterations = {}".format(iterations)
title += " | batch size = {}".format(batch_size)
plot_cost_function_curve(train_X_1,
train_y_norm,
compute_cost,
title=title,
weights_list=weights_history,
cost_list=cost_history)
_, _, cost_history_full = batch_gradient_descent(train_X_1,
train_y_norm,
initial_w,
learning_rate=0.001,
num_iters=1000)
all_costs.append(cost_history_full)
labels_size = ["batch size = " + str(param[2]) for param in hyper_params]
labels_size += ["batch size = " + str(train_X_1.shape[0])]
simple_step_plot(all_costs,
"loss",
'Training loss',
figsize=(8, 8),
labels=labels_size)
```
### Por que normalizar?
O primeiro motivo para se normalizar os dados é para evitar *overflow*. Também é verdade que quando não normalizamos os dados as *features* podem apresentar diferentes escalas -- note que esse é o caso nesse dataset em que uma *feature* só tem $1$s e a outra ($m^{2}$) apresenta bastante variação. Isso influencia no gradiente de modo que a cada atualização os valores dos pesos vão mudar de modo diferente mesmo usando o mesmo *learning rate*.
Isso pode ser visto quando acompanhamos a mudança nos pesos ao longo do treinamento no dataset original e no normalizado. Note como o parâmetro $\mathbf{w}[1]$ (que pondera a feature ($m^{2}$)) muda bem mais que o parâmetro $\mathbf{w}[0]$ quando usamos o dataset não normalizado.
```python
_, weights_history_norm, cost_history_norm = batch_gradient_descent(train_X_1,
train_y_norm,
initial_w,
learning_rate,
10)
train_X_1_non_norm = add_feature_ones(train_X)
w, weights_history, cost_history = batch_gradient_descent(train_X_1_non_norm,
train_y,
initial_w,
0.000002,
10)
w0_hist_norm = [w[0] for w in weights_history_norm]
w1_hist_norm = [w[1] for w in weights_history_norm]
w0mean, w0sdt, w0max, w0min = np.mean(w0_hist_norm), np.std(w0_hist_norm), np.max(w0_hist_norm), np.min(w0_hist_norm)
w1mean, w1sdt, w1max, w1min = np.mean(w0_hist_norm), np.std(w1_hist_norm), np.max(w1_hist_norm), np.min(w1_hist_norm)
print("\nVariação dos pesos com o dataset normalizado\n")
print("w[0]:\nmean {}, std {:.2f}, max {}, min {}".format(w0mean, w0sdt, w0max, w0min))
print("w[1]:\nmean {}, *std {:.2f}*, max {}, min {}".format(w1mean, w1sdt, w1max, w1min))
w0_hist = [w[0] for w in weights_history]
w1_hist = [w[1] for w in weights_history]
w0mean, w0sdt, w0max, w0min = np.mean(w0_hist), np.std(w0_hist), np.max(w0_hist), np.min(w0_hist)
w1mean, w1sdt, w1max, w1min = np.mean(w1_hist), np.std(w1_hist), np.max(w1_hist), np.min(w1_hist)
print("\nVariação dos pesos com o dataset não normalizado\n")
print("w[0]:\nmean {}, std {:.2f}, max {}, min {}".format(w0mean, w0sdt, w0max, w0min))
print("w[1]:\nmean {}, *std {:.2f}*, max {}, min {}".format(w1mean, w1sdt, w1max, w1min))
```
#### Um dos resultados dessa atualização em scala diferente para cada feature é a não convergência do algoritmo
```python
simple_step_plot([cost_history_norm],
"loss",
'Training loss (normalized)')
simple_step_plot([cost_history],
"loss",
'Training loss (non normalized)')
plot_cost_function_curve(train_X_1_non_norm,
train_y,
compute_cost,
title="Optimization landscape\n(non normalized data)",
weights_list=weights_history,
cost_list=cost_history,
range_points=(100, 100))
```
### Mais otimização!
Há muitos outros algoritmos de otimização construídos em cima da ideia de gradiente descendente. Um bom resumo de alguns desses algoritimos pode ser encontrado [aqui](http://ruder.io/optimizing-gradient-descent/).
|
#include <stdio.h>
#include <glib.h>
#include <gsl/gsl_matrix.h>
#define MATRIX_SIZE 3
static double d_matrix[MATRIX_SIZE][MATRIX_SIZE] = {
{1., 4., 2.},
{-1., -2., 1.},
{3., 20., 19.},
};
static double d_vector[] = {8., 3., 71.};
int main(void) {
printf("Gauss.\n\n");
// Alloc matrix`s
gsl_matrix *matrix = gsl_matrix_alloc(MATRIX_SIZE, MATRIX_SIZE);
// gsl_matrix *orig_matrix = gsl_matrix_alloc(MATRIX_SIZE, MATRIX_SIZE);
gsl_vector *vector = gsl_vector_alloc(MATRIX_SIZE);
// gsl_vector *orig_vector = gsl_vector_alloc(MATRIX_SIZE);
gsl_vector *result = gsl_vector_alloc(MATRIX_SIZE);
// Init matrix
for (size_t i = 0; i < MATRIX_SIZE; i++) {
for (size_t j = 0; j < MATRIX_SIZE; j++) {
gsl_matrix_set(matrix, i, j, d_matrix[i][j]);
// gsl_matrix_set(orig_matrix, i, j, d_matrix[i][j]);
}
}
// Init vector
for (size_t j = 0; j < MATRIX_SIZE; j++) {
gsl_vector_set(vector, j, d_vector[j]);
// gsl_vector_set(orig_vector, j, d_vector[j]);
}
printf("First matrix row:\n");
for (size_t j = 0; j < MATRIX_SIZE; j++) {
double el = gsl_matrix_get(matrix, 0, j);
printf("%zu - %f\n", j, el);
}
printf("\n");
// Gauss
// Forward
// Steps by equations
size_t swap_counter = 0;
for (size_t step = 0; step < MATRIX_SIZE - 1; step++) {
// Walk by matrix rows
for (size_t eq_idx = step + 1; eq_idx < MATRIX_SIZE; eq_idx++) {
// Multiplier
{
// Get vector column from submatrix
size_t subcol_size = MATRIX_SIZE - eq_idx;
gsl_vector_view subcol = gsl_matrix_subcolumn(matrix, eq_idx, eq_idx, subcol_size);
// Find max idx
gsl_vector *subcol_copy = gsl_vector_alloc(subcol_size);
gsl_vector_memcpy(subcol_copy, &subcol.vector);
for (size_t i = 0; i < subcol_size; i++) {
gsl_vector_set(subcol_copy, i, abs(gsl_vector_get(&subcol.vector, i)));
}
size_t eq_max_idx = gsl_vector_max_index(&subcol.vector) + eq_idx;
// swap rows
double cell = gsl_matrix_get(matrix, eq_max_idx, eq_idx);
if (cell == 0) {
goto err;
}
else if (eq_idx != eq_max_idx) {
gsl_matrix_swap_rows(matrix, eq_idx, eq_max_idx);
gsl_vector_swap_elements(vector, eq_idx, eq_max_idx);
// gsl_matrix_swap_rows(orig_matrix, eq_idx, eq_max_idx);
// gsl_vector_swap_elements(orig_vector, eq_idx, eq_max_idx);
swap_counter++;
}
}
double multiplier = gsl_matrix_get(matrix, eq_idx, step) / gsl_matrix_get(matrix, step, step);
gsl_matrix_set(matrix, eq_idx, step, 0);
// Update vector value
double vector_val = gsl_vector_get(vector, eq_idx) - multiplier * gsl_vector_get(vector, step);
gsl_vector_set(vector, eq_idx, vector_val);
// Walk by eq cells
for (size_t col = step + 1; col < MATRIX_SIZE; col++) {
double cell_val = gsl_matrix_get(matrix, eq_idx, col) - multiplier * gsl_matrix_get(matrix, step, col);
gsl_matrix_set(matrix, eq_idx, col, cell_val);
}
}
}
// /Forward
// det
double det = 1;
for (size_t i = 0; i < MATRIX_SIZE; i++) {
det *= gsl_matrix_get(matrix, i, i);
}
if (swap_counter % 2 != 0) {
det *= -1;
}
printf("det = %f\n\n", det);
// /det
// Back
for (ssize_t eq_idx = MATRIX_SIZE - 1; eq_idx >= 0; eq_idx--) { //1
double sum = 0;
for (size_t col = eq_idx + 1; col <= MATRIX_SIZE - 1; col++) { // 2
sum += gsl_matrix_get(matrix, eq_idx, col) * gsl_vector_get(result, col);
}
gsl_vector_set(result, eq_idx, (gsl_vector_get(vector, eq_idx) - sum) / gsl_matrix_get(matrix, eq_idx, eq_idx));
}
// /Back
// /Gauss
printf("Result:\n");
for (size_t i = 0; i < MATRIX_SIZE; i++) {
printf("%zu - %f\n", i, gsl_vector_get(result, i));
}
printf("\nCheck:\n");
for (size_t row = 0; row < MATRIX_SIZE; row++) {
double sum = 0;
for (size_t col = 0; col < MATRIX_SIZE; col++) {
sum += d_matrix[row][col] * gsl_vector_get(result, col);
}
printf("%f = %f\n", sum, d_vector[row]);
}
exit(EXIT_SUCCESS);
err:
fprintf(stderr, "No decision.\n");
exit(EXIT_FAILURE);
}
|
[GOAL]
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N : Type w
inst✝ : Structure L N
h : Countable M
⊢ Set.Countable (Quotient.mk' '' age L M)
[PROOFSTEP]
classical
refine'
(congr_arg _ (Set.ext <| forall_quotient_iff.2 fun N => _)).mp
(countable_range fun s : Finset M => ⟦⟨closure L (s : Set M), inferInstance⟩⟧)
constructor
· rintro ⟨s, hs⟩
use Bundled.of (closure L (s : Set M))
exact ⟨⟨(fg_iff_structure_fg _).1 (fg_closure s.finite_toSet), ⟨Substructure.subtype _⟩⟩, hs⟩
· simp only [mem_range, Quotient.eq]
rintro ⟨P, ⟨⟨s, hs⟩, ⟨PM⟩⟩, hP2⟩
have : P ≈ N := by apply Quotient.eq'.mp; rw [hP2];
rfl
-- Porting note: added
refine' ⟨s.image PM, Setoid.trans (b := P) _ this⟩
rw [← Embedding.coe_toHom, Finset.coe_image, closure_image PM.toHom, hs, ← Hom.range_eq_map]
exact ⟨PM.equivRange.symm⟩
[GOAL]
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N : Type w
inst✝ : Structure L N
h : Countable M
⊢ Set.Countable (Quotient.mk' '' age L M)
[PROOFSTEP]
refine'
(congr_arg _ (Set.ext <| forall_quotient_iff.2 fun N => _)).mp
(countable_range fun s : Finset M => ⟦⟨closure L (s : Set M), inferInstance⟩⟧)
[GOAL]
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
h : Countable M
N : Bundled (Structure L)
⊢ (Quotient.mk equivSetoid N ∈
range fun s => Quotient.mk equivSetoid (Bundled.mk { x // x ∈ LowerAdjoint.toFun (closure L) ↑s })) ↔
Quotient.mk equivSetoid N ∈ Quotient.mk' '' age L M
[PROOFSTEP]
constructor
[GOAL]
case mp
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
h : Countable M
N : Bundled (Structure L)
⊢ (Quotient.mk equivSetoid N ∈
range fun s => Quotient.mk equivSetoid (Bundled.mk { x // x ∈ LowerAdjoint.toFun (closure L) ↑s })) →
Quotient.mk equivSetoid N ∈ Quotient.mk' '' age L M
[PROOFSTEP]
rintro ⟨s, hs⟩
[GOAL]
case mp.intro
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
h : Countable M
N : Bundled (Structure L)
s : Finset M
hs :
(fun s => Quotient.mk equivSetoid (Bundled.mk { x // x ∈ LowerAdjoint.toFun (closure L) ↑s })) s =
Quotient.mk equivSetoid N
⊢ Quotient.mk equivSetoid N ∈ Quotient.mk' '' age L M
[PROOFSTEP]
use Bundled.of (closure L (s : Set M))
[GOAL]
case h
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
h : Countable M
N : Bundled (Structure L)
s : Finset M
hs :
(fun s => Quotient.mk equivSetoid (Bundled.mk { x // x ∈ LowerAdjoint.toFun (closure L) ↑s })) s =
Quotient.mk equivSetoid N
⊢ Bundled.of { x // x ∈ LowerAdjoint.toFun (closure L) ↑s } ∈ age L M ∧
Quotient.mk' (Bundled.of { x // x ∈ LowerAdjoint.toFun (closure L) ↑s }) = Quotient.mk equivSetoid N
[PROOFSTEP]
exact ⟨⟨(fg_iff_structure_fg _).1 (fg_closure s.finite_toSet), ⟨Substructure.subtype _⟩⟩, hs⟩
[GOAL]
case mpr
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
h : Countable M
N : Bundled (Structure L)
⊢ Quotient.mk equivSetoid N ∈ Quotient.mk' '' age L M →
Quotient.mk equivSetoid N ∈
range fun s => Quotient.mk equivSetoid (Bundled.mk { x // x ∈ LowerAdjoint.toFun (closure L) ↑s })
[PROOFSTEP]
simp only [mem_range, Quotient.eq]
[GOAL]
case mpr
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
h : Countable M
N : Bundled (Structure L)
⊢ Quotient.mk equivSetoid N ∈ Quotient.mk' '' age L M →
∃ y, Bundled.mk { x // x ∈ LowerAdjoint.toFun (closure L) ↑y } ≈ N
[PROOFSTEP]
rintro ⟨P, ⟨⟨s, hs⟩, ⟨PM⟩⟩, hP2⟩
[GOAL]
case mpr.intro.intro.intro.mk.intro.intro
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
h : Countable M
N P : Bundled (Structure L)
hP2 : Quotient.mk' P = Quotient.mk equivSetoid N
s : Finset ↑P
hs : LowerAdjoint.toFun (closure L) ↑s = ⊤
PM : ↑P ↪[L] M
⊢ ∃ y, Bundled.mk { x // x ∈ LowerAdjoint.toFun (closure L) ↑y } ≈ N
[PROOFSTEP]
have : P ≈ N := by apply Quotient.eq'.mp; rw [hP2];
rfl
-- Porting note: added
[GOAL]
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
h : Countable M
N P : Bundled (Structure L)
hP2 : Quotient.mk' P = Quotient.mk equivSetoid N
s : Finset ↑P
hs : LowerAdjoint.toFun (closure L) ↑s = ⊤
PM : ↑P ↪[L] M
⊢ P ≈ N
[PROOFSTEP]
apply Quotient.eq'.mp
[GOAL]
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
h : Countable M
N P : Bundled (Structure L)
hP2 : Quotient.mk' P = Quotient.mk equivSetoid N
s : Finset ↑P
hs : LowerAdjoint.toFun (closure L) ↑s = ⊤
PM : ↑P ↪[L] M
⊢ Quotient.mk' P = Quotient.mk' N
[PROOFSTEP]
rw [hP2]
[GOAL]
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
h : Countable M
N P : Bundled (Structure L)
hP2 : Quotient.mk' P = Quotient.mk equivSetoid N
s : Finset ↑P
hs : LowerAdjoint.toFun (closure L) ↑s = ⊤
PM : ↑P ↪[L] M
⊢ Quotient.mk equivSetoid N = Quotient.mk' N
[PROOFSTEP]
rfl
-- Porting note: added
[GOAL]
case mpr.intro.intro.intro.mk.intro.intro
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
h : Countable M
N P : Bundled (Structure L)
hP2 : Quotient.mk' P = Quotient.mk equivSetoid N
s : Finset ↑P
hs : LowerAdjoint.toFun (closure L) ↑s = ⊤
PM : ↑P ↪[L] M
this : P ≈ N
⊢ ∃ y, Bundled.mk { x // x ∈ LowerAdjoint.toFun (closure L) ↑y } ≈ N
[PROOFSTEP]
refine' ⟨s.image PM, Setoid.trans (b := P) _ this⟩
[GOAL]
case mpr.intro.intro.intro.mk.intro.intro
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
h : Countable M
N P : Bundled (Structure L)
hP2 : Quotient.mk' P = Quotient.mk equivSetoid N
s : Finset ↑P
hs : LowerAdjoint.toFun (closure L) ↑s = ⊤
PM : ↑P ↪[L] M
this : P ≈ N
⊢ Bundled.mk { x // x ∈ LowerAdjoint.toFun (closure L) ↑(Finset.image (↑PM) s) } ≈ P
[PROOFSTEP]
rw [← Embedding.coe_toHom, Finset.coe_image, closure_image PM.toHom, hs, ← Hom.range_eq_map]
[GOAL]
case mpr.intro.intro.intro.mk.intro.intro
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
h : Countable M
N P : Bundled (Structure L)
hP2 : Quotient.mk' P = Quotient.mk equivSetoid N
s : Finset ↑P
hs : LowerAdjoint.toFun (closure L) ↑s = ⊤
PM : ↑P ↪[L] M
this : P ≈ N
⊢ Bundled.mk { x // x ∈ Hom.range (Embedding.toHom PM) } ≈ P
[PROOFSTEP]
exact ⟨PM.equivRange.symm⟩
[GOAL]
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝⁶ : Structure L M
N : Type w
inst✝⁵ : Structure L N
ι : Type w
inst✝⁴ : Preorder ι
inst✝³ : IsDirected ι fun x x_1 => x ≤ x_1
inst✝² : Nonempty ι
G : ι → Type (max w w')
inst✝¹ : (i : ι) → Structure L (G i)
f : (i j : ι) → i ≤ j → G i ↪[L] G j
inst✝ : DirectedSystem G fun i j h => ↑(f i j h)
⊢ age L (DirectLimit G f) = ⋃ (i : ι), age L (G i)
[PROOFSTEP]
classical
ext M
simp only [mem_iUnion]
constructor
· rintro ⟨Mfg, ⟨e⟩⟩
obtain ⟨s, hs⟩ := Mfg.range e.toHom
let out := @Quotient.out _ (DirectLimit.setoid G f)
obtain ⟨i, hi⟩ := Finset.exists_le (s.image (Sigma.fst ∘ out))
have e' := (DirectLimit.of L ι G f i).equivRange.symm.toEmbedding
refine' ⟨i, Mfg, ⟨e'.comp ((Substructure.inclusion _).comp e.equivRange.toEmbedding)⟩⟩
rw [← hs, closure_le]
intro x hx
refine' ⟨f (out x).1 i (hi (out x).1 (Finset.mem_image_of_mem _ hx)) (out x).2, _⟩
rw [Embedding.coe_toHom, DirectLimit.of_apply, @Quotient.mk_eq_iff_out _ (_),
DirectLimit.equiv_iff G f _ (hi (out x).1 (Finset.mem_image_of_mem _ hx)), DirectedSystem.map_self]
rfl
· rintro ⟨i, Mfg, ⟨e⟩⟩
exact ⟨Mfg, ⟨Embedding.comp (DirectLimit.of L ι G f i) e⟩⟩
[GOAL]
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝⁶ : Structure L M
N : Type w
inst✝⁵ : Structure L N
ι : Type w
inst✝⁴ : Preorder ι
inst✝³ : IsDirected ι fun x x_1 => x ≤ x_1
inst✝² : Nonempty ι
G : ι → Type (max w w')
inst✝¹ : (i : ι) → Structure L (G i)
f : (i j : ι) → i ≤ j → G i ↪[L] G j
inst✝ : DirectedSystem G fun i j h => ↑(f i j h)
⊢ age L (DirectLimit G f) = ⋃ (i : ι), age L (G i)
[PROOFSTEP]
ext M
[GOAL]
case h
L : Language
K : Set (Bundled (Structure L))
M✝ : Type w
inst✝⁶ : Structure L M✝
N : Type w
inst✝⁵ : Structure L N
ι : Type w
inst✝⁴ : Preorder ι
inst✝³ : IsDirected ι fun x x_1 => x ≤ x_1
inst✝² : Nonempty ι
G : ι → Type (max w w')
inst✝¹ : (i : ι) → Structure L (G i)
f : (i j : ι) → i ≤ j → G i ↪[L] G j
inst✝ : DirectedSystem G fun i j h => ↑(f i j h)
M : Bundled (Structure L)
⊢ M ∈ age L (DirectLimit G f) ↔ M ∈ ⋃ (i : ι), age L (G i)
[PROOFSTEP]
simp only [mem_iUnion]
[GOAL]
case h
L : Language
K : Set (Bundled (Structure L))
M✝ : Type w
inst✝⁶ : Structure L M✝
N : Type w
inst✝⁵ : Structure L N
ι : Type w
inst✝⁴ : Preorder ι
inst✝³ : IsDirected ι fun x x_1 => x ≤ x_1
inst✝² : Nonempty ι
G : ι → Type (max w w')
inst✝¹ : (i : ι) → Structure L (G i)
f : (i j : ι) → i ≤ j → G i ↪[L] G j
inst✝ : DirectedSystem G fun i j h => ↑(f i j h)
M : Bundled (Structure L)
⊢ M ∈ age L (DirectLimit G f) ↔ ∃ i, M ∈ age L (G i)
[PROOFSTEP]
constructor
[GOAL]
case h.mp
L : Language
K : Set (Bundled (Structure L))
M✝ : Type w
inst✝⁶ : Structure L M✝
N : Type w
inst✝⁵ : Structure L N
ι : Type w
inst✝⁴ : Preorder ι
inst✝³ : IsDirected ι fun x x_1 => x ≤ x_1
inst✝² : Nonempty ι
G : ι → Type (max w w')
inst✝¹ : (i : ι) → Structure L (G i)
f : (i j : ι) → i ≤ j → G i ↪[L] G j
inst✝ : DirectedSystem G fun i j h => ↑(f i j h)
M : Bundled (Structure L)
⊢ M ∈ age L (DirectLimit G f) → ∃ i, M ∈ age L (G i)
[PROOFSTEP]
rintro ⟨Mfg, ⟨e⟩⟩
[GOAL]
case h.mp.intro.intro
L : Language
K : Set (Bundled (Structure L))
M✝ : Type w
inst✝⁶ : Structure L M✝
N : Type w
inst✝⁵ : Structure L N
ι : Type w
inst✝⁴ : Preorder ι
inst✝³ : IsDirected ι fun x x_1 => x ≤ x_1
inst✝² : Nonempty ι
G : ι → Type (max w w')
inst✝¹ : (i : ι) → Structure L (G i)
f : (i j : ι) → i ≤ j → G i ↪[L] G j
inst✝ : DirectedSystem G fun i j h => ↑(f i j h)
M : Bundled (Structure L)
Mfg : Structure.FG L ↑M
e : ↑M ↪[L] DirectLimit G f
⊢ ∃ i, M ∈ age L (G i)
[PROOFSTEP]
obtain ⟨s, hs⟩ := Mfg.range e.toHom
[GOAL]
case h.mp.intro.intro.intro
L : Language
K : Set (Bundled (Structure L))
M✝ : Type w
inst✝⁶ : Structure L M✝
N : Type w
inst✝⁵ : Structure L N
ι : Type w
inst✝⁴ : Preorder ι
inst✝³ : IsDirected ι fun x x_1 => x ≤ x_1
inst✝² : Nonempty ι
G : ι → Type (max w w')
inst✝¹ : (i : ι) → Structure L (G i)
f : (i j : ι) → i ≤ j → G i ↪[L] G j
inst✝ : DirectedSystem G fun i j h => ↑(f i j h)
M : Bundled (Structure L)
Mfg : Structure.FG L ↑M
e : ↑M ↪[L] DirectLimit G f
s : Finset (DirectLimit G f)
hs : LowerAdjoint.toFun (closure L) ↑s = Hom.range (Embedding.toHom e)
⊢ ∃ i, M ∈ age L (G i)
[PROOFSTEP]
let out := @Quotient.out _ (DirectLimit.setoid G f)
[GOAL]
case h.mp.intro.intro.intro
L : Language
K : Set (Bundled (Structure L))
M✝ : Type w
inst✝⁶ : Structure L M✝
N : Type w
inst✝⁵ : Structure L N
ι : Type w
inst✝⁴ : Preorder ι
inst✝³ : IsDirected ι fun x x_1 => x ≤ x_1
inst✝² : Nonempty ι
G : ι → Type (max w w')
inst✝¹ : (i : ι) → Structure L (G i)
f : (i j : ι) → i ≤ j → G i ↪[L] G j
inst✝ : DirectedSystem G fun i j h => ↑(f i j h)
M : Bundled (Structure L)
Mfg : Structure.FG L ↑M
e : ↑M ↪[L] DirectLimit G f
s : Finset (DirectLimit G f)
hs : LowerAdjoint.toFun (closure L) ↑s = Hom.range (Embedding.toHom e)
out : Quotient (DirectLimit.setoid G f) → Structure.Sigma f := Quotient.out
⊢ ∃ i, M ∈ age L (G i)
[PROOFSTEP]
obtain ⟨i, hi⟩ := Finset.exists_le (s.image (Sigma.fst ∘ out))
[GOAL]
case h.mp.intro.intro.intro.intro
L : Language
K : Set (Bundled (Structure L))
M✝ : Type w
inst✝⁶ : Structure L M✝
N : Type w
inst✝⁵ : Structure L N
ι : Type w
inst✝⁴ : Preorder ι
inst✝³ : IsDirected ι fun x x_1 => x ≤ x_1
inst✝² : Nonempty ι
G : ι → Type (max w w')
inst✝¹ : (i : ι) → Structure L (G i)
f : (i j : ι) → i ≤ j → G i ↪[L] G j
inst✝ : DirectedSystem G fun i j h => ↑(f i j h)
M : Bundled (Structure L)
Mfg : Structure.FG L ↑M
e : ↑M ↪[L] DirectLimit G f
s : Finset (DirectLimit G f)
hs : LowerAdjoint.toFun (closure L) ↑s = Hom.range (Embedding.toHom e)
out : Quotient (DirectLimit.setoid G f) → Structure.Sigma f := Quotient.out
i : ι
hi : ∀ (i_1 : ι), i_1 ∈ Finset.image (Sigma.fst ∘ out) s → i_1 ≤ i
⊢ ∃ i, M ∈ age L (G i)
[PROOFSTEP]
have e' := (DirectLimit.of L ι G f i).equivRange.symm.toEmbedding
[GOAL]
case h.mp.intro.intro.intro.intro
L : Language
K : Set (Bundled (Structure L))
M✝ : Type w
inst✝⁶ : Structure L M✝
N : Type w
inst✝⁵ : Structure L N
ι : Type w
inst✝⁴ : Preorder ι
inst✝³ : IsDirected ι fun x x_1 => x ≤ x_1
inst✝² : Nonempty ι
G : ι → Type (max w w')
inst✝¹ : (i : ι) → Structure L (G i)
f : (i j : ι) → i ≤ j → G i ↪[L] G j
inst✝ : DirectedSystem G fun i j h => ↑(f i j h)
M : Bundled (Structure L)
Mfg : Structure.FG L ↑M
e : ↑M ↪[L] DirectLimit G f
s : Finset (DirectLimit G f)
hs : LowerAdjoint.toFun (closure L) ↑s = Hom.range (Embedding.toHom e)
out : Quotient (DirectLimit.setoid G f) → Structure.Sigma f := Quotient.out
i : ι
hi : ∀ (i_1 : ι), i_1 ∈ Finset.image (Sigma.fst ∘ out) s → i_1 ≤ i
e' : { x // x ∈ Hom.range (Embedding.toHom (DirectLimit.of L ι G f i)) } ↪[L] G i
⊢ ∃ i, M ∈ age L (G i)
[PROOFSTEP]
refine' ⟨i, Mfg, ⟨e'.comp ((Substructure.inclusion _).comp e.equivRange.toEmbedding)⟩⟩
[GOAL]
case h.mp.intro.intro.intro.intro
L : Language
K : Set (Bundled (Structure L))
M✝ : Type w
inst✝⁶ : Structure L M✝
N : Type w
inst✝⁵ : Structure L N
ι : Type w
inst✝⁴ : Preorder ι
inst✝³ : IsDirected ι fun x x_1 => x ≤ x_1
inst✝² : Nonempty ι
G : ι → Type (max w w')
inst✝¹ : (i : ι) → Structure L (G i)
f : (i j : ι) → i ≤ j → G i ↪[L] G j
inst✝ : DirectedSystem G fun i j h => ↑(f i j h)
M : Bundled (Structure L)
Mfg : Structure.FG L ↑M
e : ↑M ↪[L] DirectLimit G f
s : Finset (DirectLimit G f)
hs : LowerAdjoint.toFun (closure L) ↑s = Hom.range (Embedding.toHom e)
out : Quotient (DirectLimit.setoid G f) → Structure.Sigma f := Quotient.out
i : ι
hi : ∀ (i_1 : ι), i_1 ∈ Finset.image (Sigma.fst ∘ out) s → i_1 ≤ i
e' : { x // x ∈ Hom.range (Embedding.toHom (DirectLimit.of L ι G f i)) } ↪[L] G i
⊢ Hom.range (Embedding.toHom e) ≤ Hom.range (Embedding.toHom (DirectLimit.of L ι G f i))
[PROOFSTEP]
rw [← hs, closure_le]
[GOAL]
case h.mp.intro.intro.intro.intro
L : Language
K : Set (Bundled (Structure L))
M✝ : Type w
inst✝⁶ : Structure L M✝
N : Type w
inst✝⁵ : Structure L N
ι : Type w
inst✝⁴ : Preorder ι
inst✝³ : IsDirected ι fun x x_1 => x ≤ x_1
inst✝² : Nonempty ι
G : ι → Type (max w w')
inst✝¹ : (i : ι) → Structure L (G i)
f : (i j : ι) → i ≤ j → G i ↪[L] G j
inst✝ : DirectedSystem G fun i j h => ↑(f i j h)
M : Bundled (Structure L)
Mfg : Structure.FG L ↑M
e : ↑M ↪[L] DirectLimit G f
s : Finset (DirectLimit G f)
hs : LowerAdjoint.toFun (closure L) ↑s = Hom.range (Embedding.toHom e)
out : Quotient (DirectLimit.setoid G f) → Structure.Sigma f := Quotient.out
i : ι
hi : ∀ (i_1 : ι), i_1 ∈ Finset.image (Sigma.fst ∘ out) s → i_1 ≤ i
e' : { x // x ∈ Hom.range (Embedding.toHom (DirectLimit.of L ι G f i)) } ↪[L] G i
⊢ ↑s ⊆ ↑(Hom.range (Embedding.toHom (DirectLimit.of L ι G f i)))
[PROOFSTEP]
intro x hx
[GOAL]
case h.mp.intro.intro.intro.intro
L : Language
K : Set (Bundled (Structure L))
M✝ : Type w
inst✝⁶ : Structure L M✝
N : Type w
inst✝⁵ : Structure L N
ι : Type w
inst✝⁴ : Preorder ι
inst✝³ : IsDirected ι fun x x_1 => x ≤ x_1
inst✝² : Nonempty ι
G : ι → Type (max w w')
inst✝¹ : (i : ι) → Structure L (G i)
f : (i j : ι) → i ≤ j → G i ↪[L] G j
inst✝ : DirectedSystem G fun i j h => ↑(f i j h)
M : Bundled (Structure L)
Mfg : Structure.FG L ↑M
e : ↑M ↪[L] DirectLimit G f
s : Finset (DirectLimit G f)
hs : LowerAdjoint.toFun (closure L) ↑s = Hom.range (Embedding.toHom e)
out : Quotient (DirectLimit.setoid G f) → Structure.Sigma f := Quotient.out
i : ι
hi : ∀ (i_1 : ι), i_1 ∈ Finset.image (Sigma.fst ∘ out) s → i_1 ≤ i
e' : { x // x ∈ Hom.range (Embedding.toHom (DirectLimit.of L ι G f i)) } ↪[L] G i
x : DirectLimit G f
hx : x ∈ ↑s
⊢ x ∈ ↑(Hom.range (Embedding.toHom (DirectLimit.of L ι G f i)))
[PROOFSTEP]
refine' ⟨f (out x).1 i (hi (out x).1 (Finset.mem_image_of_mem _ hx)) (out x).2, _⟩
[GOAL]
case h.mp.intro.intro.intro.intro
L : Language
K : Set (Bundled (Structure L))
M✝ : Type w
inst✝⁶ : Structure L M✝
N : Type w
inst✝⁵ : Structure L N
ι : Type w
inst✝⁴ : Preorder ι
inst✝³ : IsDirected ι fun x x_1 => x ≤ x_1
inst✝² : Nonempty ι
G : ι → Type (max w w')
inst✝¹ : (i : ι) → Structure L (G i)
f : (i j : ι) → i ≤ j → G i ↪[L] G j
inst✝ : DirectedSystem G fun i j h => ↑(f i j h)
M : Bundled (Structure L)
Mfg : Structure.FG L ↑M
e : ↑M ↪[L] DirectLimit G f
s : Finset (DirectLimit G f)
hs : LowerAdjoint.toFun (closure L) ↑s = Hom.range (Embedding.toHom e)
out : Quotient (DirectLimit.setoid G f) → Structure.Sigma f := Quotient.out
i : ι
hi : ∀ (i_1 : ι), i_1 ∈ Finset.image (Sigma.fst ∘ out) s → i_1 ≤ i
e' : { x // x ∈ Hom.range (Embedding.toHom (DirectLimit.of L ι G f i)) } ↪[L] G i
x : DirectLimit G f
hx : x ∈ ↑s
⊢ ↑(Embedding.toHom (DirectLimit.of L ι G f i)) (↑(f (out x).fst i (_ : (out x).fst ≤ i)) (out x).snd) = x
[PROOFSTEP]
rw [Embedding.coe_toHom, DirectLimit.of_apply, @Quotient.mk_eq_iff_out _ (_),
DirectLimit.equiv_iff G f _ (hi (out x).1 (Finset.mem_image_of_mem _ hx)), DirectedSystem.map_self]
[GOAL]
L : Language
K : Set (Bundled (Structure L))
M✝ : Type w
inst✝⁶ : Structure L M✝
N : Type w
inst✝⁵ : Structure L N
ι : Type w
inst✝⁴ : Preorder ι
inst✝³ : IsDirected ι fun x x_1 => x ≤ x_1
inst✝² : Nonempty ι
G : ι → Type (max w w')
inst✝¹ : (i : ι) → Structure L (G i)
f : (i j : ι) → i ≤ j → G i ↪[L] G j
inst✝ : DirectedSystem G fun i j h => ↑(f i j h)
M : Bundled (Structure L)
Mfg : Structure.FG L ↑M
e : ↑M ↪[L] DirectLimit G f
s : Finset (DirectLimit G f)
hs : LowerAdjoint.toFun (closure L) ↑s = Hom.range (Embedding.toHom e)
out : Quotient (DirectLimit.setoid G f) → Structure.Sigma f := Quotient.out
i : ι
hi : ∀ (i_1 : ι), i_1 ∈ Finset.image (Sigma.fst ∘ out) s → i_1 ≤ i
e' : { x // x ∈ Hom.range (Embedding.toHom (DirectLimit.of L ι G f i)) } ↪[L] G i
x : DirectLimit G f
hx : x ∈ ↑s
⊢ (Structure.Sigma.mk f i (↑(f (out x).fst i (_ : (out x).fst ≤ i)) (out x).snd)).fst ≤ i
L : Language
K : Set (Bundled (Structure L))
M✝ : Type w
inst✝⁶ : Structure L M✝
N : Type w
inst✝⁵ : Structure L N
ι : Type w
inst✝⁴ : Preorder ι
inst✝³ : IsDirected ι fun x x_1 => x ≤ x_1
inst✝² : Nonempty ι
G : ι → Type (max w w')
inst✝¹ : (i : ι) → Structure L (G i)
f : (i j : ι) → i ≤ j → G i ↪[L] G j
inst✝ : DirectedSystem G fun i j h => ↑(f i j h)
M : Bundled (Structure L)
Mfg : Structure.FG L ↑M
e : ↑M ↪[L] DirectLimit G f
s : Finset (DirectLimit G f)
hs : LowerAdjoint.toFun (closure L) ↑s = Hom.range (Embedding.toHom e)
out : Quotient (DirectLimit.setoid G f) → Structure.Sigma f := Quotient.out
i : ι
hi : ∀ (i_1 : ι), i_1 ∈ Finset.image (Sigma.fst ∘ out) s → i_1 ≤ i
e' : { x // x ∈ Hom.range (Embedding.toHom (DirectLimit.of L ι G f i)) } ↪[L] G i
x : DirectLimit G f
hx : x ∈ ↑s
⊢ (Structure.Sigma.mk f i (↑(f (out x).fst i (_ : (out x).fst ≤ i)) (out x).snd)).fst ≤ i
[PROOFSTEP]
rfl
[GOAL]
case h.mpr
L : Language
K : Set (Bundled (Structure L))
M✝ : Type w
inst✝⁶ : Structure L M✝
N : Type w
inst✝⁵ : Structure L N
ι : Type w
inst✝⁴ : Preorder ι
inst✝³ : IsDirected ι fun x x_1 => x ≤ x_1
inst✝² : Nonempty ι
G : ι → Type (max w w')
inst✝¹ : (i : ι) → Structure L (G i)
f : (i j : ι) → i ≤ j → G i ↪[L] G j
inst✝ : DirectedSystem G fun i j h => ↑(f i j h)
M : Bundled (Structure L)
⊢ (∃ i, M ∈ age L (G i)) → M ∈ age L (DirectLimit G f)
[PROOFSTEP]
rintro ⟨i, Mfg, ⟨e⟩⟩
[GOAL]
case h.mpr.intro.intro.intro
L : Language
K : Set (Bundled (Structure L))
M✝ : Type w
inst✝⁶ : Structure L M✝
N : Type w
inst✝⁵ : Structure L N
ι : Type w
inst✝⁴ : Preorder ι
inst✝³ : IsDirected ι fun x x_1 => x ≤ x_1
inst✝² : Nonempty ι
G : ι → Type (max w w')
inst✝¹ : (i : ι) → Structure L (G i)
f : (i j : ι) → i ≤ j → G i ↪[L] G j
inst✝ : DirectedSystem G fun i j h => ↑(f i j h)
M : Bundled (Structure L)
i : ι
Mfg : Structure.FG L ↑M
e : ↑M ↪[L] G i
⊢ M ∈ age L (DirectLimit G f)
[PROOFSTEP]
exact ⟨Mfg, ⟨Embedding.comp (DirectLimit.of L ι G f i) e⟩⟩
[GOAL]
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N : Type w
inst✝ : Structure L N
hn : Set.Nonempty K
h : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
hc : Set.Countable (Quotient.mk' '' K)
fg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
⊢ ∃ M, Structure.CG L ↑M ∧ age L ↑M = K
[PROOFSTEP]
obtain ⟨F, hF⟩ := hc.exists_eq_range (hn.image _)
[GOAL]
case intro
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N : Type w
inst✝ : Structure L N
hn : Set.Nonempty K
h : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
hc : Set.Countable (Quotient.mk' '' K)
fg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
F : ℕ → Quotient equivSetoid
hF : Quotient.mk' '' K = range F
⊢ ∃ M, Structure.CG L ↑M ∧ age L ↑M = K
[PROOFSTEP]
simp only [Set.ext_iff, forall_quotient_iff, mem_image, mem_range, Quotient.eq'] at hF
[GOAL]
case intro
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N : Type w
inst✝ : Structure L N
hn : Set.Nonempty K
h : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
hc : Set.Countable (Quotient.mk' '' K)
fg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
F : ℕ → Quotient equivSetoid
hF :
∀ (a : Bundled (Structure L)),
(∃ x, x ∈ K ∧ Quotient.mk' x = Quotient.mk equivSetoid a) ↔ ∃ y, F y = Quotient.mk equivSetoid a
⊢ ∃ M, Structure.CG L ↑M ∧ age L ↑M = K
[PROOFSTEP]
simp_rw [Quotient.eq_mk_iff_out] at hF
[GOAL]
case intro
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N : Type w
inst✝ : Structure L N
hn : Set.Nonempty K
h : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
hc : Set.Countable (Quotient.mk' '' K)
fg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
F : ℕ → Quotient equivSetoid
hF : ∀ (a : Bundled (Structure L)), (∃ x, x ∈ K ∧ Quotient.out (Quotient.mk' x) ≈ a) ↔ ∃ y, Quotient.out (F y) ≈ a
⊢ ∃ M, Structure.CG L ↑M ∧ age L ↑M = K
[PROOFSTEP]
have hF' : ∀ n : ℕ, (F n).out ∈ K := by
intro n
obtain ⟨P, hP1, hP2⟩ :=
(hF (F n).out).2
⟨n, Setoid.refl _⟩
-- Porting note: fix hP2 because `Quotient.out (Quotient.mk' x) ≈ a` was not simplified
-- to `x ≈ a` in hF
replace hP2 := Setoid.trans (Setoid.symm (Quotient.mk_out P)) hP2
exact (h _ _ hP2).1 hP1
[GOAL]
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N : Type w
inst✝ : Structure L N
hn : Set.Nonempty K
h : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
hc : Set.Countable (Quotient.mk' '' K)
fg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
F : ℕ → Quotient equivSetoid
hF : ∀ (a : Bundled (Structure L)), (∃ x, x ∈ K ∧ Quotient.out (Quotient.mk' x) ≈ a) ↔ ∃ y, Quotient.out (F y) ≈ a
⊢ ∀ (n : ℕ), Quotient.out (F n) ∈ K
[PROOFSTEP]
intro n
[GOAL]
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N : Type w
inst✝ : Structure L N
hn : Set.Nonempty K
h : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
hc : Set.Countable (Quotient.mk' '' K)
fg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
F : ℕ → Quotient equivSetoid
hF : ∀ (a : Bundled (Structure L)), (∃ x, x ∈ K ∧ Quotient.out (Quotient.mk' x) ≈ a) ↔ ∃ y, Quotient.out (F y) ≈ a
n : ℕ
⊢ Quotient.out (F n) ∈ K
[PROOFSTEP]
obtain ⟨P, hP1, hP2⟩ :=
(hF (F n).out).2
⟨n, Setoid.refl _⟩
-- Porting note: fix hP2 because `Quotient.out (Quotient.mk' x) ≈ a` was not simplified
-- to `x ≈ a` in hF
[GOAL]
case intro.intro
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N : Type w
inst✝ : Structure L N
hn : Set.Nonempty K
h : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
hc : Set.Countable (Quotient.mk' '' K)
fg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
F : ℕ → Quotient equivSetoid
hF : ∀ (a : Bundled (Structure L)), (∃ x, x ∈ K ∧ Quotient.out (Quotient.mk' x) ≈ a) ↔ ∃ y, Quotient.out (F y) ≈ a
n : ℕ
P : Bundled (Structure L)
hP1 : P ∈ K
hP2 : Quotient.out (Quotient.mk' P) ≈ Quotient.out (F n)
⊢ Quotient.out (F n) ∈ K
[PROOFSTEP]
replace hP2 := Setoid.trans (Setoid.symm (Quotient.mk_out P)) hP2
[GOAL]
case intro.intro
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N : Type w
inst✝ : Structure L N
hn : Set.Nonempty K
h : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
hc : Set.Countable (Quotient.mk' '' K)
fg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
F : ℕ → Quotient equivSetoid
hF : ∀ (a : Bundled (Structure L)), (∃ x, x ∈ K ∧ Quotient.out (Quotient.mk' x) ≈ a) ↔ ∃ y, Quotient.out (F y) ≈ a
n : ℕ
P : Bundled (Structure L)
hP1 : P ∈ K
hP2 : P ≈ Quotient.out (F n)
⊢ Quotient.out (F n) ∈ K
[PROOFSTEP]
exact (h _ _ hP2).1 hP1
[GOAL]
case intro
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N : Type w
inst✝ : Structure L N
hn : Set.Nonempty K
h : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
hc : Set.Countable (Quotient.mk' '' K)
fg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
F : ℕ → Quotient equivSetoid
hF : ∀ (a : Bundled (Structure L)), (∃ x, x ∈ K ∧ Quotient.out (Quotient.mk' x) ≈ a) ↔ ∃ y, Quotient.out (F y) ≈ a
hF' : ∀ (n : ℕ), Quotient.out (F n) ∈ K
⊢ ∃ M, Structure.CG L ↑M ∧ age L ↑M = K
[PROOFSTEP]
choose P hPK hP hFP using fun (N : K) (n : ℕ) => jep N N.2 (F (n + 1)).out (hF' _)
[GOAL]
case intro
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N : Type w
inst✝ : Structure L N
hn : Set.Nonempty K
h : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
hc : Set.Countable (Quotient.mk' '' K)
fg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
F : ℕ → Quotient equivSetoid
hF : ∀ (a : Bundled (Structure L)), (∃ x, x ∈ K ∧ Quotient.out (Quotient.mk' x) ≈ a) ↔ ∃ y, Quotient.out (F y) ≈ a
hF' : ∀ (n : ℕ), Quotient.out (F n) ∈ K
P : ↑K → ℕ → Bundled (Structure L)
hPK : ∀ (N : ↑K) (n : ℕ), P N n ∈ K
hP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (↑N) (P N n)
hFP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (Quotient.out (F (n + 1))) (P N n)
⊢ ∃ M, Structure.CG L ↑M ∧ age L ↑M = K
[PROOFSTEP]
let G : ℕ → K :=
@Nat.rec (fun _ => K) ⟨(F 0).out, hF' 0⟩ fun n N =>
⟨P N n, hPK N n⟩
-- Poting note: was
-- let f : ∀ i j, i ≤ j → G i ↪[L] G j := DirectedSystem.natLeRec fun n => (hP _ n).some
[GOAL]
case intro
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N : Type w
inst✝ : Structure L N
hn : Set.Nonempty K
h : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
hc : Set.Countable (Quotient.mk' '' K)
fg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
F : ℕ → Quotient equivSetoid
hF : ∀ (a : Bundled (Structure L)), (∃ x, x ∈ K ∧ Quotient.out (Quotient.mk' x) ≈ a) ↔ ∃ y, Quotient.out (F y) ≈ a
hF' : ∀ (n : ℕ), Quotient.out (F n) ∈ K
P : ↑K → ℕ → Bundled (Structure L)
hPK : ∀ (N : ↑K) (n : ℕ), P N n ∈ K
hP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (↑N) (P N n)
hFP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (Quotient.out (F (n + 1))) (P N n)
G : ℕ → ↑K :=
Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) } fun n N =>
{ val := P N n, property := (_ : P N n ∈ K) }
⊢ ∃ M, Structure.CG L ↑M ∧ age L ↑M = K
[PROOFSTEP]
let f : ∀ (i j : ℕ), i ≤ j → (G i).val ↪[L] (G j).val :=
by
refine DirectedSystem.natLERec (G' := fun i => (G i).val) (L := L) ?_
dsimp only
exact (fun n => (hP _ n).some)
[GOAL]
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N : Type w
inst✝ : Structure L N
hn : Set.Nonempty K
h : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
hc : Set.Countable (Quotient.mk' '' K)
fg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
F : ℕ → Quotient equivSetoid
hF : ∀ (a : Bundled (Structure L)), (∃ x, x ∈ K ∧ Quotient.out (Quotient.mk' x) ≈ a) ↔ ∃ y, Quotient.out (F y) ≈ a
hF' : ∀ (n : ℕ), Quotient.out (F n) ∈ K
P : ↑K → ℕ → Bundled (Structure L)
hPK : ∀ (N : ↑K) (n : ℕ), P N n ∈ K
hP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (↑N) (P N n)
hFP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (Quotient.out (F (n + 1))) (P N n)
G : ℕ → ↑K :=
Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) } fun n N =>
{ val := P N n, property := (_ : P N n ∈ K) }
⊢ (i j : ℕ) → i ≤ j → ↑↑(G i) ↪[L] ↑↑(G j)
[PROOFSTEP]
refine DirectedSystem.natLERec (G' := fun i => (G i).val) (L := L) ?_
[GOAL]
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N : Type w
inst✝ : Structure L N
hn : Set.Nonempty K
h : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
hc : Set.Countable (Quotient.mk' '' K)
fg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
F : ℕ → Quotient equivSetoid
hF : ∀ (a : Bundled (Structure L)), (∃ x, x ∈ K ∧ Quotient.out (Quotient.mk' x) ≈ a) ↔ ∃ y, Quotient.out (F y) ≈ a
hF' : ∀ (n : ℕ), Quotient.out (F n) ∈ K
P : ↑K → ℕ → Bundled (Structure L)
hPK : ∀ (N : ↑K) (n : ℕ), P N n ∈ K
hP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (↑N) (P N n)
hFP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (Quotient.out (F (n + 1))) (P N n)
G : ℕ → ↑K :=
Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) } fun n N =>
{ val := P N n, property := (_ : P N n ∈ K) }
⊢ (n : ℕ) → (fun i => ↑↑(G i)) n ↪[L] (fun i => ↑↑(G i)) (n + 1)
[PROOFSTEP]
dsimp only
[GOAL]
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N : Type w
inst✝ : Structure L N
hn : Set.Nonempty K
h : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
hc : Set.Countable (Quotient.mk' '' K)
fg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
F : ℕ → Quotient equivSetoid
hF : ∀ (a : Bundled (Structure L)), (∃ x, x ∈ K ∧ Quotient.out (Quotient.mk' x) ≈ a) ↔ ∃ y, Quotient.out (F y) ≈ a
hF' : ∀ (n : ℕ), Quotient.out (F n) ∈ K
P : ↑K → ℕ → Bundled (Structure L)
hPK : ∀ (N : ↑K) (n : ℕ), P N n ∈ K
hP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (↑N) (P N n)
hFP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (Quotient.out (F (n + 1))) (P N n)
G : ℕ → ↑K :=
Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) } fun n N =>
{ val := P N n, property := (_ : P N n ∈ K) }
⊢ (n : ℕ) →
↑↑(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n) ↪[L]
↑↑(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) (n + 1))
[PROOFSTEP]
exact (fun n => (hP _ n).some)
[GOAL]
case intro
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N : Type w
inst✝ : Structure L N
hn : Set.Nonempty K
h : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
hc : Set.Countable (Quotient.mk' '' K)
fg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
F : ℕ → Quotient equivSetoid
hF : ∀ (a : Bundled (Structure L)), (∃ x, x ∈ K ∧ Quotient.out (Quotient.mk' x) ≈ a) ↔ ∃ y, Quotient.out (F y) ≈ a
hF' : ∀ (n : ℕ), Quotient.out (F n) ∈ K
P : ↑K → ℕ → Bundled (Structure L)
hPK : ∀ (N : ↑K) (n : ℕ), P N n ∈ K
hP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (↑N) (P N n)
hFP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (Quotient.out (F (n + 1))) (P N n)
G : ℕ → ↑K :=
Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) } fun n N =>
{ val := P N n, property := (_ : P N n ∈ K) }
f : (i j : ℕ) → i ≤ j → ↑↑(G i) ↪[L] ↑↑(G j) :=
DirectedSystem.natLERec
(id fun n =>
Nonempty.some
(_ :
(fun M N => Nonempty (↑M ↪[L] ↑N))
(↑(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n))
(P
(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n)
n)))
⊢ ∃ M, Structure.CG L ↑M ∧ age L ↑M = K
[PROOFSTEP]
have : DirectedSystem (fun n ↦ (G n).val) fun i j h ↦ ↑(f i j h) := by dsimp; infer_instance
[GOAL]
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N : Type w
inst✝ : Structure L N
hn : Set.Nonempty K
h : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
hc : Set.Countable (Quotient.mk' '' K)
fg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
F : ℕ → Quotient equivSetoid
hF : ∀ (a : Bundled (Structure L)), (∃ x, x ∈ K ∧ Quotient.out (Quotient.mk' x) ≈ a) ↔ ∃ y, Quotient.out (F y) ≈ a
hF' : ∀ (n : ℕ), Quotient.out (F n) ∈ K
P : ↑K → ℕ → Bundled (Structure L)
hPK : ∀ (N : ↑K) (n : ℕ), P N n ∈ K
hP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (↑N) (P N n)
hFP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (Quotient.out (F (n + 1))) (P N n)
G : ℕ → ↑K :=
Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) } fun n N =>
{ val := P N n, property := (_ : P N n ∈ K) }
f : (i j : ℕ) → i ≤ j → ↑↑(G i) ↪[L] ↑↑(G j) :=
DirectedSystem.natLERec
(id fun n =>
Nonempty.some
(_ :
(fun M N => Nonempty (↑M ↪[L] ↑N))
(↑(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n))
(P
(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n)
n)))
⊢ DirectedSystem (fun n => ↑↑(G n)) fun i j h => ↑(f i j h)
[PROOFSTEP]
dsimp
[GOAL]
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N : Type w
inst✝ : Structure L N
hn : Set.Nonempty K
h : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
hc : Set.Countable (Quotient.mk' '' K)
fg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
F : ℕ → Quotient equivSetoid
hF : ∀ (a : Bundled (Structure L)), (∃ x, x ∈ K ∧ Quotient.out (Quotient.mk' x) ≈ a) ↔ ∃ y, Quotient.out (F y) ≈ a
hF' : ∀ (n : ℕ), Quotient.out (F n) ∈ K
P : ↑K → ℕ → Bundled (Structure L)
hPK : ∀ (N : ↑K) (n : ℕ), P N n ∈ K
hP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (↑N) (P N n)
hFP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (Quotient.out (F (n + 1))) (P N n)
G : ℕ → ↑K :=
Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) } fun n N =>
{ val := P N n, property := (_ : P N n ∈ K) }
f : (i j : ℕ) → i ≤ j → ↑↑(G i) ↪[L] ↑↑(G j) :=
DirectedSystem.natLERec
(id fun n =>
Nonempty.some
(_ :
(fun M N => Nonempty (↑M ↪[L] ↑N))
(↑(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n))
(P
(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n)
n)))
⊢ DirectedSystem
(fun n =>
↑↑(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n))
fun i j h =>
↑(DirectedSystem.natLERec
(fun n =>
Nonempty.some
(_ :
(fun M N => Nonempty (↑M ↪[L] ↑N))
(↑(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n))
(P
(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n)
n)))
i j h)
[PROOFSTEP]
infer_instance
[GOAL]
case intro
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N : Type w
inst✝ : Structure L N
hn : Set.Nonempty K
h : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
hc : Set.Countable (Quotient.mk' '' K)
fg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
F : ℕ → Quotient equivSetoid
hF : ∀ (a : Bundled (Structure L)), (∃ x, x ∈ K ∧ Quotient.out (Quotient.mk' x) ≈ a) ↔ ∃ y, Quotient.out (F y) ≈ a
hF' : ∀ (n : ℕ), Quotient.out (F n) ∈ K
P : ↑K → ℕ → Bundled (Structure L)
hPK : ∀ (N : ↑K) (n : ℕ), P N n ∈ K
hP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (↑N) (P N n)
hFP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (Quotient.out (F (n + 1))) (P N n)
G : ℕ → ↑K :=
Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) } fun n N =>
{ val := P N n, property := (_ : P N n ∈ K) }
f : (i j : ℕ) → i ≤ j → ↑↑(G i) ↪[L] ↑↑(G j) :=
DirectedSystem.natLERec
(id fun n =>
Nonempty.some
(_ :
(fun M N => Nonempty (↑M ↪[L] ↑N))
(↑(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n))
(P
(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n)
n)))
this : DirectedSystem (fun n => ↑↑(G n)) fun i j h => ↑(f i j h)
⊢ ∃ M, Structure.CG L ↑M ∧ age L ↑M = K
[PROOFSTEP]
refine ⟨Bundled.of (@DirectLimit L _ _ (fun n ↦ (G n).val) _ f _ _), ?_, ?_⟩
[GOAL]
case intro.refine_1
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N : Type w
inst✝ : Structure L N
hn : Set.Nonempty K
h : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
hc : Set.Countable (Quotient.mk' '' K)
fg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
F : ℕ → Quotient equivSetoid
hF : ∀ (a : Bundled (Structure L)), (∃ x, x ∈ K ∧ Quotient.out (Quotient.mk' x) ≈ a) ↔ ∃ y, Quotient.out (F y) ≈ a
hF' : ∀ (n : ℕ), Quotient.out (F n) ∈ K
P : ↑K → ℕ → Bundled (Structure L)
hPK : ∀ (N : ↑K) (n : ℕ), P N n ∈ K
hP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (↑N) (P N n)
hFP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (Quotient.out (F (n + 1))) (P N n)
G : ℕ → ↑K :=
Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) } fun n N =>
{ val := P N n, property := (_ : P N n ∈ K) }
f : (i j : ℕ) → i ≤ j → ↑↑(G i) ↪[L] ↑↑(G j) :=
DirectedSystem.natLERec
(id fun n =>
Nonempty.some
(_ :
(fun M N => Nonempty (↑M ↪[L] ↑N))
(↑(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n))
(P
(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n)
n)))
this : DirectedSystem (fun n => ↑↑(G n)) fun i j h => ↑(f i j h)
⊢ Structure.CG L ↑(Bundled.of (DirectLimit (fun n => ↑↑(G n)) f))
[PROOFSTEP]
exact DirectLimit.cg _ (fun n => (fg _ (G n).2).cg)
[GOAL]
case intro.refine_2
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N : Type w
inst✝ : Structure L N
hn : Set.Nonempty K
h : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
hc : Set.Countable (Quotient.mk' '' K)
fg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
F : ℕ → Quotient equivSetoid
hF : ∀ (a : Bundled (Structure L)), (∃ x, x ∈ K ∧ Quotient.out (Quotient.mk' x) ≈ a) ↔ ∃ y, Quotient.out (F y) ≈ a
hF' : ∀ (n : ℕ), Quotient.out (F n) ∈ K
P : ↑K → ℕ → Bundled (Structure L)
hPK : ∀ (N : ↑K) (n : ℕ), P N n ∈ K
hP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (↑N) (P N n)
hFP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (Quotient.out (F (n + 1))) (P N n)
G : ℕ → ↑K :=
Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) } fun n N =>
{ val := P N n, property := (_ : P N n ∈ K) }
f : (i j : ℕ) → i ≤ j → ↑↑(G i) ↪[L] ↑↑(G j) :=
DirectedSystem.natLERec
(id fun n =>
Nonempty.some
(_ :
(fun M N => Nonempty (↑M ↪[L] ↑N))
(↑(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n))
(P
(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n)
n)))
this : DirectedSystem (fun n => ↑↑(G n)) fun i j h => ↑(f i j h)
⊢ age L ↑(Bundled.of (DirectLimit (fun n => ↑↑(G n)) f)) = K
[PROOFSTEP]
refine
(age_directLimit (fun n ↦ (G n).val) f).trans
(subset_antisymm (iUnion_subset fun n N hN => hp (G n).val (G n).2 hN) fun N KN => ?_)
[GOAL]
case intro.refine_2
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
hn : Set.Nonempty K
h : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
hc : Set.Countable (Quotient.mk' '' K)
fg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
F : ℕ → Quotient equivSetoid
hF : ∀ (a : Bundled (Structure L)), (∃ x, x ∈ K ∧ Quotient.out (Quotient.mk' x) ≈ a) ↔ ∃ y, Quotient.out (F y) ≈ a
hF' : ∀ (n : ℕ), Quotient.out (F n) ∈ K
P : ↑K → ℕ → Bundled (Structure L)
hPK : ∀ (N : ↑K) (n : ℕ), P N n ∈ K
hP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (↑N) (P N n)
hFP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (Quotient.out (F (n + 1))) (P N n)
G : ℕ → ↑K :=
Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) } fun n N =>
{ val := P N n, property := (_ : P N n ∈ K) }
f : (i j : ℕ) → i ≤ j → ↑↑(G i) ↪[L] ↑↑(G j) :=
DirectedSystem.natLERec
(id fun n =>
Nonempty.some
(_ :
(fun M N => Nonempty (↑M ↪[L] ↑N))
(↑(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n))
(P
(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n)
n)))
this : DirectedSystem (fun n => ↑↑(G n)) fun i j h => ↑(f i j h)
N : Bundled (Structure L)
KN : N ∈ K
⊢ N ∈ ⋃ (i : ℕ), age L ↑↑(G i)
[PROOFSTEP]
have : Quotient.out (Quotient.mk' N) ≈ N := Quotient.eq_mk_iff_out.mp rfl
[GOAL]
case intro.refine_2
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
hn : Set.Nonempty K
h : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
hc : Set.Countable (Quotient.mk' '' K)
fg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
F : ℕ → Quotient equivSetoid
hF : ∀ (a : Bundled (Structure L)), (∃ x, x ∈ K ∧ Quotient.out (Quotient.mk' x) ≈ a) ↔ ∃ y, Quotient.out (F y) ≈ a
hF' : ∀ (n : ℕ), Quotient.out (F n) ∈ K
P : ↑K → ℕ → Bundled (Structure L)
hPK : ∀ (N : ↑K) (n : ℕ), P N n ∈ K
hP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (↑N) (P N n)
hFP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (Quotient.out (F (n + 1))) (P N n)
G : ℕ → ↑K :=
Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) } fun n N =>
{ val := P N n, property := (_ : P N n ∈ K) }
f : (i j : ℕ) → i ≤ j → ↑↑(G i) ↪[L] ↑↑(G j) :=
DirectedSystem.natLERec
(id fun n =>
Nonempty.some
(_ :
(fun M N => Nonempty (↑M ↪[L] ↑N))
(↑(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n))
(P
(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n)
n)))
this✝ : DirectedSystem (fun n => ↑↑(G n)) fun i j h => ↑(f i j h)
N : Bundled (Structure L)
KN : N ∈ K
this : Quotient.out (Quotient.mk' N) ≈ N
⊢ N ∈ ⋃ (i : ℕ), age L ↑↑(G i)
[PROOFSTEP]
obtain ⟨n, ⟨e⟩⟩ := (hF N).1 ⟨N, KN, this⟩
[GOAL]
case intro.refine_2.intro.intro
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
hn : Set.Nonempty K
h : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
hc : Set.Countable (Quotient.mk' '' K)
fg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
F : ℕ → Quotient equivSetoid
hF : ∀ (a : Bundled (Structure L)), (∃ x, x ∈ K ∧ Quotient.out (Quotient.mk' x) ≈ a) ↔ ∃ y, Quotient.out (F y) ≈ a
hF' : ∀ (n : ℕ), Quotient.out (F n) ∈ K
P : ↑K → ℕ → Bundled (Structure L)
hPK : ∀ (N : ↑K) (n : ℕ), P N n ∈ K
hP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (↑N) (P N n)
hFP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (Quotient.out (F (n + 1))) (P N n)
G : ℕ → ↑K :=
Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) } fun n N =>
{ val := P N n, property := (_ : P N n ∈ K) }
f : (i j : ℕ) → i ≤ j → ↑↑(G i) ↪[L] ↑↑(G j) :=
DirectedSystem.natLERec
(id fun n =>
Nonempty.some
(_ :
(fun M N => Nonempty (↑M ↪[L] ↑N))
(↑(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n))
(P
(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n)
n)))
this✝ : DirectedSystem (fun n => ↑↑(G n)) fun i j h => ↑(f i j h)
N : Bundled (Structure L)
KN : N ∈ K
this : Quotient.out (Quotient.mk' N) ≈ N
n : ℕ
e : ↑(Quotient.out (F n)) ≃[L] ↑N
⊢ N ∈ ⋃ (i : ℕ), age L ↑↑(G i)
[PROOFSTEP]
refine mem_iUnion_of_mem n ⟨fg _ KN, ⟨Embedding.comp ?_ e.symm.toEmbedding⟩⟩
[GOAL]
case intro.refine_2.intro.intro
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
hn : Set.Nonempty K
h : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
hc : Set.Countable (Quotient.mk' '' K)
fg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
F : ℕ → Quotient equivSetoid
hF : ∀ (a : Bundled (Structure L)), (∃ x, x ∈ K ∧ Quotient.out (Quotient.mk' x) ≈ a) ↔ ∃ y, Quotient.out (F y) ≈ a
hF' : ∀ (n : ℕ), Quotient.out (F n) ∈ K
P : ↑K → ℕ → Bundled (Structure L)
hPK : ∀ (N : ↑K) (n : ℕ), P N n ∈ K
hP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (↑N) (P N n)
hFP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (Quotient.out (F (n + 1))) (P N n)
G : ℕ → ↑K :=
Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) } fun n N =>
{ val := P N n, property := (_ : P N n ∈ K) }
f : (i j : ℕ) → i ≤ j → ↑↑(G i) ↪[L] ↑↑(G j) :=
DirectedSystem.natLERec
(id fun n =>
Nonempty.some
(_ :
(fun M N => Nonempty (↑M ↪[L] ↑N))
(↑(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n))
(P
(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n)
n)))
this✝ : DirectedSystem (fun n => ↑↑(G n)) fun i j h => ↑(f i j h)
N : Bundled (Structure L)
KN : N ∈ K
this : Quotient.out (Quotient.mk' N) ≈ N
n : ℕ
e : ↑(Quotient.out (F n)) ≃[L] ↑N
⊢ ↑(Quotient.out (F n)) ↪[L] ↑↑(G n)
[PROOFSTEP]
cases' n with n
[GOAL]
case intro.refine_2.intro.intro.zero
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
hn : Set.Nonempty K
h : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
hc : Set.Countable (Quotient.mk' '' K)
fg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
F : ℕ → Quotient equivSetoid
hF : ∀ (a : Bundled (Structure L)), (∃ x, x ∈ K ∧ Quotient.out (Quotient.mk' x) ≈ a) ↔ ∃ y, Quotient.out (F y) ≈ a
hF' : ∀ (n : ℕ), Quotient.out (F n) ∈ K
P : ↑K → ℕ → Bundled (Structure L)
hPK : ∀ (N : ↑K) (n : ℕ), P N n ∈ K
hP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (↑N) (P N n)
hFP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (Quotient.out (F (n + 1))) (P N n)
G : ℕ → ↑K :=
Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) } fun n N =>
{ val := P N n, property := (_ : P N n ∈ K) }
f : (i j : ℕ) → i ≤ j → ↑↑(G i) ↪[L] ↑↑(G j) :=
DirectedSystem.natLERec
(id fun n =>
Nonempty.some
(_ :
(fun M N => Nonempty (↑M ↪[L] ↑N))
(↑(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n))
(P
(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n)
n)))
this✝ : DirectedSystem (fun n => ↑↑(G n)) fun i j h => ↑(f i j h)
N : Bundled (Structure L)
KN : N ∈ K
this : Quotient.out (Quotient.mk' N) ≈ N
e : ↑(Quotient.out (F Nat.zero)) ≃[L] ↑N
⊢ ↑(Quotient.out (F Nat.zero)) ↪[L] ↑↑(G Nat.zero)
[PROOFSTEP]
dsimp
[GOAL]
case intro.refine_2.intro.intro.zero
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
hn : Set.Nonempty K
h : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
hc : Set.Countable (Quotient.mk' '' K)
fg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
F : ℕ → Quotient equivSetoid
hF : ∀ (a : Bundled (Structure L)), (∃ x, x ∈ K ∧ Quotient.out (Quotient.mk' x) ≈ a) ↔ ∃ y, Quotient.out (F y) ≈ a
hF' : ∀ (n : ℕ), Quotient.out (F n) ∈ K
P : ↑K → ℕ → Bundled (Structure L)
hPK : ∀ (N : ↑K) (n : ℕ), P N n ∈ K
hP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (↑N) (P N n)
hFP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (Quotient.out (F (n + 1))) (P N n)
G : ℕ → ↑K :=
Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) } fun n N =>
{ val := P N n, property := (_ : P N n ∈ K) }
f : (i j : ℕ) → i ≤ j → ↑↑(G i) ↪[L] ↑↑(G j) :=
DirectedSystem.natLERec
(id fun n =>
Nonempty.some
(_ :
(fun M N => Nonempty (↑M ↪[L] ↑N))
(↑(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n))
(P
(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n)
n)))
this✝ : DirectedSystem (fun n => ↑↑(G n)) fun i j h => ↑(f i j h)
N : Bundled (Structure L)
KN : N ∈ K
this : Quotient.out (Quotient.mk' N) ≈ N
e : ↑(Quotient.out (F Nat.zero)) ≃[L] ↑N
⊢ ↑(Quotient.out (F 0)) ↪[L] ↑(Quotient.out (F 0))
[PROOFSTEP]
exact Embedding.refl _ _
[GOAL]
case intro.refine_2.intro.intro.succ
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
hn : Set.Nonempty K
h : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
hc : Set.Countable (Quotient.mk' '' K)
fg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
F : ℕ → Quotient equivSetoid
hF : ∀ (a : Bundled (Structure L)), (∃ x, x ∈ K ∧ Quotient.out (Quotient.mk' x) ≈ a) ↔ ∃ y, Quotient.out (F y) ≈ a
hF' : ∀ (n : ℕ), Quotient.out (F n) ∈ K
P : ↑K → ℕ → Bundled (Structure L)
hPK : ∀ (N : ↑K) (n : ℕ), P N n ∈ K
hP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (↑N) (P N n)
hFP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (Quotient.out (F (n + 1))) (P N n)
G : ℕ → ↑K :=
Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) } fun n N =>
{ val := P N n, property := (_ : P N n ∈ K) }
f : (i j : ℕ) → i ≤ j → ↑↑(G i) ↪[L] ↑↑(G j) :=
DirectedSystem.natLERec
(id fun n =>
Nonempty.some
(_ :
(fun M N => Nonempty (↑M ↪[L] ↑N))
(↑(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n))
(P
(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n)
n)))
this✝ : DirectedSystem (fun n => ↑↑(G n)) fun i j h => ↑(f i j h)
N : Bundled (Structure L)
KN : N ∈ K
this : Quotient.out (Quotient.mk' N) ≈ N
n : ℕ
e : ↑(Quotient.out (F (Nat.succ n))) ≃[L] ↑N
⊢ ↑(Quotient.out (F (Nat.succ n))) ↪[L] ↑↑(G (Nat.succ n))
[PROOFSTEP]
dsimp
[GOAL]
case intro.refine_2.intro.intro.succ
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
hn : Set.Nonempty K
h : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
hc : Set.Countable (Quotient.mk' '' K)
fg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
F : ℕ → Quotient equivSetoid
hF : ∀ (a : Bundled (Structure L)), (∃ x, x ∈ K ∧ Quotient.out (Quotient.mk' x) ≈ a) ↔ ∃ y, Quotient.out (F y) ≈ a
hF' : ∀ (n : ℕ), Quotient.out (F n) ∈ K
P : ↑K → ℕ → Bundled (Structure L)
hPK : ∀ (N : ↑K) (n : ℕ), P N n ∈ K
hP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (↑N) (P N n)
hFP : ∀ (N : ↑K) (n : ℕ), (fun M N => Nonempty (↑M ↪[L] ↑N)) (Quotient.out (F (n + 1))) (P N n)
G : ℕ → ↑K :=
Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) } fun n N =>
{ val := P N n, property := (_ : P N n ∈ K) }
f : (i j : ℕ) → i ≤ j → ↑↑(G i) ↪[L] ↑↑(G j) :=
DirectedSystem.natLERec
(id fun n =>
Nonempty.some
(_ :
(fun M N => Nonempty (↑M ↪[L] ↑N))
(↑(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n))
(P
(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n)
n)))
this✝ : DirectedSystem (fun n => ↑↑(G n)) fun i j h => ↑(f i j h)
N : Bundled (Structure L)
KN : N ∈ K
this : Quotient.out (Quotient.mk' N) ≈ N
n : ℕ
e : ↑(Quotient.out (F (Nat.succ n))) ≃[L] ↑N
⊢ ↑(Quotient.out (F (Nat.succ n))) ↪[L]
↑(P
(Nat.rec { val := Quotient.out (F 0), property := (_ : Quotient.out (F 0) ∈ K) }
(fun n N => { val := P N n, property := (_ : P N n ∈ K) }) n)
n)
[PROOFSTEP]
exact (hFP _ n).some
[GOAL]
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝² : Structure L M
N : Type w
inst✝¹ : Structure L N
inst✝ : Countable ((l : ℕ) × Functions L l)
⊢ (∃ M, Countable ↑M ∧ age L ↑M = K) ↔
Set.Nonempty K ∧
(∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)) ∧
Set.Countable (Quotient.mk' '' K) ∧
(∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M) ∧ Hereditary K ∧ JointEmbedding K
[PROOFSTEP]
constructor
[GOAL]
case mp
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝² : Structure L M
N : Type w
inst✝¹ : Structure L N
inst✝ : Countable ((l : ℕ) × Functions L l)
⊢ (∃ M, Countable ↑M ∧ age L ↑M = K) →
Set.Nonempty K ∧
(∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)) ∧
Set.Countable (Quotient.mk' '' K) ∧
(∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M) ∧ Hereditary K ∧ JointEmbedding K
[PROOFSTEP]
rintro ⟨M, h1, h2, rfl⟩
[GOAL]
case mp.intro.intro.refl
L : Language
M✝ : Type w
inst✝² : Structure L M✝
N : Type w
inst✝¹ : Structure L N
inst✝ : Countable ((l : ℕ) × Functions L l)
M : Bundled (Structure L)
h1 : Countable ↑M
⊢ Set.Nonempty (age L ↑M) ∧
(∀ (M_1 N : Bundled (Structure L)), Nonempty (↑M_1 ≃[L] ↑N) → (M_1 ∈ age L ↑M ↔ N ∈ age L ↑M)) ∧
Set.Countable (Quotient.mk' '' age L ↑M) ∧
(∀ (M_1 : Bundled (Structure L)), M_1 ∈ age L ↑M → Structure.FG L ↑M_1) ∧
Hereditary (age L ↑M) ∧ JointEmbedding (age L ↑M)
[PROOFSTEP]
refine'
⟨age.nonempty M, age.is_equiv_invariant L M, age.countable_quotient M, fun N hN => hN.1, age.hereditary M,
age.jointEmbedding M⟩
[GOAL]
case mpr
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝² : Structure L M
N : Type w
inst✝¹ : Structure L N
inst✝ : Countable ((l : ℕ) × Functions L l)
⊢ Set.Nonempty K ∧
(∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)) ∧
Set.Countable (Quotient.mk' '' K) ∧
(∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M) ∧ Hereditary K ∧ JointEmbedding K →
∃ M, Countable ↑M ∧ age L ↑M = K
[PROOFSTEP]
rintro ⟨Kn, eqinv, cq, hfg, hp, jep⟩
[GOAL]
case mpr.intro.intro.intro.intro.intro
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝² : Structure L M
N : Type w
inst✝¹ : Structure L N
inst✝ : Countable ((l : ℕ) × Functions L l)
Kn : Set.Nonempty K
eqinv : ∀ (M N : Bundled (Structure L)), Nonempty (↑M ≃[L] ↑N) → (M ∈ K ↔ N ∈ K)
cq : Set.Countable (Quotient.mk' '' K)
hfg : ∀ (M : Bundled (Structure L)), M ∈ K → Structure.FG L ↑M
hp : Hereditary K
jep : JointEmbedding K
⊢ ∃ M, Countable ↑M ∧ age L ↑M = K
[PROOFSTEP]
obtain ⟨M, hM, rfl⟩ := exists_cg_is_age_of Kn eqinv cq hfg hp jep
[GOAL]
case mpr.intro.intro.intro.intro.intro.intro.intro
L : Language
M✝ : Type w
inst✝² : Structure L M✝
N : Type w
inst✝¹ : Structure L N
inst✝ : Countable ((l : ℕ) × Functions L l)
M : Bundled (Structure L)
hM : Structure.CG L ↑M
Kn : Set.Nonempty (age L ↑M)
eqinv : ∀ (M_1 N : Bundled (Structure L)), Nonempty (↑M_1 ≃[L] ↑N) → (M_1 ∈ age L ↑M ↔ N ∈ age L ↑M)
cq : Set.Countable (Quotient.mk' '' age L ↑M)
hfg : ∀ (M_1 : Bundled (Structure L)), M_1 ∈ age L ↑M → Structure.FG L ↑M_1
hp : Hereditary (age L ↑M)
jep : JointEmbedding (age L ↑M)
⊢ ∃ M_1, Countable ↑M_1 ∧ age L ↑M_1 = age L ↑M
[PROOFSTEP]
exact ⟨M, Structure.cg_iff_countable.1 hM, rfl⟩
[GOAL]
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N : Type w
inst✝ : Structure L N
h : IsUltrahomogeneous L M
⊢ Amalgamation (age L M)
[PROOFSTEP]
rintro N P Q NP NQ ⟨Nfg, ⟨-⟩⟩ ⟨Pfg, ⟨PM⟩⟩ ⟨Qfg, ⟨QM⟩⟩
[GOAL]
case intro.intro.intro.intro.intro.intro
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
h : IsUltrahomogeneous L M
N P Q : Bundled (Structure L)
NP : ↑N ↪[L] ↑P
NQ : ↑N ↪[L] ↑Q
Nfg : Structure.FG L ↑N
Pfg : Structure.FG L ↑P
PM : ↑P ↪[L] M
Qfg : Structure.FG L ↑Q
QM : ↑Q ↪[L] M
⊢ ∃ Q_1 NQ_1 PQ, Q_1 ∈ age L M ∧ Embedding.comp NQ_1 NP = Embedding.comp PQ NQ
[PROOFSTEP]
obtain ⟨g, hg⟩ := h (PM.comp NP).toHom.range (Nfg.range _) ((QM.comp NQ).comp (PM.comp NP).equivRange.symm.toEmbedding)
[GOAL]
case intro.intro.intro.intro.intro.intro.intro
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
h : IsUltrahomogeneous L M
N P Q : Bundled (Structure L)
NP : ↑N ↪[L] ↑P
NQ : ↑N ↪[L] ↑Q
Nfg : Structure.FG L ↑N
Pfg : Structure.FG L ↑P
PM : ↑P ↪[L] M
Qfg : Structure.FG L ↑Q
QM : ↑Q ↪[L] M
g : M ≃[L] M
hg :
Embedding.comp (Embedding.comp QM NQ) (Equiv.toEmbedding (Equiv.symm (Embedding.equivRange (Embedding.comp PM NP)))) =
Embedding.comp (Equiv.toEmbedding g) (subtype (Hom.range (Embedding.toHom (Embedding.comp PM NP))))
⊢ ∃ Q_1 NQ_1 PQ, Q_1 ∈ age L M ∧ Embedding.comp NQ_1 NP = Embedding.comp PQ NQ
[PROOFSTEP]
let s := (g.toHom.comp PM.toHom).range ⊔ QM.toHom.range
[GOAL]
case intro.intro.intro.intro.intro.intro.intro
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
h : IsUltrahomogeneous L M
N P Q : Bundled (Structure L)
NP : ↑N ↪[L] ↑P
NQ : ↑N ↪[L] ↑Q
Nfg : Structure.FG L ↑N
Pfg : Structure.FG L ↑P
PM : ↑P ↪[L] M
Qfg : Structure.FG L ↑Q
QM : ↑Q ↪[L] M
g : M ≃[L] M
hg :
Embedding.comp (Embedding.comp QM NQ) (Equiv.toEmbedding (Equiv.symm (Embedding.equivRange (Embedding.comp PM NP)))) =
Embedding.comp (Equiv.toEmbedding g) (subtype (Hom.range (Embedding.toHom (Embedding.comp PM NP))))
s : Substructure L M := Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ⊔ Hom.range (Embedding.toHom QM)
⊢ ∃ Q_1 NQ_1 PQ, Q_1 ∈ age L M ∧ Embedding.comp NQ_1 NP = Embedding.comp PQ NQ
[PROOFSTEP]
refine'
⟨Bundled.of s, Embedding.comp (Substructure.inclusion le_sup_left) (g.toEmbedding.comp PM).equivRange.toEmbedding,
Embedding.comp (Substructure.inclusion le_sup_right) QM.equivRange.toEmbedding,
⟨(fg_iff_structure_fg _).1 (FG.sup (Pfg.range _) (Qfg.range _)), ⟨Substructure.subtype _⟩⟩, _⟩
[GOAL]
case intro.intro.intro.intro.intro.intro.intro
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
h : IsUltrahomogeneous L M
N P Q : Bundled (Structure L)
NP : ↑N ↪[L] ↑P
NQ : ↑N ↪[L] ↑Q
Nfg : Structure.FG L ↑N
Pfg : Structure.FG L ↑P
PM : ↑P ↪[L] M
Qfg : Structure.FG L ↑Q
QM : ↑Q ↪[L] M
g : M ≃[L] M
hg :
Embedding.comp (Embedding.comp QM NQ) (Equiv.toEmbedding (Equiv.symm (Embedding.equivRange (Embedding.comp PM NP)))) =
Embedding.comp (Equiv.toEmbedding g) (subtype (Hom.range (Embedding.toHom (Embedding.comp PM NP))))
s : Substructure L M := Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ⊔ Hom.range (Embedding.toHom QM)
⊢ Embedding.comp
(Embedding.comp
(Substructure.inclusion
(_ :
Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ≤
Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ⊔ Hom.range (Embedding.toHom QM)))
(Equiv.toEmbedding (Embedding.equivRange (Embedding.comp (Equiv.toEmbedding g) PM))))
NP =
Embedding.comp
(Embedding.comp
(Substructure.inclusion
(_ :
Hom.range (Embedding.toHom QM) ≤
Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ⊔ Hom.range (Embedding.toHom QM)))
(Equiv.toEmbedding (Embedding.equivRange QM)))
NQ
[PROOFSTEP]
ext n
[GOAL]
case intro.intro.intro.intro.intro.intro.intro.h
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
h : IsUltrahomogeneous L M
N P Q : Bundled (Structure L)
NP : ↑N ↪[L] ↑P
NQ : ↑N ↪[L] ↑Q
Nfg : Structure.FG L ↑N
Pfg : Structure.FG L ↑P
PM : ↑P ↪[L] M
Qfg : Structure.FG L ↑Q
QM : ↑Q ↪[L] M
g : M ≃[L] M
hg :
Embedding.comp (Embedding.comp QM NQ) (Equiv.toEmbedding (Equiv.symm (Embedding.equivRange (Embedding.comp PM NP)))) =
Embedding.comp (Equiv.toEmbedding g) (subtype (Hom.range (Embedding.toHom (Embedding.comp PM NP))))
s : Substructure L M := Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ⊔ Hom.range (Embedding.toHom QM)
n : ↑N
⊢ ↑(Embedding.comp
(Embedding.comp
(Substructure.inclusion
(_ :
Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ≤
Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ⊔ Hom.range (Embedding.toHom QM)))
(Equiv.toEmbedding (Embedding.equivRange (Embedding.comp (Equiv.toEmbedding g) PM))))
NP)
n =
↑(Embedding.comp
(Embedding.comp
(Substructure.inclusion
(_ :
Hom.range (Embedding.toHom QM) ≤
Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ⊔ Hom.range (Embedding.toHom QM)))
(Equiv.toEmbedding (Embedding.equivRange QM)))
NQ)
n
[PROOFSTEP]
apply Subtype.ext
[GOAL]
case intro.intro.intro.intro.intro.intro.intro.h.a
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
h : IsUltrahomogeneous L M
N P Q : Bundled (Structure L)
NP : ↑N ↪[L] ↑P
NQ : ↑N ↪[L] ↑Q
Nfg : Structure.FG L ↑N
Pfg : Structure.FG L ↑P
PM : ↑P ↪[L] M
Qfg : Structure.FG L ↑Q
QM : ↑Q ↪[L] M
g : M ≃[L] M
hg :
Embedding.comp (Embedding.comp QM NQ) (Equiv.toEmbedding (Equiv.symm (Embedding.equivRange (Embedding.comp PM NP)))) =
Embedding.comp (Equiv.toEmbedding g) (subtype (Hom.range (Embedding.toHom (Embedding.comp PM NP))))
s : Substructure L M := Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ⊔ Hom.range (Embedding.toHom QM)
n : ↑N
⊢ ↑(↑(Embedding.comp
(Embedding.comp
(Substructure.inclusion
(_ :
Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ≤
Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ⊔ Hom.range (Embedding.toHom QM)))
(Equiv.toEmbedding (Embedding.equivRange (Embedding.comp (Equiv.toEmbedding g) PM))))
NP)
n) =
↑(↑(Embedding.comp
(Embedding.comp
(Substructure.inclusion
(_ :
Hom.range (Embedding.toHom QM) ≤
Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ⊔ Hom.range (Embedding.toHom QM)))
(Equiv.toEmbedding (Embedding.equivRange QM)))
NQ)
n)
[PROOFSTEP]
have hgn := (Embedding.ext_iff.1 hg) ((PM.comp NP).equivRange n)
[GOAL]
case intro.intro.intro.intro.intro.intro.intro.h.a
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
h : IsUltrahomogeneous L M
N P Q : Bundled (Structure L)
NP : ↑N ↪[L] ↑P
NQ : ↑N ↪[L] ↑Q
Nfg : Structure.FG L ↑N
Pfg : Structure.FG L ↑P
PM : ↑P ↪[L] M
Qfg : Structure.FG L ↑Q
QM : ↑Q ↪[L] M
g : M ≃[L] M
hg :
Embedding.comp (Embedding.comp QM NQ) (Equiv.toEmbedding (Equiv.symm (Embedding.equivRange (Embedding.comp PM NP)))) =
Embedding.comp (Equiv.toEmbedding g) (subtype (Hom.range (Embedding.toHom (Embedding.comp PM NP))))
s : Substructure L M := Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ⊔ Hom.range (Embedding.toHom QM)
n : ↑N
hgn :
↑(Embedding.comp (Embedding.comp QM NQ)
(Equiv.toEmbedding (Equiv.symm (Embedding.equivRange (Embedding.comp PM NP)))))
(↑(Embedding.equivRange (Embedding.comp PM NP)) n) =
↑(Embedding.comp (Equiv.toEmbedding g) (subtype (Hom.range (Embedding.toHom (Embedding.comp PM NP)))))
(↑(Embedding.equivRange (Embedding.comp PM NP)) n)
⊢ ↑(↑(Embedding.comp
(Embedding.comp
(Substructure.inclusion
(_ :
Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ≤
Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ⊔ Hom.range (Embedding.toHom QM)))
(Equiv.toEmbedding (Embedding.equivRange (Embedding.comp (Equiv.toEmbedding g) PM))))
NP)
n) =
↑(↑(Embedding.comp
(Embedding.comp
(Substructure.inclusion
(_ :
Hom.range (Embedding.toHom QM) ≤
Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ⊔ Hom.range (Embedding.toHom QM)))
(Equiv.toEmbedding (Embedding.equivRange QM)))
NQ)
n)
[PROOFSTEP]
simp only [Embedding.comp_apply, Equiv.coe_toEmbedding, Equiv.symm_apply_apply, Substructure.coeSubtype,
Embedding.equivRange_apply] at hgn
[GOAL]
case intro.intro.intro.intro.intro.intro.intro.h.a
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
h : IsUltrahomogeneous L M
N P Q : Bundled (Structure L)
NP : ↑N ↪[L] ↑P
NQ : ↑N ↪[L] ↑Q
Nfg : Structure.FG L ↑N
Pfg : Structure.FG L ↑P
PM : ↑P ↪[L] M
Qfg : Structure.FG L ↑Q
QM : ↑Q ↪[L] M
g : M ≃[L] M
hg :
Embedding.comp (Embedding.comp QM NQ) (Equiv.toEmbedding (Equiv.symm (Embedding.equivRange (Embedding.comp PM NP)))) =
Embedding.comp (Equiv.toEmbedding g) (subtype (Hom.range (Embedding.toHom (Embedding.comp PM NP))))
s : Substructure L M := Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ⊔ Hom.range (Embedding.toHom QM)
n : ↑N
hgn : ↑QM (↑NQ n) = ↑g (↑PM (↑NP n))
⊢ ↑(↑(Embedding.comp
(Embedding.comp
(Substructure.inclusion
(_ :
Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ≤
Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ⊔ Hom.range (Embedding.toHom QM)))
(Equiv.toEmbedding (Embedding.equivRange (Embedding.comp (Equiv.toEmbedding g) PM))))
NP)
n) =
↑(↑(Embedding.comp
(Embedding.comp
(Substructure.inclusion
(_ :
Hom.range (Embedding.toHom QM) ≤
Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ⊔ Hom.range (Embedding.toHom QM)))
(Equiv.toEmbedding (Embedding.equivRange QM)))
NQ)
n)
[PROOFSTEP]
simp only [Embedding.comp_apply, Equiv.coe_toEmbedding]
[GOAL]
case intro.intro.intro.intro.intro.intro.intro.h.a
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
h : IsUltrahomogeneous L M
N P Q : Bundled (Structure L)
NP : ↑N ↪[L] ↑P
NQ : ↑N ↪[L] ↑Q
Nfg : Structure.FG L ↑N
Pfg : Structure.FG L ↑P
PM : ↑P ↪[L] M
Qfg : Structure.FG L ↑Q
QM : ↑Q ↪[L] M
g : M ≃[L] M
hg :
Embedding.comp (Embedding.comp QM NQ) (Equiv.toEmbedding (Equiv.symm (Embedding.equivRange (Embedding.comp PM NP)))) =
Embedding.comp (Equiv.toEmbedding g) (subtype (Hom.range (Embedding.toHom (Embedding.comp PM NP))))
s : Substructure L M := Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ⊔ Hom.range (Embedding.toHom QM)
n : ↑N
hgn : ↑QM (↑NQ n) = ↑g (↑PM (↑NP n))
⊢ ↑(↑(Substructure.inclusion
(_ :
Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ≤
Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ⊔ Hom.range (Embedding.toHom QM)))
(↑(Embedding.equivRange (Embedding.comp (Equiv.toEmbedding g) PM)) (↑NP n))) =
↑(↑(Substructure.inclusion
(_ :
Hom.range (Embedding.toHom QM) ≤
Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ⊔ Hom.range (Embedding.toHom QM)))
(↑(Embedding.equivRange QM) (↑NQ n)))
[PROOFSTEP]
erw [Substructure.coe_inclusion, Substructure.coe_inclusion]
[GOAL]
case intro.intro.intro.intro.intro.intro.intro.h.a
L : Language
K : Set (Bundled (Structure L))
M : Type w
inst✝¹ : Structure L M
N✝ : Type w
inst✝ : Structure L N✝
h : IsUltrahomogeneous L M
N P Q : Bundled (Structure L)
NP : ↑N ↪[L] ↑P
NQ : ↑N ↪[L] ↑Q
Nfg : Structure.FG L ↑N
Pfg : Structure.FG L ↑P
PM : ↑P ↪[L] M
Qfg : Structure.FG L ↑Q
QM : ↑Q ↪[L] M
g : M ≃[L] M
hg :
Embedding.comp (Embedding.comp QM NQ) (Equiv.toEmbedding (Equiv.symm (Embedding.equivRange (Embedding.comp PM NP)))) =
Embedding.comp (Equiv.toEmbedding g) (subtype (Hom.range (Embedding.toHom (Embedding.comp PM NP))))
s : Substructure L M := Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ⊔ Hom.range (Embedding.toHom QM)
n : ↑N
hgn : ↑QM (↑NQ n) = ↑g (↑PM (↑NP n))
⊢ ↑(Set.inclusion
(_ :
Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ≤
Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ⊔ Hom.range (Embedding.toHom QM))
(↑(Embedding.equivRange (Embedding.comp (Equiv.toEmbedding g) PM)) (↑NP n))) =
↑(Set.inclusion
(_ :
Hom.range (Embedding.toHom QM) ≤
Hom.range (Hom.comp (Equiv.toHom g) (Embedding.toHom PM)) ⊔ Hom.range (Embedding.toHom QM))
(↑(Embedding.equivRange QM) (↑NQ n)))
[PROOFSTEP]
simp only [Embedding.comp_apply, Equiv.coe_toEmbedding, Set.coe_inclusion, Embedding.equivRange_apply, hgn]
|
theory Base
imports "Separation_Logic_Imperative_HOL.Sep_Main" Named_Simpsets More_Eisbach_Tools
begin
no_notation Ref.update ("_ := _" 62)
notation Ref.update ("_ :=\<^sub>R _" 62)
abbreviation contains ("(_/ \<in>\<^sub>L _)" [51, 51] 50) where
"contains x xs \<equiv> x \<in> set xs"
lemma ent_iff:"A = B \<longleftrightarrow> (B \<Longrightarrow>\<^sub>A A) \<and> (A \<Longrightarrow>\<^sub>A B)"
using ent_iffI by auto
lemma htriple_frame_fwd:
assumes R: "P \<Longrightarrow>\<^sub>A R"
assumes F: "Ps \<Longrightarrow>\<^sub>A P*F"
assumes I: "<R*F> c <Q>"
shows "<Ps> c <Q>"
using assms
by (metis cons_rule ent_refl fr_refl)
lemma mod_starE:
assumes "h \<Turnstile> P1 * P2"
obtains h1 h2 where "h1 \<Turnstile> P1" "h2 \<Turnstile> P2"
using assms mod_starD by blast
method hoare_triple_preI uses rule = rule hoare_triple_preI,
(determ\<open>elim mod_starE rule[elim_format]\<close>)?, ((determ\<open>thin_tac "_ \<Turnstile> _"\<close>)+)?
method sep_drule uses r =
rule ent_frame_fwd[OF r] htriple_frame_fwd[OF r], (assumption+)?, frame_inference
end
|
[STATEMENT]
lemma is_binqueue_select:
"is_binqueue l xs \<Longrightarrow> Some t \<in> set xs \<Longrightarrow> \<exists>k. is_bintree k t \<and> is_heap t"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>is_binqueue l xs; Some t \<in> set xs\<rbrakk> \<Longrightarrow> \<exists>k. is_bintree_list k (children t) \<and> is_heap_list (priority t) (children t)
[PROOF STEP]
by (induct xs arbitrary: l) (auto intro: is_binqueue.intros elim: is_binqueue.cases) |
/-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
! This file was ported from Lean 3 source module tactic.dec_trivial
! leanprover-community/mathlib commit 13881d7a4086e038e49e116066b379a043d13d34
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Tactic.Interactive
/-!
# `dec_trivial` tactic
The `dec_trivial` tactic tries to use decidability to prove a goal.
It is basically a glorified wrapper around `exact dec_trivial`.
There is an extra option to make it a little bit smarter:
`dec_trivial!` will revert all hypotheses on which the target depends,
before it tries `exact dec_trivial`.
-/
open Tactic.Interactive
/- ./././Mathport/Syntax/Translate/Tactic/Mathlib/Core.lean:38:34: unsupported: setup_tactic_parser -/
/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/
/-- `dec_trivial` tries to use decidability to prove a goal
(i.e., using `exact dec_trivial`).
The variant `dec_trivial!` will revert all hypotheses on which the target depends,
before it tries `exact dec_trivial`.
Example:
```lean
example (n : ℕ) (h : n < 2) : n = 0 ∨ n = 1 :=
by dec_trivial!
```
-/
unsafe def tactic.interactive.dec_trivial (revert_deps : parse (parser.optional (tk "!"))) :
tactic Unit :=
if revert_deps.isSome then andthen revert_target_deps tactic.exact_dec_trivial
else tactic.exact_dec_trivial
#align tactic.interactive.dec_trivial tactic.interactive.dec_trivial
add_tactic_doc
{ Name := "dec_trivial"
category := DocCategory.tactic
declNames := [`tactic.interactive.dec_trivial]
tags := ["basic", "finishing"] }
|
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
// Helmet Software Framework
//
// Copyright (C) 2018 Hat Boy Software, Inc.
//
// @author Matthew Alan Gray - <[email protected]>
// @author Tony Richards - <[email protected]>
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
#pragma once
#include <Helmet/Workbench/I_Frame.hpp>
#include <boost/smart_ptr/shared_ptr.hpp>
#include <boost/property_tree/ptree_fwd.hpp>
#include <list>
#include <wx/aui/aui.h>
namespace boost{
namespace filesystem{
class path;
}
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
namespace Helmet {
namespace Workbench {
class I_Workbench;
class I_MenuBar;
class I_StatusBar;
class I_Notebook;
} // namespace Workbench
} // namespace Helmet
namespace Topper {
class Workbench;
class Notebook;
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
class TopFrame
: public Helmet::Workbench::I_Frame
, public wxFrame
{
/// @name Types
/// @{
public:
typedef boost::shared_ptr<Helmet::Workbench::I_Frame> pFrame_type;
typedef boost::shared_ptr<Helmet::Workbench::I_Workbench> pWorkbench_type;
typedef std::list<pFrame_type> pFrames_type;
/// @}
/// @name I_Frame implementation
/// @{
public:
void setName(const std::string& _name) override;
const std::string getName() const override;
void addChildFrame(I_Frame& _frame) override;
void removeChildFrame(I_Frame& _frame) override;
void getChildFrames(I_FrameVisitor& _visitor) override;
void show(bool _visible) override;
void handleEvent(pEvent_type _pEvent) override;
/// @}
/// @name TopFrame implementation
/// @{
public:
Helmet::Workbench::I_MenuBar& getMenuBar();
Helmet::Workbench::I_StatusBar& getStatusBar();
Notebook& getBottomNotebook();
Notebook& getLeftNotebook();
Notebook& getCenterNotebook();
/// @}
/// @name Event Handlers
/// @{
private:
/// @}
/// @name 'Structors
/// @{
public:
TopFrame(pWorkbench_type _pWorkbench, const std::string& _pTitle, int _xpos, int _ypos, int _width, int _height);
~TopFrame() override;
/// @}
/// @name Member Variables
/// @{
private:
std::string m_name;
wxAuiManager m_mgr;
pWorkbench_type m_pWorkbench;
pFrames_type m_pFrames;
/// @}
}; // class TopFrame
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
} // namespace Topper
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
|
# Music machine learning - Neural networks
### Author: Philippe Esling ([email protected])
In this course we will cover
1. A [quick introduction](#intro) on the code that we will adress and auxiliary functions
2. A simple implementation for a [single neuron](#single)
3. An implementation of [regression](#implem) using scikit-learn
4. Some [common good practices](#practices) in machine learning
# Introducing neural networks
In this tutorial, we will cover a more advanced classification algorithm through the use of *neural networks*. The tutorial starts by performing a simple **single neuron** discrimination of two random distributions. Then, we will study the typical **XOR problem** by using a more advanced 2-layer **perceptron**. Finally, we generalize the use of neural networks in order to perform classification on a given set of audio files.
We are going to use relatively _low-level_ libraries to perform the first exercises (implementing your own neurons)
```python
import time
import numpy as np
%matplotlib inline
from matplotlib import pyplot as plt
```
To simplify your work, we provide a first set of functions that provides simple plotting functionnalities (from the `helper_plot.py` file)
|**File**|*Explanation*|
|-------:|:---------|
|`plot_boundary`|Plots the decision boundary of a single neuron with 2-dimensional inputs|
|`plot_patterns`|Plots (bi-dimensionnal) input patterns|
```python
from helper_plot import plot_boundary
from helper_plot import plot_patterns
```
Remember that a single neuron is only able to learn _linearly separable_ problems. To produce such classes of problems, we provide a script that draw a set of random 2-dimensional points, then choose a random line in this space that will act as the linear frontier between 2 classes (hence defining a linear 2-class problem). The variables that will be used by your code are the following.
```Matlab
desired % classes of the patterns
inputs % 2 x n final matrix of random input patterns
weights % 2 x 1 vector of neuron weights
bias % 1 x 1 vector of bias
```
You can execute the code below to see our simple classification problem. (Note that running the same cell multiple times produces a different starting dataset).
```python
# Number of points to generate
nPats = 30 + np.floor(np.random.rand() * 30);
# Generate 2-dimensional random points
patterns = np.random.rand(2, int(nPats)) * 2 - 1;
# Slope of separating line
slope = np.log(np.random.rand() * 10);
yint = np.random.rand() * 2 - 1;
# Create the indexes for a two-class problem
desired = (patterns[1,:] - patterns[0,:] * slope - yint > 0) * 1;
# Plot the corresponding pattern
fig = plot_patterns(patterns,desired);
```
## Single neuron
For the first parts of the tutorial, we will perform the simplest classification model possible in a neural network setting, a single neuron. We briefly recall here that; given an input vector $ \mathbf{x} \in \mathbb{R}^{n} $, a single neuron computes the function
$$
\begin{equation}
y=\sigma\left(\sum_{i = 1}^{n}w_{i}.x_{i} + b\right)
\end{equation}
$$
with $ \mathbf{w} \in \mathbb{R}^{n} $ a weight vector, $ b $ a bias and $ \sigma\left(\right) $ an *activation function*. Therefore, if we consider the *threshold* activation function ($ \sigma_0\left(x\right)=1 $ if $ x \geq 0$), a single neuron simply performs an *affine transform* and then a *linear* discrimination of the space. A network will be composed of _layers_ of these neurons, which produce successive computations
Geometrically, a single neuron computes an hyperplane that separates the space. In order to learn, we have to adjust the weights and know "how much wrong we are". To do so, we consider that we know the desired output $ d $ of a system for a given example $ \mathbf{x} $ (eg. a predicted value for a regression system, a class value for a classification system). Therefore, we define the loss function $ \mathcal{L}_{\mathcal{D}} $ over a whole dataset as
$$
\begin{equation}
\mathcal{L}=\sum_{j=1}^{k_{\mathcal{D}}}\left\Vert d_{j}-y_{j}\right\Vert ^{2}
\end{equation}
$$
In order to know how to change the weights based on the value of the errors, we need to now "how to change it to make it better". Therefore, we should compute the sets of derivatives of the error given each parameter
$$
\begin{equation}
\Delta\bar{\mathbf{w}}=\left(\frac{\delta\mathcal{L}_{\mathcal{D}}}{\delta w_{1}},\ldots,\frac{\delta\mathcal{L}_{\mathcal{D}}}{\delta w_{n}}\right)
\end{equation}
$$
***
**Exercise**
1. Perform the derivatives of the output given a single neuron
2. Perform the derivatives for the bias as well
***
### Training your own neuron
We will start by training a single neuron to learn how to perform this discrimination with a linear problem (so that a single neuron is enough to solve it).
```python
# Inputs to use
inputs = patterns;
# Initialize the weights
weights = np.random.randn(1, 2);
print(weights)
bias = np.random.randn(1, 1)
# Learning rate
eta = 0.2;
# Weight decay
lambdaW = 0.001
```
[[0.49535084 0.05333204]]
Now you need to update the following code loop to ensure that your neuron learns to separate between the classes
***
**Exercise**
1. Update the loop so that it computes the forward propagation error
2. Update the loop to perform learning (based on back-propagation)
3. Run the learning procedure, which should produce a result similar to that displayed on the website
4. Perform multiple re-runs by **tweaking the hyperparameters** (learning rate, weight decay)
5. What observations can you make on the learning process?
6. (Optional) Change the input patterns, and confirm your observations.
6. (Optional) Incorporate the bias in the weights to obtain a **vectorized** code.
***
```python
beta=1
def T_func (x):
return 1/(1+np.exp(-beta*x))
x=np.linspace(-10,10,500)
plt.figure()
plt.plot(x,T_func(x))
# Plot the corresponding pattern
fig = plot_patterns(patterns,desired);
plt.draw()
# Update loop
for i in range(400):
######################
output=T_func(np.sum(weights.T*inputs+bias[0,0],axis=0))
error=desired-output
bias[0,0]=bias[0,0]+eta*np.mean(error*beta*output*(1-output))
#for j in range(2):
# weights[0,j]=weights[0,j]+eta*np.mean(error*beta*output*(1-output)*inputs[j,:])#-lambdaW*weights[0,j]**2
weights=weights+eta*np.mean(error*beta*output*(1-output)*inputs,axis=1)#-lambdaW*weights[0,j]**2
######################
#print('%2d. weights = %f, %f, %f' % (i, bias[0, 0], weights[0, 0], weights[0, 1]))
if (i % 10)==0:
plot_boundary(np.concatenate((bias, weights), axis=1), i, '--', fig)
plt.draw()
#time.sleep(0.2)
plot_boundary(np.concatenate((bias, weights), axis=1), i, '-', fig);
```
### 2-layer XOR problem
In most cases, classification problems are far from being linear. Therefore, we need more advanced methods to be able to compute non-linear class boundaries. The advantage of neural networks is that the same principle can be applied in a *layer-wise* fashion. This allows to further discriminate the space in sub-regions (as seen in the course). We will try to implement the 2-layer *perceptron* that can provide a solution to the infamous XOR problem. The idea is now to have the output of the first neurons to be connected to a set of other neurons. Therefore, if we take back our previous formulation, we have the same output for the first neuron(s) $y$, that we will now term as $y_{1}$. Then, we feed these outputs to a second layer of neurons, which gives
$$
\begin{equation}
y_{2}=\sigma\left(\sum_{i = 1}^{n}w_{i}.y_{1}^{i} + b\right)
\end{equation}
$$
Finally, we will rely on the same loss $\mathcal{L_{D}}$ as in the previous exercise, but the outputs used are $y_2$ instead of $y$. As in the previous case, we now need to compute the derivatives of the weights and biases for several layers . However, you should see that some form of generalization might be possible for any number of layer.
***
**Exercise**
1. Perform the derivatives for the last layer specifically
2. Define a generalized derivative for any previous layer
***
We can construct the prototypical set of XOR values by using the following code (note that this is the most simple case, but still this is typically a problem that cannot be solved by a _linear classifier_
```python
patterns = np.array([[-1, -1],[-1, 1],[1, -1],[1, 1]]).transpose() # Input patterns
desired = np.array([0, 1, 1, 0]) # Corresponding classes
# Initialize based on their sizes
nInputs = patterns.shape[0]
nOutputs = 1
nPat = patterns.shape[1]
# First plot the patterns
fig = plot_patterns(patterns, desired);
```
The variables that will be used by your code are the following.
```Matlab
patterns % 2 x n matrix of random points
desired % classes of the patterns
inputs1 % 3 x n final matrix of inputs (accounting for bias)
nHiddens % Number of hidden units
learnRate % Learning rate parameter
momentum % Momentum parameter (bonus)
weights1 % 1st layer weights
weights2 % 2nd layer weights
TSS_Limit % Sum-squared error limit
```
```python
nHiddens = 2 # Number of hidden units
learnRate = 0.001 # Learning rate parameter
momentum = 0.1 # Momentum parameter
# Overall input patterns
inputs = patterns
TSS_Limit = 0.02 # Sum-squared error limit
# Learning rate
eta = 0.4
#options
sparse_coeff=0
lambda_coeff=0.0001
```
***
**Exercise**
1. Update the forward propagation and error computation (compared to desired).
2. Update the back-propagation part to learn the weights of both layers.
3. Run the learning, which should produce a result similar to that displayed below.
4. Perform multiple re-runs of the learning procedure (re-launching with different initializations)
5. What observations can you make on the learning process?
6. What happens if you initialize all weights to zeros?
7. (Optional) Implement the *sparsity* constraint in your neural network.
7. (Optional) Implement the *weight decay* constraint in your network.
7. (Optional) Add the *momentum* to the learning procedure.
*For optional questions, please look after the first code box for more information*
***
```python
# Weights of first and second layer
weights1 = (np.random.randn(nHiddens, nInputs) - 0.5) # 1st layer weights
weights2 = (np.random.randn(nOutputs, nHiddens) - 0.5) # 2nd layer weights
bias1 = (np.random.randn(nHiddens, 1) - 0.5) # 1st layer biases
bias2 = (np.random.randn(nOutputs, 1) - 0.5) # 2nd layer biases
# First plot the patterns
fig = plot_patterns(patterns, desired);
# Iterate for a fixed number of iterations
deltaL_prev=0
delta_hidden_prev=0
loss=[0]*10000
for epoch in range(10000):
######################
out_hidden=T_func(np.dot(weights1.T,inputs)+bias1)
outputs=T_func(np.dot(weights2,out_hidden)+bias2)
error=desired-outputs
loss[epoch]=np.sum(error**2)
#backpropagation
deltaL=outputs*(1-outputs)*error+momentum*deltaL_prev
delta_hidden=out_hidden*(1-out_hidden)*weights2.T*deltaL+momentum*delta_hidden_prev
weights2+=eta*(np.mean(deltaL*out_hidden,axis=1)-2*lambda_coeff*weights2-sparse_coeff*np.sign(weights2))
bias2+=eta*np.mean(deltaL,axis=1)
weights1+=eta*(np.mean(delta_hidden*inputs,axis=1)-2*lambda_coeff*weights1-sparse_coeff*np.sign(weights1))
bias1+=eta*np.mean(delta_hidden,axis=1).reshape(2,1)
deltaL_prev=deltaL
delta_hidden_prev=delta_hidden
######################
#print('Epoch %3d: Error = %f' % (epoch, TSS));
#if TSS < TSS_Limit:
# break
if (epoch % 1000)==0:
plot_boundary(np.concatenate((bias2, weights2), axis=1), epoch, '--', fig)
plot_boundary(np.concatenate((bias1, weights1), axis=1), epoch, '-', fig)
plt.figure()
plt.plot(loss)
```
```python
print(outputs)
print(desired)
```
[[0.07343813 0.92411483 0.92732521 0.07487704]]
[0 1 1 0]
**Optional questions**
2. *Weight decay* constraint
As nothing constrains the weights in the network, we can note that usually all weights vector given a multiplicative factor might be equivalent, which can stall the learning (and lead to exploding weights). The *weight decay* allows to regularize the learning by penalizing weights with a too wide amplitude. The idea is to add this constraint as a term to the final loss (which leads to an indirect "pressure" on the learning process. Therefore, the final loss will be defined as
$$
\begin{equation}
\mathcal{L}_{final}=\mathcal{L_D} + \lambda \sum_{l} \sum_{i} \sum_{j} \left( W_{ij}^{l} \right)^{2}
\end{equation}
$$
where the parameter $\lambda$ controls the relative importance of the two terms.
3. *Momentum* in learning
Usually, in complex problems, the gradient can be very noisy and, therefore, the learning might oscillate widely. In order to reduce this problem, we can *smooth* the different gradient updates by retaining the values of the gradient at each iteration and then performing an update based on the latest gradient $\delta_{i}^{t}$ and the gradient at the previous iteration $\delta_{i}^{t-1}$. Therefore, a gradient update is applied as
$$
\begin{equation}
\delta_{final}^{t} = \delta_{i}^{t} + m.\delta_{i}^{t-1}
\end{equation}
$$
with $m$ the momentum parameter, which control the amount of gradient smoothing.
## 3-layer audio classification
Finally, we will attack a complete audio classification problem and try to perform neural network learning on a set of audio files. The data structure will be the same as the one used for parts 1 and 2. As discussed during the courses, even though a 2-layer neural network can provide non-linear boundaries, it can not perform "holes" inside those regions. In order to obtain an improved classification, we will now rely on a 3-layer neural network. The modification to the code of section 3.2 should be minimal, as the back-propagation will be similar for the new layer as one of the two others. We do not develop the math here as it is simply a re-application of the previous rules with an additional layer (which derivatives you should have generalized in the previous exercise).
However, up until now, we only performed *binary classification* problems, but this time we need to obtain a decision rule for multiple classes. Therefore, we cannot rely on simply computing the distance between desired patterns and the obtained binary value. The idea here is to rely on the *softmax regression*, by considering classes as a vector of probabilities. The desired answers will therefore be considered as a set of *probabilities*, where the desired class is $1$ and the others are $0$ (called *one-hot* representation). Then, the cost function will rely on the softmax formulation
$$
\begin{equation}
\mathcal{L_D}(\theta) = - \frac{1}{m} \left[ \sum_{i=1}^{m} \sum_{j=1}^{k} 1\left\{y^{(i)} = j\right\} log \frac{e^{\theta_{j}^{T} x^{(i)}}}{\sum_{l=1}^{k} e^{ \theta_{l}^{T} x^{(i)} }} \right]
\end{equation}
$$
Therefore, we compute the output of the softmax by taking
$$
\begin{equation}
p(y^{(i)} = j | x^{(i)}; \theta) = \frac{e^{\theta_{j}^{T} x^{(i)}}}{\sum_{l=1}^{k} e^{ \theta_{l}^{T} x^{(i)}} }
\end{equation}
$$
By taking derivatives, we can show that the gradient of the softmax layer is
$$
\begin{equation}
\nabla_{\theta_{j}} \mathcal{L_D}(\theta) = - \frac{1}{m} \sum_{i=1}^{m}{ \left[ x^{(i)} \left( 1\{ y^{(i)} = j\} - p(y^{(i)} = j \mid x^{(i)}, \theta) \right) \right]}
\end{equation}
$$
### Sweet activation functions
As discussed in the course, the interest of stacking layers is that there is an _activation function_, which allows non-linear interactions between the dimensions (and avoids to only compute a single huge affine transform). Although the `sigmoid` function has been historically the most used, there has been some large developments since. Notably the `ReLU` (Rectified Linear Unit) is one of the major difference in modern networks (we will see more about that in a later course)
```python
# Function for computing the Sigmoid activation
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def dsigmoid(a):
return a * (1.0 - a)
# Function for computing the ReLU activation
def relu(x):
return np.maximum(0, x)
def drelu(x):
return 1 / (1 + np.exp(-x))
# Function for computing the Tanh activation
def tanh(x):
return np.tanh(x);
def dtanh(x):
return np.cosh(x) ^ -2
```
Here, we plot some simple examples of what these activation functions look like. You can try to rely on these functions in your previous training code and witness the differences in training.
```python
from helper_plot import prep_plots, finalize_plots
funcs = [('sigmoid',sigmoid,'red'), ('tanh',tanh,'orange'), ('relu',relu,'yellow')]
axes = prep_plots([funcs[0][0], funcs[1][0], funcs[2][0]], fig_size=(18,5), fig_num=1)
x_plot = np.linspace(-5,5,100)
np.maximum(0, x_plot)
for f in range(3):
axes[f].plot(x_plot, funcs[f][1](x_plot), color=funcs[f][2], linewidth=4, label=funcs[f][0])
finalize_plots(axes, fig_title="Activation functions")
```
## Coding the whole network from scratch
You should now have all the tools necessary to apply neural networks from scratch to a more complex problem. In the following exercise, we simply removed any guideline code, and you need to code all the procedure for training a NN and **apply it to audio data**. You will use the spectral features discussed in the previous exercise as an input.
***
**Exercise**
1. Based on the previous neural network, upgrade the code to a 3-layer neural network
2. Implement the *softmax regression* on top of your 3-layer network
3. Use the provided code to perform classification on a pre-defined set of features
4. As previously, change the set of features to assess their different accuracies
5. Evaluate the neural network accuracy for all features combinations
6. What happens if the learning rate is too large ? What is this phenomenon ?
7. (Optional) Perform a more advanced visualization of the learning process.
***
#### Structure du réseau
```python
#couche d'entrée
InputsS = 6 #nombre de neurones sur la couche d'entrée
nInputs = 5 #nombre de données d'entrée
#couches intermédiaires
nLayers = 3
nHiddens = 5 #nombre de neurones sur les couches intermédiaires
#couche de sortie
nOutputs = 16
```
#### DOnnées d'entrée
```python
inputs=np.ones((5,2))
```
#### Paramètres d'apprentissage
```python
learnRate = 0.001 # Learning rate parameter
momentum = 0.1 # Momentum parameter
# Overall input patterns
TSS_Limit = 0.02 # Sum-squared error limit
# Learning rate
eta = 0.4
#options
sparse_coeff=0.0001
lambda_coeff=0.0001
```
#### Initialisation
```python
# Weights of first and second layer
weightsIn = (np.random.randn(InputsS, nInputs) - 0.5) # Weights layer d'entrée
weightsOut = (np.random.randn(nOutputs, nHiddens) - 0.5) # Weights layer de sortie
weightsHidden1 = (np.random.randn(nHiddens, InputsS) - 0.5) #Weights premier hidden layer
if nLayers>1:
weightsHidden = [(np.random.randn(nHiddens, nHiddens) - 0.5) for i in range(nLayers-1)] #Weights hidden layers
bias1 = (np.random.randn(1, InputsS) - 0.5) # Entry layer biases
bias2 = (np.random.randn(1, nOutputs) - 0.5) # Out layer biases
biasHidden = (np.random.randn(nLayers, nHiddens) - 0.5) # Hidden layers biases
# First plot the patterns
# Iterate for a fixed number of iterations
deltaL_prev=0
delta_hidden_prev=0
loss=[0]*10000
out_hidden=np.zeros((nLayers,nHiddens))
```
```python
```
```python
for i in range(1,2):
print(i)
```
1
#### Entrainement
```python
# Iterate for a fixed number of iterations
for epoch in range(500):
######################
#Forward propagation
#Input Layer
out_input = np.dot(weightsIn,inputs.T)+bias1 #Sortie avant fonction d'activation
out_input = out_input #Après fonction d'activation
#First Hidden layer
out_line = np.dot(weightsHidden1,out_input.T)+biasHidden[0].reshape(nHiddens,1)
out_hidden[0,:] = out_line.reshape(nHiddens)
out_hidden[0,:] = out_hidden[0,:]
#Other Hidden Layers
for i in range(1,nLayers) :
out_line = np.dot(weightsHidden[i-1],out_hidden[0,:].T)+biasHidden[i].reshape(1,nHiddens)
out_hidden[i,:] = out_line.reshape(nHiddens)
#Output Layer
outputs=(np.dot(weightsOut,out_hidden[nLayers-1,:].reshape(nHiddens,1))+bias2.reshape(nOutputs,1)).T #Sortie avant fonction d'activation
outputs=outputs #Après fonction d'activation
"""
##############
error=desired-outputs
loss[epoch]=np.sum(error**2)
#backpropagation
deltaL=outputs*(1-outputs)*error+momentum*deltaL_prev
delta_hidden=out_hidden*(1-out_hidden)*weights2.T*deltaL+momentum*delta_hidden_prev
weights2+=eta*(np.mean(deltaL*out_hidden,axis=1)-2*lambda_coeff*weights2-sparse_coeff*np.sign(weights2))
bias2+=eta*np.mean(deltaL,axis=1)
weights1+=eta*(np.mean(delta_hidden*inputs,axis=1)-2*lambda_coeff*weights1-sparse_coeff*np.sign(weights1))
bias1+=eta*np.mean(delta_hidden,axis=1).reshape(2,1)
deltaL_prev=deltaL
delta_hidden_prev=delta_hidden
######################
print('Epoch %3d: Error = %f\n' % epoch, TSS);
if TSS < TSS_Limit:
break
plo_boundary(np.concatenate(bias1, weights1), epoch, '-');
"""
```
```python
outputs
```
array([[ 70.42226608, 4.7112851 , -26.64462671, 92.34633111,
154.81953653, 247.7670092 , -26.17720895, 27.6813103 ,
8.32751212, 21.76950085, 81.78149506, 46.20283095,
164.39043612, 5.53618167, 29.35867026, -35.35415959]])
```python
out_input
```
array([[ 0.13385349, -5.85639205, -1.93544627, -1.99704253, -3.38893765,
-0.84334717]])
```python
out_hidden[0]
```
array([ 0.21383226, 21.63732873, 7.77252951, 1.5625695 , 13.05477784])
```python
weightsHidden1
```
array([[ 0.23417693, 0.15465218, -2.20514202, 0.19922594, 0.43572309],
[ 0.08814463, 0.0476187 , 0.56392929, -2.69049748, -1.28021802],
[ 1.02261729, -0.02580423, -0.17268853, -0.88280955, 0.25610718],
[-0.93405185, 0.05106439, -0.12841387, -0.67851671, -1.26372586],
[-1.59020093, -1.47292629, -0.13376435, 0.45529411, 0.15879279],
[ 0.37104001, -1.01940478, 1.71356566, 0.50818289, -0.35745936]])
```python
np.dot(weightsIn,inputs.T)+bias1.T
```
array([[-5.94042325, -0.91678248, -1.5795785 , -3.64397425, -2.99679312,
-2.32534787]])
## Using Pytorch to enjoy life
Up to now, we have been writing every operations by ourselves (in order to better understand the mathematics behind NN). However, there exists of course some simplifying libraries that provide large simplifications to this question.
One of the most powerful and complete library of this sort is `Pytorch`, which has been developed for several years (even prior to the recent boom of deep learning). `Pytorch` provides a large set of pre-coded layers, but also **computational graphs** and **autograd**, which are very powerful paradigms allowing to define complex operators and automatically taking derivatives.
### Defining our network
When building neural networks we frequently think of arranging the computation into layers, some of which have learnable parameters which will be optimized during learning. In `PyTorch`, the `nn` package provides higher-level abstractions over raw computational graphs that are useful for building neural networks. The `nn` package defines a set of `Modules`, which are roughly equivalent to neural network layers. A `Module` receives input `Tensors` and computes output `Tensors`, but may also hold internal state such as `Tensors` containing learnable parameters. The nn package also defines a set of useful loss functions that are commonly used when training neural networks.
In the following example, we use the `nn` package to show how easy it is to instantiate our previous three-layers network
```python
import torch
# Define the input dimensions
in_size = 1000
# Number of neurons in a layer
hidden_size = 100
# Output (target) dimension
output_size = 10
# Use the nn package to define our model and loss function.
model = torch.nn.Sequential(
torch.nn.Linear(in_size, hidden_size),
torch.nn.ReLU(),
torch.nn.Linear(hidden_size, hidden_size),
torch.nn.ReLU(),
torch.nn.Linear(hidden_size, output_size),
torch.nn.Softmax()
)
```
### Optimizing the network
Up to this point we have updated the weights of our models by manually performing the gradient descent algorithm (changing the parameters vectors). Although this is not a huge burden for simple optimization algorithms like stochastic gradient descent, in practice we often train neural networks using more sophisticated optimizers like AdaGrad, RMSProp or Adam (that we will see later in this course)
The `optim` package in PyTorch abstracts the idea of an optimization algorithm and provides implementations of commonly used optimization algorithms, and greatly simplfies the training loop associated with training a neural network.
For the sake of presentation we will use random inputs $\mathbf{x}$ that should be matched with random outputs $\mathbf{y}$
```python
batch_size = 64
# Create random Tensors to hold inputs and outputs
x = torch.randn(N, D_in)
y = torch.randn(N, D_out)
```
In the following example we optimize the model using the Adam algorithm provided by the `optim` package, based on a `MSE` loss.
```python
# Learning rate
learning_rate = 1e-4
# Loss function that we will use
loss_fn = torch.nn.MSELoss(reduction='sum')
# Optimizer to fit the weights of the network
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
for t in range(500):
# Forward pass: compute predicted y by passing x to the model.
y_pred = model(x)
# Compute the loss.
loss = loss_fn(y_pred, y)
# Before the backward pass, zero all of the network gradients
optimizer.zero_grad()
# Backward pass: compute gradient of the loss with respect to parameters
loss.backward()
# Calling the step function to update the parameters
optimizer.step()
```
## Using Pytorch to classify audio
Now that we know the main components of `Pytorch` to define and optimize networks, your assignement is to define a complete classification problem from audio data, by relying on this toolbox
***
**Exercise**
1. Use `Pytorch` to define a model for audio classification
2. Import the audio features dataset and check that your model produces an output
3. Write the optimization loop (think carefully about the _loss function_
4. As previously, change the set of features to assess their different accuracies
5. Think of how you could use more complex features (time series, audio, STFT) to classify your data
***
```python
######################
# YOUR CODE GOES HERE
######################
```
|
\filetitle{figure}{Start new figure}{report/figure}
\paragraph{Syntax}\label{syntax}
\begin{verbatim}
P.figure(Caption,...)
\end{verbatim}
\paragraph{Syntax to capture an existing figure
window}\label{syntax-to-capture-an-existing-figure-window}
This is an obsolete syntax, and will be removed from IRIS in a future
release. Use \href{report/userfigure}{\texttt{report/userfigure}}
instead.
\begin{verbatim}
P.figure(Caption,H,...)
\end{verbatim}
\paragraph{Input arguments}\label{input-arguments}
\begin{itemize}
\item
\texttt{P} {[} struct {]} - Report object created by the
\href{report/new}{\texttt{report.new}} function.
\item
\texttt{Caption} {[} char \textbar{} cellstr {]} - Title or a cell
array with title and subtitle displayed at the top of the figure; see
Description for splitting the title or subtitle into multiple lines.
\item
\texttt{H} {[} numeric {]} - See help on
\href{report/userfigure}{\texttt{report/userfigure}}.
\end{itemize}
\paragraph{Options}\label{options}
\begin{itemize}
\item
\texttt{'aspectRatio='} {[} \texttt{@auto} \textbar{} numeric {]} -
Plot box aspect ratio for all graphs in the figure; must be a 1-by-2
vector describing the horizontal-to-vertical ratio.
\item
\texttt{'captionTypeface='} {[} cellstr \textbar{} char \textbar{}
\emph{\texttt{'\textbackslash{}large\textbackslash{}bfseries'}} {]} -
LaTeX format commands for typesetting the figure caption; the
subcaption format can be entered as the second cell in a cell array.
\item
\texttt{'close='} {[} \emph{\texttt{true}} \textbar{} \texttt{false}
{]} - (Inheritable from parent objects) Close the underlying figure
window when finished; see Description.
\item
\texttt{'separator='} {[} char \textbar{}
\emph{\texttt{'\textbackslash{}medskip\textbackslash{}par'}} {]} -
(Inheritable from parent objects) LaTeX commands that will be inserted
after the figure.
\item
\texttt{'figureOptions='} {[} cell \textbar{} \emph{empty} {]} -
Figure options that will be applied to the figure handle at opening.
\item
\texttt{'figureScale='} {[} numeric \textbar{} \emph{\texttt{0.85}}
{]} - (Inheritable from parent objects) Scale of the figure in the
LaTeX document.
\item
\texttt{'figureTrim='} {[} numeric \textbar{} \emph{\texttt{0}} {]} -
Trim figure when it is inserted into the report by the specified
amount of points; must be either a scalar or a 1-by-4 vector (points
removed from left, bottom, right, top).
\item
\texttt{'footnote='} {[} char \textbar{} \emph{empty} {]} - Footnote
at the figure title; only shows if the title is non-empty.
\item
\texttt{'sideways='} {[} \texttt{true} \textbar{}
\emph{\texttt{false}} {]} - (Inheritable from parent objects) Print
the table rotated by 90 degrees.
\item
\texttt{'style='} {[} struct \textbar{} \emph{empty} {]} - Apply this
cascading style structure to the figure; see
\href{qreport/qstyle}{\texttt{qstyle}}.
\item
\texttt{'subplot='} {[} numeric \textbar{} \emph{\texttt{'auto'}} {]}
- (Inheritable from parent objects) Subplot division of the figure.
\item
\texttt{'typeface='} {[} char \textbar{} \emph{empty} {]} - (Not
inheritable from parent objects) LaTeX code specifying the typeface
for the figure as a whole; it must use the declarative forms (such as
\texttt{\textbackslash{}itshape}) and not the command forms (such as
\texttt{\textbackslash{}textit\{...\}}).
\item
\texttt{'visible='} {[} \texttt{true} \textbar{} \emph{\texttt{false}}
{]} - (Inheritable from parent objects) Visibility of the underlying
Matlab figure window.
\end{itemize}
\paragraph{Generic options}\label{generic-options}
See help on \href{report/Contents}{generic options} in report objects.
\paragraph{Description}\label{description}
Figures are top-level report objects and cannot be nested within other
report objects, except \href{report/align}{\texttt{align}}. Figure
objects can have the following types of children:
\begin{itemize}
\itemsep1pt\parskip0pt\parsep0pt
\item
\href{report/graph}{\texttt{graph}};
\item
\href{report/empty}{\texttt{empty}}.
\end{itemize}
\subparagraph{Titles and subtitles}\label{titles-and-subtitles}
The input argument \texttt{Caption} can be either a text string, or a
1-by-2 cell array of strings. In the latter case, the first cell will be
printed as a title, and the second cell will be printed as a subtitle.
To split the title or subtitle into multiple lines, use the following
LaTeX commands wrapped in curly brackets:
\texttt{\{\textbackslash{}\textbackslash{}\}} or
\texttt{\{\textbackslash{}\textbackslash{}{[}Xpt{]}\}}, where \texttt{X}
is the width of an extra vertical space (in points) added between the
respective lines.
\subparagraph{Figure handle}\label{figure-handle}
If the option \texttt{'close='} is set to \texttt{false} the figure
window will remain open after the report is published. The handle to
this figure window will be included in the field \texttt{.figureHandle}
of the information struct \texttt{Info} returned by
\href{report/publish}{\texttt{report/publish}}.
\paragraph{Example}\label{example}
|
/-
Copyright (c) 2020 Wojciech Nawrocki. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Wojciech Nawrocki
-/
import Lean.Data.Json
import Lean.Data.Lsp.Basic
namespace Lean
namespace Lsp
open Json
structure CompletionOptions where
triggerCharacters? : Option (Array String) := none
allCommitCharacters? : Option (Array String) := none
resolveProvider : Bool := false
deriving FromJson, ToJson
inductive CompletionItemKind where
| text | method | function | constructor | field
| variable | class | interface | module | property
| unit | value | enum | keyword | snippet
| color | file | reference | folder | enumMember
| constant | struct | event | operator | typeParameter
deriving Inhabited, DecidableEq, Repr
instance : ToJson CompletionItemKind where
toJson a := toJson (a.toCtorIdx + 1)
instance : FromJson CompletionItemKind where
fromJson? v := do
let i : Nat ← fromJson? v
return CompletionItemKind.ofNat (i-1)
structure InsertReplaceEdit where
newText : String
insert : Range
replace : Range
deriving FromJson, ToJson
structure CompletionItem where
label : String
detail? : Option String := none
documentation? : Option MarkupContent := none
kind? : Option CompletionItemKind := none
textEdit? : Option InsertReplaceEdit := none
/-
tags? : CompletionItemTag[]
deprecated? : boolean
preselect? : boolean
sortText? : string
filterText? : string
insertText? : string
insertTextFormat? : InsertTextFormat
insertTextMode? : InsertTextMode
additionalTextEdits? : TextEdit[]
commitCharacters? : string[]
command? : Command
data? : any -/
deriving FromJson, ToJson, Inhabited
structure CompletionList where
isIncomplete : Bool
items : Array CompletionItem
deriving FromJson, ToJson
structure CompletionParams extends TextDocumentPositionParams where
-- context? : CompletionContext
deriving FromJson, ToJson
structure Hover where
/- NOTE we should also accept MarkedString/MarkedString[] here
but they are deprecated, so maybe can get away without. -/
contents : MarkupContent
range? : Option Range := none
deriving ToJson, FromJson
structure HoverParams extends TextDocumentPositionParams
deriving FromJson, ToJson
structure DeclarationParams extends TextDocumentPositionParams
deriving FromJson, ToJson
structure DefinitionParams extends TextDocumentPositionParams
deriving FromJson, ToJson
structure TypeDefinitionParams extends TextDocumentPositionParams
deriving FromJson, ToJson
structure ReferenceContext where
includeDeclaration : Bool
deriving FromJson, ToJson
structure ReferenceParams extends TextDocumentPositionParams where
context : ReferenceContext
deriving FromJson, ToJson
structure WorkspaceSymbolParams where
query : String
deriving FromJson, ToJson
structure DocumentHighlightParams extends TextDocumentPositionParams
deriving FromJson, ToJson
inductive DocumentHighlightKind where
| text
| read
| write
instance : ToJson DocumentHighlightKind where
toJson
| DocumentHighlightKind.text => 1
| DocumentHighlightKind.read => 2
| DocumentHighlightKind.write => 3
structure DocumentHighlight where
range : Range
kind? : Option DocumentHighlightKind := none
deriving ToJson
abbrev DocumentHighlightResult := Array DocumentHighlight
structure DocumentSymbolParams where
textDocument : TextDocumentIdentifier
deriving FromJson, ToJson
inductive SymbolKind where
| file
| module
| namespace
| package
| class
| method
| property
| field
| constructor
| enum
| interface
| function
| variable
| constant
| string
| number
| boolean
| array
| object
| key
| null
| enumMember
| struct
| event
| operator
| typeParameter
instance : ToJson SymbolKind where
toJson
| SymbolKind.file => 1
| SymbolKind.module => 2
| SymbolKind.namespace => 3
| SymbolKind.package => 4
| SymbolKind.class => 5
| SymbolKind.method => 6
| SymbolKind.property => 7
| SymbolKind.field => 8
| SymbolKind.constructor => 9
| SymbolKind.enum => 10
| SymbolKind.interface => 11
| SymbolKind.function => 12
| SymbolKind.variable => 13
| SymbolKind.constant => 14
| SymbolKind.string => 15
| SymbolKind.number => 16
| SymbolKind.boolean => 17
| SymbolKind.array => 18
| SymbolKind.object => 19
| SymbolKind.key => 20
| SymbolKind.null => 21
| SymbolKind.enumMember => 22
| SymbolKind.struct => 23
| SymbolKind.event => 24
| SymbolKind.operator => 25
| SymbolKind.typeParameter => 26
structure DocumentSymbolAux (Self : Type) where
name : String
detail? : Option String := none
kind : SymbolKind
-- tags? : Array SymbolTag
range : Range
selectionRange : Range
children? : Option (Array Self) := none
deriving ToJson
inductive DocumentSymbol where
| mk (sym : DocumentSymbolAux DocumentSymbol)
partial instance : ToJson DocumentSymbol where
toJson :=
let rec go
| DocumentSymbol.mk sym =>
have : ToJson DocumentSymbol := ⟨go⟩
toJson sym
go
structure DocumentSymbolResult where
syms : Array DocumentSymbol
instance : ToJson DocumentSymbolResult where
toJson dsr := toJson dsr.syms
inductive SymbolTag where
| deprecated
instance : ToJson SymbolTag where
toJson
| SymbolTag.deprecated => 1
structure SymbolInformation where
name : String
kind : SymbolKind
tags : Array SymbolTag := #[]
location : Location
containerName? : Option String := none
deriving ToJson
inductive SemanticTokenType where
-- Used by Lean
| keyword
| variable
| property
| function
/- Other types included by default in the LSP specification.
Not used by the Lean core, but useful to users extending the Lean server. -/
| namespace
| type
| class
| enum
| interface
| struct
| typeParameter
| parameter
| enumMember
| event
| method
| macro
| modifier
| comment
| string
| number
| regexp
| operator
| decorator
-- Extensions
| leanSorryLike
deriving ToJson, FromJson
-- must be in the same order as the constructors
def SemanticTokenType.names : Array String :=
#["keyword", "variable", "property", "function", "namespace", "type", "class",
"enum", "interface", "struct", "typeParameter", "parameter", "enumMember",
"event", "method", "macro", "modifier", "comment", "string", "number",
"regexp", "operator", "decorator", "leanSorryLike"]
def SemanticTokenType.toNat (type : SemanticTokenType) : Nat :=
type.toCtorIdx
-- sanity check
-- TODO: restore after update-stage0
--example {v : SemanticTokenType} : open SemanticTokenType in
-- names[v.toNat]?.map (toString <| toJson ·) = some (toString <| toJson v) := by
-- cases v <;> native_decide
/--
The semantic token modifiers included by default in the LSP specification.
Not used by the Lean core, but implementing them here allows them to be
utilized by users extending the Lean server.
-/
inductive SemanticTokenModifier where
| declaration
| definition
| readonly
| static
| deprecated
| abstract
| async
| modification
| documentation
| defaultLibrary
deriving ToJson, FromJson
-- must be in the same order as the constructors
def SemanticTokenModifier.names : Array String :=
#["declaration", "definition", "readonly", "static", "deprecated", "abstract",
"async", "modification", "documentation", "defaultLibrary"]
def SemanticTokenModifier.toNat (modifier : SemanticTokenModifier) : Nat :=
modifier.toCtorIdx
-- sanity check
example {v : SemanticTokenModifier} : open SemanticTokenModifier in
names[v.toNat]?.map (toString <| toJson ·) = some (toString <| toJson v) := by
cases v <;> native_decide
structure SemanticTokensLegend where
tokenTypes : Array String
tokenModifiers : Array String
deriving FromJson, ToJson
structure SemanticTokensOptions where
legend : SemanticTokensLegend
range : Bool
full : Bool /- | {
delta?: boolean;
} -/
deriving FromJson, ToJson
structure SemanticTokensParams where
textDocument : TextDocumentIdentifier
deriving FromJson, ToJson
structure SemanticTokensRangeParams where
textDocument : TextDocumentIdentifier
range : Range
deriving FromJson, ToJson
structure SemanticTokens where
resultId? : Option String := none
data : Array Nat
deriving FromJson, ToJson
structure FoldingRangeParams where
textDocument : TextDocumentIdentifier
deriving FromJson, ToJson
inductive FoldingRangeKind where
| comment
| imports
| region
instance : ToJson FoldingRangeKind where
toJson
| FoldingRangeKind.comment => "comment"
| FoldingRangeKind.imports => "imports"
| FoldingRangeKind.region => "region"
structure FoldingRange where
startLine : Nat
endLine : Nat
kind? : Option FoldingRangeKind := none
deriving ToJson
end Lsp
end Lean
|
[STATEMENT]
lemma negligible_polynomial_times [negligible_intros]:
"\<lbrakk> polynomial f; negligible g \<rbrakk> \<Longrightarrow> negligible (\<lambda>x. f x * g x)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>polynomial f; negligible g\<rbrakk> \<Longrightarrow> negligible (\<lambda>x. f x * g x)
[PROOF STEP]
by(clarsimp simp add: polynomial.simps negligible_poly_times) |
# This file was generated, do not modify it. # hide
for name in names(datac)
col = datac[:, name]
ratio_missing = sum(ismissing.(col)) / nrows(datac) * 100
println(rpad(name, 30), round(ratio_missing, sigdigits=3))
end |
lemma countably_additiveI[case_names countably]: "(\<And>A. range A \<subseteq> M \<Longrightarrow> disjoint_family A \<Longrightarrow> (\<Union>i. A i) \<in> M \<Longrightarrow> (\<Sum>i. f (A i)) = f (\<Union>i. A i)) \<Longrightarrow> countably_additive M f" |
{-# OPTIONS --rewriting #-}
module Properties where
import Properties.Contradiction
import Properties.Dec
import Properties.Equality
import Properties.Remember
import Properties.Step
import Properties.StrictMode
import Properties.TypeCheck
|
(*|
###############################################
How to prove equality from equality of ``Some``
###############################################
:Link: https://stackoverflow.com/q/60304522
|*)
(*|
Question
********
I want to prove equality of two ``nat`` numbers in Coq:
|*)
Goal forall (a b : nat), Some a = Some b -> a = b.
Proof. intros. (* .unfold *)
Abort. (* .none *)
(*|
Answer (Théo Winterhalter)
**************************
When you have an equality such as this, usually, the quickest way to
go is by using the ``inversion`` tactic which will more or less
exploit injectivity of constructors.
|*)
Lemma foo : forall (a b : nat), Some a = Some b -> a = b.
Proof.
intros a b e. inversion e. reflexivity.
Qed.
(*|
The case of ``Some`` however is special enough that you might want to
write it differently (especially if you want to be able to read the
proof that's generated). You can write some *get* function for
``option`` using a default value:
|*)
Definition get_opt_default {A : Type} (x : A) (o : option A) :=
match o with
| Some a => a
| None => x
end.
(*|
So that ``get_opt_default x (Some a) = a``. Now using ``f_equal
(get_opt_default a)`` on equality ``Some a = Some b`` you get
.. code-block:: coq
get_opt_default a (Some a) = get_opt_default a (Some b)
which simplifies to
.. code-block:: coq
a = b
.. coq::
|*)
Lemma Some_inj : forall A (a b : A), Some a = Some b -> a = b.
Proof.
intros A a b e. apply (f_equal (get_opt_default a)) in e.
cbn in e. exact e.
Qed.
(*|
This is something that can be done in general. Basically you write an
extractor for your value as a function and you apply it to both sides
of the equality. By computation it will yield the expected result.
|*)
(*|
Answer (Arthur Azevedo De Amorim)
*********************************
The ``congruence`` tactic is powerful enough to solve this goal by
itself. More generally, there are situations where you would like to
derive ``a = b`` as an additional hypothesis starting from an equality
``H : x = y`` of terms that begin with the same constructor. In this
case, you can call
.. code-block:: coq
injection H.
to extract the equalities implied by this hypothesis.
|*)
(*|
Answer (ejgallego)
******************
I think it is instructive to write the basic lemma down:
|*)
Definition some_inj A (x y : A) (h_eq : Some x = Some y) : x = y :=
match h_eq with
| eq_refl _ => eq_refl
end.
(*|
Actually, that seems surprising; indeed Coq is elaborating the match
to help the user, and the reality is a bit more ugly, as witnessed by
the term:
|*)
Print some_inj. (* .unfold *)
(*|
So indeed the return type of the match is doing quite a bit of work to
tell Coq that the constructor is injective.
|*)
|
library( "rmacrolite" )
# # Setup MACRO directory (if needed)
# rmacroliteSetModelVar( "C:/swash/macro" )
# Import a par-file
# Path to an example par-file
par_file_path <- system.file( "par-files",
"chat_winCer_GW-X_900gHa_d182_1910-1911.par",
package = "rmacrolite" )
# Import the example par-file
par_file <- rmacroliteImportParFile(
file = par_file_path )
# Run the simulation
out <- rmacroliteRun( x = par_file )
# Inspect the results
# View the water and solute balance as output by MACRO
# attributes( out ) # full list of attributes
attr( x = out, which = "waterSoluteBalance" )
library( "macroutils2" )
macroPlot( x = out[, c( "Date", "WOUT_99-100_100",
"SFLOW_99-100_100" ) ], gui = FALSE, subPlots = TRUE )
|
[STATEMENT]
lemma avg_proj_onto_right :
assumes "VectorSpace fsmult W" "GSubspace U" "add_independentS [W,U]"
"V = W \<oplus> U"
defines P : "P \<equiv> (\<Oplus>[W,U]\<down>1)"
defines CP: "CP \<equiv> (\<lambda>g. Gmult (- g) \<circ> P \<circ> Gmult g)"
defines T : "T \<equiv> fsmult (1/ordG) \<circ> (\<Sum>g\<in>G. CP g)"
shows "T ` V = U"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. T ` V = U
[PROOF STEP]
proof
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. T ` V \<subseteq> U
2. U \<subseteq> T ` V
[PROOF STEP]
from assms(2)
[PROOF STATE]
proof (chain)
picking this:
RModule FG (\<cdot>) U \<and> U \<subseteq> V
[PROOF STEP]
have U: "FGModule G smult U"
[PROOF STATE]
proof (prove)
using this:
RModule FG (\<cdot>) U \<and> U \<subseteq> V
goal (1 subgoal):
1. FGModule G (\<cdot>) U
[PROOF STEP]
using GSubspace_is_FGModule
[PROOF STATE]
proof (prove)
using this:
RModule FG (\<cdot>) U \<and> U \<subseteq> V
RModule FG (\<cdot>) ?U \<and> ?U \<subseteq> V \<Longrightarrow> FGModule G (\<cdot>) ?U
goal (1 subgoal):
1. FGModule G (\<cdot>) U
[PROOF STEP]
by fast
[PROOF STATE]
proof (state)
this:
FGModule G (\<cdot>) U
goal (2 subgoals):
1. T ` V \<subseteq> U
2. U \<subseteq> T ` V
[PROOF STEP]
show "T ` V \<subseteq> U"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. T ` V \<subseteq> U
[PROOF STEP]
proof (rule image_subsetI)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>x. x \<in> V \<Longrightarrow> T x \<in> U
[PROOF STEP]
fix v
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>x. x \<in> V \<Longrightarrow> T x \<in> U
[PROOF STEP]
assume v: "v \<in> V"
[PROOF STATE]
proof (state)
this:
v \<in> V
goal (1 subgoal):
1. \<And>x. x \<in> V \<Longrightarrow> T x \<in> U
[PROOF STEP]
with assms(1,3,4) P U
[PROOF STATE]
proof (chain)
picking this:
VectorSpace (\<sharp>\<cdot>) W
add_independentS [W, U]
V = W \<oplus> U
P \<equiv> \<lambda>a. if a \<in> (\<Oplus>G\<leftarrow>[W, U]. G) then W\<oplus>U\<leftarrow> a ! 1 else (0::'v)
FGModule G (\<cdot>) U
v \<in> V
[PROOF STEP]
have "\<And>g. g \<in> G \<Longrightarrow> P (g *\<cdot> v) \<in> U"
[PROOF STATE]
proof (prove)
using this:
VectorSpace (\<sharp>\<cdot>) W
add_independentS [W, U]
V = W \<oplus> U
P \<equiv> \<lambda>a. if a \<in> (\<Oplus>G\<leftarrow>[W, U]. G) then W\<oplus>U\<leftarrow> a ! 1 else (0::'v)
FGModule G (\<cdot>) U
v \<in> V
goal (1 subgoal):
1. \<And>g. g \<in> G \<Longrightarrow> P (g *\<cdot> v) \<in> U
[PROOF STEP]
using Gmult_closed VectorSpace.AbGroup FGModule.AbGroup
AbGroup_inner_dirsum_el_decomp_nth_onto_nth[of "[W,U]" 1]
[PROOF STATE]
proof (prove)
using this:
VectorSpace (\<sharp>\<cdot>) W
add_independentS [W, U]
V = W \<oplus> U
P \<equiv> \<lambda>a. if a \<in> (\<Oplus>G\<leftarrow>[W, U]. G) then W\<oplus>U\<leftarrow> a ! 1 else (0::'v)
FGModule G (\<cdot>) U
v \<in> V
\<lbrakk>?g \<in> G; ?v \<in> V\<rbrakk> \<Longrightarrow> ?g *\<cdot> ?v \<in> V
VectorSpace ?smult ?V \<Longrightarrow> AbGroup ?V
FGModule ?G ?smult ?V \<Longrightarrow> AbGroup ?V
\<lbrakk>\<forall>G\<in>set [W, U]. AbGroup G; add_independentS [W, U]; 1 < length [W, U]\<rbrakk> \<Longrightarrow> (\<lambda>a. if a \<in> (\<Oplus>G\<leftarrow>[W, U]. G) then W\<oplus>U\<leftarrow> a ! 1 else (0::'v)) ` (\<Oplus>G\<leftarrow>[W, U]. G) = [W, U] ! 1
goal (1 subgoal):
1. \<And>g. g \<in> G \<Longrightarrow> P (g *\<cdot> v) \<in> U
[PROOF STEP]
by fastforce
[PROOF STATE]
proof (state)
this:
?g6 \<in> G \<Longrightarrow> P (?g6 *\<cdot> v) \<in> U
goal (1 subgoal):
1. \<And>x. x \<in> V \<Longrightarrow> T x \<in> U
[PROOF STEP]
with U CP
[PROOF STATE]
proof (chain)
picking this:
FGModule G (\<cdot>) U
CP \<equiv> \<lambda>g. (*\<cdot>) (- g) \<circ> P \<circ> (*\<cdot>) g
?g6 \<in> G \<Longrightarrow> P (?g6 *\<cdot> v) \<in> U
[PROOF STEP]
have "\<And>g. g \<in> G \<Longrightarrow> CP g v \<in> U"
[PROOF STATE]
proof (prove)
using this:
FGModule G (\<cdot>) U
CP \<equiv> \<lambda>g. (*\<cdot>) (- g) \<circ> P \<circ> (*\<cdot>) g
?g6 \<in> G \<Longrightarrow> P (?g6 *\<cdot> v) \<in> U
goal (1 subgoal):
1. \<And>g. g \<in> G \<Longrightarrow> CP g v \<in> U
[PROOF STEP]
using FGModule.Gmult_closed GroupG Group.neg_closed
[PROOF STATE]
proof (prove)
using this:
FGModule G (\<cdot>) U
CP \<equiv> \<lambda>g. (*\<cdot>) (- g) \<circ> P \<circ> (*\<cdot>) g
?g6 \<in> G \<Longrightarrow> P (?g6 *\<cdot> v) \<in> U
\<lbrakk>FGModule ?G ?smult ?V; ?g \<in> ?G; ?v \<in> ?V\<rbrakk> \<Longrightarrow> aezfun_scalar_mult.Gmult ?smult ?g ?v \<in> ?V
Group G
\<lbrakk>Group ?G; ?g \<in> ?G\<rbrakk> \<Longrightarrow> - ?g \<in> ?G
goal (1 subgoal):
1. \<And>g. g \<in> G \<Longrightarrow> CP g v \<in> U
[PROOF STEP]
by fastforce
[PROOF STATE]
proof (state)
this:
?g6 \<in> G \<Longrightarrow> CP ?g6 v \<in> U
goal (1 subgoal):
1. \<And>x. x \<in> V \<Longrightarrow> T x \<in> U
[PROOF STEP]
with assms(2) U T
[PROOF STATE]
proof (chain)
picking this:
RModule FG (\<cdot>) U \<and> U \<subseteq> V
FGModule G (\<cdot>) U
T \<equiv> (\<sharp>\<cdot>) ((1::'f) / ordG) \<circ> sum CP G
?g6 \<in> G \<Longrightarrow> CP ?g6 v \<in> U
[PROOF STEP]
show "T v \<in> U"
[PROOF STATE]
proof (prove)
using this:
RModule FG (\<cdot>) U \<and> U \<subseteq> V
FGModule G (\<cdot>) U
T \<equiv> (\<sharp>\<cdot>) ((1::'f) / ordG) \<circ> sum CP G
?g6 \<in> G \<Longrightarrow> CP ?g6 v \<in> U
goal (1 subgoal):
1. T v \<in> U
[PROOF STEP]
using finiteG FGModule.sum_closed[of G smult U G "\<lambda>g. CP g v"]
sum_fun_apply[of G CP] FGModule.fsmult_closed[of G smult U]
[PROOF STATE]
proof (prove)
using this:
RModule FG (\<cdot>) U \<and> U \<subseteq> V
FGModule G (\<cdot>) U
T \<equiv> (\<sharp>\<cdot>) ((1::'f) / ordG) \<circ> sum CP G
?g6 \<in> G \<Longrightarrow> CP ?g6 v \<in> U
finite G
\<lbrakk>FGModule G (\<cdot>) U; finite G; (\<lambda>g. CP g v) ` G \<subseteq> U\<rbrakk> \<Longrightarrow> (\<Sum>a\<in>G. CP a v) \<in> U
finite G \<Longrightarrow> sum CP G ?x = (\<Sum>a\<in>G. CP a ?x)
\<lbrakk>FGModule G (\<cdot>) U; ?v \<in> U\<rbrakk> \<Longrightarrow> ?a \<sharp>\<cdot> ?v \<in> U
goal (1 subgoal):
1. T v \<in> U
[PROOF STEP]
by fastforce
[PROOF STATE]
proof (state)
this:
T v \<in> U
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
T ` V \<subseteq> U
goal (1 subgoal):
1. U \<subseteq> T ` V
[PROOF STEP]
show "T ` V \<supseteq> U"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. U \<subseteq> T ` V
[PROOF STEP]
proof
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>x. x \<in> U \<Longrightarrow> x \<in> T ` V
[PROOF STEP]
fix u
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>x. x \<in> U \<Longrightarrow> x \<in> T ` V
[PROOF STEP]
assume u: "u \<in> U"
[PROOF STATE]
proof (state)
this:
u \<in> U
goal (1 subgoal):
1. \<And>x. x \<in> U \<Longrightarrow> x \<in> T ` V
[PROOF STEP]
with u T CP P assms(1,2,3)
[PROOF STATE]
proof (chain)
picking this:
u \<in> U
T \<equiv> (\<sharp>\<cdot>) ((1::'f) / ordG) \<circ> sum CP G
CP \<equiv> \<lambda>g. (*\<cdot>) (- g) \<circ> P \<circ> (*\<cdot>) g
P \<equiv> \<lambda>a. if a \<in> (\<Oplus>G\<leftarrow>[W, U]. G) then W\<oplus>U\<leftarrow> a ! 1 else (0::'v)
VectorSpace (\<sharp>\<cdot>) W
RModule FG (\<cdot>) U \<and> U \<subseteq> V
add_independentS [W, U]
u \<in> U
[PROOF STEP]
have "T u = u"
[PROOF STATE]
proof (prove)
using this:
u \<in> U
T \<equiv> (\<sharp>\<cdot>) ((1::'f) / ordG) \<circ> sum CP G
CP \<equiv> \<lambda>g. (*\<cdot>) (- g) \<circ> P \<circ> (*\<cdot>) g
P \<equiv> \<lambda>a. if a \<in> (\<Oplus>G\<leftarrow>[W, U]. G) then W\<oplus>U\<leftarrow> a ! 1 else (0::'v)
VectorSpace (\<sharp>\<cdot>) W
RModule FG (\<cdot>) U \<and> U \<subseteq> V
add_independentS [W, U]
u \<in> U
goal (1 subgoal):
1. T u = u
[PROOF STEP]
using GSubspace_is_FinGroupRep FinGroupRepresentation.avg_proj_eq_id_on_right
[PROOF STATE]
proof (prove)
using this:
u \<in> U
T \<equiv> (\<sharp>\<cdot>) ((1::'f) / ordG) \<circ> sum CP G
CP \<equiv> \<lambda>g. (*\<cdot>) (- g) \<circ> P \<circ> (*\<cdot>) g
P \<equiv> \<lambda>a. if a \<in> (\<Oplus>G\<leftarrow>[W, U]. G) then W\<oplus>U\<leftarrow> a ! 1 else (0::'v)
VectorSpace (\<sharp>\<cdot>) W
RModule FG (\<cdot>) U \<and> U \<subseteq> V
add_independentS [W, U]
u \<in> U
RModule FG (\<cdot>) ?U \<and> ?U \<subseteq> V \<Longrightarrow> FinGroupRepresentation G (\<cdot>) ?U
\<lbrakk>FinGroupRepresentation ?G ?smult ?V; VectorSpace (aezfun_scalar_mult.fsmult ?smult) ?W; add_independentS [?W, ?V]; ?v \<in> ?V\<rbrakk> \<Longrightarrow> (aezfun_scalar_mult.fsmult ?smult ((1::?'f) / of_nat (card ?G)) \<circ> (\<Sum>g\<in>?G. aezfun_scalar_mult.Gmult ?smult (- g) \<circ> (\<lambda>a. if a \<in> (\<Oplus>G\<leftarrow>[?W, ?V]. G) then ?W\<oplus>?V\<leftarrow> a ! 1 else (0::?'v)) \<circ> aezfun_scalar_mult.Gmult ?smult g)) ?v = ?v
goal (1 subgoal):
1. T u = u
[PROOF STEP]
by fast
[PROOF STATE]
proof (state)
this:
T u = u
goal (1 subgoal):
1. \<And>x. x \<in> U \<Longrightarrow> x \<in> T ` V
[PROOF STEP]
from this[THEN sym] assms(1-4) u
[PROOF STATE]
proof (chain)
picking this:
u = T u
VectorSpace (\<sharp>\<cdot>) W
RModule FG (\<cdot>) U \<and> U \<subseteq> V
add_independentS [W, U]
V = W \<oplus> U
u \<in> U
[PROOF STEP]
show "u \<in> T ` V"
[PROOF STATE]
proof (prove)
using this:
u = T u
VectorSpace (\<sharp>\<cdot>) W
RModule FG (\<cdot>) U \<and> U \<subseteq> V
add_independentS [W, U]
V = W \<oplus> U
u \<in> U
goal (1 subgoal):
1. u \<in> T ` V
[PROOF STEP]
using Module.AbGroup RModule.AbGroup AbGroup_subset_inner_dirsum
[PROOF STATE]
proof (prove)
using this:
u = T u
VectorSpace (\<sharp>\<cdot>) W
RModule FG (\<cdot>) U \<and> U \<subseteq> V
add_independentS [W, U]
V = W \<oplus> U
u \<in> U
Module ?smult ?M \<Longrightarrow> AbGroup ?M
RModule ?R ?smult ?M \<Longrightarrow> AbGroup ?M
\<lbrakk>\<forall>G\<in>set ?Gs. AbGroup G; add_independentS ?Gs; ?H \<in> set ?Gs\<rbrakk> \<Longrightarrow> ?H \<subseteq> (\<Oplus>G\<leftarrow>?Gs. G)
goal (1 subgoal):
1. u \<in> T ` V
[PROOF STEP]
by fast
[PROOF STATE]
proof (state)
this:
u \<in> T ` V
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
U \<subseteq> T ` V
goal:
No subgoals!
[PROOF STEP]
qed |
'''
This module is no longer used
'''
from __future__ import absolute_import
import os
import numpy as np
import itertools
FEATURES_TO_INCLUDE=["score"]
class windowAl2co(object):
def __init__(self, winSize):
self.winSize= winSize
self.noProfileWin=[ 0.0 for feat in FEATURES_TO_INCLUDE]
def compute(self,inName,outName):
prefix, chainType, f_chain, rest = os.path.split(inName)[-1].split("_")
winSizeStep= int(self.winSize/2)
profile=[]
letras=[]
ids=[]
f=open(inName)
header=f.readline().split()
resIdIndex= header.index("structResId")
letterIndex= header.index("resName")
featuresIndices= []
for featName in FEATURES_TO_INCLUDE:
featuresIndices.append(header.index(featName))
for line in f:
## print( [line])
lineArray= line.split()
if len(lineArray)!=0:
resInd=lineArray[resIdIndex]
letras.append(lineArray[letterIndex])
# print(lineArray, len(lineArray), firstValueIndex, firstValueIndex+self.numProfileElem)
# print (lineArray[firstValueIndex:(firstValueIndex+self.numProfileElem)])
profile.append([float(lineArray[i]) for i in featuresIndices])
ids.append((f_chain,resInd))
f.close()
numElements= len(ids)
myProfile={}
myLetters={}
mean_of_profile={}
for resNum,resId in enumerate(ids):
myProfile[resId]=[ profile[i] if (i>=0 and i<= numElements-1) else self.noProfileWin
for i in range(resNum-winSizeStep, resNum+winSizeStep+1)]
myLetters[resId]= [letras[resNum]]
mean_of_profile[resId]= np.mean(myProfile[resId])
mean_of_means_of_profile= np.mean(list(mean_of_profile.values()))
sigma_of_means_of_profile= np.std(list(mean_of_profile.values()))
outFile= open(outName,"w")
for resId in sorted(ids):
header= ["chainId structResId resName"] + list(itertools.chain.from_iterable
([FEATURES_TO_INCLUDE for i in range(self.winSize)])) + \
["winAverage", "winAverageNormalized"]
outFile.write( " ".join(header)+"\n")
out= list(resId)+myLetters[resId]+list(itertools.chain.from_iterable(myProfile[resId])) + [mean_of_profile[resId]] + \
[ (mean_of_profile[resId] - mean_of_means_of_profile)/ sigma_of_means_of_profile ]
out= [str(val) for val in out]
outFile.write( " ".join(out)+"\n")
break
for resId in sorted(ids):
out= list(resId)+myLetters[resId]+list(itertools.chain.from_iterable(myProfile[resId])) + [mean_of_profile[resId]] + \
[ (mean_of_profile[resId] - mean_of_means_of_profile)/ sigma_of_means_of_profile ]
out= [str(val) for val in out]
outFile.write( " ".join(out)+"\n")
outFile.close()
def windowAllAl2co(inputDir, outPutDir, wsize):
inputDir= os.path.expanduser(inputDir)
outPutDir= os.path.expanduser(outPutDir)
if not os.path.isdir(outPutDir):
os.makedirs(outPutDir)
for fname in os.listdir(inputDir):
print( fname)
inName= os.path.join(inputDir, fname)
prefixAndChainInfo= fname.split(".")[0]
prefixAndChainInfo+= ".wsize"+str(wsize)+".winAl2co.tab"
outName= os.path.join(outPutDir, prefixAndChainInfo)
windowAl2co(wsize).compute(inName,outName)
return None
def test():
# inName= "/home/rsanchez/Tesis/rriPredMethod/data/ppdockingBenchData/computedFeatures/seqStep/conservation/al2co/1A2K_l_A_u.al2co"
# outName= "/home/rsanchez/Tesis/rriPredMethod/data/ppdockingBenchData/computedFeatures/seqStep/conservation/winAl2co/1A2K_l_A_u.al2coWinPrueba"
# windowAl2co(5).compute(inName,outName)
inputDir= "~/Tesis/rriPredMethod/data/ppdockingBenchData/computedFeatures/seqStep/conservation/al2co/"
outPutDir= "~/Tesis/rriPredMethod/data/ppdockingBenchData/computedFeatures/seqStep/conservation/winAl2co"
windowAllAl2co(inputDir, outPutDir, wsize= 11)
if __name__== "__main__":
test()
|
import mcl.defs
import mcl.rhl
import parlang.defs
import syncablep
import mcl.compute_list
import mcl.ts_updates
open mcl
open mcl.mclk
open mcl.rhl
namespace assign_mcl
open parlang
open parlang.state
open parlang.thread_state
/- not in use -/
-- lemma store_access_elim_name {sig : signature} {n n_idx} {s : state n (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)} {var} {idx : vector (expression sig type.int) n_idx}
-- {t h₄} {h₃ : type_of (sig.val var) = t } {f} {t : fin n} {i} {ac₁ : vector bool n} {updates}
-- (h₁ : i ∉ accesses (vector.nth ((map_active_threads ac₁ (f ∘ compute_list updates) s).threads) t))
-- (h₂ : i.1 ≠ var) :
-- i ∉ accesses (vector.nth ((map_active_threads ac₁ (f ∘ (thread_state.tlocal_to_shared var idx h₃ h₄) ∘ compute_list updates) s).threads) t) := begin
-- sorry,
-- end
-- lemma store_no_stores_name {sig : signature} {dim} {idx : vector (expression sig type.int) dim} {var t} {h₁ : type_of (sig.val var) = t} {h₂} {computes : list (memory (parlang_mcl_tlocal sig) → memory (parlang_mcl_tlocal sig))}
-- {ts : thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)} {i : mcl_address sig}
-- {n} {s : state n (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)} {m : memory (parlang_mcl_shared sig)} {tid}
-- {f : thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig) → thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)} :
-- syncable ((f ∘ compute_list computes) s) m →
-- i.fst ≠ var →
-- i ∉ ((f ∘ compute_list computes) (s.threads.nth tid)).stores →
-- i ∉ ((f ∘ thread_state.tlocal_to_shared var idx h₁ h₂ ∘ compute_list computes) (s.threads.nth tid)).stores := begin
-- intros syncable i_not_var i_not_in_f,
-- unfold parlang.state.syncable at syncable,
-- specialize syncable i,
-- cases ts,
-- induction computes,
-- {
-- simp [compute_list, thread_state.tlocal_to_shared, store],
-- }, {
-- }
-- end
end assign_mcl |
(*
File: CompleteOrder.thy
Author: Bohua Zhan
Results about Cauchy completeness and completeness of ordered fields.
*)
theory CompleteOrder
imports SeqRing
begin
section \<open>Cauchy completeness\<close>
definition cauchy_complete_field :: "i \<Rightarrow> o" where [rewrite]:
"cauchy_complete_field(R) \<longleftrightarrow> (is_ord_field(R) \<and> (\<forall>X\<in>seqs(R). cauchy(X) \<longrightarrow> converges(X)))"
lemma cauchy_completeD [forward]:
"cauchy_complete_field(R) \<Longrightarrow> is_ord_field(R)"
"is_sequence(X) \<Longrightarrow> cauchy(X) \<Longrightarrow> cauchy_complete_field(target_str(X)) \<Longrightarrow> converges(X)" by auto2+
lemma cauchy_completeI [forward]:
"is_ord_field(R) \<Longrightarrow> \<forall>X\<in>seqs(R). cauchy(X) \<longrightarrow> converges(X) \<Longrightarrow> cauchy_complete_field(R)" by auto2
setup {* del_prfstep_thm @{thm cauchy_complete_field_def} *}
section \<open>Monotone convergence theorem\<close>
lemma seq_has_increment_induct [backward1]:
"ord_ring_seq(X) \<Longrightarrow> R = target_str(X) \<Longrightarrow> k \<in>. \<nat> \<Longrightarrow> N \<in> nat \<Longrightarrow> a >\<^sub>R \<zero>\<^sub>R \<Longrightarrow>
\<forall>k\<in>.\<nat>. \<exists>n\<ge>\<^sub>\<nat>k. X`n -\<^sub>R X`k \<ge>\<^sub>R a \<Longrightarrow> \<exists>n\<ge>\<^sub>\<nat>k. X`n -\<^sub>R X`k \<ge>\<^sub>R of_nat(R,N) *\<^sub>R a"
@proof
@var_induct "N \<in> nat" arbitrary k @with
@subgoal "N = N' +\<^sub>\<nat> 1"
@obtain k1 where "k1\<ge>\<^sub>\<nat>k" "X`k1 -\<^sub>R X`k \<ge>\<^sub>R of_nat(R,N') *\<^sub>R a"
@obtain k2 where "k2\<ge>\<^sub>\<nat>k1" "X`k2 -\<^sub>R X`k1 \<ge>\<^sub>R a"
@have "X`k2 -\<^sub>R X`k = (X`k2 -\<^sub>R X`k1) +\<^sub>R (X`k1 -\<^sub>R X`k)"
@have "(of_nat(R,N') +\<^sub>R 1\<^sub>R) *\<^sub>R a = a +\<^sub>R of_nat(R,N') *\<^sub>R a"
@endgoal
@end
@qed
lemma monotone_cauchy [forward]:
"ord_field_seq(X) \<Longrightarrow> seq_incr(X) \<Longrightarrow> upper_bounded(X) \<Longrightarrow> R = target_str(X) \<Longrightarrow>
is_archimedean(R) \<Longrightarrow> cauchy(X)"
@proof
@contradiction
@obtain a where "a >\<^sub>R \<zero>\<^sub>R" "\<forall>k\<in>.\<nat>. \<exists>n\<ge>\<^sub>\<nat>k. \<bar>X`n -\<^sub>R X`k\<bar>\<^sub>R \<ge>\<^sub>R a"
@have "\<forall>k\<in>.\<nat>. \<exists>n\<ge>\<^sub>\<nat>k. X`n -\<^sub>R X`k \<ge>\<^sub>R a"
@obtain "M\<in>.R" where "\<forall>n\<in>.\<nat>. X`n \<le>\<^sub>R M"
@obtain "N\<in>nat" where "of_nat(R,N) *\<^sub>R a >\<^sub>R (M -\<^sub>R X`0)"
@obtain n where "n \<ge>\<^sub>\<nat> 0" "X`n -\<^sub>R X`0 \<ge>\<^sub>R of_nat(R,N) *\<^sub>R a" @have "X`n \<le>\<^sub>R M"
@qed
lemma monotone_incr_converges [forward]:
"is_sequence(X) \<Longrightarrow> seq_incr(X) \<Longrightarrow> upper_bounded(X) \<Longrightarrow> R = target_str(X) \<Longrightarrow>
cauchy_complete_field(R) \<Longrightarrow> is_archimedean(R) \<Longrightarrow> converges(X)" by auto2
lemma monotone_decr_converges [forward]:
"is_sequence(X) \<Longrightarrow> seq_decr(X) \<Longrightarrow> lower_bounded(X) \<Longrightarrow> R = target_str(X) \<Longrightarrow>
cauchy_complete_field(R) \<Longrightarrow> is_archimedean(R) \<Longrightarrow> converges(X)"
@proof @have "upper_bounded(seq_neg(X))" @have "seq_incr(seq_neg(X))" @qed
section \<open>A simple test for vanishing of sequences\<close>
definition half_seq :: "i \<Rightarrow> o" where [rewrite]:
"half_seq(X) \<longleftrightarrow> (let R = target_str(X) in \<forall>n\<in>.\<nat>. \<bar>X`(n +\<^sub>\<nat> 1)\<bar>\<^sub>R \<le>\<^sub>R \<bar>X`n\<bar>\<^sub>R /\<^sub>R 2\<^sub>R)"
lemma half_seqD:
"half_seq(X) \<Longrightarrow> R = target_str(X) \<Longrightarrow> n \<in>. \<nat> \<Longrightarrow> \<bar>X`(n +\<^sub>\<nat> 1)\<bar>\<^sub>R \<le>\<^sub>R \<bar>X`n\<bar>\<^sub>R /\<^sub>R 2\<^sub>R" by auto2
setup {* add_forward_prfstep_cond @{thm half_seqD} [with_term "\<bar>?X`(?n +\<^sub>\<nat> 1)\<bar>\<^sub>target_str(?X)"] *}
lemma half_seqI [backward]:
"R = target_str(X) \<Longrightarrow> \<forall>n\<in>.\<nat>. \<bar>X`(n +\<^sub>\<nat> 1)\<bar>\<^sub>R \<le>\<^sub>R \<bar>X`n\<bar>\<^sub>R /\<^sub>R 2\<^sub>R \<Longrightarrow> half_seq(X)" by auto2
setup {* del_prfstep_thm @{thm half_seq_def} *}
lemma ord_field_divide_le_trans1 [backward1]:
"is_ord_field(R) \<Longrightarrow> d \<in>. R \<Longrightarrow> c >\<^sub>R \<zero>\<^sub>R \<Longrightarrow> e >\<^sub>R \<zero>\<^sub>R \<Longrightarrow> a \<le>\<^sub>R b /\<^sub>R c \<Longrightarrow>
b \<le>\<^sub>R d /\<^sub>R e \<Longrightarrow> a \<le>\<^sub>R d /\<^sub>R (e *\<^sub>R c)"
@proof @have "a *\<^sub>R c \<le>\<^sub>R b" @have "a \<le>\<^sub>R d /\<^sub>R e /\<^sub>R c" @qed
lemma half_seq_induct [resolve]:
"ord_field_seq(X) \<Longrightarrow> R = target_str(X) \<Longrightarrow> half_seq(X) \<Longrightarrow> n \<in> nat \<Longrightarrow>
\<bar>X`n\<bar>\<^sub>R \<le>\<^sub>R \<bar>X`0\<bar>\<^sub>R /\<^sub>R (2\<^sub>R ^\<^sub>R n)"
@proof @var_induct "n \<in> nat" @qed
setup {* del_prfstep_thm @{thm ord_field_divide_le_trans1} *}
lemma half_seq_abs_decr [forward]:
"ord_field_seq(X) \<Longrightarrow> R = target_str(X) \<Longrightarrow> half_seq(X) \<Longrightarrow> seq_abs_decr(X)"
@proof @have "\<forall>n\<in>.\<nat>. \<bar>X`(n +\<^sub>\<nat> 1)\<bar>\<^sub>R \<le>\<^sub>R \<bar>X`n\<bar>\<^sub>R" @qed
lemma ord_field_divide_le_trans2 [forward]:
"is_ord_field(R) \<Longrightarrow> b \<in>. R \<Longrightarrow> a >\<^sub>R b /\<^sub>R c \<Longrightarrow> d \<le>\<^sub>R b /\<^sub>R a \<Longrightarrow> a >\<^sub>R \<zero>\<^sub>R \<Longrightarrow> c >\<^sub>R \<zero>\<^sub>R \<Longrightarrow> c >\<^sub>R d"
@proof
@have "a *\<^sub>R c >\<^sub>R b" @have "d *\<^sub>R a \<le>\<^sub>R b" @have "a *\<^sub>R c >\<^sub>R a *\<^sub>R d"
@qed
lemma half_seq_vanishes [forward]:
"ord_field_seq(X) \<Longrightarrow> R = target_str(X) \<Longrightarrow> half_seq(X) \<Longrightarrow> is_archimedean(R) \<Longrightarrow> vanishes(X)"
@proof
@have "\<forall>r. r >\<^sub>R \<zero>\<^sub>R \<longrightarrow> (\<exists>k\<in>.\<nat>. \<forall>n\<ge>\<^sub>\<nat>k. \<bar>X`n\<bar>\<^sub>R <\<^sub>R r)" @with
@obtain "k\<in>nat" where "2\<^sub>R ^\<^sub>R k >\<^sub>R \<bar>X`0\<bar>\<^sub>R /\<^sub>R r"
@have "\<forall>n\<ge>\<^sub>\<nat>k. \<bar>X`n\<bar>\<^sub>R <\<^sub>R r" @with
@have "\<bar>X`k\<bar>\<^sub>R \<le>\<^sub>R \<bar>X`0\<bar>\<^sub>R /\<^sub>R (2\<^sub>R ^\<^sub>R k)"
@have "\<bar>X`n\<bar>\<^sub>R \<le>\<^sub>R \<bar>X`k\<bar>\<^sub>R" @end @end
@qed
setup {* del_prfstep_thm @{thm ord_field_divide_le_trans2} *}
section \<open>Dedekind cut\<close>
(* A dedekind cut is a set that is closed downward and has no greatest element *)
definition dedekind_cut :: "i \<Rightarrow> i \<Rightarrow> o" where [rewrite]:
"dedekind_cut(R,U) \<longleftrightarrow> (U \<noteq> \<emptyset> \<and> U \<subset> carrier(R) \<and> (\<forall>a\<in>U. \<forall>b \<le>\<^sub>R a. b \<in> U) \<and> (\<forall>a\<in>U. \<exists>b >\<^sub>R a. b\<in>U))"
lemma dedekind_cutI1 [forward]:
"dedekind_cut(R,U) \<Longrightarrow> a \<in> U \<Longrightarrow> \<forall>b \<le>\<^sub>R a. b \<in> U" by auto2
lemma dedekind_cutI2 [backward2]:
"dedekind_cut(R,U) \<Longrightarrow> a \<in> U \<Longrightarrow> \<exists>b >\<^sub>R a. b \<in> U" by auto2
lemma dedekind_cutI_ex [resolve]:
"dedekind_cut(R,U) \<Longrightarrow> \<exists>x\<in>.R. x \<in> U" by auto2
lemma dedekind_cutI_ex2 [resolve]:
"dedekind_cut(R,U) \<Longrightarrow> \<exists>x\<in>.R. x \<notin> U" by auto2
setup {* del_prfstep_thm_eqforward @{thm dedekind_cut_def} *}
(* For any dedekind cut, we define two sequences converging to the boundary point. *)
definition DCSeqs :: "i \<Rightarrow> i \<Rightarrow> i" where [rewrite]:
"DCSeqs(R,U) = Seq_rec2(R,
SOME a\<in>.R. a \<in> U, \<lambda>x p q. if avg(R,p,q) \<notin> U then p else avg(R,p,q),
SOME b\<in>.R. b \<notin> U, \<lambda>x p q. if avg(R,p,q) \<notin> U then avg(R,p,q) else q)"
lemma DCSeqs_type [forward]:
"is_ord_field(R) \<Longrightarrow> dedekind_cut(R,U) \<Longrightarrow> A = fst(DCSeqs(R,U)) \<Longrightarrow> B = snd(DCSeqs(R,U)) \<Longrightarrow>
A \<in> seqs(R) \<and> B \<in> seqs(R) \<and> A`0 \<in> U \<and> B`0 \<notin> U" by auto2
lemma DCSeqs_eval1 [rewrite]:
"is_ord_field(R) \<Longrightarrow> n \<in>. \<nat> \<Longrightarrow> dedekind_cut(R,U) \<Longrightarrow> A = fst(DCSeqs(R,U)) \<Longrightarrow> B = snd(DCSeqs(R,U)) \<Longrightarrow>
A`(n +\<^sub>\<nat> 1) = (if avg(R,A`n,B`n) \<notin> U then A`n else avg(R,A`n,B`n))" by auto2
lemma DCSeqs_eval2 [rewrite]:
"is_ord_field(R) \<Longrightarrow> n \<in>. \<nat> \<Longrightarrow> dedekind_cut(R,U) \<Longrightarrow> A = fst(DCSeqs(R,U)) \<Longrightarrow> B = snd(DCSeqs(R,U)) \<Longrightarrow>
B`(n +\<^sub>\<nat> 1) = (if avg(R,A`n,B`n) \<notin> U then avg(R,A`n,B`n) else B`n)" by auto2
setup {* del_prfstep_thm @{thm DCSeqs_def} *}
lemma DCSeqs_le [backward]:
"is_ord_field(R) \<Longrightarrow> is_archimedean(R) \<Longrightarrow> A = fst(DCSeqs(R,U)) \<Longrightarrow> B = snd(DCSeqs(R,U)) \<Longrightarrow>
n \<in> source(A) \<Longrightarrow> n \<in> source(B) \<Longrightarrow> dedekind_cut(R,U) \<Longrightarrow> A`n \<le>\<^sub>R B`n"
@proof @var_induct "n \<in> nat" @qed
lemma dedekind_complete [resolve]:
"cauchy_complete_field(R) \<Longrightarrow> is_archimedean(R) \<Longrightarrow> dedekind_cut(R,U) \<Longrightarrow> \<exists>x\<in>.R. \<forall>y\<in>.R. y <\<^sub>R x \<longleftrightarrow> y \<in> U"
@proof
@let "A = fst(DCSeqs(R,U))" "B = snd(DCSeqs(R,U))"
@have "converges(A)" @with
@have "seq_incr(A)" @with @have "\<forall>n\<in>.\<nat>. A`(n +\<^sub>\<nat> 1) \<ge>\<^sub>R A`n" @end
@have "upper_bounded(A)" @with
@have "\<forall>n\<in>.\<nat>. A`n \<le>\<^sub>R B`0" @with @var_induct "n \<in>. \<nat>" @end @end @end
@have "converges(B)" @with
@have "seq_decr(B)" @with @have "\<forall>n\<in>.\<nat>. B`(n +\<^sub>\<nat> 1) \<le>\<^sub>R B`n" @end
@have "lower_bounded(B)" @with
@have "\<forall>n\<in>.\<nat>. B`n \<ge>\<^sub>R A`0" @with @var_induct "n \<in>. \<nat>" @end @end @end
@obtain x where "converges_to(B,x)"
@let "S = seq_ring(R)"
@have "vanishes(B -\<^sub>S A)" @with @have "half_seq(B -\<^sub>S A)" @end
@have (@rule) "\<forall>n\<in>nat. A`n \<in> U" @with @var_induct "n \<in> nat" @end
@have (@rule) "\<forall>n\<in>nat. B`n \<notin> U" @with @var_induct "n \<in> nat" @end
@have "\<forall>y\<in>.R. y <\<^sub>R x \<longleftrightarrow> y \<in> U" @with
@case "y <\<^sub>R x" @with @obtain "n\<in>nat" where "y <\<^sub>R A`n" @end
@case "y \<in> U" @with
@have "x \<in> U" @obtain x' where "x' >\<^sub>R x" "x' \<in> U"
@obtain "n\<in>nat" where "x' >\<^sub>R B`n" @have "B`n \<notin> U"
@end
@end
@qed
section \<open>Least upper bound property\<close>
lemma least_upper_bound_complete [forward]:
"cauchy_complete_field(R) \<Longrightarrow> is_archimedean(R) \<Longrightarrow> S \<noteq> \<emptyset> \<Longrightarrow> upper_bound(R,S) \<noteq> \<emptyset> \<Longrightarrow> has_sup(R,S)"
@proof
@let "U = carrier(R) \<midarrow> upper_bound(R,S)"
@have "dedekind_cut(R,U)" @with
@have "U \<noteq> \<emptyset>" @with
@obtain "x \<in> S" @obtain y where "y <\<^sub>R x" @have "y \<in> U" @end
@have "U \<noteq> carrier(R)" @with
@obtain "z \<in> upper_bound(R,S)" @have "z \<notin> U" @end
@have "\<forall>a\<in>U. \<exists>b >\<^sub>R a. b \<in> U" @with
@obtain "c \<in> S" where "a <\<^sub>R c" @obtain b where "a <\<^sub>R b \<and> b <\<^sub>R c" @have "b \<in> U" @end @end
@obtain "y\<in>.R" where "\<forall>z\<in>.R. z <\<^sub>R y \<longleftrightarrow> z \<in> U"
@have "y \<notin> U" @have "y \<in> upper_bound(R,S)"
@have "has_sup(R,S) \<and> sup(R,S) = y"
@qed
lemma complete_to_linear_continuum [forward]:
"cauchy_complete_field(R) \<Longrightarrow> is_archimedean(R) \<Longrightarrow> linear_continuum(R)"
@proof @have "\<forall>S. S \<noteq> \<emptyset> \<longrightarrow> upper_bound(R,S) \<noteq> \<emptyset> \<longrightarrow> has_sup(R,S)" @qed
end
|
! PR tree-optimization/29581
! { dg-do run }
! { dg-skip-if "" { *-*-* } { "-O0" } { "" } }
! { dg-additional-options "-ftree-loop-linear" }
SUBROUTINE FOO (K)
INTEGER I, J, K, A(5,5), B
COMMON A
A(1,1) = 1
10 B = 0
DO 30 I = 1, K
DO 20 J = 1, K
B = B + A(I,J)
20 CONTINUE
A(I,I) = A(I,I) * 2
30 CONTINUE
IF (B.GE.3) RETURN
GO TO 10
END SUBROUTINE
PROGRAM BAR
INTEGER A(5,5)
COMMON A
CALL FOO (2)
IF (A(1,1).NE.8) STOP 1
A(1,1) = 0
IF (ANY(A.NE.0)) STOP 2
END
|
!--------------------------------------------------------------------
!
!
! PURPOSE
!
! This program solves nonlinear Klein-Gordon equation in 3 dimensions
! u_{tt}-(u_{xx}+u_{yy}+u_{zz})+u=Es*|u|^2u
! using a second order implicit-explicit time stepping scheme.
!
! The boundary conditions are u(x=-Lx*pi,y,z)=u(x=Lx*\pi,y,z),
! u(x,y=-Ly*pi,z)=u(x,y=Ly*pi,z),u(x,y,z=-Ly*pi)=u(x,y,z=Ly*pi),
! The initial condition is u=0.5*exp(-x^2-y^2-z^2)*sin(10*x+12*y)
!
! .. Parameters ..
! Nx = number of modes in x - power of 2 for FFT
! Ny = number of modes in y - power of 2 for FFT
! Nz = number of modes in z - power of 2 for FFT
! Nt = number of timesteps to take
! Tmax = maximum simulation time
! plotgap = number of timesteps between plots
! pi = 3.14159265358979323846264338327950288419716939937510d0
! Lx = width of box in x direction
! Ly = width of box in y direction
! Lz = width of box in z direction
! ES = +1 for focusing and -1 for defocusing
! .. Scalars ..
! i = loop counter in x direction
! j = loop counter in y direction
! k = loop counter in z direction
! n = loop counter for timesteps direction
! allocatestatus = error indicator during allocation
! start = variable to record start time of program
! finish = variable to record end time of program
! count_rate = variable for clock count rate
! dt = timestep
! modescalereal = Number to scale after backward FFT
! ierr = error code
! plotnum = number of plot
! myid = Process id
! p_row = number of rows for domain decomposition
! p_col = number of columns for domain decomposition
! filesize = total filesize
! disp = displacement to start writing data from
! .. Arrays ..
! unew = approximate solution
! vnew = Fourier transform of approximate solution
! u = approximate solution
! v = Fourier transform of approximate solution
! uold = approximate solution
! vold = Fourier transform of approximate solution
! nonlin = nonlinear term, u^3
! nonlinhat = Fourier transform of nonlinear term, u^3
! .. Vectors ..
! kx = fourier frequencies in x direction
! ky = fourier frequencies in y direction
! kz = fourier frequencies in z direction
! x = x locations
! y = y locations
! z = z locations
! time = times at which save data
! en = total energy
! enstr = strain energy
! enpot = potential energy
! enkin = kinetic energy
! name_config = array to store filename for data to be saved
! fftfxyz = array to setup 2D Fourier transform
! fftbxyz = array to setup 2D Fourier transform
! .. Special Structures ..
! decomp = contains information on domain decomposition
! see http://www.2decomp.org/ for more information
! REFERENCES
!
! ACKNOWLEDGEMENTS
!
! ACCURACY
!
! ERROR INDICATORS AND WARNINGS
!
! FURTHER COMMENTS
! Check that the initial iterate is consistent with the
! boundary conditions for the domain specified
!--------------------------------------------------------------------
! External routines required
! getgrid.f90 -- Get initial grid of points
! initialdata.f90 -- Get initial data
! enercalc.f90 -- Subroutine to calculate the energy
! savedata.f90 -- Save initial data
! storeold.f90 -- Store old data
! External libraries required
! 2DECOMP&FFT -- Domain decomposition and Fast Fourier Library
! (http://www.2decomp.org/index.html)
! MPI library
PROGRAM Kg
use decomp_2d
use decomp_2d_fft
use decomp_2d_io
!coprocessing:
use KGadaptor_module
implicit none
INCLUDE 'mpif.h'
! Declare variables
INTEGER(kind=4) :: Nx, Ny, Nz, Nt, plotgap
REAL(kind=8), PARAMETER :: &
pi=3.14159265358979323846264338327950288419716939937510d0
REAL(kind=8) :: Lx,Ly,Lz,Es,dt,starttime,modescalereal
COMPLEX(kind=8), DIMENSION(:), ALLOCATABLE :: kx,ky,kz
REAL(kind=8), DIMENSION(:), ALLOCATABLE :: x,y,z
COMPLEX(kind=8), DIMENSION(:,:,:), ALLOCATABLE:: u,nonlin
COMPLEX(kind=8), DIMENSION(:,:,:), ALLOCATABLE:: v,nonlinhat
COMPLEX(kind=8), DIMENSION(:,:,:), ALLOCATABLE:: uold
COMPLEX(kind=8), DIMENSION(:,:,:), ALLOCATABLE:: vold
COMPLEX(kind=8), DIMENSION(:,:,:), ALLOCATABLE:: unew
COMPLEX(kind=8), DIMENSION(:,:,:), ALLOCATABLE:: vnew
REAL(kind=8), DIMENSION(:,:,:), ALLOCATABLE :: savearray
REAL(kind=8), DIMENSION(:), ALLOCATABLE :: time,enkin,enstr,enpot,en
INTEGER(kind=4) :: ierr,i,j,k,n,allocatestatus,myid,numprocs
INTEGER(kind=4) :: start, finish, count_rate, plotnum
TYPE(DECOMP_INFO) :: decomp
INTEGER(kind=MPI_OFFSET_KIND) :: filesize, disp
INTEGER(kind=4) :: p_row=0, p_col=0
CHARACTER*100 :: name_config
! initialisation of 2DECOMP&FFT
CALL MPI_INIT(ierr)
CALL MPI_COMM_SIZE(MPI_COMM_WORLD, numprocs, ierr)
CALL MPI_COMM_RANK(MPI_COMM_WORLD, myid, ierr)
CALL readinputfile(Nx,Ny,Nz,Nt,plotgap,Lx,Ly,Lz, &
Es,DT,starttime,myid,ierr)
! do automatic domain decomposition
CALL decomp_2d_init(Nx,Ny,Nz,p_row,p_col)
! get information about domain decomposition choosen
CALL decomp_info_init(Nx,Ny,Nz,decomp)
! initialise FFT library
CALL decomp_2d_fft_init
ALLOCATE(kx(decomp%zst(1):decomp%zen(1)),&
ky(decomp%zst(2):decomp%zen(2)),&
kz(decomp%zst(3):decomp%zen(3)),&
x(decomp%xst(1):decomp%xen(1)),&
y(decomp%xst(2):decomp%xen(2)),&
z(decomp%xst(3):decomp%xen(3)),&
u(decomp%xst(1):decomp%xen(1),&
decomp%xst(2):decomp%xen(2),&
decomp%xst(3):decomp%xen(3)),&
v(decomp%zst(1):decomp%zen(1),&
decomp%zst(2):decomp%zen(2),&
decomp%zst(3):decomp%zen(3)),&
nonlin(decomp%xst(1):decomp%xen(1),&
decomp%xst(2):decomp%xen(2),&
decomp%xst(3):decomp%xen(3)),&
nonlinhat(decomp%zst(1):decomp%zen(1),&
decomp%zst(2):decomp%zen(2),&
decomp%zst(3):decomp%zen(3)),&
uold(decomp%xst(1):decomp%xen(1),&
decomp%xst(2):decomp%xen(2),&
decomp%xst(3):decomp%xen(3)),&
vold(decomp%zst(1):decomp%zen(1),&
decomp%zst(2):decomp%zen(2),&
decomp%zst(3):decomp%zen(3)),&
unew(decomp%xst(1):decomp%xen(1),&
decomp%xst(2):decomp%xen(2),&
decomp%xst(3):decomp%xen(3)),&
vnew(decomp%zst(1):decomp%zen(1),&
decomp%zst(2):decomp%zen(2),&
decomp%zst(3):decomp%zen(3)),&
savearray(decomp%xst(1):decomp%xen(1),&
decomp%xst(2):decomp%xen(2),&
decomp%xst(3):decomp%xen(3)),&
time(1:1+Nt/plotgap),enkin(1:1+Nt/plotgap),&
enstr(1:1+Nt/plotgap),enpot(1:1+Nt/plotgap),&
en(1:1+Nt/plotgap),stat=allocatestatus)
IF (allocatestatus .ne. 0) stop
IF (myid.eq.0) THEN
PRINT *,'allocated arrays'
END IF
! setup fourier frequencies
CALL getgrid(myid,Nx,Ny,Nz,Lx,Ly,Lz,pi,name_config,x,y,z,kx,ky,kz,decomp)
IF (myid.eq.0) THEN
PRINT *,'Setup grid and fourier frequencies'
END IF
CALL initialdata(Nx,Ny,Nz,x,y,z,u,uold,decomp)
plotnum=1
name_config = 'data/u'
savearray=REAL(u)
! CALL savedata(Nx,Ny,Nz,plotnum,name_config,savearray,decomp)
CALL decomp_2d_fft_3d(u,v,DECOMP_2D_FFT_FORWARD)
CALL decomp_2d_fft_3d(uold,vold,DECOMP_2D_FFT_FORWARD)
modescalereal=1.0d0/REAL(Nx,KIND(0d0))
modescalereal=modescalereal/REAL(Ny,KIND(0d0))
modescalereal=modescalereal/REAL(Nz,KIND(0d0))
CALL enercalc(myid,Nx,Ny,Nz,dt,Es,modescalereal,&
enkin(plotnum),enstr(plotnum),&
enpot(plotnum),en(plotnum),&
kx,ky,kz,nonlin,nonlinhat,&
v,vold,u,uold,decomp)
IF (myid.eq.0) THEN
PRINT *,'Got initial data, starting timestepping'
END IF
time(plotnum)=0.0d0+starttime
CALL system_clock(start,count_rate)
!coprocessing:
call coprocessorinitialize("pipeline.py", 11)
DO n=1,Nt
DO k=decomp%xst(3),decomp%xen(3)
DO j=decomp%xst(2),decomp%xen(2)
DO i=decomp%xst(1),decomp%xen(1)
nonlin(i,j,k)=(abs(u(i,j,k))*2)*u(i,j,k)
END DO
END DO
END DO
CALL decomp_2d_fft_3d(nonlin,nonlinhat,DECOMP_2D_FFT_FORWARD)
DO k=decomp%zst(3),decomp%zen(3)
DO j=decomp%zst(2),decomp%zen(2)
DO i=decomp%zst(1),decomp%zen(1)
vnew(i,j,k)=&
( 0.25*(kx(i)*kx(i) + ky(j)*ky(j)+ kz(k)*kz(k)-1.0d0)&
*(2.0d0*v(i,j,k)+vold(i,j,k))&
+(2.0d0*v(i,j,k)-vold(i,j,k))/(dt*dt)&
+Es*nonlinhat(i,j,k) )&
/(1/(dt*dt)-0.25*(kx(i)*kx(i)+ ky(j)*ky(j)+ kz(k)*kz(k)-1.0d0))
END DO
END DO
END DO
CALL decomp_2d_fft_3d(vnew,unew,DECOMP_2D_FFT_BACKWARD)
! normalize result
DO k=decomp%xst(3),decomp%xen(3)
DO j=decomp%xst(2),decomp%xen(2)
DO i=decomp%xst(1),decomp%xen(1)
unew(i,j,k)=unew(i,j,k)*modescalereal
END DO
END DO
END DO
IF (mod(n,plotgap)==0) THEN
plotnum=plotnum+1
time(plotnum)=n*dt+starttime
IF (myid.eq.0) THEN
PRINT *,'time',n*dt+starttime
END IF
CALL enercalc(myid,Nx,Ny,Nz,dt,Es,modescalereal,&
enkin(plotnum),enstr(plotnum),&
enpot(plotnum),en(plotnum),&
kx,ky,kz,nonlin,nonlinhat,&
vnew,v,unew,u,decomp)
savearray=REAL(unew,kind(0d0))
! CALL savedata(Nx,Ny,Nz,plotnum,name_config,savearray,decomp)
END IF
!coprocessing:
call KGadaptor(Nx, Ny, Nz, decomp%xst(1), decomp%xen(1), &
decomp%xst(2), decomp%xen(2), decomp%xst(3), decomp%xen(3), &
n, n*dt+starttime, savearray)
! .. Update old values ..
CALL storeold(Nx,Ny,Nz,unew,u,uold,vnew,v,vold,decomp)
END DO
!coprocessing:
call coprocessorfinalize()
CALL system_clock(finish,count_rate)
IF (myid.eq.0) THEN
PRINT *,'Finished time stepping'
PRINT*,'Program took ',&
REAL(finish-start,kind(0d0))/REAL(count_rate,kind(0d0)),&
'for Time stepping'
CALL saveresults(Nt,plotgap,time,en,enstr,enkin,enpot)
! Save times at which output was made in text format
PRINT *,'Saved data'
END IF
CALL decomp_2d_fft_finalize
CALL decomp_2d_finalize
DEALLOCATE(kx,ky,kz,x,y,z,u,v,nonlin,nonlinhat,savearray,&
uold,vold,unew,vnew,time,enkin,enstr,enpot,en,&
stat=allocatestatus)
IF (allocatestatus .ne. 0) STOP
IF (myid.eq.0) THEN
PRINT *,'Deallocated arrays'
PRINT *,'Program execution complete'
END IF
CALL MPI_FINALIZE(ierr)
END PROGRAM Kg
|
#pragma once
#include <gsl/gsl>
#include "halley/utils/utils.h"
#include "halley/data_structures/vector.h"
#include "halley/file/path.h"
#include "halley/data_structures/maybe.h"
namespace Halley {
class String;
class Path;
class FileSystem
{
public:
static bool exists(const Path& p);
static bool createDir(const Path& p);
static bool createParentDir(const Path& p);
static int64_t getLastWriteTime(const Path& p);
static bool isFile(const Path& p);
static bool isDirectory(const Path& p);
static void copyFile(const Path& src, const Path& dst);
static bool remove(const Path& path);
static void writeFile(const Path& path, gsl::span<const gsl::byte> data);
static void writeFile(const Path& path, const Bytes& data);
static void writeFile(const Path& path, const String& data);
static Bytes readFile(const Path& path);
static Vector<Path> enumerateDirectory(const Path& path);
static Path getRelative(const Path& path, const Path& parentPath);
static Path getAbsolute(const Path& path);
static size_t fileSize(const Path& path);
static Path getTemporaryPath();
static int runCommand(const String& command);
};
class ScopedTemporaryFile final {
public:
ScopedTemporaryFile();
ScopedTemporaryFile(const String& extension);
~ScopedTemporaryFile();
ScopedTemporaryFile(const ScopedTemporaryFile& other) = delete;
ScopedTemporaryFile(ScopedTemporaryFile&& other) noexcept;
ScopedTemporaryFile& operator=(const ScopedTemporaryFile& other) = delete;
ScopedTemporaryFile& operator=(ScopedTemporaryFile&& other) noexcept;
const Path& getPath() const;
private:
std::optional<Path> path;
};
}
|
!
! Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
! See https://llvm.org/LICENSE.txt for license information.
! SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
!
! test f2008 bessel_j1 intrinsic
program p
use ISO_C_BINDING
use check_mod
interface
subroutine get_expected_f( src1, expct, n ) bind(C)
use ISO_C_BINDING
type(C_PTR), value :: src1
type(C_PTR), value :: expct
integer(C_INT), value :: n
end subroutine
subroutine get_expected_d( src1, expct, n ) bind(C)
use ISO_C_BINDING
type(C_PTR), value :: src1
type(C_PTR), value :: expct
integer(C_INT), value :: n
end subroutine
end interface
integer, parameter :: N=22
real*4, target, dimension(N) :: r_src1
real*4, target, dimension(N) :: r_rslt
real*4, target, dimension(N) :: r_expct
real*8 :: valuer
real*8, target, dimension(N) :: d_src1
real*8, target, dimension(N) :: d_rslt
real*8, target, dimension(N) :: d_expct
real*8 :: value8
valuer = -.2
valued = -.2_8
do i = 0,N-1
r_src1(i+1) = valuer + i
d_src1(i+1) = valued + i
enddo
r_rslt = bessel_j1(r_src1)
d_rslt = bessel_j1(d_src1)
call get_expected_f(C_LOC(r_src1), C_LOC(r_expct), N)
call get_expected_d(C_LOC(d_src1), C_LOC(d_expct), N)
call checkr4( r_rslt, r_expct, N, rtoler=0.0000003)
call checkr8( d_rslt, d_expct, N, rtoler=0.0000003_8)
! print *, "r_expct:"
! print *, r_expct
! print *, "r_rslt:"
! print *, r_rslt
!
! print *, "d_expct:"
! print *, d_expct
! print *, "d_rslt:"
! print *, d_rslt
end program
|
import algebra.module
import analysis.inner_product_space.basic
import data.matrix.notation
import data.matrix.dmatrix
import linear_algebra.basic
import linear_algebra.bilinear_form
import linear_algebra.quadratic_form.basic
import linear_algebra.finsupp
import tactic
import linear_algebra.matrix.nonsingular_inverse
noncomputable theory
/-
According to Wikipedia, everyone's favourite reliable source of knowledge,
linear algebra studies linear equations and linear maps, representing them
in vector spaces and through matrices.
Vector spaces are special cases of modules where scalars live any semiring,
not necessarily a field.
-/
#print module
-- class module (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M]
-- extends distrib_mul_action R M := ...
/-
In other words: let `R` be a semiring and `M` have `0` and a commutative operator `+`,
then a module structure over `R` on `M` has a scalar multiplication `•` (`has_smul.smul`),
which satisfies the following identities:
-/
#check add_smul -- ∀ (r s : R) (x : M), (r + s) • x = r • x + s • x
#check smul_add -- ∀ (r : R) (x y : M), r • (x + y) = r • x + r • y
#check mul_smul -- ∀ (r s : R) (x : M), (r * s) • x = r • (s • x)
#check one_smul -- ∀ (x : M), 1 • x = x
#check zero_smul -- ∀ (x : M), 0 • x = 0
#check smul_zero -- ∀ (r : R), r • 0 = 0
/-
These equations define modules (and vector spaces).
-/
/-
The last two identities follow automatically from the previous if `M` has a negation operator,
turning it into an additive group, so the function `module.of_core` does the proofs for you:
-/
#check module.of_core
section module
/-
Typical examples of modules (and vector spaces):
-/
-- import algebra.pi_instances
variables {n : Type} [fintype n]
example : module ℕ (n → ℕ) := infer_instance -- Or as mathematicians commonly know it: `ℕ^n`.
example : module ℤ (n → ℤ) := infer_instance
example : module ℚ (n → ℚ) := infer_instance
/- If you want a specifically `k`-dimensional module, use `fin k` as the `fintype`. -/
example {k : ℕ} : module ℤ (fin k → ℤ) := infer_instance
variables {R M N : Type} [ring R] [add_comm_group M] [add_comm_group N] [module R M] [module R N]
example : module R R := infer_instance
example : module ℤ R := infer_instance
example : module R (M × N) := infer_instance
example : module R (M × N) := infer_instance
example {R' : Type} [comm_ring R'] (f : R →+* R') : module R R' := ring_hom.to_module f
/- To explicitly construct elements of `fin k → R`, use the following notation: -/
-- import data.matrix.notation
example : fin 4 → ℤ := ![1, 2, -4, 3]
end module
section linear_map
variables {R M : Type} [comm_ring R] [add_comm_group M] [module R M]
/-
Maps between modules that respect `+` and `•` are called `linear_map`,
and an `R`-linear map from `M` to `N` has notation `M →ₗ[R] N`:
-/
#print linear_map
/- They are bundled, meaning we define them by giving the map and the proofs simultaneously: -/
def twice : M →ₗ[R] M :=
{ to_fun := λ x, (2 : R) • x,
map_add' := λ x y, smul_add 2 x y,
map_smul' := λ s x, smul_comm 2 s x }
/- Linear maps can be applied as if they were functions: -/
#check twice (![37, 42] : fin 2 → ℚ)
/- Some basic operations on linear maps: -/
-- import linear_algebra.basic
#check linear_map.comp -- composition
#check linear_map.has_zero -- 0
#check linear_map.has_add -- (+)
#check linear_map.has_smul -- (•)
/-
A linear equivalence is an invertible linear map.
These are the correct notion of "isomorphism of modules".
-/
#print linear_equiv
/- The identity function is defined twice: once as linear map and once as linear equivalence. -/
#check linear_map.id
#check linear_equiv.refl
end linear_map
section submodule
variables {R M : Type} [comm_ring R] [add_comm_group M] [module R M]
/-
The submodules of a module `M` are subsets of `M` (i.e. elements of `set M`)
that are closed under the module operations `0`, `+` and `•`.
`subspace` is defined to be a special case of `submodule`.
-/
#print submodule
#print subspace
/-
Note that the `ideal`s of a ring `R` are defined to be exactly the `R`-submodules of `R`.
This should save us a lot of re-definition work.
-/
#print ideal
/-
You can directly define a submodule by giving its carrier subset and proving that
the carrier is closed under each operation:
-/
def zero_submodule : submodule R M :=
{ carrier := {0},
zero_mem' := by simp,
add_mem' := by { intros x y hx hy, simp at hx hy, simp [hx, hy] },
smul_mem' := by { intros r x hx, simp at hx, simp [hx] } }
/- There are many library functions for defining submodules: -/
variables (S T : submodule R M)
#check (twice.range : submodule R M) -- the image of `twice` in `M`
#check (twice.ker : submodule R M) -- the kernel of `twice` in `M`
#check submodule.span ℤ {(2 : ℤ)} -- also known as 2ℤ
#check S.map twice -- also known as {twice x | x ∈ S}
#check S.comap twice -- also known as {x | twice x ∈ S}
/- For submodule inclusion, we write `≤`: -/
#check S ≤ T
#check S < T
/- The zero submodule is written `⊥` and the whole module as a submodule is written `⊤`: -/
example {x : M} : x ∈ (⊥ : submodule R M) ↔ x = 0 := submodule.mem_bot R
example {x : M} : x ∈ (⊤ : submodule R M) := submodule.mem_top
/- Intersection and sum of submodules are usually written with the lattice operators `⊓` and `⊔`: -/
#check submodule.mem_inf -- x ∈ S ⊓ T ↔ x ∈ S ∧ x ∈ T
#check submodule.mem_sup -- x ∈ S ⊔ T ↔ ∃ (y ∈ S) (z ∈ T), x = y + z
/- The embedding of a submodule in the ambient space, is called `subtype`: -/
#check submodule.subtype
/- Finally, we can take the quotient modulo a submodule.
Note the nonstandard ⧸, typed with \quot .
-/
#check ℤ ⧸ submodule.span ℤ {(2 : ℤ)}
end submodule
section forms
variables {n R : Type} [comm_ring R] [fintype n]
/- In addition to linear maps, there are bilinear forms, quadratic forms and sesquilinear forms. -/
-- import linear_algebra.bilinear_form
-- import linear_algebra.quadratic_form
#check bilin_form
/- Defining a bilinear form works similarly to defining a linear map: -/
def dot_product : bilin_form R (n → R) :=
{ bilin := λ x y, matrix.dot_product x y,
bilin_add_left := matrix.add_dot_product,
bilin_smul_left := matrix.smul_dot_product,
bilin_add_right := matrix.dot_product_add,
bilin_smul_right := matrix.dot_product_smul }
/- Some other constructions on forms: -/
#check bilin_form.to_quadratic_form
#check quadratic_form.associated
#check quadratic_form.has_smul
#check quadratic_form.proj
end forms
section matrix
variables {m n R : Type} [fintype m] [fintype n] [comm_ring R]
/-
Matrices in mathlib are basically no more than a rectangular block of entries.
Under the hood, they are specified by a function taking a row and column,
and returning the entry at that index.
They are useful when you want to compute an invariant such as the determinant,
as these are typically noncomputable for linear maps.
A type of matrices `matrix m n α` requires that the types `m` and `n` of the indices
are `fintype`s, and there is no restriction on the type `α` of the entries.
-/
#print matrix
/-
Like vectors in `n → R`, matrices are typically indexed over `fin k`.
To define a matrix, you map the indexes to the entry:
-/
def example_matrix : matrix (fin 2) (fin 3) ℤ := λ i j, i + j
#eval example_matrix 1 2
/- Like vectors, we can use `![...]` notation to define matrices: -/
def other_example_matrix : matrix (fin 3) (fin 2) ℤ :=
![![0, 1],
![1, 2],
![2, 3]]
/- We have the 0 matrix and the sum of two matrices: -/
example (i j) : (0 : matrix m n R) i j = 0 := dmatrix.zero_apply i j
example (A B : matrix m n R) (i j) : (A + B) i j = A i j + B i j := dmatrix.add_apply A B i j
/-
Matrices have multiplication and transpose operators `matrix.mul` and `matrix.transpose`.
The following line allows `⬝` and `ᵀ` to stand for these two respectively:
-/
open_locale matrix
#check example_matrix ⬝ other_example_matrix
#check example_matrixᵀ
/- On square matrices, we have a semiring structure with `(*) = (⬝)` and `1` as the identity matrix. -/
#check matrix.semiring
/-
When working with matrices, a "vector" is always of the form `n → R`
where `n` is a `fintype`. The operations between matrices and vectors are defined.
-/
#check matrix.col -- turn a vector into a column matrix
#check matrix.row -- turn a vector into a row matrix
#check matrix.vec_mul_vec -- column vector times row vector
/-
You have to explicitly specify whether vectors are multiplied on the left or on the right:
-/
#check example_matrix.mul_vec -- (fin 3 → ℤ) → (fin 2 → ℤ), right multiplication
#check matrix.vec_mul _ example_matrix -- (fin 2 → ℤ) → (fin 3 → ℤ), left multiplication
/- You can convert a matrix to a linear map, which acts by right multiplication of vectors. -/
variables {M N : Type} [add_comm_group M] [add_comm_group N] [module R M] [module R N]
#check matrix.to_lin' -- matrix m n R → ((n → R) →ₗ[R] (m → R))
/-
Going between linear maps and matrices is an isomorphism,
as long as you have chosen a basis for each module.
-/
variables [decidable_eq m] [decidable_eq n]
variables (v : basis m R M) (w : basis n R N)
#check linear_map.to_matrix v w -- (M →ₗ[R] N) ≈ₗ[R] matrix n m R
/-
Invertible (i.e. nonsingular) matrices have an inverse operation denoted by `⁻¹`.
-/
#check matrix.inv_def
end matrix
section odds_and_ends
/- Other useful parts of the library: -/
-- import analysis.inner_product_space.basic
#print normed_space -- module with a norm
#print inner_product_space -- normed space with an inner product in ℝ or ℂ
#print finite_dimensional.finrank -- the rank (or dimension) of a space, as a natural number (infinity -> 0)
#print module.rank -- the rank (or dimension) of a module (or vector space), as a cardinal
end odds_and_ends
|
Find the best Poland WordPress web design companies in the agency listings below. You can narrow down your search by size, portfolio, services, budget and more to streamline the process.
Top Poland WordPress web design and development companies create customized designs that engage with your audience, drive conversions and increase sales. Their expert understanding of the WordPress platform makes it easy to create the digital destination that will resonate with your consumers. |
(**
CoLoR, a Coq library on rewriting and termination.
See the COPYRIGHTS and LICENSE files.
- Joerg Endrullis, 2008-07-28
- Frederic Blanqui, 2007-02-05
when the union of two wellfounded relations is wellfounded
*)
Set Implicit Arguments.
From Coq Require Import Lia Wellfounded.Union.
From CoLoR Require Import SN RelUtil LogicUtil AccUtil NotSN_IS ClassicUtil
LeastNat DepChoice.
Section S.
Variables (A : Type) (R S : relation A).
(***********************************************************************)
(** When the two relations commute. *)
Lemma SN_union_commut t :
(forall x, SN S x -> SN R x) -> SN S t -> R @ S << S @ R -> SN (R U S) t.
Proof.
intros h s c. apply Acc_transp_SN. rewrite transp_union. apply Acc_union.
intros x y. unfold transp. intros xy z yz.
assert (a : (R@S) x z). exists y. fo.
apply c in a. fo.
intros x hx. apply SN_Acc_transp. apply h. apply Acc_transp_SN. hyp.
apply SN_Acc_transp. hyp.
Qed.
Lemma WF_union_commut : WF R -> WF S -> R @ S << S @ R -> WF (R U S).
Proof.
intros R_wf S_wf commut. apply wf_transp_WF. rewrite transp_union.
apply wf_union. intros x y. unfold transp. intros xy z yz.
assert (a : (R@S) x z). exists y. fo.
apply commut in a. fo. apply WF_wf_transp. hyp. apply WF_wf_transp. hyp.
Qed.
(***********************************************************************)
(** When a relation absorbs the other. *)
Lemma wf_union_absorb : WF R -> WF S -> R @ S << R -> WF (R U S).
Proof.
intros R_wf S_wf RS x. apply notNT_SN. intros [f [f1 f2]].
(* We prove that, for all [i], there is [j > i] such that
[R (f j) (f (j+1))]. *)
assert (a1 : forall i, exists j, i < j /\ R (f j) (f (1+j))).
apply NNPP. rewrite not_forall_eq. intros [i0 hi0].
rewrite not_exists_eq in hi0.
assert (hi0' : forall i, i0 < i -> S (f i) (f (1+i))).
intros i ii0. gen (hi0 i). rewrite not_and_eq. fo.
absurd (NT S (f (i0+1))). apply SN_notNT. fo.
exists (fun i => f (i+(i0+1))). split. refl. intro i. apply hi0'. lia.
(* We prove that, for all [i], there is [j > i] such that
[R (f j) (f (j+1))] and, for all [k] between [i] and [j],
[S (f k) (f (k+1))]. *)
assert (a2 : forall i, exists j, i < j /\ R (f j) (f (1+j))
/\ forall k, i < k < j -> S (f k) (f (1+k))).
intro i. gen (ch_min (a1 i)); intros [j [[[j1 j2] j3] j4]].
ex j. split. hyp. split. hyp. intros k ikj. destruct (f2 k). 2: hyp.
assert (j <= k). apply j3. fo. lia.
(* Let [i0] be the first or second [R] step in [f]. *)
destruct (a2 0) as [i0 [i0h [i0r i0s]]].
(* Let [b] be the function mapping [j] to [i] and such that [b 0 = i0]. *)
destruct (dep_choice i0 a2) as [b [b1 b2]].
(* We prove that there is an infinite sequence of [R @ S#] steps
starting from [f i0]. *)
assert (a3 : NT (R @ S#) (f i0)). ex (fun i => f (b i)). split.
rewrite b2. refl.
intro i. ex (f (1 + b i)). split.
destruct i. rewrite b2. hyp. gen (b1 i). fo.
apply rtc_intro_seq. gen (b1 i). lia.
intros k hk. gen (b1 i). intros [c1 [c2 c3]]. apply c3. lia.
(* We therefore get a contradiction since [R @ S# << R] and [R] is WF. *)
revert a3. apply SN_notNT. apply (SN_incl R).
apply absorbs_right_rtc. hyp. fo.
Qed.
(***********************************************************************)
(** Commutation and SN *)
Lemma sn_comm_sntr :
forall x, SN R x -> (forall y, R#1 x y -> SN S y) ->
S@R << R!1@S#1 -> SN (R!1 U S!1) x.
Proof.
intros x snr sns comm.
assert (snrt := SN_tc1 snr); clear snr.
(* Induction on x R! ... *)
induction snrt as [x _ IHr].
apply SN_intro. intros y xRSy.
destruct xRSy as [xRy | xSy]. apply IHr. hyp.
assert (SN (S!1) y) as sny.
apply SN_tc1. apply sns. apply tc1_incl_rtc1; hyp.
(* x R! y *)
intros y0 yRy0. apply sns.
apply trans_comp_incl. class. exists y; split; trivial.
apply tc1_incl_rtc1. hyp.
(* x S! y *)
assert (SN (S!1) y) as sny. apply SN_tc1.
apply SN_inv_rtc1 with x. apply tc1_incl_rtc1. hyp.
apply sns. refl.
(* Induction on y S! ... *)
induction sny as [y _ IHs].
apply SN_intro. intros z yRSz.
destruct yRSz as [yRz | ySz].
assert ((R!1 @ (R U S)#1) x z) as xRz.
apply comm_s_r; trivial.
destruct yRz as [y z yRz | y m z yRm mRz].
exists z. split. exists y. split; trivial.
apply union_rel_rt1_right. apply tc1_incl_rtc1. hyp. refl.
exists m. split. exists y. split; trivial.
apply union_rel_rt1_right. apply tc1_incl_rtc1. hyp.
apply union_rel_rt1_left. apply tc1_incl_rtc1. hyp.
destruct xRz as [m [xRm mz]].
assert (SN (R!1 U S!1) m) as SNm.
apply IHr. hyp. intros y0 mRy0.
apply sns. apply trans_comp_incl. class. exists m.
split; trivial. apply tc1_incl_rtc1. hyp.
apply SN_inv_rtc1 with m. apply incl_union_rt1_union. hyp. hyp.
apply IHs; trivial. trans y; trivial.
Qed.
Lemma sn_comm_sn :
forall x, SN R x -> (forall y, R#1 x y -> SN S y) ->
S@R << R!1@S#1 -> SN (R U S) x.
Proof.
intros x snr sns comm.
assert (SN (R!1 U S!1) x) as sntr.
apply sn_comm_sntr; trivial.
apply (SN_incl (R!1 U S!1)).
apply union_incl.
intros a b. apply t1_step.
intros a b. apply t1_step.
hyp.
Qed.
End S.
|
{-# OPTIONS --allow-unsolved-metas #-}
module Term where
open import OscarPrelude
open import VariableName
open import FunctionName
open import Arity
open import Vector
mutual
data Term : Set
where
variable : VariableName → Term
function : FunctionName → Terms → Term
record Terms : Set
where
constructor ⟨_⟩
inductive
field
{arity} : Arity
terms : Vector Term arity
open Terms public
termVariable-inj : ∀ {𝑥₁ 𝑥₂} → Term.variable 𝑥₁ ≡ variable 𝑥₂ → 𝑥₁ ≡ 𝑥₂
termVariable-inj refl = refl
termFunction-inj₁ : ∀ {𝑓₁ 𝑓₂ τ₁s τ₂s} → Term.function 𝑓₁ τ₁s ≡ function 𝑓₂ τ₂s → 𝑓₁ ≡ 𝑓₂
termFunction-inj₁ refl = refl
termFunction-inj₂ : ∀ {𝑓₁ 𝑓₂ τ₁s τ₂s} → Term.function 𝑓₁ τ₁s ≡ function 𝑓₂ τ₂s → τ₁s ≡ τ₂s
termFunction-inj₂ refl = refl
terms-inj : ∀ {𝑎} → {τs₁ τs₂ : Vector Term 𝑎} → (τs₁≡τs₂ : (Terms.⟨_⟩ {𝑎} τs₁) ≡ ⟨ τs₂ ⟩) → τs₁ ≡ τs₂
terms-inj refl = refl
module _ where
open import TermByFunctionNames
mutual
termToTermByFunctionNames : Term → Σ Nat TermByFunctionNames
termToTermByFunctionNames (variable x) = _ , (variable x)
termToTermByFunctionNames (function x x₁) = {!!}
termsToVec : Terms → Σ Nat (λ arity → Σ (Vec (Σ Nat TermByFunctionNames) arity) λ τs → Σ Nat λ n → n ≡ sum (vecToList $ (fst <$> τs)))
termsToVec (⟨_⟩ {arity = arity₁} ⟨ vector₁ ⟩) = {!!}
iTermToTerm : Σ Nat TermByFunctionNames → Term
iTermToTerm = {!!}
eq-term-round : ∀ τ → iTermToTerm (termToTermByFunctionNames τ) ≡ τ
eq-term-round = {!!}
eq-iterm-round : ∀ τ → termToTermByFunctionNames (iTermToTerm τ) ≡ τ
eq-iterm-round = {!!}
instance EqTerm : Eq Term
Eq._==_ EqTerm x y with termToTermByFunctionNames x | graphAt termToTermByFunctionNames x | termToTermByFunctionNames y | graphAt termToTermByFunctionNames y
Eq._==_ EqTerm x y | ix | ingraph eqx | iy | ingraph eqy with ix ≟ iy
Eq._==_ EqTerm x y | ix | ingraph eqx | .ix | ingraph eqy | yes refl = yes $ ((cong iTermToTerm eqy ⟨≡⟩ʳ cong iTermToTerm eqx) ⟨≡⟩ eq-term-round x) ʳ⟨≡⟩ eq-term-round y
Eq._==_ EqTerm x y | ix | ingraph eqx | iy | ingraph eqy | no neq = {!!}
instance EqTerms : Eq Terms
EqTerms = {!!}
{-
module _ {i : Size}
where
mutual
EqTerm⇑ : (x y : Term) → Delay i ∘ Dec $ x ≡ y
EqTerm⇑ (variable _) (variable _) = now (decEq₁ termVariable-inj $ _≟_ _ _)
EqTerm⇑ (function 𝑓₁ τ₁s) (function 𝑓₂ τ₂s) =
{-
τ₁s≟τ₂s ← EqTerms⇑ τ₁s τ₂s -|
(now $ decEq₂ termFunction-inj₁ termFunction-inj₂ (𝑓₁ ≟ 𝑓₂) τ₁s≟τ₂s)
-}
EqTerms⇑ τ₁s τ₂s >>= λ
τ₁s≟τ₂s → now $ decEq₂ termFunction-inj₁ termFunction-inj₂ (𝑓₁ ≟ 𝑓₂) τ₁s≟τ₂s
EqTerm⇑ (variable _) (function _ _) = now $ no λ ()
EqTerm⇑ (function _ _) (variable _) = now $ no λ ()
EqTerms⇑ : (x y : Terms) → Delay i ∘ Dec $ x ≡ y
EqTerms⇑ (⟨_⟩ {𝑎₁} τ₁s) (⟨_⟩ {𝑎₂} τ₂s)
with 𝑎₁ ≟ 𝑎₂
… | no 𝑎₁≢𝑎₂ = now $ no λ {τ₁≡τ₂ → 𝑎₁≢𝑎₂ (cong arity τ₁≡τ₂)}
… | yes refl =
EqVectorTerm⇑ τ₁s τ₂s >>= λ
{ (yes refl) → now $ yes refl
; (no τ₁s≢τ₂s) → now $ no (λ ⟨τ₁s⟩≡⟨τ₂s⟩ → τ₁s≢τ₂s (terms-inj ⟨τ₁s⟩≡⟨τ₂s⟩)) }
EqVectorTerm⇑ : ∀ {n} → (x y : Vector Term n) → Delay i ∘ Dec $ x ≡ y
EqVectorTerm⇑ ⟨ [] ⟩ ⟨ [] ⟩ = now (yes refl)
EqVectorTerm⇑ ⟨ τ₁ ∷ τ₁s ⟩ ⟨ τ₂ ∷ τ₂s ⟩ =
EqTerm⇑ τ₁ τ₂ >>= λ
{ (yes refl) → EqVectorTerm⇑ ⟨ τ₁s ⟩ ⟨ τ₂s ⟩ >>= λ
{ (yes refl) → now $ yes refl
; (no τ₁s≢τ₂s) → now $ no λ τ₁₁s≡τ₁₂s → τ₁s≢τ₂s $ cong ⟨_⟩ ((vcons-inj-tail (cong vector τ₁₁s≡τ₁₂s))) }
; (no τ₁≢τ₂) → now $ no λ τ₁₁s≡τ₂₂s → τ₁≢τ₂ $ vcons-inj-head (cong vector τ₁₁s≡τ₂₂s) }
EqVectorTerm⇓ : ∀ {n} → (x y : Vector Term n) → EqVectorTerm⇑ x y ⇓
EqVectorTerm⇓ ⟨ [] ⟩ ⟨ [] ⟩ = _ , now⇓
EqVectorTerm⇓ ⟨ variable 𝑥₁ ∷ τ₁s ⟩ ⟨ variable 𝑥₂ ∷ τ₂s ⟩
with 𝑥₁ ≟ 𝑥₂
… | yes refl with EqVectorTerm⇓ ⟨ τ₁s ⟩ ⟨ τ₂s ⟩
EqVectorTerm⇓ ⟨ variable 𝑥₁ ∷ τ₁s ⟩ ⟨ variable .𝑥₁ ∷ .τ₁s ⟩ | yes refl | (yes refl , snd₁) = _ , snd₁ >>=⇓ now⇓
EqVectorTerm⇓ ⟨ variable 𝑥₁ ∷ τ₁s ⟩ ⟨ variable .𝑥₁ ∷ τ₂s ⟩ | yes refl | (no x , snd₁) = _ , snd₁ >>=⇓ now⇓
EqVectorTerm⇓ ⟨ variable 𝑥₁ ∷ τ₁s ⟩ ⟨ variable 𝑥₂ ∷ τ₂s ⟩ | no 𝑥₁≢𝑥₂ = _ , now⇓
EqVectorTerm⇓ ⟨ variable x ∷ τ₁s ⟩ ⟨ function x₁ x₂ ∷ τ₂s ⟩ = _ , now⇓
EqVectorTerm⇓ ⟨ function x x₁ ∷ τ₁s ⟩ ⟨ variable x₂ ∷ τ₂s ⟩ = _ , now⇓
EqVectorTerm⇓ ⟨ function 𝑓₁ (⟨_⟩ {𝑎₁} τ₁s) ∷ τ₁₂s ⟩ ⟨ function 𝑓₂ (⟨_⟩ {𝑎₂} τ₂s) ∷ τ₂₂s ⟩
with 𝑎₁ ≟ 𝑎₂ | 𝑓₁ ≟ 𝑓₂
… | no 𝑎₁≢𝑎₂ | no 𝑓₁≢𝑓₂ = _ , now⇓
… | no 𝑎₁≢𝑎₂ | yes refl = _ , now⇓
… | yes refl | no 𝑓₁≢𝑓₂
with EqVectorTerm⇓ τ₁s τ₂s
… | (no τ₁s≢τ₂s , τ⇓) = _ , τ⇓ >>=⇓ now⇓ >>=⇓ now⇓ >>=⇓ now⇓
… | (yes refl , τ⇓) = _ , τ⇓ >>=⇓ now⇓ >>=⇓ now⇓ >>=⇓ now⇓
EqVectorTerm⇓ ⟨ function 𝑓₁ (⟨_⟩ {𝑎₁} τ₁s) ∷ τ₁₂s ⟩ ⟨ function 𝑓₂ (⟨_⟩ {𝑎₂} τ₂s) ∷ τ₂₂s ⟩ | yes refl | yes refl
with EqVectorTerm⇓ τ₁s τ₂s | EqVectorTerm⇓ ⟨ τ₁₂s ⟩ ⟨ τ₂₂s ⟩
… | (no τ₁s≢τ₂s , τ⇓) | (no τ₁₂s≢τ₂₂s , τs⇓) = _ , τ⇓ >>=⇓ now⇓ >>=⇓ now⇓ >>=⇓ now⇓
… | (yes refl , τ⇓) | (no τ₁₂s≢τ₂₂s , τs⇓) = _ , τ⇓ >>=⇓ now⇓ >>=⇓ now⇓ >>=⇓ (τs⇓ >>=⇓ now⇓)
… | (no τ₁s≢τ₂s , τ⇓) | (yes refl , τs⇓) = _ , τ⇓ >>=⇓ now⇓ >>=⇓ now⇓ >>=⇓ now⇓
… | (yes refl , τ⇓) | (yes refl , τs⇓) = _ , τ⇓ >>=⇓ now⇓ >>=⇓ now⇓ >>=⇓ (τs⇓ >>=⇓ now⇓)
EqTerms⇓ : (x y : Terms) → EqTerms⇑ x y ⇓
EqTerms⇓ (⟨_⟩ {𝑎₁} τ₁s) (⟨_⟩ {𝑎₂} τ₂s)
with 𝑎₁ ≟ 𝑎₂
… | no 𝑎₁≢𝑎₂ = _ , now⇓
… | yes refl
with EqVectorTerm⇓ τ₁s τ₂s
… | (yes refl , τ⇓) = _ , τ⇓ >>=⇓ now⇓
… | (no _ , τ⇓) = _ , τ⇓ >>=⇓ now⇓
EqTerm⇓ : (x y : Term) → EqTerm⇑ x y ⇓
EqTerm⇓ (variable x) (variable x₁) = _ , now⇓
EqTerm⇓ (function _ τ₁s) (function _ τ₂s)
with EqTerms⇓ τ₁s τ₂s
… | (_ , τ⇓) = _ , τ⇓ >>=⇓ now⇓
EqTerm⇓ (variable x) (function x₁ x₂) = _ , now⇓
EqTerm⇓ (function x x₁) (variable x₂) = _ , now⇓
instance EqTerm : Eq Term
EqTerm = record { _==_ = λ x y → fst (EqTerm⇓ x y) }
instance EqTerms : Eq Terms
Eq._==_ EqTerms x y = fst (EqTerms⇓ x y)
-}
module _ where
open import Membership
instance MembershipTermTerms : Membership Term Terms
Membership._∈_ MembershipTermTerms = _ᵗ∈ᵗˢ_ where
data _ᵗ∈ᵗˢ_ (τ : Term) : Terms → Set
where
zero : τ ᵗ∈ᵗˢ ⟨ ⟨ τ ∷ [] ⟩ ⟩
suc : ∀ {τs} → τ ᵗ∈ᵗˢ τs → τ ᵗ∈ᵗˢ ⟨ ⟨ τ ∷ vector (terms τs) ⟩ ⟩
Membership._∉_ MembershipTermTerms x X = ¬ x ∈ X
fst (Membership.xor-membership MembershipTermTerms) x₁ x₂ = x₂ x₁
snd (Membership.xor-membership MembershipTermTerms) x₁ x₂ = x₁ x₂
instance MembershipVariableNameTerm : Membership VariableName Term
Membership._∈_ MembershipVariableNameTerm = _ᵛ∈ᵗ_ where
data _ᵛ∈ᵗ_ (𝑥 : VariableName) : Term → Set
where
variable : 𝑥 ᵛ∈ᵗ variable 𝑥
function : ∀ 𝑓 {τ : Term} {τs} → {_ : 𝑥 ∈ τ} → τ ∈ τs → 𝑥 ᵛ∈ᵗ function 𝑓 τs
Membership._∉_ MembershipVariableNameTerm x X = ¬ x ∈ X
fst (Membership.xor-membership MembershipVariableNameTerm) x₁ x₂ = x₂ x₁
snd (Membership.xor-membership MembershipVariableNameTerm) x₁ x₂ = x₁ x₂
module _ where
import UnifyTermL
import UnifyMguCorrectL
module L where
open UnifyTermL (Maybe FunctionName) public
open UnifyMguCorrectL (Maybe FunctionName) public
mutual
TermLtoTerm : ∃ L.Term → Term
TermLtoTerm (fst₁ , UnifyTermL.i x) = {!!}
TermLtoTerm (fst₁ , UnifyTermL.leaf nothing) = {!!}
TermLtoTerm (fst₁ , UnifyTermL.leaf (just x)) = {!!}
TermLtoTerm (fst₁ , (snd₁ UnifyTermL.fork snd₂)) = {!!}
TermtoTermL : Term → ∃ L.Term
TermtoTermL (variable x) = {!!} , (L.i {!!})
TermtoTermL (function x ⟨ ⟨ [] ⟩ ⟩) = {!!} , L.leaf (just x) L.fork L.leaf nothing
TermtoTermL (function x ⟨ ⟨ x₁ ∷ vector₁ ⟩ ⟩) = {!!} , {!!} L.fork {!!}
|
```python
from IPython.core.display import display_html
from urllib.request import urlopen
display_html(urlopen('http://j.mp/1Ye5iWA').read(), raw=True)
```
<link href='http://fonts.googleapis.com/css?family=EB+Garamond' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Lato:100,100italic' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="//cdn.jsdelivr.net/font-hack/2.013/css/hack-extended.min.css">
<style>
@font-face{
font-family: "Computer Modern";
src: url('http://mirrors.ctan.org/fonts/cm-unicode/fonts/otf/cmunss.otf');}
div.cell{
max-width: 800px;
margin-left: auto;
margin-right: auto;}
h1 {
font-family: 'Lato', sans-serif;}
h2 {
font-family: 'Lato', serif;}
h3{
font-family: 'Lato', serif;
margin-top: 12px;
margin-bottom: 3px;}
h4{
font-family: 'Lato', serif;}
h5 {
font-family: 'Lato', serif;}
div.text_cell_render{
font-family: 'EB Garamond', 'Computer Modern', 'Helvetica Neue', Arial, Helvetica, Geneva, sans-serif;
line-height: 140%;
font-size: 14pt;
max-width: 650px;
margin-left: auto;
margin-right: auto;}
.CodeMirror{
font-family: 'Hack', 'Consolas', 'Inconsolata', monospace;}
.text_cell_render h1 {
font-weight: 100;
font-size: 48pt;
line-height: 100%;
color: #CD2305;
margin-bottom: 0.5em;
margin-top: 0.5em;
display: block;}
.text_cell_render h2 {
font-weight: 100;
font-size: 36pt;}
.text_cell_render h3 {
font-weight: 100;
font-size: 21pt;}
.text_cell_render h4 {
font-weight: 100;
font-size: 18pt;}
.text_cell_render h5 {
font-weight: 100;
font-size: 16pt;
color: #CD2305;
font-style: italic;
margin-bottom: 0.5em;
margin-top: 0.5em;
display: block;}
.text_cell_render h6 {
font-weight: 100;
font-size: 14pt;
color: #CD2305;
font-style: italic;
margin-bottom: 0.5em;
margin-top: 0.5em;
display: block;}
.warning{
background-color: #FFFFE0;
border-color: #FFCC99;
border-left: 5px solid #FFCC99;
padding: 0.5em;}
.error{
background-color: #fcf2f2;
border-color: #dFb5b4;
border-left: 5px solid #dfb5b4;
padding: 0.5em;}
</style>
# Dinámica del Robot Manipulador SCARA
Se tiene un robot manipulador tipo SCARA, como el de la siguiente figura, del cual se quiere obtener sus ecuaciones de movimiento, asi como una simulación bajo cierta ley de control.
Empezaremos obteniendo una representación simple de las posiciones de los centros de masa para los eslabones del robot.
Primero tenemos que importar las librerias de computo simbolico:
```python
from sympy import var, sin, cos, Matrix, Integer, eye, Function, Rational, exp, Symbol, I, solve, pi, trigsimp, dsolve, sinh, cosh, simplify
from sympy.physics.mechanics import mechanics_printing
mechanics_printing()
```
Y declaramos todas las constantes involucradas en este calculo simbolico:
```python
var("m1 m2 m3 J1 J2 J3 l1 l2 L1 L2 L0 t g")
```
Asi como algunas de las variables de nuestro problema:
```python
q1 = Function("q1")(t)
q2 = Function("q2")(t)
q3 = Function("q3")(t)
```
Y empezamos con el calculo de la posicion de los centros de masa de los eslabones, asi como su derivada y el cuadrado de la velocidad lineal de cada eslabon:
```python
x1 = l1*cos(q1)
y1 = l1*sin(q1)
z1 = L0
v1 = x1.diff("t")**2 + y1.diff("t")**2 + z1.diff("t")**2
v1.trigsimp()
```
```python
x2 = L1*cos(q1) + l2*cos(q1 + q2)
y2 = L1*sin(q1) + l2*sin(q1 + q2)
z2 = L0
v2 = x2.diff("t")**2 + y2.diff("t")**2 + z2.diff("t")**2
v2.trigsimp()
```
```python
x3 = L1*cos(q1) + L2*cos(q1 + q2)
y3 = L1*sin(q1) + L2*sin(q1 + q2)
z3 = L0 - q3
v3 = x3.diff("t")**2 + y3.diff("t")**2 + z3.diff("t")**2
v3.trigsimp()
```
Declaramos $\omega_i$ como la velocidad angular de cada eslabon:
```python
ω1 = q1.diff("t")
ω2 = q2.diff("t")
ω3 = 0
```
Y procedemos al calculo de la energía cinética de cada eslabon:
```python
K1 = Rational(1, 2)*m1*v1 + Rational(1, 2)*J1*ω1**2
K1
```
```python
K2 = Rational(1, 2)*m1*v2 + Rational(1, 2)*J2*ω2**2
K2
```
```python
K3 = Rational(1, 2)*m1*v3 + Rational(1, 2)*J3*ω3**2
K3
```
Calculamos tambien la energía potencial de cada eslabon:
```python
U1 = m1*g*z1
U1
```
```python
U2 = m2*g*z2
U2
```
```python
U3 = m3*g*z3
U3
```
Por lo que ya podemos calcular tanto la energía cinética de nuestro sistema como la potencial:
```python
K = K1 + K2 + K3
K
```
```python
U = U1 + U2 + U3
U
```
y el Lagrangiano queda:
```python
L = (K - U).expand().simplify()
L
```
Por lo que ahora solo tenemos que aplicar la ecuación de Euler-Lagrange para obtener las ecuaciones de movimiento del sistema:
```python
τ1 = (L.diff(q1.diff(t)).diff(t) - L.diff(q1)).simplify().expand().collect(q1.diff(t).diff(t)).collect(q2.diff(t).diff(t))
```
```python
τ2 = (L.diff(q2.diff(t)).diff(t) - L.diff(q2)).simplify().expand().collect(q1.diff(t).diff(t)).collect(q2.diff(t).diff(t))
```
```python
τ3 = (L.diff(q3.diff(t)).diff(t) - L.diff(q3)).simplify().expand().collect(q1.diff(t).diff(t)).collect(q2.diff(t).diff(t))
```
```python
τ1
```
```python
τ2
```
```python
τ3
```
Una vez que tenemos las ecuaciones de movimiento, debemos simular el comportamiento del sistema por medio de la función ```odeint```, y obtener una gráfica de la trayectoria del sistema:
```python
from scipy.integrate import odeint
from numpy import linspace
```
Para utilizar la función ```odeint```, debemos crear una función, que describa la dinámica del sistema:
```python
def scara(estado, tiempo):
# Se importan funciones necesarias
from numpy import sin, cos, matrix
# Se desenvuelven variables del estado y tiempo
q1, q2, q3, q̇1, q̇2, q̇3 = estado
t = tiempo
# Se declaran constantes del sistema
m1, m2, m3 = 1, 1, 1
J1, J2, J3 = 1, 1, 1
l1, l2 = 0.5, 0.5
L1, L2 = 1, 1
L = 1
g = 9.81
# Se declaran constantes del control
kp1, kp2, kp3 = -30, -60, -60
kv1, kv2, kv3 = -20, -20, -18
# Señales de control nulas
#tau1, tau2, tau3 = 0, 0, 0
# Posiciones a alcanzar
qd1, qd2, qd3 = 1, 1, 1
# Se declaran señales de control del sistema
tau1 = kp1*(q1 - qd1) + kv1*q̇1
tau2 = kp2*(q2 - qd2) + kv2*q̇2
tau3 = kp3*(q3 - qd3) + kv3*q̇3 + m3*g
# Se calculan algunos terminos comunes
λ1 = m1*L1*(l2 + L2)
λ2 = m1*(l2**2 + L2**2)
λ3 = m1*(l1**2 + L1**2)
# Se calculan las matrices de masas, Coriolis,
# y vectores de gravedad, control, posicion y velocidad
M = matrix([[J1 + 2*λ1*cos(q2) + m1*L1**2 + λ2 + λ3, λ1*cos(q2) + λ2, 0],
[λ1*cos(q2) + λ2, J2 + λ2, 0],
[0, 0, m1]])
C = matrix([[-2*q̇1, -q̇2, 0], [q̇1, 0, 0], [0, 0, 0]])
G = matrix([[0], [0], [-m3*g]])
Tau = matrix([[tau1], [tau2], [tau3]])
q = matrix([[q1], [q2], [q3]])
q̇ = matrix([[q̇1], [q̇2], [q̇3]])
# Se calcula la derivada del estado del sistema
qp1 = q̇1
qp2 = q̇2
qp3 = q̇3
qpp = M.I*(Tau - C*q̇ - G)
qpp1, qpp2, qpp3 = qpp.tolist()
return [qp1, qp2, qp3, qpp1[0], qpp2[0], qpp3[0]]
```
Y declarar un arreglo con todos los tiempos a simular, mandar a llamar a la función ```odeint```, y listo!
```python
t = linspace(0, 10, 1000)
estados_simulados = odeint(func = scara, y0 = [0, 0, 0, 0, 0, 0], t = t)
```
Desempacamos los elementos que nos entrega ```odeint```:
```python
q1, q2, q3, q̇1, q̇2, q̇3 = list(zip(*estados_simulados.tolist()))
```
Importamos la libreria para graficar:
```python
%matplotlib notebook
from matplotlib.pyplot import plot, style, figure
from mpl_toolkits.mplot3d import Axes3D
style.use("ggplot")
```
Hacemos la grafica de las trayectorias del sistema, $q_1$, $q_2$ y $q_3$:
```python
fig1 = figure(figsize=(12, 8))
ax1 = fig1.gca()
p1, = ax1.plot(t, q1)
p2, = ax1.plot(t, q2)
p3, = ax1.plot(t, q3)
ax1.legend([p1, p2, p3],[r"$q_1$", r"$q_2$", r"$q_3$"])
ax1.set_ylim(-0.1, 1.2)
ax1.set_xlim(-0.1, 10);
```
<IPython.core.display.Javascript object>
Realizamos la cinemática del manipulador para poder graficar en 3D:
```python
def tras_x(x):
from numpy import matrix
A = matrix([[1, 0, 0, x],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]])
return A
def tras_z(z):
from numpy import matrix
A = matrix([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, z],
[0, 0, 0, 1]])
return A
def rot_z(θ):
from numpy import matrix, sin, cos
A = matrix([[cos(θ), -sin(θ), 0, 0],
[sin(θ), cos(θ), 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]])
return A
def cinematica_scara(q1, q2, q3, l1, l2, L):
from numpy import matrix
p0 = matrix([[0], [0], [0], [1]])
p1 = tras_z(L)*p0
p2 = rot_z(q1)*tras_x(l1)*p1
p3 = rot_z(q2)*tras_x(l2)*p2
p4 = tras_z(-q3)*p3
return [[p0.tolist()[0][0], p1.tolist()[0][0], p2.tolist()[0][0], p3.tolist()[0][0], p4.tolist()[0][0]],
[p0.tolist()[1][0], p1.tolist()[1][0], p2.tolist()[1][0], p3.tolist()[1][0], p4.tolist()[1][0]],
[p0.tolist()[2][0], p1.tolist()[2][0], p2.tolist()[2][0], p3.tolist()[2][0], p4.tolist()[2][0]]]
```
```python
from numpy import pi
τ = 2*pi
xs, ys, zs = cinematica_scara(τ/12, τ/9, 0.5, 1, 1, 1)
```
```python
fig2 = figure(figsize=(8, 8))
ax2 = fig2.gca(projection='3d')
ax2.plot(xs, ys, zs, "-o")
ax2.set_xlim(-2, 2)
ax2.set_ylim(-2, 2)
ax2.set_zlim(0, 1.5);
```
<IPython.core.display.Javascript object>
Cambiamos el ambiente de matplotlib, para poder graficar interactivamente, y declaramos una función que tome la cinematica del robot y grafique los puntos:
```python
%matplotlib inline
```
```python
def grafica_scara(q1, q2, q3, l1, l2, L):
xs, ys , zs = cinematica_scara(q1, q2, q3, l1, l2, L)
fig = figure(figsize=(8, 8))
ax = fig.gca(projection='3d')
ax.plot(xs, ys, zs, "-o")
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
ax.set_zlim(0, 1.5);
```
```python
grafica_scara(τ/12, τ/9, 0.2, 1, 1, 1)
```
Importamos la libreria para interactuar con los datos y le pasamos la función que grafica:
```python
# Se importan widgets de IPython para interactuar con la funcion
from IPython.html.widgets import interact, fixed
```
/Users/roberto/miniconda3/lib/python3.5/site-packages/IPython/html.py:14: ShimWarning: The `IPython.html` package has been deprecated. You should import from `notebook` instead. `IPython.html.widgets` has moved to `ipywidgets`.
"`IPython.html.widgets` has moved to `ipywidgets`.", ShimWarning)
```python
# Se llama a la funcion interactiva
interact(grafica_scara, q1=(0, τ), q2=(0, τ), q3=(0, 1.0), l1=fixed(1), l2=fixed(1), L=fixed(1))
```
Para realizar una animación con los datos de la simulación primero importamos la libreria necesaria y creamos la misma grafica dentro del ambiente de animación:
```python
from matplotlib import animation
from numpy import arange
```
```python
# Se define el tamaño de la figura
fig = figure(figsize=(8, 8))
# Se define una sola grafica en la figura y se dan los limites de los ejes x y y
axi = fig.add_subplot(111, autoscale_on=False, xlim=(-2, 2), ylim=(-2, 2), projection='3d')
# Se utilizan graficas de linea para el resorte y amortiguador
robot, = axi.plot([], [], [], "-o", lw=2)
def init():
# Esta funcion se ejecuta una sola vez y sirve para inicializar el sistema
robot.set_data([], [])
return robot
def animate(i):
# Esta funcion se ejecuta para cada cuadro del GIF
# Se obtienen las coordenadas del robot y se meten los datos en su grafica de linea
xs, ys, zs = cinematica_scara(q1[i], q2[i], q3[i], 1, 1, 1)
robot.set_data(xs, ys)
robot .set_3d_properties(zs)
return robot
# Se hace la animacion dandole el nombre de la figura definida al principio, la funcion que
# se debe ejecutar para cada cuadro, el numero de cuadros que se debe de hacer, el periodo
# de cada cuadro y la funcion inicial
ani = animation.FuncAnimation(fig, animate, arange(1, len(q1)), interval=25,
blit=True, init_func=init)
# Se guarda el GIF en el archivo indicado
ani.save('./imagenes/simulacion-scara.gif', writer='imagemagick');
```
|
function position_periodic(x::Float64, L::Float64)
if x > L
x = x - L
elseif x < 0.0
x = x + L
end
return x
end
|
State Before: α : Type ?u.159211
r : α → α → Prop
o : Ordinal
f : (a : Ordinal) → a < o → Ordinal
c : Cardinal
hc : IsRegular c
ho : card o < c
⊢ card o < Ordinal.cof (ord c) State After: no goals Tactic: rwa [hc.cof_eq] |
module Math.Probably.Student where
import Numeric.LinearAlgebra
import Math.Probably.FoldingStats
import Text.Printf
--http://www.haskell.org/haskellwiki/Gamma_and_Beta_function
--cof :: [Double]
cof = [76.18009172947146,-86.50532032941677,24.01409824083091,
-1.231739572450155,0.001208650973866179,-0.000005395239384953]
--ser :: Double
ser = 1.000000000190015
--gammaln :: Double -> Double
gammaln xx = let tmp' = (xx+5.5) - (xx+0.5)*log(xx+5.5)
ser' = foldl (+) ser $ map (\(y,c) -> c/(xx+y)) $ zip [1..] cof
in -tmp' + log(2.5066282746310005 * ser' / xx)
beta z w = exp (gammaln z + gammaln w - gammaln (z+w))
fac :: (Enum a, Num a) => a -> a
fac n = product [1..n]
ixbeta :: (Enum a, Floating a) => a -> a -> a -> a
ixbeta x a b = let top = fac $ a+b-1
down j = fac j * fac (a+b-1-j)
in sum $ map (\j->(top/down j)*(x**j)*(1-x)**(a+b-1-j)) [a..a+b-1]
studentIntegral :: (Enum a, Floating a) => a -> a -> a
studentIntegral t v = 1-ixbeta (v/(v+t*t)) (v/2) (1/2)
tTerms :: Vector Double
tTerms = fromList $ map tTermUnmemo [1..100]
tTermUnmemo :: Int -> Double
tTermUnmemo nu = gammaln ((realToFrac nu+1)/2) - log(realToFrac nu*pi)/2 - gammaln (realToFrac nu/2)
tTerm1 :: Int -> Double
tTerm1 df | df <= 100 = tTerms@>df
| otherwise = tTermUnmemo df
tDist :: Int -> Double -> Double
tDist df t = tTerm1 df - (realToFrac df +1/2) * log (1+(t*t)/(realToFrac df))
tDist3 :: Double -> Double -> Int -> Double -> Double
tDist3 mean prec df x
= tTerm1 df
+ log(prec)/2
- (realToFrac df +1/2) * log (1+(prec*xMinusMu*xMinusMu)/(realToFrac df))
where xMinusMu = x-mean
oneSampleT :: Floating b => b -> Fold b b
oneSampleT v0 = fmap (\(mean,sd,n)-> (mean - v0)/(sd/(sqrt n))) meanSDNF
pairedSampleT :: Fold (Double, Double) Double
pairedSampleT = before (fmap (\(mean,sd,n)-> (mean)/(sd/(sqrt n))) meanSDNF)
(uncurry (-))
data TTestResult = TTestResult { degFreedom :: Int,
tValue :: Double,
pValue :: Double }
ppTTestRes :: TTestResult -> String
ppTTestRes (TTestResult df tval pval) = printf "paired t(%d)=%.3g, p=%.3g" df tval pval
pairedTTest :: [(Double,Double)] -> TTestResult
pairedTTest vls =
let tval = runStat pairedSampleT vls
df = length vls - 1
pval = (1-) $ studentIntegral (tval) (realToFrac df)
in TTestResult df tval pval
oneSampleTTest :: [Double] -> TTestResult
oneSampleTTest vls =
let tval = runStat (oneSampleT 0) vls
df = length vls - 1
pval = (1-) $ studentIntegral (tval) (realToFrac df)
in TTestResult df tval pval
|
(* Author: Gerwin Klein, Tobias Nipkow *)
theory Big_Step_7_8 imports Com_7_8 begin
subsection "Big-Step Semantics of Commands"
text {*
The big-step semantics is a straight-forward inductive definition
with concrete syntax. Note that the first paramenter is a tuple,
so the syntax becomes @{text "(c,s) \<Rightarrow> s'"}.
*}
text_raw{*\snip{BigStepdef}{0}{1}{% *}
inductive
big_step :: "com \<times> state \<Rightarrow> state \<Rightarrow> bool" (infix "\<Rightarrow>" 55)
where
Skip: "(SKIP,s) \<Rightarrow> s" |
Assign: "(x ::= a,s) \<Rightarrow> s(x := aval a s)" |
Seq: "\<lbrakk> (c\<^sub>1,s\<^sub>1) \<Rightarrow> s\<^sub>2; (c\<^sub>2,s\<^sub>2) \<Rightarrow> s\<^sub>3 \<rbrakk> \<Longrightarrow> (c\<^sub>1;;c\<^sub>2, s\<^sub>1) \<Rightarrow> s\<^sub>3" |
IfTrue: "\<lbrakk> bval b s; (c\<^sub>1,s) \<Rightarrow> t \<rbrakk> \<Longrightarrow> (IF b THEN c\<^sub>1 ELSE c\<^sub>2, s) \<Rightarrow> t" |
IfFalse: "\<lbrakk> \<not>bval b s; (c\<^sub>2,s) \<Rightarrow> t \<rbrakk> \<Longrightarrow> (IF b THEN c\<^sub>1 ELSE c\<^sub>2, s) \<Rightarrow> t" |
WhileFalse: "\<not>bval b s \<Longrightarrow> (WHILE b DO c,s) \<Rightarrow> s" |
WhileTrue:
"\<lbrakk> bval b s\<^sub>1; (c,s\<^sub>1) \<Rightarrow> s\<^sub>2; (WHILE b DO c, s\<^sub>2) \<Rightarrow> s\<^sub>3 \<rbrakk>
\<Longrightarrow> (WHILE b DO c, s\<^sub>1) \<Rightarrow> s\<^sub>3" |
RepeatTrue: "\<lbrakk> bval b t; (c, s) \<Rightarrow> t \<rbrakk> \<Longrightarrow> (REPEAT c UNTIL b, s) \<Rightarrow> t" |
RepeatFalse:
"\<lbrakk> \<not>bval b s\<^sub>2; (c, s\<^sub>1) \<Rightarrow> s\<^sub>2; (REPEAT c UNTIL b, s\<^sub>2) \<Rightarrow> s\<^sub>3 \<rbrakk>
\<Longrightarrow> (REPEAT c UNTIL b, s\<^sub>1) \<Rightarrow> s\<^sub>3"
text_raw{*}%endsnip*}
text_raw{*\snip{BigStepEx}{1}{2}{% *}
schematic_lemma ex: "(''x'' ::= N 5;; ''y'' ::= V ''x'', s) \<Rightarrow> ?t"
apply(rule Seq)
apply(rule Assign)
apply simp
apply(rule Assign)
done
text_raw{*}%endsnip*}
thm ex[simplified]
text{* We want to execute the big-step rules: *}
code_pred big_step .
text{* For inductive definitions we need command
\texttt{values} instead of \texttt{value}. *}
values "{t. (SKIP, \<lambda>_. 0) \<Rightarrow> t}"
text{* We need to translate the result state into a list
to display it. *}
values "{map t [''x''] |t. (SKIP, <''x'' := 42>) \<Rightarrow> t}"
values "{map t [''x''] |t. (''x'' ::= N 2, <''x'' := 42>) \<Rightarrow> t}"
values "{map t [''x'',''y''] |t.
(WHILE Less (V ''x'') (V ''y'') DO (''x'' ::= Plus (V ''x'') (N 5)),
<''x'' := 0, ''y'' := 13>) \<Rightarrow> t}"
values "{map t [''x'',''y''] |t.
(REPEAT (''x'' ::= Plus (V ''x'') (N 5)) UNTIL Less (V ''y'') (V ''x''),
<''x'' := 0, ''y'' := 13>) \<Rightarrow> t}"
text{* Proof automation: *}
text {* The introduction rules are good for automatically
construction small program executions. The recursive cases
may require backtracking, so we declare the set as unsafe
intro rules. *}
declare big_step.intros [intro]
text{* The standard induction rule
@{thm [display] big_step.induct [no_vars]} *}
thm big_step.induct
text{*
This induction schema is almost perfect for our purposes, but
our trick for reusing the tuple syntax means that the induction
schema has two parameters instead of the @{text c}, @{text s},
and @{text s'} that we are likely to encounter. Splitting
the tuple parameter fixes this:
*}
lemmas big_step_induct = big_step.induct[split_format(complete)]
thm big_step_induct
text {*
@{thm [display] big_step_induct [no_vars]}
*}
subsection "Rule inversion"
text{* What can we deduce from @{prop "(SKIP,s) \<Rightarrow> t"} ?
That @{prop "s = t"}. This is how we can automatically prove it: *}
inductive_cases SkipE[elim!]: "(SKIP,s) \<Rightarrow> t"
thm SkipE
text{* This is an \emph{elimination rule}. The [elim] attribute tells auto,
blast and friends (but not simp!) to use it automatically; [elim!] means that
it is applied eagerly.
Similarly for the other commands: *}
inductive_cases AssignE[elim!]: "(x ::= a,s) \<Rightarrow> t"
thm AssignE
inductive_cases SeqE[elim!]: "(c1;;c2,s1) \<Rightarrow> s3"
thm SeqE
inductive_cases IfE[elim!]: "(IF b THEN c1 ELSE c2,s) \<Rightarrow> t"
thm IfE
inductive_cases WhileE[elim]: "(WHILE b DO c,s) \<Rightarrow> t"
thm WhileE
text{* Only [elim]: [elim!] would not terminate. *}
inductive_cases RepeatE[elim]: "(REPEAT c UNTIL b,s) \<Rightarrow> t"
thm RepeatE
text{* An automatic example: *}
text{* Rule inversion by hand via the ``cases'' method: *}
lemma assumes "(IF b THEN SKIP ELSE SKIP, s) \<Rightarrow> t"
shows "t = s"
proof-
from assms show ?thesis
proof cases --"inverting assms"
case IfTrue thm IfTrue
thus ?thesis by blast
next
case IfFalse thus ?thesis by blast
qed
qed
(* Using rule inversion to prove simplification rules: *)
lemma assign_simp:
"(x ::= a,s) \<Rightarrow> s' \<longleftrightarrow> (s' = s(x := aval a s))"
by auto
text {* An example combining rule inversion and derivations *}
lemma Seq_assoc:
"(c1;; c2;; c3, s) \<Rightarrow> s' \<longleftrightarrow> (c1;; (c2;; c3), s) \<Rightarrow> s'"
proof
assume "(c1;; c2;; c3, s) \<Rightarrow> s'"
then obtain s1 s2 where
c1: "(c1, s) \<Rightarrow> s1" and
c2: "(c2, s1) \<Rightarrow> s2" and
c3: "(c3, s2) \<Rightarrow> s'" by auto
from c2 c3
have "(c2;; c3, s1) \<Rightarrow> s'" by (rule Seq)
with c1
show "(c1;; (c2;; c3), s) \<Rightarrow> s'" by (rule Seq)
next
-- "The other direction is analogous"
assume "(c1;; (c2;; c3), s) \<Rightarrow> s'"
thus "(c1;; c2;; c3, s) \<Rightarrow> s'" by auto
qed
subsection "Command Equivalence"
text {*
We call two statements @{text c} and @{text c'} equivalent wrt.\ the
big-step semantics when \emph{@{text c} started in @{text s} terminates
in @{text s'} iff @{text c'} started in the same @{text s} also terminates
in the same @{text s'}}. Formally:
*}
text_raw{*\snip{BigStepEquiv}{0}{1}{% *}
abbreviation
equiv_c :: "com \<Rightarrow> com \<Rightarrow> bool" (infix "\<sim>" 50) where
"c \<sim> c' \<equiv> (\<forall>s t. (c,s) \<Rightarrow> t = (c',s) \<Rightarrow> t)"
text_raw{*}%endsnip*}
text {*
Warning: @{text"\<sim>"} is the symbol written \verb!\ < s i m >! (without spaces).
As an example, we show that loop unfolding is an equivalence
transformation on programs:
*}
lemma unfold_while:
"(WHILE b DO c) \<sim> (IF b THEN c;; WHILE b DO c ELSE SKIP)" (is "?w \<sim> ?iw")
proof -
-- "to show the equivalence, we look at the derivation tree for"
-- "each side and from that construct a derivation tree for the other side"
{ fix s t assume "(?w, s) \<Rightarrow> t"
-- "as a first thing we note that, if @{text b} is @{text False} in state @{text s},"
-- "then both statements do nothing:"
{ assume "\<not>bval b s"
hence "t = s" using `(?w,s) \<Rightarrow> t` by blast
hence "(?iw, s) \<Rightarrow> t" using `\<not>bval b s` by blast
}
moreover
-- "on the other hand, if @{text b} is @{text True} in state @{text s},"
-- {* then only the @{text WhileTrue} rule can have been used to derive @{text "(?w, s) \<Rightarrow> t"} *}
{ assume "bval b s"
with `(?w, s) \<Rightarrow> t` obtain s' where
"(c, s) \<Rightarrow> s'" and "(?w, s') \<Rightarrow> t" by auto
-- "now we can build a derivation tree for the @{text IF}"
-- "first, the body of the True-branch:"
hence "(c;; ?w, s) \<Rightarrow> t" by (rule Seq)
-- "then the whole @{text IF}"
with `bval b s` have "(?iw, s) \<Rightarrow> t" by (rule IfTrue)
}
ultimately
-- "both cases together give us what we want:"
have "(?iw, s) \<Rightarrow> t" by blast
}
moreover
-- "now the other direction:"
{ fix s t assume "(?iw, s) \<Rightarrow> t"
-- "again, if @{text b} is @{text False} in state @{text s}, then the False-branch"
-- "of the @{text IF} is executed, and both statements do nothing:"
{ assume "\<not>bval b s"
hence "s = t" using `(?iw, s) \<Rightarrow> t` by blast
hence "(?w, s) \<Rightarrow> t" using `\<not>bval b s` by blast
}
moreover
-- "on the other hand, if @{text b} is @{text True} in state @{text s},"
-- {* then this time only the @{text IfTrue} rule can have be used *}
{ assume "bval b s"
with `(?iw, s) \<Rightarrow> t` have "(c;; ?w, s) \<Rightarrow> t" by auto
-- "and for this, only the Seq-rule is applicable:"
then obtain s' where
"(c, s) \<Rightarrow> s'" and "(?w, s') \<Rightarrow> t" by auto
-- "with this information, we can build a derivation tree for the @{text WHILE}"
with `bval b s`
have "(?w, s) \<Rightarrow> t" by (rule WhileTrue)
}
ultimately
-- "both cases together again give us what we want:"
have "(?w, s) \<Rightarrow> t" by blast
}
ultimately
show ?thesis by blast
qed
text {* Luckily, such lengthy proofs are seldom necessary. Isabelle can
prove many such facts automatically. *}
lemma while_unfold:
"(WHILE b DO c) \<sim> (IF b THEN c;; WHILE b DO c ELSE SKIP)"
by blast
lemma triv_if:
"(IF b THEN c ELSE c) \<sim> c"
by blast
lemma commute_if:
"(IF b1 THEN (IF b2 THEN c11 ELSE c12) ELSE c2)
\<sim>
(IF b2 THEN (IF b1 THEN c11 ELSE c2) ELSE (IF b1 THEN c12 ELSE c2))"
by blast
lemma sim_while_cong_aux:
"(WHILE b DO c,s) \<Rightarrow> t \<Longrightarrow> c \<sim> c' \<Longrightarrow> (WHILE b DO c',s) \<Rightarrow> t"
apply(induction "WHILE b DO c" s t arbitrary: b c rule: big_step_induct)
apply blast
apply blast
done
lemma sim_while_cong: "c \<sim> c' \<Longrightarrow> WHILE b DO c \<sim> WHILE b DO c'"
by (metis sim_while_cong_aux)
text {* Command equivalence is an equivalence relation, i.e.\ it is
reflexive, symmetric, and transitive. Because we used an abbreviation
above, Isabelle derives this automatically. *}
lemma sim_refl: "c \<sim> c" by simp
lemma sim_sym: "(c \<sim> c') = (c' \<sim> c)" by auto
lemma sim_trans: "c \<sim> c' \<Longrightarrow> c' \<sim> c'' \<Longrightarrow> c \<sim> c''" by auto
subsection "Execution is deterministic"
text {* This proof is automatic. *}
theorem big_step_determ: "\<lbrakk> (c,s) \<Rightarrow> t; (c,s) \<Rightarrow> u \<rbrakk> \<Longrightarrow> u = t"
by (induction arbitrary: u rule: big_step.induct) blast+
text {*
This is the proof as you might present it in a lecture. The remaining
cases are simple enough to be proved automatically:
*}
text_raw{*\snip{BigStepDetLong}{0}{2}{% *}
theorem
"(c,s) \<Rightarrow> t \<Longrightarrow> (c,s) \<Rightarrow> t' \<Longrightarrow> t' = t"
proof (induction arbitrary: t' rule: big_step.induct)
-- "the only interesting case, @{text WhileTrue}:"
fix b c s s\<^sub>1 t t'
-- "The assumptions of the rule:"
assume "bval b s" and "(c,s) \<Rightarrow> s\<^sub>1" and "(WHILE b DO c,s\<^sub>1) \<Rightarrow> t"
-- {* Ind.Hyp; note the @{text"\<And>"} because of arbitrary: *}
assume IHc: "\<And>t'. (c,s) \<Rightarrow> t' \<Longrightarrow> t' = s\<^sub>1"
assume IHw: "\<And>t'. (WHILE b DO c,s\<^sub>1) \<Rightarrow> t' \<Longrightarrow> t' = t"
-- "Premise of implication:"
assume "(WHILE b DO c,s) \<Rightarrow> t'"
with `bval b s` obtain s\<^sub>1' where
c: "(c,s) \<Rightarrow> s\<^sub>1'" and
w: "(WHILE b DO c,s\<^sub>1') \<Rightarrow> t'"
by auto
from c IHc have "s\<^sub>1' = s\<^sub>1" by blast
with w IHw show "t' = t" by blast
qed blast+ -- "prove the rest automatically"
text_raw{*}%endsnip*}
end
|
Formal statement is: lemma compact_closed_differences: fixes S T :: "'a::real_normed_vector set" assumes "compact S" "closed T" shows "closed (\<Union>x\<in> S. \<Union>y \<in> T. {x - y})" Informal statement is: If $S$ is compact and $T$ is closed, then the set of differences $S - T = \{x - y \mid x \in S, y \in T\}$ is closed. |
% trainTestSurfaceContextScript
%
% Assumes you have created:
% imsegs : data structure that contains information on all training
% and testing images
% trainind: the indices of the training images
% testind: the indices of the testing images
basedir = '???'; % set this appropriately
imdir = [basedir '/images/all_images'];
datadir = [basedir '/data'];
resultsdir = [basedir '/results'];
DO_TRAIN = 1;
DO_TEST = 1;
if DO_TRAIN
nsegments = [10 20 30 40 50 60 80 100];
% Computes the superpixel features
if ~exist('spfeatures')
spfeatures = mcmcGetAllSuperpixelData(imdir, imsegs);
save([datadir '/superpixelData.mat'], 'spfeatures');
end
% Trains the superpixel classifiers
if ~exist('vclassifierSP')
[vclassifierSP, hclassifierSP] = ...
mcmcTrainSuperpixelClassifier(spfeatures(trainind), imsegs(trainind));
save([datadir '/superpixelClassifier.mat'], 'vclassifierSP', 'hclassifierSP');
end
% Computes the same-label features
if ~exist('efeatures')
[efeatures, adjlist] = mcmcGetAllEdgeData(spfeatures, imsegs);
save([datadir '/edgeData.mat'], 'efeatures', 'adjlist');
end
% Trains the same-label classifier
if ~exist('eclassifier')
eclassifier = mcmcTrainEdgeClassifier(efeatures(trainind), ...
adjlist(trainind), imsegs(trainind));
ecal = calibrateEdgeClassifier(efeatures(trainind), adjlist(trainind), ...
imsegs(trainind), eclassifier, 1);
ecal = ecal{1};
save([datadir '/edgeClassifier.mat'], 'eclassifier', 'ecal');
end
% Computes the multiple segmentations, the segment features, and the
% ground truth labels for each segment
if ~exist('labdata')
% gather data
for f = 1:numel(imsegs)
disp([num2str(f) ': ' imsegs(f).imname])
[pvSP{f}, phSP{f}, pE{f}] = mcmcInitialize(spfeatures{f}, efeatures{f}, ...
adjlist{f}, imsegs(f), vclassifierSP, hclassifierSP, eclassifier, ecal, 'none');
smaps{f} = generateMultipleSegmentations2(pE{f}, adjlist{f}, imsegs(f).nseg, nsegments);
im = im2double(imread([imdir '/' imsegs(f).imname]));
imdata = mcmcComputeImageData(im, imsegs(f));
for k = 1:numel(nsegments)
labdata{f, k} = mcmcGetSegmentFeatures(imsegs(f), spfeatures{f}, imdata, smaps{f}(:, k), (1:max(smaps{f}(:, k))));
[mclab{f, k}, mcprc{f, k}, allprc{f, k}, trainw{f, k}] = segmentation2labels(imsegs(f), smaps{f}(:, k));
unilabel{f, k} = mclab{f, k}.*(mcprc{f, k}>0.95);
seglabel{f,k} = 1*(mcprc{f, k}>0.95) + (-1)*(mcprc{f, k}<0.95);
end
end
save([datadir '/allData.mat'], 'smaps', 'labdata', 'segdata', 'mclab', 'mcprc', 'allprc', 'seglabel', 'unilabel', 'trainw', 'pvSP', 'phSP', 'pE');
end
% Trains the segment classifiers
if ~exist('vclassifier')
sclassifier = mcmcTrainSegmentationClassifier2(labdata(trainind, :), seglabel(trainind{k}, :), trainw(trainind, :));
[vclassifier, hclassifier] = ...
mcmcTrainSegmentClassifier2(labdata(trainind, :), unilabel(trainind, :), trainw(trainind, :), 50000);
end
save([datadir '/allClassifiers.mat'], 'vclassifier', 'hclassifier', 'sclassifier', 'eclassifier', 'vclassifierSP', 'hclassifierSP');
end
if DO_TEST
% Computes the label confidences for each superpixel in the test images
% and gives the final accuracy.
% pg{image number}(superpixel number, [000 left center right porous solid sky])
% gives the superpixel label confidences
[vacc, hacc, vcm, hcm, pg] = ...
testMultipleSegmentationsCV2(imsegs(testind), labdata(testind, :), ...
labdata(testind, :), smaps(testind), ...
vclassifier, hclassifier, sclassifier, pvSP(testind), phSP(testind), 1);
save([datadir '/results.mat'], 'vacc', 'hacc', 'vcm', 'hcm', 'pg');
% Computes and writes the labeled images
for f = 1:testind
im = im2double(imread([imdir '/' imsegs(f).imname]));
[pv, ph] = splitpg(pg{f});
lim = APPgetLabeledImage2(im, imsegs(f), pv, ph);
imwrite(im, [resultsdir '/' imsegs(f).imname]);
imwrite(lim, [resultsdir '/' strtok(imsegs(f).imname, '.') '.l.jpg']);
end
end |
[STATEMENT]
lemma Dirichlet_kernel_0 [simp]:
"\<bar>x\<bar> < 2 * pi \<Longrightarrow> Dirichlet_kernel 0 x = 1/2"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<bar>x\<bar> < 2 * pi \<Longrightarrow> Dirichlet_kernel 0 x = 1 / 2
[PROOF STEP]
by (auto simp: Dirichlet_kernel_def sin_zero_iff) |
Require Import Coq.PArith.BinPos.
Require Import Crypto.Compilers.SmartMap.
Require Import Crypto.Compilers.Wf.
Require Import Crypto.Compilers.Named.Context.
Require Import Crypto.Compilers.Named.Syntax.
Require Import Crypto.Compilers.Named.ContextDefinitions.
Require Import Crypto.Compilers.Named.InterpretToPHOASWf.
Require Import Crypto.Compilers.Named.WfFromUnit.
Require Import Crypto.Compilers.Named.PositiveContext.
Require Import Crypto.Compilers.Named.PositiveContext.Defaults.
Require Import Crypto.Compilers.Named.PositiveContext.DefaultsProperties.
Require Import Crypto.Compilers.Syntax.
Require Import Crypto.Compilers.GeneralizeVar.
Require Import Crypto.Util.Decidable.
Require Import Crypto.Util.Option.
Require Import Crypto.Util.Sigma.
Require Import Crypto.Util.Tactics.BreakMatch.
Section language.
Context {base_type_code : Type}
{op : flat_type base_type_code -> flat_type base_type_code -> Type}
(base_type_code_beq : base_type_code -> base_type_code -> bool)
(base_type_code_bl_transparent : forall x y, base_type_code_beq x y = true -> x = y)
(base_type_code_lb : forall x y, x = y -> base_type_code_beq x y = true)
(failb : forall var t, @Syntax.exprf base_type_code op var (Tbase t))
{interp_base_type : base_type_code -> Type}
(interp_op : forall src dst, op src dst -> interp_flat_type interp_base_type src -> interp_flat_type interp_base_type dst).
Local Notation GeneralizeVar
:= (@GeneralizeVar
base_type_code op base_type_code_beq base_type_code_bl_transparent
failb).
Local Notation PositiveContextOk := (@PositiveContextOk base_type_code _ base_type_code_beq base_type_code_bl_transparent base_type_code_lb).
Local Instance dec_base_type_code_eq : DecidableRel (@eq base_type_code).
Proof using base_type_code_lb base_type_code_bl_transparent.
refine (fun x y => (if base_type_code_beq x y as b return base_type_code_beq x y = b -> Decidable (x = y)
then fun pf => left (base_type_code_bl_transparent _ _ pf)
else fun pf => right _) eq_refl).
{ clear -pf base_type_code_lb.
let pf := pf in
abstract (intro; erewrite base_type_code_lb in pf by eassumption; congruence). }
Defined.
Local Arguments Compile.compile : simpl never.
Lemma Wf_GeneralizeVar
{t} (e1 : expr base_type_code op t)
e'
(He' : GeneralizeVar e1 = Some e')
: Wf e'.
Proof using base_type_code_lb.
unfold GeneralizeVar, option_map in *.
break_innermost_match_hyps; try congruence; intros v v'; [].
inversion_option; subst.
unfold InterpretToPHOAS.Named.InterpToPHOAS, InterpretToPHOAS.Named.InterpToPHOAS_gen.
destruct t as [src dst].
eapply (@wf_interp_to_phoas
base_type_code op FMapPositive.PositiveMap.key _ _ _ _
(PositiveContext base_type_code _ base_type_code_beq base_type_code_bl_transparent)
(PositiveContext base_type_code _ base_type_code_beq base_type_code_bl_transparent)
PositiveContextOk PositiveContextOk
(failb _) (failb _) _ _);
[ revert v | revert v' ];
refine (_ : Wf.Named.Wf _ e);
apply Wf_from_unit; auto using PositiveContextOk.
Qed.
Lemma Wf_GeneralizeVar_arrow
{s d} (e : expr base_type_code op (Arrow s d))
e'
(He' : GeneralizeVar e = Some e')
: Wf e'.
Proof using base_type_code_lb. eapply Wf_GeneralizeVar; eassumption. Qed.
End language.
Hint Resolve Wf_GeneralizeVar Wf_GeneralizeVar_arrow : wf.
|
function boundaries_to_sparse(boundary)
n = length(boundary)
I = Vector{Int}(undef, n)
J = Vector{Int}(undef, n)
V = Vector{Bool}(undef, n)
for (idx, el) in enumerate(boundary)
cell, face = el
I[idx] = face
J[idx] = cell
V[idx] = true
end
return sparse(I, J, V)
end
"""
generate_grid(celltype::Cell, nel::NTuple, [left::Vec, right::Vec)
Return a `Grid` for a rectangle in 1, 2 or 3 dimensions. `celltype` defined the type of cells,
e.g. `Triangle` or `Hexahedron`. `nel` is a tuple of the number of elements in each direction.
`left` and `right` are optional endpoints of the domain. Defaults to -1 and 1 in all directions.
"""
generate_grid
# Line
function generate_grid(::Type{Line}, nel::NTuple{1,Int}, left::Vec{1,T}=Vec{1}((-1.0,)), right::Vec{1,T}=Vec{1}((1.0,))) where {T}
nel_x = nel[1]
n_nodes = nel_x + 1
# Generate nodes
coords_x = collect(range(left[1], stop=right[1], length=n_nodes))
nodes = Node{1,T}[]
for i in 1:n_nodes
push!(nodes, Node((coords_x[i],)))
end
# Generate cells
cells = Line[]
for i in 1:nel_x
push!(cells, Line((i, i+1)))
end
# Cell faces
boundary = Vector([(1, 1),
(nel_x, 2)])
boundary_matrix = boundaries_to_sparse(boundary)
# Cell face sets
facesets = Dict("left" => Set{Tuple{Int,Int}}([boundary[1]]),
"right" => Set{Tuple{Int,Int}}([boundary[2]]))
return Grid(cells, nodes, facesets=facesets, boundary_matrix=boundary_matrix)
end
# QuadraticLine
function generate_grid(::Type{QuadraticLine}, nel::NTuple{1,Int}, left::Vec{1,T}=Vec{1}((-1.0,)), right::Vec{1,T}=Vec{1}((1.0,))) where {T}
nel_x = nel[1]
n_nodes = 2*nel_x + 1
# Generate nodes
coords_x = collect(range(left[1], stop=right[1], length=n_nodes))
nodes = Node{1,T}[]
for i in 1:n_nodes
push!(nodes, Node((coords_x[i],)))
end
# Generate cells
cells = QuadraticLine[]
for i in 1:nel_x
push!(cells, QuadraticLine((2*i-1, 2*i+1, 2*i)))
end
# Cell faces
boundary = Tuple{Int,Int}[(1, 1),
(nel_x, 2)]
boundary_matrix = boundaries_to_sparse(boundary)
# Cell face sets
facesets = Dict("left" => Set{Tuple{Int,Int}}([boundary[1]]),
"right" => Set{Tuple{Int,Int}}([boundary[2]]))
return Grid(cells, nodes, facesets=facesets, boundary_matrix=boundary_matrix)
end
function _generate_2d_nodes!(nodes, nx, ny, LL, LR, UR, UL)
for i in 0:ny-1
ratio_bounds = i / (ny-1)
x0 = LL[1] * (1 - ratio_bounds) + ratio_bounds * UL[1]
x1 = LR[1] * (1 - ratio_bounds) + ratio_bounds * UR[1]
y0 = LL[2] * (1 - ratio_bounds) + ratio_bounds * UL[2]
y1 = LR[2] * (1 - ratio_bounds) + ratio_bounds * UR[2]
for j in 0:nx-1
ratio = j / (nx-1)
x = x0 * (1 - ratio) + ratio * x1
y = y0 * (1 - ratio) + ratio * y1
push!(nodes, Node((x, y)))
end
end
end
function generate_grid(C::Type{Cell{2,M,N}}, nel::NTuple{2,Int}, X::Vector{Vec{2,T}}) where {M,N,T}
@assert length(X) == 4
generate_grid(C, nel, X[1], X[2], X[3], X[4])
end
function generate_grid(C::Type{Cell{2,M,N}}, nel::NTuple{2,Int}, left::Vec{2,T}=Vec{2}((-1.0,-1.0)), right::Vec{2,T}=Vec{2}((1.0,1.0))) where {M,N,T}
LL = left
UR = right
LR = Vec{2}((UR[1], LL[2]))
UL = Vec{2}((LL[1], UR[2]))
generate_grid(C, nel, LL, LR, UR, UL)
end
# Quadrilateral
function generate_grid(C::Type{Quadrilateral}, nel::NTuple{2,Int}, LL::Vec{2,T}, LR::Vec{2,T}, UR::Vec{2,T}, UL::Vec{2,T}) where {T}
nel_x = nel[1]; nel_y = nel[2]; nel_tot = nel_x*nel_y
n_nodes_x = nel_x + 1; n_nodes_y = nel_y + 1
n_nodes = n_nodes_x * n_nodes_y
# Generate nodes
nodes = Node{2,T}[]
_generate_2d_nodes!(nodes, n_nodes_x, n_nodes_y, LL, LR, UR, UL)
# Generate cells
node_array = reshape(collect(1:n_nodes), (n_nodes_x, n_nodes_y))
cells = Quadrilateral[]
for j in 1:nel_y, i in 1:nel_x
push!(cells, Quadrilateral((node_array[i,j], node_array[i+1,j], node_array[i+1,j+1], node_array[i,j+1])))
end
# Cell faces
cell_array = reshape(collect(1:nel_tot),(nel_x, nel_y))
boundary = Tuple{Int,Int}[[(cl, 1) for cl in cell_array[:,1]];
[(cl, 2) for cl in cell_array[end,:]];
[(cl, 3) for cl in cell_array[:,end]];
[(cl, 4) for cl in cell_array[1,:]]]
boundary_matrix = boundaries_to_sparse(boundary)
# Cell face sets
offset = 0
facesets = Dict{String, Set{Tuple{Int,Int}}}()
facesets["bottom"] = Set{Tuple{Int,Int}}(boundary[(1:length(cell_array[:,1])) .+ offset]); offset += length(cell_array[:,1])
facesets["right"] = Set{Tuple{Int,Int}}(boundary[(1:length(cell_array[end,:])) .+ offset]); offset += length(cell_array[end,:])
facesets["top"] = Set{Tuple{Int,Int}}(boundary[(1:length(cell_array[:,end])) .+ offset]); offset += length(cell_array[:,end])
facesets["left"] = Set{Tuple{Int,Int}}(boundary[(1:length(cell_array[1,:])) .+ offset]); offset += length(cell_array[1,:])
return Grid(cells, nodes, facesets=facesets, boundary_matrix=boundary_matrix)
end
# QuadraticQuadrilateral
function generate_grid(::Type{QuadraticQuadrilateral}, nel::NTuple{2,Int}, LL::Vec{2,T}, LR::Vec{2,T}, UR::Vec{2,T}, UL::Vec{2,T}) where {T}
nel_x = nel[1]; nel_y = nel[2]; nel_tot = nel_x*nel_y
n_nodes_x = 2*nel_x + 1; n_nodes_y = 2*nel_y + 1
n_nodes = n_nodes_x * n_nodes_y
# Generate nodes
nodes = Node{2,T}[]
_generate_2d_nodes!(nodes, n_nodes_x, n_nodes_y, LL, LR, UR, UL)
# Generate cells
node_array = reshape(collect(1:n_nodes), (n_nodes_x, n_nodes_y))
cells = QuadraticQuadrilateral[]
for j in 1:nel_y, i in 1:nel_x
push!(cells, QuadraticQuadrilateral((node_array[2*i-1,2*j-1],node_array[2*i+1,2*j-1],node_array[2*i+1,2*j+1],node_array[2*i-1,2*j+1],
node_array[2*i,2*j-1],node_array[2*i+1,2*j],node_array[2*i,2*j+1],node_array[2*i-1,2*j],
node_array[2*i,2*j])))
end
# Cell faces
cell_array = reshape(collect(1:nel_tot),(nel_x, nel_y))
boundary = Tuple{Int,Int}[[(cl, 1) for cl in cell_array[:,1]];
[(cl, 2) for cl in cell_array[end,:]];
[(cl, 3) for cl in cell_array[:,end]];
[(cl, 4) for cl in cell_array[1,:]]]
boundary_matrix = boundaries_to_sparse(boundary)
# Cell face sets
offset = 0
facesets = Dict{String, Set{Tuple{Int,Int}}}()
facesets["bottom"] = Set{Tuple{Int,Int}}(boundary[(1:length(cell_array[:,1])) .+ offset]); offset += length(cell_array[:,1])
facesets["right"] = Set{Tuple{Int,Int}}(boundary[(1:length(cell_array[end,:])) .+ offset]); offset += length(cell_array[end,:])
facesets["top"] = Set{Tuple{Int,Int}}(boundary[(1:length(cell_array[:,end])) .+ offset]); offset += length(cell_array[:,end])
facesets["left"] = Set{Tuple{Int,Int}}(boundary[(1:length(cell_array[1,:])) .+ offset]); offset += length(cell_array[1,:])
return Grid(cells, nodes, facesets=facesets, boundary_matrix=boundary_matrix)
end
# Hexahedron
function generate_grid(::Type{Hexahedron}, nel::NTuple{3,Int}, left::Vec{3,T}=Vec{3}((-1.0,-1.0,-1.0)), right::Vec{3,T}=Vec{3}((1.0,1.0,1.0))) where {T}
nel_x = nel[1]; nel_y = nel[2]; nel_z = nel[3]; nel_tot = nel_x*nel_y*nel_z
n_nodes_x = nel_x + 1; n_nodes_y = nel_y + 1; n_nodes_z = nel_z + 1
n_nodes = n_nodes_x * n_nodes_y * n_nodes_z
# Generate nodes
coords_x = range(left[1], stop=right[1], length=n_nodes_x)
coords_y = range(left[2], stop=right[2], length=n_nodes_y)
coords_z = range(left[3], stop=right[3], length=n_nodes_z)
nodes = Node{3,T}[]
for k in 1:n_nodes_z, j in 1:n_nodes_y, i in 1:n_nodes_x
push!(nodes, Node((coords_x[i], coords_y[j], coords_z[k])))
end
# Generate cells
node_array = reshape(collect(1:n_nodes), (n_nodes_x, n_nodes_y, n_nodes_z))
cells = Hexahedron[]
for k in 1:nel_z, j in 1:nel_y, i in 1:nel_x
push!(cells, Hexahedron((node_array[i,j,k], node_array[i+1,j,k], node_array[i+1,j+1,k], node_array[i,j+1,k],
node_array[i,j,k+1], node_array[i+1,j,k+1], node_array[i+1,j+1,k+1], node_array[i,j+1,k+1])))
end
# Cell faces
cell_array = reshape(collect(1:nel_tot),(nel_x, nel_y, nel_z))
boundary = Tuple{Int,Int}[[(cl, 1) for cl in cell_array[:,:,1][:]];
[(cl, 2) for cl in cell_array[:,1,:][:]];
[(cl, 3) for cl in cell_array[end,:,:][:]];
[(cl, 4) for cl in cell_array[:,end,:][:]];
[(cl, 5) for cl in cell_array[1,:,:][:]];
[(cl, 6) for cl in cell_array[:,:,end][:]]]
boundary_matrix = boundaries_to_sparse(boundary)
# Cell face sets
offset = 0
facesets = Dict{String,Set{Tuple{Int,Int}}}()
facesets["bottom"] = Set{Tuple{Int,Int}}(boundary[(1:length(cell_array[:,:,1][:])) .+ offset]); offset += length(cell_array[:,:,1][:])
facesets["front"] = Set{Tuple{Int,Int}}(boundary[(1:length(cell_array[:,1,:][:])) .+ offset]); offset += length(cell_array[:,1,:][:])
facesets["right"] = Set{Tuple{Int,Int}}(boundary[(1:length(cell_array[end,:,:][:])) .+ offset]); offset += length(cell_array[end,:,:][:])
facesets["back"] = Set{Tuple{Int,Int}}(boundary[(1:length(cell_array[:,end,:][:])) .+ offset]); offset += length(cell_array[:,end,:][:])
facesets["left"] = Set{Tuple{Int,Int}}(boundary[(1:length(cell_array[1,:,:][:])) .+ offset]); offset += length(cell_array[1,:,:][:])
facesets["top"] = Set{Tuple{Int,Int}}(boundary[(1:length(cell_array[:,:,end][:])) .+ offset]); offset += length(cell_array[:,:,end][:])
return Grid(cells, nodes, facesets=facesets, boundary_matrix=boundary_matrix)
end
# Triangle
function generate_grid(::Type{Triangle}, nel::NTuple{2,Int}, LL::Vec{2,T}, LR::Vec{2,T}, UR::Vec{2,T}, UL::Vec{2,T}) where {T}
nel_x = nel[1]; nel_y = nel[2]; nel_tot = 2*nel_x*nel_y
n_nodes_x = nel_x + 1; n_nodes_y = nel_y + 1
n_nodes = n_nodes_x * n_nodes_y
# Generate nodes
nodes = Node{2,T}[]
_generate_2d_nodes!(nodes, n_nodes_x, n_nodes_y, LL, LR, UR, UL)
# Generate cells
node_array = reshape(collect(1:n_nodes), (n_nodes_x, n_nodes_y))
cells = Triangle[]
for j in 1:nel_y, i in 1:nel_x
push!(cells, Triangle((node_array[i,j], node_array[i+1,j], node_array[i,j+1]))) # ◺
push!(cells, Triangle((node_array[i+1,j], node_array[i+1,j+1], node_array[i,j+1]))) # ◹
end
# Cell faces
cell_array = reshape(collect(1:nel_tot),(2, nel_x, nel_y))
boundary = Tuple{Int,Int}[[(cl, 1) for cl in cell_array[1,:,1]];
[(cl, 1) for cl in cell_array[2,end,:]];
[(cl, 2) for cl in cell_array[2,:,end]];
[(cl, 3) for cl in cell_array[1,1,:]]]
boundary_matrix = boundaries_to_sparse(boundary)
# Cell face sets
offset = 0
facesets = Dict{String,Set{Tuple{Int,Int}}}()
facesets["bottom"] = Set{Tuple{Int,Int}}(boundary[(1:length(cell_array[1,:,1])) .+ offset]); offset += length(cell_array[1,:,1])
facesets["right"] = Set{Tuple{Int,Int}}(boundary[(1:length(cell_array[2,end,:])) .+ offset]); offset += length(cell_array[2,end,:])
facesets["top"] = Set{Tuple{Int,Int}}(boundary[(1:length(cell_array[2,:,end])) .+ offset]); offset += length(cell_array[2,:,end])
facesets["left"] = Set{Tuple{Int,Int}}(boundary[(1:length(cell_array[1,1,:])) .+ offset]); offset += length(cell_array[1,1,:])
return Grid(cells, nodes, facesets=facesets, boundary_matrix=boundary_matrix)
end
# QuadraticTriangle
function generate_grid(::Type{QuadraticTriangle}, nel::NTuple{2,Int}, LL::Vec{2,T}, LR::Vec{2,T}, UR::Vec{2,T}, UL::Vec{2,T}) where {T}
nel_x = nel[1]; nel_y = nel[2]; nel_tot = 2*nel_x*nel_y
n_nodes_x = 2*nel_x + 1; n_nodes_y = 2*nel_y + 1
n_nodes = n_nodes_x * n_nodes_y
# Generate nodes
nodes = Node{2,T}[]
_generate_2d_nodes!(nodes, n_nodes_x, n_nodes_y, LL, LR, UR, UL)
# Generate cells
node_array = reshape(collect(1:n_nodes), (n_nodes_x, n_nodes_y))
cells = QuadraticTriangle[]
for j in 1:nel_y, i in 1:nel_x
push!(cells, QuadraticTriangle((node_array[2*i-1,2*j-1], node_array[2*i+1,2*j-1], node_array[2*i-1,2*j+1],
node_array[2*i,2*j-1], node_array[2*i,2*j], node_array[2*i-1,2*j]))) # ◺
push!(cells, QuadraticTriangle((node_array[2*i+1,2*j-1], node_array[2*i+1,2*j+1], node_array[2*i-1,2*j+1],
node_array[2*i+1,2*j], node_array[2*i,2*j+1], node_array[2*i,2*j]))) # ◹
end
# Cell faces
cell_array = reshape(collect(1:nel_tot),(2, nel_x, nel_y))
boundary = Tuple{Int,Int}[[(cl, 1) for cl in cell_array[1,:,1]];
[(cl, 1) for cl in cell_array[2,end,:]];
[(cl, 2) for cl in cell_array[2,:,end]];
[(cl, 3) for cl in cell_array[1,1,:]]]
boundary_matrix = boundaries_to_sparse(boundary)
# Cell face sets
offset = 0
facesets = Dict{String,Set{Tuple{Int,Int}}}()
facesets["bottom"] = Set{Tuple{Int,Int}}(boundary[(1:length(cell_array[1,:,1])) .+ offset]); offset += length(cell_array[1,:,1])
facesets["right"] = Set{Tuple{Int,Int}}(boundary[(1:length(cell_array[2,end,:])) .+ offset]); offset += length(cell_array[2,end,:])
facesets["top"] = Set{Tuple{Int,Int}}(boundary[(1:length(cell_array[2,:,end])) .+ offset]); offset += length(cell_array[2,:,end])
facesets["left"] = Set{Tuple{Int,Int}}(boundary[(1:length(cell_array[1,1,:])) .+ offset]); offset += length(cell_array[1,1,:])
return Grid(cells, nodes, facesets=facesets, boundary_matrix=boundary_matrix)
end
# Tetrahedron
function generate_grid(::Type{Tetrahedron}, cells_per_dim::NTuple{3,Int}, left::Vec{3,T}=Vec{3}((-1.0,-1.0,-1.0)), right::Vec{3,T}=Vec{3}((1.0,1.0,1.0))) where {T}
nodes_per_dim = cells_per_dim .+ 1
cells_per_cube = 6
total_nodes = prod(nodes_per_dim)
total_elements = cells_per_cube * prod(cells_per_dim)
n_nodes_x, n_nodes_y, n_nodes_z = nodes_per_dim
n_cells_x, n_cells_y, n_cells_z = cells_per_dim
# Generate nodes
coords_x = range(left[1], stop=right[1], length=n_nodes_x)
coords_y = range(left[2], stop=right[2], length=n_nodes_y)
coords_z = range(left[3], stop=right[3], length=n_nodes_z)
numbering = reshape(1:total_nodes, nodes_per_dim)
# Pre-allocate the nodes & cells
nodes = Vector{Node{3,T}}(undef, total_nodes)
cells = Vector{Tetrahedron}(undef, total_elements)
# Generate nodes
node_idx = 1
@inbounds for k in 1:n_nodes_z, j in 1:n_nodes_y, i in 1:n_nodes_x
nodes[node_idx] = Node((coords_x[i], coords_y[j], coords_z[k]))
node_idx += 1
end
# Generate cells, case 1 from: http://www.baumanneduard.ch/Splitting%20a%20cube%20in%20tetrahedras2.htm
# cube = (1, 2, 3, 4, 5, 6, 7, 8)
# left = (1, 4, 5, 8), right = (2, 3, 6, 7)
# front = (1, 2, 5, 6), back = (3, 4, 7, 8)
# bottom = (1, 2, 3, 4), top = (5, 6, 7, 8)
cell_idx = 0
@inbounds for k in 1:n_cells_z, j in 1:n_cells_y, i in 1:n_cells_x
cell = (
numbering[i , j , k],
numbering[i+1, j , k],
numbering[i+1, j+1, k],
numbering[i , j+1, k],
numbering[i , j , k+1],
numbering[i+1, j , k+1],
numbering[i+1, j+1, k+1],
numbering[i , j+1, k+1]
)
cells[cell_idx + 1] = Tetrahedron((cell[1], cell[2], cell[4], cell[8]))
cells[cell_idx + 2] = Tetrahedron((cell[1], cell[5], cell[2], cell[8]))
cells[cell_idx + 3] = Tetrahedron((cell[2], cell[3], cell[4], cell[8]))
cells[cell_idx + 4] = Tetrahedron((cell[2], cell[7], cell[3], cell[8]))
cells[cell_idx + 5] = Tetrahedron((cell[2], cell[5], cell[6], cell[8]))
cells[cell_idx + 6] = Tetrahedron((cell[2], cell[6], cell[7], cell[8]))
cell_idx += cells_per_cube
end
# Order the cells as c_nxyz[n, x, y, z] such that we can look up boundary cells
c_nxyz = reshape(1:total_elements, (cells_per_cube, cells_per_dim...))
@views le = [map(x -> (x,4), c_nxyz[1, 1, :, :][:]) ; map(x -> (x,2), c_nxyz[2, 1, :, :][:])]
@views ri = [map(x -> (x,1), c_nxyz[4, end, :, :][:]) ; map(x -> (x,1), c_nxyz[6, end, :, :][:])]
@views fr = [map(x -> (x,1), c_nxyz[2, :, 1, :][:]) ; map(x -> (x,1), c_nxyz[5, :, 1, :][:])]
@views ba = [map(x -> (x,3), c_nxyz[3, :, end, :][:]) ; map(x -> (x,3), c_nxyz[4, :, end, :][:])]
@views bo = [map(x -> (x,1), c_nxyz[1, :, :, 1][:]) ; map(x -> (x,1), c_nxyz[3, :, :, 1][:])]
@views to = [map(x -> (x,3), c_nxyz[5, :, :, end][:]) ; map(x -> (x,3), c_nxyz[6, :, :, end][:])]
boundary_matrix = boundaries_to_sparse([le; ri; bo; to; fr; ba])
facesets = Dict(
"left" => Set(le),
"right" => Set(ri),
"front" => Set(fr),
"back" => Set(ba),
"bottom" => Set(bo),
"top" => Set(to),
)
return Grid(cells, nodes, facesets=facesets, boundary_matrix=boundary_matrix)
end
|
function estimatelearning(ID,N,T,S,y,x,Choice)
# PTypesl = PTypes(:)
# PTypeg = PType(Cl==1)
# PTypen = PType(Cl==2)
# PType4s = PType(Cl==3)
# PType4h = PType(Cl==4)
# PType2 = PType(Cl==5)
iteration = 1
J = convert(Int64,length(unique(Choice))-1)
Delta = rand(J,J)
Delta = 0.5.*(Delta+Delta')
@assert Delta == Delta'
sig = rand(J)
BigN,bstart,resid,abilsub,Resid,Csum,tresid,Psi1,sig2,cov2,sigtemp,covtemp = initlearning(N,T,J,Choice,y,x)
j=1
while maximum(maximum(abs.(covtemp.-Delta)))>1e-4
sigtemp=sig
covtemp=Delta
bstart,Delta,sig,Resid,resid,tresid,abilsub = estimatelearningcore(y,x,Choice,bstart,N,T,S,J,BigN,Delta,sig,Resid,resid,tresid,Psi1,abilsub,Csum)
sig2[j,:]=sig'
cov2[j,:]=LowerTriangular(Delta)[LowerTriangular(Delta).!=0]
println(j)
println(maximum(maximum(abs.(covtemp.-Delta))))
j+=1
end
Delta_corr = corrcov(Delta)
return bstart,sig,Delta,Delta_corr
end
|
Get the gorgeous 25% off cash back as PixelBolt coupon. Please have a look our provided PB image below for the instructions.
This is a program that can be used to ensure that. The tool is totally newbie friendly. It means anyone can use this program. It is easy to use. People can design their programs by following some simple steps. People will be able to design their videos also using this program. It shows that people from different sector can use this program that they can edit their video to promote their site. It can be helpful in that case to push the sales for the people. You can take the benefit of PixelBolt with the coupon offer. Using the PixelBolt discount will give you the tool at a less price.
PixelBolt is a newbie friendly program, so it is definitely an easy to use tool. People from different background can use it. People like to use those kinds of programs that are easy to use and takes less afford. It can be done by this tool. It is easy to use and people do not need to do too much to run this tool. There are many ways that the program can be utilized and some of the ways are less time consuming. People want to have those kind of programs that can save time significantly and saves a lot of time causing less time to consume. It gives people enough time to make a balance between their work and other stuffs.
Newbies also will not face any significant problems using this program because it has been made as newbie friendly. It has a lot of elements. It provides more than 2000 graphic elements. People can use those elements to design their website.
The tool can be used for website designing. People nowadays suffer a lot of website designing for many reasons. Website designing is not an easy task. It takes a lot of effort. Sometimes people have to spend months in online designing. Therefore, it needs proper planning. It costs a lot. It is not a cheap method, instead it is quite costly method. People have to spend a lot. However, people can decrease the amount of spending by using this tool. They can use the graphics from this software. Therefore, people can use this program to save their money and create high converting graphics.
PixelBolt can be used to create videos. Users can create videos by using this program. Users also can use the videos to post online to get more viewers. The software is easy to use and create animated videos. Users can use this software to create animated videos and promote their products online.
PixelBolt has a fixed price. The price is not too high and not too low, so any people can use this program. The price is only 37 dollars only without coupon. People with any decent income can afford this kind of application. The software itself is worth the price according to above studies.
In conclusion, please buy the PixelBolt with discount on price. We hope that you will like the Graphic and Video Making tool with PixelBolt coupon. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.