text
stringlengths 0
3.34M
|
---|
import copy
from tqdm import tqdm
import numpy as np
from scipy.spatial.transform import Rotation as R
import mujoco_py
def gravity_comp(sim, ndof=9):
# % qfrc_bias represents sum of Coriolis and gravity forces.
return sim.data.qfrc_bias[:ndof]
def get_mass_matrix(sim, ndof):
# % prepare array to hold result
m = np.ndarray(shape=(len(sim.data.qvel)**2,),
dtype=np.float64,
order='C')
# % call mujoco internal inertia matrix fuction
mujoco_py.cymj._mj_fullM(sim.model, m, sim.data.qM)
# % reshape to square, slice, and return
m=m.reshape(len(sim.data.qvel),-1)
return m[:ndof,:ndof]
def pd(qdd, qd, q, sim, kp=None, kv=None, ndof=12):
"""
inputs (in joint space):
qdd: desired accel
qd: desired vel
q: desire pos
(if any are None, that term is omitted from the control law)
kp, kv are scalars in 1D, PSD matrices otherwise
ndof is the number of degrees of freedom of the robot
returns M(q)[qdd + kpE + kvEd] + H(q,qdot)
with E = (q - sim.data.qpos), Ed = (qd - sim.data.qvel), H = sim.data.qfrc_bias
"""
# % handle None inputs
q = sim.data.qpos[:ndof] if q is None else q
qd = sim.data.qvel[:ndof] if qd is None else qd
qdd = [0]*len(sim.data.qpos[:ndof]) if qdd is None else qdd
kp = np.eye(len(sim.data.qpos[:ndof]))*150 if kp is None else kp
kv = np.eye(len(sim.data.qpos[:ndof]))*10 if kv is None else kv
# % compute the control as above
m = get_mass_matrix(sim, ndof)
bias = sim.data.qfrc_bias[:ndof]
e = q - sim.data.qpos[:ndof]
ed = qd - sim.data.qvel[:ndof]
tau_prime = qdd + np.matmul(kp, e) + np.matmul(kv, ed)
return np.matmul(m, tau_prime) + bias
def jac(sim, body, ndof):
"""
Computes Jacobian of body using q = sim.data.qpos, qdot = sim.data.qvel.
returns jacp, jacr (position, orientation jacobians)
note: I think I will soon concatenate jacp, jacr
"""
jacp = np.ndarray(shape=(3*len(sim.data.qpos)),
dtype=np.float64,
order='C')
jacr = np.ndarray(shape=jacp.shape,
dtype=np.float64,
order='C')
mujoco_py.cymj._mj_jacBody(sim.model,
sim.data,
jacp,
jacr,
body)
jacp=jacp.reshape(3,-1)
jacr=jacr.reshape(3,-1)
return jacp[:,:ndof], jacr[:,:ndof]
# def mj_ik_traj(y_star, T, env, ee_index, ndof=9):
# """
# moves end effector in a straight line in cartesian space from present pose to y_star
# TODO: position only at present - add orientation
# TODO: collision checking
# TODO: use fake environment for planning without execution
# """
# sim=env.sim
# y0 = np.array(sim.data.body_xpos[ee_index])
# q = sim.data.qpos[:ndof]
# qs=[]
# qs.append(q)
# ys = []
#
# for t in range(1,T):
# y=np.array(sim.data.body_xpos[ee_index])
# q = sim.data.qpos[:ndof]
# qvel=sim.data.qvel[:ndof]
#
# jacp,jacr = jac(sim, ee_index, ndof)
# y_hat = y0 + ( t*1.0 / (T*1.0) ) * (y_star-y0)
#
# jacp=jacp.reshape(3,-1)
#
# # % new joint positions
# q_update = np.linalg.pinv(jacp).dot( (y_hat - y).reshape(3,1) )
# q = q + q_update[:len(sim.data.qpos[:ndof])].reshape(len(sim.data.qpos[:ndof]),)
# qs.append(q)
# ys.append(y)
# action=pd(None,None, qs[t], env.sim)
# env.step(action)
#
# return qs, ys
def ee_regulation(x_des, sim, ee_index, kp=None, kv=None, ndof=9):
"""
This is pointless at present, but it is a building block
for more complex cartesian control.
PD control with gravity compensation in cartesian space
returns J^T(q)[kp(x_des - x) - kv(xdot)] + H(q,qdot)
TODO: quaternions or axis angles for full ee pose.
"""
kp = np.eye(len(sim.data.body_xpos[ee_index]))*10 if kp is None else kp
kv = np.eye(len(sim.data.body_xpos[ee_index]))*1 if kv is None else kv
jacp,jacr=jac(sim, ee_index, ndof)
# % compute
xdot = np.matmul(jacp, sim.data.qvel[:ndof])
error_vel = xdot
error_pos = x_des - sim.data.body_xpos[ee_index]
pos_term = np.matmul(kp,error_pos)
vel_term = np.matmul(kv,error_vel)
# % commanding ee pose only
F = pos_term - vel_term
torques = np.matmul(jacp.T, F) + sim.data.qfrc_bias[:ndof]
# torques = np.matmul(jacp.T, F)
return torques
def calculate_orientation_error(desired, current):
"""
Optimized function to determine orientation error
borrowed from robosuite. thanks, robosuite.
"""
def cross_product(vec1, vec2):
S = np.array(([0, -vec1[2], vec1[1]],
[vec1[2], 0, -vec1[0]],
[-vec1[1], vec1[0], 0]))
return np.dot(S, vec2)
rc1 = current[0:3, 0]
rc2 = current[0:3, 1]
rc3 = current[0:3, 2]
rd1 = desired[0:3, 0]
rd2 = desired[0:3, 1]
rd3 = desired[0:3, 2]
orientation_error = 0.5 * (cross_product(rc1, rd1) + cross_product(rc2, rd2) + cross_product(rc3, rd3))
return orientation_error
def ee_reg2(x_des, quat_des, sim, ee_index, kp=None, kv=None, ndof=12):
"""
same as ee_regulation, but now also accepting quat_des.
"""
kp = np.eye(len(sim.data.body_xpos[ee_index]))*10 if kp is None else kp
kv = np.eye(len(sim.data.body_xpos[ee_index]))*1 if kv is None else kv
jacp,jacr=jac(sim, ee_index, ndof)
# % compute position error terms as before
xdot = np.matmul(jacp, sim.data.qvel[:ndof])
error_vel = xdot
error_pos = x_des - sim.data.body_xpos[ee_index]
pos_term = np.matmul(kp,error_pos)
vel_term = np.matmul(kv,error_vel)
# % compute orientation error terms
current_ee_quat = copy.deepcopy(sim.data.body_xquat[ee_index])
current_ee_rotmat = R.from_quat([current_ee_quat[1],
current_ee_quat[2],
current_ee_quat[3],
current_ee_quat[0]])
target_ee_rotmat = R.from_quat([quat_des[1],
quat_des[2],
quat_des[3],
quat_des[0]])
ori_error = calculate_orientation_error(target_ee_rotmat.as_dcm(), current_ee_rotmat.as_dcm())
euler_dot = np.matmul(jacr, sim.data.qvel[:ndof])
ori_pos_term = np.matmul(kp, ori_error)
ori_vel_term = np.matmul(kv, euler_dot)
# % commanding ee pose only
F_pos = pos_term - vel_term
F_ori = ori_pos_term - ori_vel_term
J_full = np.concatenate([jacp, jacr])
F_full = np.concatenate([F_pos, F_ori])
torques = np.matmul(J_full.T, F_full) + sim.data.qfrc_bias[:ndof]
return torques
def generate_random_goal(n=9):
return np.random.rand(n)*np.pi / 2.0
def quat_to_scipy(q):
""" scalar last, [x,y,z,w]"""
return [q[1], q[2], q[3], q[0]]
def quat_to_mj(q):
""" scalar first, [w,x,y,z]"""
return [q[-1], q[0], q[1], q[2]]
# %%
def pseudoinv(J):
""" J is np.ndarray """
return J.T.dot(np.linalg.inv(J.dot(J.T)))
def ee_traj(y_star, T, sim, ee_index):
"""
naive straight line between present ee position and y_stars.
TODO: orientation.
"""
y0 = np.array(copy.deepcopy(sim.data.body_xpos[ee_index]))
y0_quat = np.array(copy.deepcopy(sim.data.body_xquat[ee_index]))
y_star = np.array(y_star)
ys=[]
for t in range(T):
# % new ee pose
# % TODO: orientation.
y_hat = y0 + ( t / (T) ) * (y_star-y0)
ys.append(y_hat)
return ys
def ik_traj(q0, y_star, T, sim, viewer, ee_index, ndof=6, testing=False):
"""
TODO: fix.
trajectory is proper, though PD isn't working.
"""
original_sim_state = sim.get_state()
y0 = np.array(copy.deepcopy(sim.data.body_xpos[ee_index]))
y0_quat = np.array(copy.deepcopy(sim.data.body_xquat[ee_index]))
y_star = np.array(y_star)
ys=[]
for t in tqdm(np.arange(1,T)):
y = copy.deepcopy(sim.data.body_xpos[ee_index])
# # % compute Jacobian
jacp,jacr=jac(sim, ee_index, ndof)
# % new ee pose
y_hat = y0 + ( t / (T) ) * (y_star-y0)
# % new joint positions
# TODO: orn
J_pos=np.array(jacp)
q_update = pseudoinv(J_pos).dot( (y_hat - y).reshape(3,1) )
q = q + q_update[:ndof].reshape(ndof,)
qs.append(q)
full_q = np.concatenate((q, np.zeros(6)))
full_qdot = np.zeros(12)
torques = pd(None, full_qdot, full_q, sim, ndof=len(sim.data.ctrl))
sim.data.ctrl[:ndof]=torques[:ndof]
sim.step()
viewer.render()
qs=np.array(qs)
# %% reset the simulation
sim.set_state(original_sim_state)
return qs
|
------------------------------------------------------------------------
-- The delay monad, defined using increasing sequences of potential
-- values
------------------------------------------------------------------------
{-# OPTIONS --safe #-}
module Delay-monad.Alternative where
open import Equality.Propositional
open import Prelude hiding (↑)
------------------------------------------------------------------------
-- _↓_ and _↑
module _ {a} {A : Type a} where
infix 4 _↑ _↓_
-- x ↓ y means that the computation x has the value y.
_↓_ : Maybe A → A → Type a
x ↓ y = x ≡ just y
-- x ↑ means that the computation x does not have a value.
_↑ : Maybe A → Type a
x ↑ = x ≡ nothing
------------------------------------------------------------------------
-- An alternative definition of the delay monad
module _ {a} {A : Type a} where
-- The property of being an increasing sequence.
LE : Maybe A → Maybe A → Type a
LE x y = x ≡ y ⊎ (x ↑ × ¬ y ↑)
Increasing-at : ℕ → (ℕ → Maybe A) → Type a
Increasing-at n f = LE (f n) (f (suc n))
Increasing : (ℕ → Maybe A) → Type a
Increasing f = ∀ n → Increasing-at n f
-- An alternative definition of the delay monad.
Delay : ∀ {a} → Type a → Type a
Delay A = ∃ λ (f : ℕ → Maybe A) → Increasing f
|
subroutine tara1dHydSer(arg)
use cfgio_mod, only: cfg_t, parse_cfg
implicit none
type(cfg_t):: cfg
real (kind=8), parameter :: pi = 3.14159265358979323846d0
include "fftw3.f"
integer (kind=4) N,Nh
real (kind = 8), dimension (:), allocatable :: x, ux, dux, ddux
complex (kind=8), dimension(:), allocatable :: uk,duk,dduk
integer*8 :: plan
real*8 :: L
integer :: i,t
real*8 dx,k,time,time_min,time_max,dt,nu
real (kind = 8), dimension (:), allocatable :: force_u_n, force_u_o
character (len=90) :: filename
character (len=32) :: arg
cfg = parse_cfg(arg)
call cfg%get("grid","Nx",N)
Nh = (N/2) + 1
allocate(x(N))
allocate(ux(N))
allocate(dux(N))
allocate(ddux(N))
allocate(force_u_n(N))
allocate(force_u_o(N))
allocate(uk(Nh))
allocate(duk(Nh))
allocate(dduk(Nh))
call cfg%get("length","Lx",L)
call cfg%get("resistivity","nu",nu)
call cfg%get("time","time_min",time_min)
call cfg%get("time","time_max",time_max)
call cfg%get("time","dt",dt)
L = L*pi
dx = L/dfloat(N)
do i = 1,N
x(i) = dfloat(i-1)*dx
ux(i) = dsin(x(i))
enddo
do time = time_min, time_max, dt
t = nint(time/dt) - int(time_min/dt)
call dfftw_plan_dft_r2c_1d(plan, N, ux, uk, FFTW_ESTIMATE)
call dfftw_execute_dft_r2c(plan, ux, uk)
call dfftw_destroy_plan(plan)
do i = 1,Nh
k = 2.0d0*pi*dfloat(i-1)/L
duk(i) = (0.0d0,1.0d0) * k * uk(i)
dduk(i) = - k * k * uk(i)
enddo
call dfftw_plan_dft_c2r_1d(plan, N, duk, dux, FFTW_ESTIMATE)
call dfftw_execute_dft_c2r(plan, duk, dux)
call dfftw_destroy_plan(plan)
call dfftw_plan_dft_c2r_1d(plan, N, dduk, ddux, FFTW_ESTIMATE)
call dfftw_execute_dft_c2r(plan, dduk, ddux)
call dfftw_destroy_plan(plan)
do i = 1,N
dux(i) = dux(i)/dfloat(N)
ddux(i) = ddux(i)/dfloat(N)
if (t .ge. 1000 .and. mod(t,500) == 0) then
write(filename, '("output/fort.",I8.8)') t
open(unit=t,file=filename,status='unknown')
write(t,*) t, x(i), ux(i)
endif
enddo
do i = 1,N
force_u_n(i) = -ux(i)*dux(i) + nu*ddux(i)
if (t==0) then
ux(i) = ux(i) + dt * force_u_n(i)
else
ux(i) = ux(i) + dt* ( (3.0/2.0) * force_u_n(i) - (1.0/2.0) * force_u_o(i))
endif
force_u_o(i) = force_u_n(i)
enddo
enddo
end subroutine tara1dHydSer
|
"
Для задания No 4 из Лабораторной работы No 2 написать программы
в которых Пользователь с клавиатуры вводит значения двух переменных разных типов,
которые затем сравниваются между собой. Использовать функции readline(), print(
и функции преобразования типов.
"
{
a1 <- as.integer(readline("Введите число №1 -> "))
a2 <- as.double(readline("Введите число №2 -> "))
print(paste("Тип числа №1:", typeof(a1)))
print(paste("Тип числа №2:", typeof(a2)))
if (a1 < a2) {
print("Число №1 больше")
} else{
print("Число №2 больше")
}
}
|
import tactic
import data.rat
import data.real.basic
import data.real.irrational
import game.basic.level02
namespace uwyo -- hide
open real -- hide
/-
# Chapter 2 : Sums
## Level 1
-/
/- Lemma
There are irrational numbers that sum up to a rational.
-/
theorem irrat_sum : ¬ (∀ (x y : ℝ), irrational x → irrational y → irrational (x+y)) :=
begin
intro H,
have H2 := H (sqrt 2) (-sqrt 2),
have H3 := H2 irrational_sqrt_two (irrational.neg irrational_sqrt_two),
apply H3,
existsi (0 : ℚ),
simp, done
end
end uwyo -- hide
|
/-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import field_theory.finite.basic
/-!
# The Chevalley–Warning theorem
This file contains a proof of the Chevalley–Warning theorem.
Throughout most of this file, `K` denotes a finite field
and `q` is notation for the cardinality of `K`.
## Main results
1. Let `f` be a multivariate polynomial in finitely many variables (`X s`, `s : σ`)
such that the total degree of `f` is less than `(q-1)` times the cardinality of `σ`.
Then the evaluation of `f` on all points of `σ → K` (aka `K^σ`) sums to `0`.
(`sum_mv_polynomial_eq_zero`)
2. The Chevalley–Warning theorem (`char_dvd_card_solutions`).
Let `f i` be a finite family of multivariate polynomials
in finitely many variables (`X s`, `s : σ`) such that
the sum of the total degrees of the `f i` is less than the cardinality of `σ`.
Then the number of common solutions of the `f i`
is divisible by the characteristic of `K`.
## Notation
- `K` is a finite field
- `q` is notation for the cardinality of `K`
- `σ` is the indexing type for the variables of a multivariate polynomial ring over `K`
-/
universes u v
open_locale big_operators
section finite_field
open mv_polynomial function (hiding eval) finset finite_field
variables {K : Type*} {σ : Type*} [fintype K] [field K] [fintype σ]
local notation `q` := fintype.card K
lemma mv_polynomial.sum_mv_polynomial_eq_zero [decidable_eq σ] (f : mv_polynomial σ K)
(h : f.total_degree < (q - 1) * fintype.card σ) :
(∑ x, eval x f) = 0 :=
begin
haveI : decidable_eq K := classical.dec_eq K,
calc (∑ x, eval x f)
= ∑ x : σ → K, ∑ d in f.support, f.coeff d * ∏ i, x i ^ d i : by simp only [eval_eq']
... = ∑ d in f.support, ∑ x : σ → K, f.coeff d * ∏ i, x i ^ d i : sum_comm
... = 0 : sum_eq_zero _,
intros d hd,
obtain ⟨i, hi⟩ : ∃ i, d i < q - 1, from f.exists_degree_lt (q - 1) h hd,
calc (∑ x : σ → K, f.coeff d * ∏ i, x i ^ d i)
= f.coeff d * (∑ x : σ → K, ∏ i, x i ^ d i) : mul_sum.symm
... = 0 : (mul_eq_zero.mpr ∘ or.inr) _,
calc (∑ x : σ → K, ∏ i, x i ^ d i)
= ∑ (x₀ : {j // j ≠ i} → K) (x : {x : σ → K // x ∘ coe = x₀}), ∏ j, (x : σ → K) j ^ d j :
(fintype.sum_fiberwise _ _).symm
... = 0 : fintype.sum_eq_zero _ _,
intros x₀,
let e : K ≃ {x // x ∘ coe = x₀} := (equiv.subtype_equiv_codomain _).symm,
calc (∑ x : {x : σ → K // x ∘ coe = x₀}, ∏ j, (x : σ → K) j ^ d j)
= ∑ a : K, ∏ j : σ, (e a : σ → K) j ^ d j : (e.sum_comp _).symm
... = ∑ a : K, (∏ j, x₀ j ^ d j) * a ^ d i : fintype.sum_congr _ _ _
... = (∏ j, x₀ j ^ d j) * ∑ a : K, a ^ d i : by rw mul_sum
... = 0 : by rw [sum_pow_lt_card_sub_one _ hi, mul_zero],
intros a,
let e' : {j // j = i} ⊕ {j // j ≠ i} ≃ σ := equiv.sum_compl _,
letI : unique {j // j = i} :=
{ default := ⟨i, rfl⟩, uniq := λ ⟨j, h⟩, subtype.val_injective h },
calc (∏ j : σ, (e a : σ → K) j ^ d j)
= (e a : σ → K) i ^ d i * (∏ (j : {j // j ≠ i}), (e a : σ → K) j ^ d j) :
by { rw [← e'.prod_comp, fintype.prod_sum_type, univ_unique, prod_singleton], refl }
... = a ^ d i * (∏ (j : {j // j ≠ i}), (e a : σ → K) j ^ d j) :
by rw equiv.subtype_equiv_codomain_symm_apply_eq
... = a ^ d i * (∏ j, x₀ j ^ d j) : congr_arg _ (fintype.prod_congr _ _ _) -- see below
... = (∏ j, x₀ j ^ d j) * a ^ d i : mul_comm _ _,
{ -- the remaining step of the calculation above
rintros ⟨j, hj⟩,
show (e a : σ → K) j ^ d j = x₀ ⟨j, hj⟩ ^ d j,
rw equiv.subtype_equiv_codomain_symm_apply_ne, }
end
variables [decidable_eq K] [decidable_eq σ]
/-- The Chevalley–Warning theorem.
Let `(f i)` be a finite family of multivariate polynomials
in finitely many variables (`X s`, `s : σ`) over a finite field of characteristic `p`.
Assume that the sum of the total degrees of the `f i` is less than the cardinality of `σ`.
Then the number of common solutions of the `f i` is divisible by `p`. -/
theorem char_dvd_card_solutions_family (p : ℕ) [char_p K p]
{ι : Type*} {s : finset ι} {f : ι → mv_polynomial σ K}
(h : (∑ i in s, (f i).total_degree) < fintype.card σ) :
p ∣ fintype.card {x : σ → K // ∀ i ∈ s, eval x (f i) = 0} :=
begin
have hq : 0 < q - 1, { rw [← fintype.card_units, fintype.card_pos_iff], exact ⟨1⟩ },
let S : finset (σ → K) := { x ∈ univ | ∀ i ∈ s, eval x (f i) = 0 },
have hS : ∀ (x : σ → K), x ∈ S ↔ ∀ (i : ι), i ∈ s → eval x (f i) = 0,
{ intros x, simp only [S, true_and, sep_def, mem_filter, mem_univ], },
/- The polynomial `F = ∏ i in s, (1 - (f i)^(q - 1))` has the nice property
that it takes the value `1` on elements of `{x : σ → K // ∀ i ∈ s, (f i).eval x = 0}`
while it is `0` outside that locus.
Hence the sum of its values is equal to the cardinality of
`{x : σ → K // ∀ i ∈ s, (f i).eval x = 0}` modulo `p`. -/
let F : mv_polynomial σ K := ∏ i in s, (1 - (f i)^(q - 1)),
have hF : ∀ x, eval x F = if x ∈ S then 1 else 0,
{ intro x,
calc eval x F = ∏ i in s, eval x (1 - f i ^ (q - 1)) : eval_prod s _ x
... = if x ∈ S then 1 else 0 : _,
simp only [(eval x).map_sub, (eval x).map_pow, (eval x).map_one],
split_ifs with hx hx,
{ apply finset.prod_eq_one,
intros i hi,
rw hS at hx,
rw [hx i hi, zero_pow hq, sub_zero], },
{ obtain ⟨i, hi, hx⟩ : ∃ (i : ι), i ∈ s ∧ eval x (f i) ≠ 0,
{ simpa only [hS, not_forall, not_imp] using hx },
apply finset.prod_eq_zero hi,
rw [pow_card_sub_one_eq_one (eval x (f i)) hx, sub_self], } },
-- In particular, we can now show:
have key : ∑ x, eval x F = fintype.card {x : σ → K // ∀ i ∈ s, eval x (f i) = 0},
rw [fintype.card_of_subtype S hS, card_eq_sum_ones, nat.cast_sum, nat.cast_one,
← fintype.sum_extend_by_zero S, sum_congr rfl (λ x hx, hF x)],
-- With these preparations under our belt, we will approach the main goal.
show p ∣ fintype.card {x // ∀ (i : ι), i ∈ s → eval x (f i) = 0},
rw [← char_p.cast_eq_zero_iff K, ← key],
show ∑ x, eval x F = 0,
-- We are now ready to apply the main machine, proven before.
apply F.sum_mv_polynomial_eq_zero,
-- It remains to verify the crucial assumption of this machine
show F.total_degree < (q - 1) * fintype.card σ,
calc F.total_degree ≤ ∑ i in s, (1 - (f i)^(q - 1)).total_degree : total_degree_finset_prod s _
... ≤ ∑ i in s, (q - 1) * (f i).total_degree : sum_le_sum $ λ i hi, _ -- see ↓
... = (q - 1) * (∑ i in s, (f i).total_degree) : mul_sum.symm
... < (q - 1) * (fintype.card σ) : by rwa mul_lt_mul_left hq,
-- Now we prove the remaining step from the preceding calculation
show (1 - f i ^ (q - 1)).total_degree ≤ (q - 1) * (f i).total_degree,
calc (1 - f i ^ (q - 1)).total_degree
≤ max (1 : mv_polynomial σ K).total_degree (f i ^ (q - 1)).total_degree :
total_degree_sub _ _
... ≤ (f i ^ (q - 1)).total_degree : by simp only [max_eq_right, nat.zero_le, total_degree_one]
... ≤ (q - 1) * (f i).total_degree : total_degree_pow _ _
end
/-- The Chevalley–Warning theorem.
Let `f` be a multivariate polynomial in finitely many variables (`X s`, `s : σ`)
over a finite field of characteristic `p`.
Assume that the total degree of `f` is less than the cardinality of `σ`.
Then the number of solutions of `f` is divisible by `p`.
See `char_dvd_card_solutions_family` for a version that takes a family of polynomials `f i`. -/
theorem char_dvd_card_solutions (p : ℕ) [char_p K p]
{f : mv_polynomial σ K} (h : f.total_degree < fintype.card σ) :
p ∣ fintype.card {x : σ → K // eval x f = 0} :=
begin
let F : unit → mv_polynomial σ K := λ _, f,
have : ∑ i : unit, (F i).total_degree < fintype.card σ,
{ simpa only [fintype.univ_punit, sum_singleton] using h, },
have key := char_dvd_card_solutions_family p this,
simp only [F, fintype.univ_punit, forall_eq, mem_singleton] at key,
convert key,
end
end finite_field
|
{-# OPTIONS --warning ShadowingInTelescope --allow-unsolved-metas #-}
open import Agda.Primitive
-- warning here
data _~_ {a a : Level} {A : Set a} (a : A) : A -> Set where
refl : a ~ a
module _ {a} {A : Set a} where
-- nothing: the repetition is in separate telescopes
data Eq (a : A) : (a : A) → Set where
refl : Eq a a
-- warning here
f : ∀ (a : Level) → ∀ {A : Set a} A ~ A → Set → Set
f a A ~ B = λ x → x
-- nothing here: the repetition is in separate telescopes
f' : ∀ a → Set a → Set a
f' a = g a where
g : ∀ a → Set a → Set a
g a z = z
-- nothing here: the variable {a} is not user-written
h : ∀ {a} → Set a → Set a
h = g _ where
g : ∀ a → Set a → Set a
g a z = z
i : (Set → Set → Set) → (∀ _ _ → _)
i f = f
|
In 1924 , the family moved into a four @-@ level , semi @-@ detached Victorian house at 23 The Waldrons . Barker had a studio built in the garden and her sister conducted a kindergarten in a room at the back of the house . The family lived frugally and attended both St. Edmund 's and St. Andrew 's in Croydon – " low " churches for the less privileged . Barker sometimes incorporated portraits of her fellow parishioners in her religious works . She was described by Canon Ingram Hill as " one of the pillars " of St. Andrew 's .
|
#############################################################################
# make gensym global, so that it can be shared with other 'global' routines
gensym := module ()
export ModuleApply;
local gs_counter, utf8, blocks, radix, unicode;
gs_counter := -1;
utf8 := proc(n :: integer, $)
local m;
if n<128 then n
elif n<2048 then 192+iquo(n,64,'m'), 128+m
elif n<65536 then 224+iquo(n,4096,'m'), 128+iquo(m,64,'m'), 128+m
elif n<2097152 then 240+iquo(n,262144,'m'), 128+iquo(m,4096,'m'), 128+iquo(m,64,'m'), 128+m
elif n<67108864 then 248+iquo(n,16777216,'m'), 128+iquo(m,262144,'m'), 128+iquo(m,4096,'m'), 128+iquo(m,64,'m'), 128+m
elif n<2147483648 then 248+iquo(n,1073741824,'m'), 128+iquo(m,16777216,'m'), 128+iquo(m,262144,'m'), 128+iquo(m,4096,'m'), 128+iquo(m,64,'m'), 128+m
end if
end proc;
blocks := map((b -> block(convert(op(0,b), decimal, hex), op(1,b))),
["4e00"(20950)]);
radix := `+`(op(map2(op, 2, blocks))) / 2;
unicode := proc(nn, $)
local n, b;
n := nn;
for b in blocks do
if n < op(2,b) then return n + op(1,b) else n := n - op(2,b) end if
end do
end proc;
ModuleApply := proc(x::name, $)
gs_counter := gs_counter + 1;
cat(x, op(map(StringTools:-Char, map(utf8 @ unicode, applyop(`+`, 1, map(`*`, convert(gs_counter, 'base', radix), 2), 1)))))
end proc;
end module: # gensym
#############################################################################
BindingTools := module ()
option package;
export generic_evalat, generic_evalatstar;
generic_evalat := proc(vv::{name,list(name)}, mm, eqs, $)
local v, m, eqsRemain, eq, rename, funs;
funs := map2(op, 0, indets(mm, 'function'));
eqsRemain := select(
(eq -> op(1,eq) <> op(2,eq)
and not has(op(1,eq), vv)
and (not (op(1,eq) :: 'name')
or depends(mm, op(1,eq))
or member(op(1,eq), funs))),
eqs);
if nops(eqsRemain) = 0 then return vv, mm end if;
m := mm;
rename := proc(v::name, $)
local vRename;
if depends(eqsRemain, v) then
vRename := gensym(v);
m := subs(v=vRename, m);
vRename
else
v
end if
end proc;
if vv :: name then
v := rename(vv)
else
v := map(rename, vv);
end if;
v, eval(m, eqsRemain);
end proc:
generic_evalatstar := proc(body, bound::list, eqs, $)
local indefinite, e, n, b, j;
e := foldl(((x,i) -> `if`(i::`=`,
lam(lhs(i), rhs(i), x),
lam(i, indefinite, x))),
body, op(bound));
e := eval(e, eqs); # Piggyback on `eval/lam`
n := nops(bound);
b := table();
for j from n to 1 by -1 do
b[j] := `if`(op(2,e)=indefinite, op(1,e), `=`(op(1..2,e)));
e := op(3,e);
end do;
e, [entries(b, 'nolist', 'indexorder')]
end proc:
end module: # BindingTools
|
(*
* Copyright 2014, NICTA
*
* This software may be distributed and modified according to the terms of
* the BSD 2-Clause license. Note that NO WARRANTY is provided.
* See "LICENSE_BSD2.txt" for details.
*
* @TAG(NICTA_BSD)
*)
theory WPEx
imports NonDetMonadVCG
begin
text {* Strengthen *}
lemma strengthen_congs_base: "A \<longrightarrow> A" by simp
ML {*
structure strengthen_congs = Generic_Data
(struct
type T = thm list
val empty = [@{thm "strengthen_congs_base"}]
val extend = I
val merge = Thm.merge_thms;
end);
structure Strengthen = struct
val strg_add = Thm.declaration_attribute
(fn thm =>
(strengthen_congs.map (Thm.add_thm thm)));
val strg_del = Thm.declaration_attribute
(fn thm =>
(strengthen_congs.map (Thm.del_thm thm)));
val setup =
Attrib.setup @{binding "strg"} (Attrib.add_del strg_add strg_del)
"strengthening congruence rules";
(* Divide and conquer *)
fun DIVCONQ (tac1, tac2) goal =
(tac1 goal) ORELSE ((tac2 THEN_ALL_NEW (DIVCONQ (tac1, tac2))) goal)
(* This is a little magic as it relies on A \<longrightarrow> A, the
first cong rule, eventually working *)
fun apply_rules_tac ctxt extras =
let
val r = strengthen_congs.get (Context.Proof ctxt);
in
(CHANGED (rtac mp 1 THEN (DIVCONQ
(((resolve_tac ctxt extras)
THEN_ALL_NEW (fn g => TRY (assume_tac ctxt g))),
(fn g => DETERM (resolve_tac ctxt r g))) 1)))
end;
val apply_rules_args =
Attrib.thms >> curry (fn (extras, ctxt) =>
Method.SIMPLE_METHOD (
apply_rules_tac ctxt extras
)
);
end
*}
setup "Strengthen.setup"
method_setup strengthen = {* Strengthen.apply_rules_args *}
"strengthen the goal"
lemma strengthen_congs_conj [strg]:
"\<lbrakk> A \<longrightarrow> A'; B \<longrightarrow> B' \<rbrakk> \<Longrightarrow> (A \<and> B) \<longrightarrow> (A' \<and> B')" by simp
text {* WPEx - the WP Extension Experiment *}
definition
mresults :: "('s, 'a) nondet_monad \<Rightarrow> ('a \<times> 's \<times> 's) set"
where
"mresults f = {(rv, s', s). (rv, s') \<in> fst (f s)}"
definition
assert_value_exported :: "'x \<times> 's \<Rightarrow> ('s, 'a) nondet_monad \<Rightarrow> ('x \<Rightarrow> ('s, 'a) nondet_monad)"
where
"assert_value_exported x f y \<equiv>
do s \<leftarrow> get; if x = (y, s) then f else fail od"
syntax
"_assert_bind" :: "['a, 'b] => dobind" ("_ =<= _")
translations
"do v =<= a; e od" == "a >>= CONST assert_value_exported v e"
"doE v =<= a; e odE" == "a >>=E CONST assert_value_exported v e"
lemma in_mresults_export:
"(rv, s', s) \<in> mresults (assert_value_exported (rv', s'') f rv'')
= ((rv, s', s) \<in> mresults f \<and> rv' = rv'' \<and> s'' = s)"
by (simp add: assert_value_exported_def mresults_def in_monad)
lemma in_mresults_bind:
"(rv, s', s) \<in> mresults (a >>= b)
= (\<exists>rv' s''. (rv, s', s'') \<in> mresults (b rv') \<and> (rv', s'', s) \<in> mresults a)"
apply (simp add: mresults_def bind_def)
apply (auto elim: rev_bexI)
done
lemma mresults_export_bindD:
"(rv, s', s) \<in> mresults (a >>= assert_value_exported (rv', s'') b)
\<Longrightarrow> (rv, s', s'') \<in> mresults b"
"(rv, s', s) \<in> mresults (a >>= assert_value_exported (rv', s'') b)
\<Longrightarrow> (rv', s'', s) \<in> mresults a"
by (simp_all add: in_mresults_export in_mresults_bind)
definition "wpex_name_for_id = id"
definition "wpex_name_for_id_prop p \<equiv> (p :: prop)"
lemma wpex_name_for_id_propI:
"PROP p \<Longrightarrow> PROP wpex_name_for_id_prop p"
by (simp add: wpex_name_for_id_prop_def)
lemma wpex_name_for_id_propE:
"PROP wpex_name_for_id_prop p \<Longrightarrow> PROP p"
by (simp add: wpex_name_for_id_prop_def)
lemma del_asm_rule:
"\<lbrakk> PROP P; PROP Q \<rbrakk> \<Longrightarrow> PROP Q"
by assumption
ML {*
val p_prop_var = Thm.cterm_of @{context} (Logic.varify_global @{term "P :: prop"});
fun del_asm_tac asm =
etac (cterm_instantiate [(p_prop_var, asm)] @{thm del_asm_rule});
fun subgoal_asm_as_thm tac =
Subgoal.FOCUS_PARAMS (fn focus => SUBGOAL (fn (t, _) => let
val asms = Logic.strip_assums_hyp t;
val ctxt = #context focus;
fun asm_tac asm = (Subgoal.FOCUS_PREMS (fn focus => let
fun is_asm asm' = asm aconv (Thm.concl_of asm');
val (asm' :: _) = filter is_asm (#prems focus);
in tac asm' end) (#context focus)
THEN_ALL_NEW del_asm_tac (Thm.cterm_of ctxt asm)) 1;
in
FIRST (map asm_tac asms)
end) 1);
exception SAME;
fun eta_flat (Abs (name, tp, (Abs a)))
= eta_flat (Abs (name, tp, eta_flat (Abs a)))
| eta_flat (Abs (_, _, t $ Bound 0))
= if member (op =) (loose_bnos t) 0 then raise SAME
else subst_bound (Bound 0, t)
| eta_flat (Abs (name, tp, t $ Abs a))
= eta_flat (Abs (name, tp, t $ eta_flat (Abs a)))
| eta_flat _ = raise SAME;
fun const_spine t = case strip_comb t of
(Const c, xs) => SOME (c, xs)
| (Abs v, []) => (const_spine (eta_flat (Abs v)) handle SAME => NONE)
| (Abs _, (_ :: _)) => error "const_spine: term not beta expanded"
| _ => NONE;
fun build_annotate' t wr ps = case (const_spine t, wr) of
(SOME (bd as ("NonDetMonad.bind", _), [a, b]),
"WPEx.mresults") => let
val (a', ps') = build_annotate' a "WPEx.mresults" ps;
in case const_spine b of
SOME (ass as ("WPEx.assert_value_exported", _), [rvs, c])
=> let
val (c', ps'') = build_annotate' c "WPEx.mresults" ps'
in (Const bd $ a' $ (Const ass $ rvs $ c'), ps'') end
| _ => let
val tp = fastype_of (Const bd);
val btp = domain_type (range_type tp);
val rtp = domain_type btp;
val stp = domain_type (range_type btp);
val mtp = range_type (range_type btp);
val ass = Const ("WPEx.assert_value_exported",
HOLogic.mk_prodT (rtp, stp) -->
(stp --> mtp) --> rtp --> stp --> mtp);
val rv = Bound (length ps');
val s = Bound (length ps' + 1);
val rvs = HOLogic.pair_const rtp stp $ rv $ s;
val b' = betapply (b, Bound (length ps'));
val borings = ["x", "y", "rv"];
val rvnms = case b of
Abs (rvnm, _, _) =>
if member op = borings rvnm then []
else [(rvnm, rvnm ^ "_st")]
| _ => [];
val cnms = case const_spine a' of
SOME ((cnm, _), _) => let
val cnm' = List.last (space_explode "." cnm);
in [(cnm' ^ "_rv", cnm' ^ "_st")] end
| _ => [];
val nms = hd (rvnms @ cnms @ [("rv", "s")]);
val ps'' = ps' @ [(fst nms, rtp), (snd nms, stp)];
val (b'', ps''') = build_annotate' b' "WPEx.mresults" ps'';
in (Const bd $ a' $ (ass $ rvs $ b''), ps''') end
end
| _ => (t, ps);
fun build_annotate asm =
case const_spine (HOLogic.dest_Trueprop (Envir.beta_norm asm)) of
SOME (memb as ("Set.member", _), [x, st]) => (case const_spine st of
SOME (mres as ("WPEx.mresults", _), [m]) => let
val (m', ps) = build_annotate' m "WPEx.mresults" [];
val _ = if null ps then raise SAME else ();
val t = Const memb $ x $ (Const mres $ m');
fun mk_exists ((s, tp), tm) = HOLogic.exists_const tp $ Abs (s, tp, tm);
in HOLogic.mk_Trueprop (Library.foldr mk_exists (rev ps, t)) end
| _ => raise SAME) | _ => raise SAME;
val in_mresults_ctxt =
Proof_Context.init_global @{theory NICTALib}
|> (fn ctxt => ctxt addsimps [@{thm in_mresults_export}, @{thm in_mresults_bind}])
|> Splitter.del_split @{thm split_if}
fun prove_qad ctxt term tac = Goal.prove ctxt [] [] term
(K (if Config.get ctxt quick_and_dirty andalso false
then ALLGOALS (Skip_Proof.cheat_tac ctxt)
else tac));
val preannotate_ss =
Proof_Context.init_global @{theory NICTALib}
|> put_simpset HOL_basic_ss
|> (fn ctxt => ctxt addsimps [@{thm K_bind_def}])
|> simpset_of
val in_mresults_ss =
Proof_Context.init_global @{theory NICTALib}
|> (fn ctxt => ctxt addsimps [@{thm in_mresults_export}, @{thm in_mresults_bind}])
|> Splitter.del_split @{thm split_if}
|> simpset_of
val in_mresults_cs = Classical.claset_of (Proof_Context.init_global @{theory NICTALib})
fun annotate_tac ctxt asm = let
val asm' = simplify (put_simpset preannotate_ss ctxt) asm;
val annotated = build_annotate (Thm.concl_of asm');
val ctxt' = Classical.put_claset in_mresults_cs (put_simpset in_mresults_ss ctxt)
val thm = prove_qad ctxt (Logic.mk_implies (Thm.concl_of asm', annotated))
(auto_tac ctxt'
THEN ALLGOALS (TRY o blast_tac ctxt'));
in
cut_facts_tac [asm' RS thm] 1
end
handle SAME => no_tac;
fun annotate_goal_tac ctxt
= REPEAT_DETERM1 (subgoal_asm_as_thm (annotate_tac ctxt) ctxt 1
ORELSE etac exE 1);
val annotate_method =
Scan.succeed (fn ctxt => Method.SIMPLE_METHOD (annotate_goal_tac ctxt))
: (Proof.context -> Method.method) context_parser;
*}
method_setup annotate = {* annotate_method *} "tries to annotate"
lemma use_valid_mresults:
"\<lbrakk> (rv, s', s) \<in> mresults f; \<lbrace>P\<rbrace> f \<lbrace>Q\<rbrace> \<rbrakk> \<Longrightarrow> P s \<longrightarrow> Q rv s'"
by (auto simp: mresults_def valid_def)
lemma mresults_validI:
"\<lbrakk> \<And>rv s' s. (rv, s', s) \<in> mresults f \<Longrightarrow> P s \<longrightarrow> Q rv s' \<rbrakk>
\<Longrightarrow> \<lbrace>P\<rbrace> f \<lbrace>Q\<rbrace>"
by (auto simp: mresults_def valid_def)
ML {*
val use_valid_mresults = @{thm use_valid_mresults};
val mresults_export_bindD = @{thms mresults_export_bindD};
fun dest_mresults_tac t = Seq.of_list ([t] RL mresults_export_bindD);
(* take a rule of conclusion p --> q and decide whether to use it
as an introduction rule or if of form ?P x --> ?P y to use it
as y = x *)
fun get_rule_uses ctxt rule = let
val (p, q) = (Thm.concl_of #> Envir.beta_eta_contract #> HOLogic.dest_Trueprop
#> HOLogic.dest_imp) rule;
fun mk_eqthm v (n, (x, _)) = let
val (_, tp) = dest_Var v;
val (argtps, tp') = strip_type tp;
val _ = if (tp' = @{typ bool}) then ()
else error "get_rule_uses: range type <> bool";
val ct = Thm.cterm_of ctxt;
val eq = HOLogic.eq_const (nth argtps (n - 1))
$ Bound (length argtps - n) $ x;
val v' = fold_rev Term.abs (map (pair "x") argtps) eq;
in rule
|> Thm.instantiate ([], [(ct v, ct v')])
|> simplify (put_simpset HOL_ss ctxt)
end;
in case (strip_comb p, strip_comb q) of
((v as Var _, args), (v' as Var _, args')) =>
if v = v' andalso length args = length args'
then (map (mk_eqthm v) ((1 upto length args) ~~ (args ~~ args')), [])
else ([], [])
| (_, (Var _, _)) => ([], [])
| _ => ([], [rule])
end;
fun get_wp_simps_strgs ctxt rules asms = let
val wp_rules = rules @ (WeakestPre.debug_get ctxt |> #rules |> WeakestPre.dest_rules);
val wp_rules' = filter (null o Thm.prems_of) wp_rules;
val asms' = maps (Seq.list_of o REPEAT dest_mresults_tac) asms;
val uses = asms' RL [use_valid_mresults];
val wp_rules'' = wp_rules' RL uses;
in
apply2 flat (map_split (get_rule_uses ctxt) wp_rules'')
end;
fun tac_with_wp_simps_strgs ctxt rules tac =
subgoal_asm_as_thm (fn asm => let
val (simps, strgs) = get_wp_simps_strgs ctxt rules [asm]
in
cut_facts_tac [asm] 1 THEN tac (simps, strgs)
end) ctxt;
val mresults_validI = @{thm mresults_validI};
val postcond_ss =
Proof_Context.init_global @{theory NICTALib}
|> put_simpset HOL_basic_ss
|> (fn ctxt => ctxt addsimps [@{thm pred_conj_def}])
|> simpset_of
val wp_default_ss =
Proof_Context.init_global @{theory NICTALib}
|> put_simpset HOL_ss
|> Splitter.del_split @{thm split_if}
|> simpset_of
fun raise_tac s = all_tac THEN (fn _ => error s);
fun wpx_tac ctxt rules
= TRY (rtac mresults_validI 1)
THEN (full_simp_tac (put_simpset postcond_ss ctxt) 1)
THEN TRY (annotate_goal_tac ctxt)
THEN tac_with_wp_simps_strgs ctxt rules (fn (simps, strgs) =>
REPEAT_DETERM1
(CHANGED (full_simp_tac (put_simpset wp_default_ss ctxt addsimps simps) 1)
ORELSE Strengthen.apply_rules_tac ctxt strgs)
) 1;
val wpx_method = Attrib.thms >> curry (fn (ts, ctxt) =>
Method.SIMPLE_METHOD (wpx_tac ctxt ts));
*}
method_setup wpx = {* wpx_method *} "experimental wp method"
lemma foo:
"(rv, s', s) \<in> mresults (do x \<leftarrow> get; y \<leftarrow> get; put (x + y :: nat); return () od)
\<Longrightarrow> s' = s + s"
apply annotate
apply wpx
done
lemma foo2:
"(rv, s', s) \<in> mresults (do x \<leftarrow> get; y \<leftarrow> get; put (if z = Suc 0 then x + y else x + y + z); return () od)
\<Longrightarrow> s' = s + s + (if z = Suc 0 then 0 else z)"
apply wpx
apply simp
done
text {* Have played around with it, the issues are:
1: Need to deal with non-linear code, known issue.
2: Using fastforce in annotate isn't cutting the mustard, need to automate better.
Probably half the issue is that there are too many simp rules available.
3: Related to (2), there's the question of whether you can simplify code enough
once it's been annotated. This may re-raise the specter of annotation on demand.
4: It's hard to tell whether it's worked or not.
5: Structural rules don't really work - rules that want to transform the whole
postcondition once we get up to a particular point. Related to 4, it's hard to
say where that point is hit.
6: Performance problems with getting the set of available rules.
*}
lemma valid_strengthen_with_mresults:
"\<lbrakk> \<And>s rv s'. \<lbrakk> (rv, s', s) \<in> mresults f;
wpex_name_for_id (Q' s rv s') \<rbrakk> \<Longrightarrow> Q rv s';
\<And>prev_s. \<lbrace>P prev_s\<rbrace> f \<lbrace>Q' prev_s\<rbrace> \<rbrakk>
\<Longrightarrow> \<lbrace>\<lambda>s. P s s\<rbrace> f \<lbrace>Q\<rbrace>"
apply atomize
apply (clarsimp simp: valid_def mresults_def wpex_name_for_id_def)
apply blast
done
lemma wpex_name_for_idE: "wpex_name_for_id P \<Longrightarrow> P"
by (simp add: wpex_name_for_id_def)
ML {*
val valid_strengthen_with_mresults = @{thm valid_strengthen_with_mresults};
val wpex_name_for_idE = @{thm wpex_name_for_idE};
fun wps_tac ctxt rules =
let
(* avoid duplicate simp rule etc warnings: *)
val ctxt = Context_Position.set_visible false ctxt
in
rtac valid_strengthen_with_mresults 1
THEN (safe_simp_tac (put_simpset postcond_ss ctxt) 1)
THEN Subgoal.FOCUS (fn focus => let
val ctxt = #context focus;
val (simps, _) = get_wp_simps_strgs ctxt rules (#prems focus);
in CHANGED (simp_tac (put_simpset wp_default_ss ctxt addsimps simps) 1) end) ctxt 1
THEN etac wpex_name_for_idE 1
end
val wps_method = Attrib.thms >> curry
(fn (ts, ctxt) => Method.SIMPLE_METHOD (wps_tac ctxt ts));
*}
method_setup wps = {* wps_method *} "experimental wp simp method"
lemma foo3:
"\<lbrace>P\<rbrace> do v \<leftarrow> return (Suc 0); return (Suc (Suc 0)) od \<lbrace>op =\<rbrace>"
apply (rule hoare_pre)
apply (rule hoare_seq_ext)+
apply (wps | rule hoare_vcg_prop)+
oops
end
|
static char help[] = "Broker for DYNHELICS\n";
#include <stdio.h>
#include <unistd.h>
#include <helics.h>
#include <petsc.h>
int main(int argc,char **argv)
{
helics_broker broker;
const char* helicsversion;
int isconnected;
char initstring[PETSC_MAX_PATH_LEN];
PetscInt nfederates=0;
PetscErrorCode ierr;
PetscInitialize(&argc,&argv,"petscopt",help);
helicsversion = helicsGetVersion();
printf("BROKER: Helics version = %s\n",helicsversion);
printf("%s",help);
ierr = PetscOptionsGetInt(NULL,NULL,"-nfeds",&nfederates,NULL);CHKERRQ(ierr);
if(!nfederates) {
SETERRQ(PETSC_COMM_SELF,0,"Number of federates need to be given with option -nfeds");
}
ierr = PetscSNPrintf(initstring,PETSC_MAX_PATH_LEN-1,"%d",nfederates);
ierr = PetscStrcat(initstring," --name=mainbroker");
/* Create broker */
broker = helicsCreateBroker("zmq","",initstring);
isconnected = helicsBrokerIsConnected(broker);
if(isconnected) {
printf("BROKER: Created and connected\n");
}
while(helicsBrokerIsConnected(broker)) {
usleep(1000); /* Sleep for 1 millisecond */
}
printf("BROKER: disconnected\n");
helicsBrokerFree(broker);
helicsCloseLibrary();
printf("Helics library closed\n");
PetscFinalize();
return 0;
}
|
@doc raw"""
costIntrICTV12(M, f, u, v, α, β)
Compute the intrinsic infimal convolution model, where the addition is replaced
by a mid point approach and the two functions involved are [`costTV2`](@ref)
and [`costTV`](@ref). The model reads
```math
E(u,v) =
\frac{1}{2}\sum_{i ∈ \mathcal G}
d_{\mathcal M}\bigl(g(\frac{1}{2},v_i,w_i),f_i\bigr)
+\alpha\bigl( \beta\mathrm{TV}(v) + (1-\beta)\mathrm{TV}_2(w) \bigr).
```
"""
function costIntrICTV12(M::Manifold, f, u, v, α, β)
IC = 1/2*distance(M, shortest_geodesic(M, u, v, 0.5), f)^2
TV12 = β * costTV(M, u) + (1-β) * costTV2(M, v)
return IC + α*TV12
end
@doc raw"""
costL2TV(M, f, α, x)
compute the $\ell^2$-TV functional on the `PowerManifold manifold `M` for given
(fixed) data `f` (on `M`), a nonnegative weight `α`, and evaluated at `x` (on `M`),
i.e.
```math
E(x) = d_{\mathcal M}^2(f,x) + \alpha \operatorname{TV}(x)
```
# See also
[`costTV`](@ref)
"""
costL2TV(M, f, α, x) = 1/2 * distance(M, f, x)^2 + α*costTV(M, x)
@doc raw"""
costL2TVTV2(M, f, α, β, x)
compute the $\ell^2$-TV-TV2 functional on the `PowerManifold` manifold `M` for
given (fixed) data `f` (on `M`), nonnegative weight `α`, `β`, and evaluated
at `x` (on `M`), i.e.
```math
E(x) = d_{\mathcal M}^2(f,x) + \alpha\operatorname{TV}(x)
+ \beta\operatorname{TV}_2(x)
```
# See also
[`costTV`](@ref), [`costTV2`](@ref)
"""
costL2TVTV2(M::PowerManifold, f, α, β, x) = 1/2*distance(M,f,x)^2 + α*costTV(M,x) + β*costTV2(M,x)
@doc raw"""
costL2TV2(M, f, β, x)
compute the $\ell^2$-TV2 functional on the `PowerManifold` manifold `M`
for given data `f`, nonnegative parameter `β`, and evaluated at `x`, i.e.
```math
E(x) = d_{\mathcal M}^2(f,x) + \beta\operatorname{TV}_2(x)
```
# See also
[`costTV2`](@ref)
"""
function costL2TV2(M::PowerManifold, f, β, x)
return 1/2*distance(M,f,x)^2 + β*costTV2(M,x)
end
@doc raw"""
costTV(M, x, p)
Compute the $\operatorname{TV}^p$ functional for a tuple `pT` of pointss
on a [Manifold](https://juliamanifolds.github.io/Manifolds.jl/stable/interface.html#ManifoldsBase.Manifold) `M`, i.e.
```math
E(x_1,x_2) = d_{\mathcal M}^p(x_1,x_2), \quad x_1,x_2 ∈ \mathcal M
```
# See also
[`∇TV`](@ref), [`prox_TV`](@ref)
"""
function costTV(M::Manifold, x::Tuple{T,T}, p::Int=1) where {T}
return distance(M,x[1],x[2])^p
end
@doc raw"""
costTV(M,x [,p=2,q=1])
Compute the $\operatorname{TV}^p$ functional for data `x`on the `PowerManifold`
manifold `M`, i.e. $\mathcal M = \mathcal N^n$, where $n ∈ \mathbb N^k$ denotes
the dimensions of the data `x`.
Let $\mathcal I_i$ denote the forward neighbors, i.e. with $\mathcal G$ as all
indices from $\mathbf{1} ∈ \mathbb N^k$ to $n$ we have
$\mathcal I_i = \{i+e_j, j=1,\ldots,k\}\cap \mathcal G$.
The formula reads
```math
E^q(x) = \sum_{i ∈ \mathcal G}
\bigl( \sum_{j ∈ \mathcal I_i} d^p_{\mathcal M}(x_i,x_j) \bigr)^{q/p}.
```
# See also
[`∇TV`](@ref), [`prox_TV`](@ref)
"""
function costTV(M::PowerManifold, x, p=1, q=1)
power_size = power_dimensions(M)
R = CartesianIndices(Tuple(power_size))
d = length(power_size)
maxInd = last(R)
cost = fill(0.,Tuple(power_size))
for k in 1:d # for all directions
ek = CartesianIndex(ntuple(i -> (i==k) ? 1 : 0, d) ) #k th unit vector
for i in R # iterate over all pixel
j = i+ek # compute neighbor
if all( map(<=, j.I, maxInd.I)) # is this neighbor in range?
cost[i] += costTV(
M.manifold,
(get_component(M,x,i),get_component(M,x,j)),
p
)
end
end
end
cost = (cost).^(1/p)
if q > 0
return sum(cost.^q)^(1/q)
else
return cost
end
end
@doc raw"""
costTV2(M,(x1,x2,x3) [,p=1])
Compute the $\operatorname{TV}_2^p$ functional for the 3-tuple of points
`(x1,x2,x3)`on the [Manifold](https://juliamanifolds.github.io/Manifolds.jl/stable/interface.html#ManifoldsBase.Manifold) `M`. Denote by
```math
\mathcal C = \bigl\{ c ∈ \mathcal M \ |\ g(\tfrac{1}{2};x_1,x_3) \text{ for some geodesic }g\bigr\}
```
the set of mid points between $x_1$ and $x_3$. Then the functionr reads
$d_2^p(x_1,x_2,x_3) = \min_{c ∈ \mathcal C} d_{\mathcal M}(c,x_2).$
# See also
[`∇TV2`](@ref), [`prox_TV2`](@ref)
"""
function costTV2(M::MT, x::Tuple{T,T,T}, p=1) where {MT <: Manifold, T}
# note that here mid_point returns the closest to x2 from the e midpoints between x1 x3
return 1/p*distance(M,mid_point(M,x[1],x[3]),x[2])^p
end
@doc raw"""
costTV2(M,x [,p=1])
compute the $\operatorname{TV}_2^p$ functional for data `x` on the
`PowerManifold` manifoldmanifold `M`, i.e. $\mathcal M = \mathcal N^n$,
where $n ∈ \mathbb N^k$ denotes the dimensions of the data `x`.
Let $\mathcal I_i^{\pm}$ denote the forward and backward neighbors, respectively,
i.e. with $\mathcal G$ as all indices from $\mathbf{1} ∈ \mathbb N^k$ to $n$ we
have $\mathcal I^\pm_i = \{i\pm e_j, j=1,\ldots,k\}\cap \mathcal I$.
The formula then reads
```math
E(x) = \sum_{i ∈ \mathcal I,\ j_1 ∈ \mathcal I^+_i,\ j_2 ∈ \mathcal I^-_i}
d^p_{\mathcal M}(c_i(x_{j_1},x_{j_2}), x_i),
```
where $c_i(\cdot,\cdot)$ denotes the mid point between its two arguments that is
nearest to $x_i$.
# See also
[`∇TV2`](@ref), [`prox_TV2`](@ref)
"""
function costTV2(M::PowerManifold, x, p::Int=1, Sum::Bool=true)
Tt = Tuple( power_dimensions(M) )
R = CartesianIndices( Tt )
d = length(Tt)
minInd, maxInd = first(R), last(R)
cost = fill(0., Tt)
for k in 1:d # for all directions
ek = CartesianIndex(ntuple(i -> (i==k) ? 1 : 0, d) ) #k th unit vector
for i in R # iterate over all pixel
jF = i+ek # compute forward neighbor
jB = i-ek # compute backward neighbor
if all( map(<=, jF.I, maxInd.I) ) && all( map(>=, jB.I, minInd.I)) # are neighbors in range?
cost[i] += costTV2(
M.manifold,
(get_component(M,x,jB),get_component(M,x,i),get_component(M,x,jF)),
p,
)
end
end # i in R
end # directions
if p != 1
cost = (cost).^(1/p)
end
if Sum
return sum(cost)
else
return cost
end
end
|
module Data.Vect.Extra
import Data.Vect
%access export
%default total
namespace Equality
vecEq : Eq type => Vect n type -> Vect m type -> Bool
vecEq [] [] = True
vecEq [] (x :: xs) = False
vecEq (x :: xs) [] = False
vecEq (x :: xs) (y :: ys) = x == y && vecEq xs ys
namespace Decidable
namespace SameLength
decEq : DecEq type
=> (n = m)
-> (xs : Vect n type)
-> (ys : Vect m type)
-> Dec (xs = ys)
decEq Refl xs ys with (decEq xs ys)
decEq Refl ys ys | (Yes Refl) = Yes Refl
decEq Refl xs ys | (No contra) = No contra
namespace DiffLength
vectorsDiffLength : DecEq type
=> (contra : (n = m) -> Void)
-> {xs : Vect n type}
-> {ys : Vect m type}
-> (xs = ys) -> Void
vectorsDiffLength contra Refl = contra Refl
decEq : DecEq type
=> (xs : Vect n type)
-> (ys : Vect m type)
-> Dec (xs = ys)
decEq xs ys {n} {m} with (decEq n m)
decEq xs ys {n = m} {m = m} | (Yes Refl) = decEq Refl xs ys
decEq xs ys {n = n} {m = m} | (No contra) = No (vectorsDiffLength contra)
|
lemma measure_UNION: assumes measurable: "range A \<subseteq> sets M" "disjoint_family A" assumes finite: "emeasure M (\<Union>i. A i) \<noteq> \<infinity>" shows "(\<lambda>i. measure M (A i)) sums (measure M (\<Union>i. A i))" |
\chapter{Trees, branches and (square) roots: why evolutionary relatedness is not linearly related to functional distance}
\chaptermark{Trees, branches and (square) roots}
\graphicspath{{Chapter3/Figs/}}
\begin{center}
{\large Andrew D. Letten and William K. Cornwell}
\small\textit{\textbf{Methods in Ecology and Evolution}} \textbf{(2014)}\\
\url{http://doi.wiley.com/10.1111/2041-210X.12237}
\vspace{1in}
\includegraphics[width=0.15\linewidth]{Chapter3/Figs/Einstein_whitejpg}
\vfill
This study was conceived by ADL and WCK. ADL and WCK contributed equally to scripting code for simulations and writing the manuscript.
\end{center}
\newpage
\section{Summary}
\begin{enumerate}
\item{
An increasingly popular practice in community ecology is to use the
evolutionary distance amongst interacting species as a proxy for their
overall functional similarity.
}
\item{
At the core of this approach is the implicit, yet poorly recognized,
assumption that trait dissimilarity increases linearly with divergence time,
i.e. all evolutionary time is considered equal. However, given a classic
Brownian model of trait evolution, we show that the expected functional
displacement of any two taxa is more appropriately represented as a linear
function of time's square root.
}
\item{
In light of this mismatch between theory and methodology, we argue that
current methods at the interface of ecology and evolutionary biology often greatly
overweight deep time relative to recent time.
}
\item{
An easy solution to this weighting problem is a square--root transformation of
the phylogenetic distance matrix. Using simulated models of trait evolution
and community assembly, we show that this transformation yields considerably
higher statistical power, with improvements in 92\% of trials. This methodological update is likely to improve our understanding of the connection between evolutionary relatedness and contemporary ecological processes.
}
\end{enumerate}
\newpage
\section{Introduction}
With increasingly precise estimates of the most common ancestor amongst interacting species, modern phylogenetics offers the
promise of a synthesis of contemporary ecology and evolutionary history \citep{Webb2002, Johnson2007, Cavender-Bares2009, cadotte2013,
Swenson2013}. Following on this, the last 10-15 years have seen a precipitous rise in the number of studies examining ecological
patterns and processes through the lens of evolutionary relatedness. Whilst this integrative approach has undoubtedly yielded new
insights, much of the foregoing research has proved inconclusive; contemporary ecological interactions often appear, using
conventional methods, to be unrelated to evolutionary history \citep{Cahill2008, Bennett2013, Narwani2013, Fritschie2013}. In this
comment we offer one explanation for the poor performance of the phylogenetic metrics used in contemporary ecology, as well as a
partial solution.
From the beginning of the phylogeny--ecology synthesis, evolutionary
relatedness has often been used a proxy for the traits mediating species'
interactions with each other and their environment. It is impossible to
measure all the relevant traits for complex ecological interactions, but
because evolution is a conservative branching process and traits are on
average more conserved than random, phylogenies have the potential to provide
an integrative measure across all traits \citep{Webb2000}. It follows that the
strength of this inference is contingent on an accurate model of how
phylogenetic and functional distance covary. There is a widespread assumption in the literature \citep[see Figure 1b of][]
{cadotte2013} that phylogenetic and functional distance scale linearly. This assumption is
implicit in many of the conventional metrics for assessing phylogenetic community structure and
phylogenetic diversity \citep{vellend2010}. Below we consider this assumption
critically, using current theory on trait evolution.
The classic, ``default'' model for trait evolution is Brownian motion
\citep[Figure \ref{sq_root_fig}b and][]{Felsenstein1985}.
The diffusion equation for Brownian motion \citep{Einstein1905} has the form:
\begin{equation}
\frac{\partial\rho}{\partial t}=\sigma^2\frac{\partial^2\rho}{\partial x^2}
\end{equation}
where $\sigma^2$ is the diffusion constant, t is time, $\rho$ is density and $x$ is position in space. That equation has the solution:
\begin{equation}
\rho(x,t)=\frac{\rho_0}{\sqrt{4\pi \sigma^2t}}e^{-\frac{x^2}{4\sigma^2t}}
\end{equation}
which implies that the second moment of the distribution is:
\begin{equation}
\overline{x^2}=2\sigma^2t.
\end{equation}
In other words, the variance goes up linearly with time and the standard deviation rises with time's square root, or as
Einstein put it: ``the mean displacement is therefore proportional to the square root of the time''. Applied in a phylogenetic context
this means that while among species variance in trait values goes up linearly
with time \citep{Felsenstein1985}, the expected displacement of any two taxa in trait space
does not increase linearly with time, but rather with time's square root (Figure \ref{sq_root_fig}). This non-linearity is true both for one trait
and for Euclidean distance in \textit{n}-dimensional trait space. Indeed, there is no plausible
model for expected trait dissimilarity to be linearly related to evolutionary
time. For there to be a linear relationship, after a speciation event, the functional distance between two lineages would increase constantly and continuously as their traits evolve away from each other. It is difficult to imagine a scenario where that would be the case.
\begin{figure}[H]
\centering
\includegraphics[width=1.00\textwidth]{sq_root_resub.png}
\caption{Panel (a) shows a Yule phylogeny. Panel (b) shows a ``traitgram'' with one Brownian motion
simulation with the trait value on the y--axis. Panel (c) shows the effect of time on the standard deviation of trait values at the tips for 2000 simulations with the same Brownian motion rate parameter; each point represents the standard deviation of the trait values of extant species within a separate simulation. Panel (d) shows the pairwise trait differences for 50000 simulations plotted against phylogenetic distance. Panel (e) simply takes the data from panel (d) and places them in bins, to show the statistical expectation at a given relatedness. Panel (e) shows the effect of taking the square root of the phylogenetic distance matrix on the relationship between the phylogenetic distance and the expected trait difference. Note that the expectation for the trait standard deviation and the pairwise difference is linear with respect to the square root of time as shown analytically in the text. All simulations use code from FitzJohn (2012) and Revell (2012).}
\label{sq_root_fig}
\end{figure}
While this technical point is well understood in parts of the comparative methods literature
\citep{Hardy2012}, the implications for many ecological applications has gone largely unnoticed.
If evolutionary relatedness is used as a proxy for functional distance, the non-linearity of their
scaling relationship means that more recent evolution should have a disproportional
influence on contemporary ecology. Current methods used in community phylogenetics \citep[see
review of methods
in][]{vellend2010} typically treat evolutionary relatedness linearly; 1 and 6 million
year relatedness difference is treated as having the same expected effect as a
101 and 106 million year relatedness difference. All evolutionary time is
considered equal, whether that time occurred over the last 5 million years or
more than 100 million years ago. Combined with imbalanced trees, this creates
a problem that is well known in empirical investigations: the statistical
over-weighting of early-diverged, low diversity clades \citep{Kembel2006}.
When those clades are included in the sample (or in a randomization), they
have a disproportionate weight on the test statistic, a weight that is highly
disproportionate to the expected trait difference under a Brownian model.
The root of this problem is in the distribution of pairwise phylogenetic distances. In the
basic simulated birth-death trees, there is an equal probability at every time
step for every branch of either a speciation or an extinction event. This creates what are known as balanced trees \citep[][also Figure
\ref{tree_fig}]{heard1997}. Balanced trees are rare in empirical studies, as heterogeneity in net diversification \citep{alfaro2009} creates trees that are imbalanced \citep{mooers1995} and have peculiar distributions of pairwise distances (e.g. the vascular plant tree from \citet{zanne2014} in Figure \ref{phylo_dist_hist}).
\begin{figure}[H]
\centering
\includegraphics[width=1.00\textwidth]{trees_resub.pdf}
\caption{Example of a real tree (top), obtained by randomly selecting taxa from the Zanne et al. (2014) tree, compared with a
homogeneous birth-death simulation tree (bottom).}
\label{tree_fig}
\end{figure}
Drawing from theory on Brownian motion reveals a simple solution to the weighting
problem: a square--root transform of the phylogenetic distance matrix. For
example, the mean pairwise distance \citep[sensu][]{Webb2000}:
\begin{equation}
MPD=\frac{2\sum_{i=1}^{n-1} \sum^n_{j=i+1} d_{i,j}}{(n)(n-1)}
\end{equation}
can be redefined as the mean of the square--root transformed pairwise distances:
\begin{equation}
MPD^*=\frac{2\sum_{i=1}^{n-1} \sum^n_{j=i+1} \sqrt{d_{i,j}}}{(n)(n-1)}
\end{equation}
where $n$ is the number of taxa and $d_{i,j}$ is the pairwise phylogenetic
distance between species $i$ and species $j$. This quantity $MPD^*$ is
proportional to the mean of the expected pairwise differences for traits
evolving under a Brownian model, for both one trait in one dimension and for
$m$ traits in $m$ dimensional space. This equation is provided as an example:
very similar adjustments are possible to most of the common community
phylogenetics statistics \citep[see definitions within][]{vellend2010}, simply
via a square-root transform of the distance matrix.
With this transformation, long--ago time is down weighted compared to recent
time. As such, the effect of the presence or absence of a species on MPD
is weighted in proportion to the mean pairwise expected trait difference to all other species under a Brownian model. In practical terms this re-scaling can be accomplished exceedingly
easily with one additional line of code in combination with the tools in
widely available statistical packages
\citep{Kembel2010}.
\begin{figure}[H]
\centering
\includegraphics[width=1.00\textwidth]{phylo_dist_hist_corrected.pdf}
\caption{The pairwise phylogenetic distances from a recent phylogeny of vascular plants by Zanne et al. (2014) and a simulated phylogeny
of the same age and number of
extant species.}
\label{phylo_dist_hist}
\end{figure}
\section{Simulations}
To explore the empirical implications of this idea, we conducted simulations applying a similar framework to that described by \citet[][in this case repeating the `filtering-derived' and `neutral assembly' algorithms]{kraft2007}. We simulated trait evolution by Brownian motion on both a real tree and a homogenous birth-death simulated tree (Figure \ref{tree_fig}). To keep the pool size (number of tree tips) consistent across the real and simulated trees, the real tree was randomly pruned down to 200 taxa. In each run, we 'evolved' a trait across the phylogeny and then applied one of two community assembly filters to obtain a final community of 40 taxa. Under the 'filtering derived' assembly filter, the most derived (extreme) trait-value was treated as the optimum, with the remaining 39 places in the community selected from taxa having the nearest trait values to that optimum. This process simulated community assembly via habitat filtering \citep{Diaz1998}, whereby the abiotic environment sets some threshold on the range of strategies (and thereby trait values) that are able to sustain a positive population growth rate (e.g. tolerance of inundation along a hydrological gradient). In contrast with the deterministic nature of the `filtering-derived' algorithm, under the `neutral assembly' algorithm the community was obtained by randomly selecting 40 species independent of their trait values. One--thousand runs were conducted for each community assembly algorithm on each of the real and simulated phylogenies. Finally, we quantified the effect of the filter using conventional community phylogenetics methods (MPD and MNTD - mean nearest taxon distance), and compared the standard approach with that of a square--root transform of the phylogenetic distance matrix (all code to perform replicate simulations is provided in Appendix B).
Simulation results indicate the transformed test has considerably higher statistical power (Figure
\ref{stat_power_fig}) for detecting the signal of community assembly. Using
the square--root transform improved 92\% of trials for both MPD and MNTD. Using the standardized effect size metric developed by
\cite{Webb2000}, whereby:
$$SES_{METRIC} = \frac{METRIC_{observed} - mean(METRIC_{null})}{sd(METRIC_{null})}$$
the median improvement in standardized effect size was 0.64
for MPD and 0.43 for MNTD (simulated and real trees combined).
This is a comparatively large increase in effect size from a simple statistical
adjustment. The improvement was similar for real and simulated
trees, but may be more crucial in the real case because the general power of
community phylogenetics is lower for the real tree \citep{Kembel2006}. While a comprehensive exploration of the effect of the transformation on type 1 error rates is beyond the scope of this paper \citep[see][]{kraft2007}, simulations indicated that the expected reduction in type 2 error rate is in the order of 5-25\% (depending on the community to pool size ratio and other factors).
\begin{figure}[H]
\centering
\includegraphics[width=1.00\textwidth]{bm_diff_p220_c40.pdf}
\caption{Improved statistical power from down-weighting long-ago evolution: change in standardized effect size for mean pairwise
distance (MPD) and mean nearest taxa distance (MNTD) using a square-root transformed phylogenetic distance matrix versus the
conventional approach. Box plots with grey-fill group communities assembled under a neutral (random sample) model; box plots with
red-fill group communities assembled under a 'habitat filter' model.}
\label{stat_power_fig}
\end{figure}
\section{Other models of trait evolution}
While a highly useful ``default'' model, we do not expect that a Brownian
motion model will prove to be a fully adequate model for trait
evolution at large scales. In general, the current evidence suggests that
actually the square--root transform does not go far enough toward
down--weighting long--ago evolution compared to recent evolution in many cases
\citep{butler2004, harmon2010, smith2010evolution}. In the event that there
are bounding or mean-reverting processes \citep[e.g. Ornstein--Uhlenbeck (OU)][]{butler2004}, phylogenetic
signal will be less strong than under a Brownian model. Under these alternative models the effect
of evolutionary
relatedness
decays more rapidly, a phenomena defined as ``phylogenetic half-life'' by \citet{hansen2008comparative}.
If trait evolution typically includes this type of process, the problem we describe here will be even more extreme.
In this case \citep[see][]{kelly2014phylogenetic}, the square--root transformation will not
go far enough. For the alternatives to Brownian motion, such as OU and
heterogeneous models where rates of evolution vary among clades \citep{beaulieu2012modeling}, there are analogous tree scaling approaches \citep{Pearse2013a}, but these, unlike the square--root transformation,
require \emph{a priori} information about trait evolution in the relevant
clade.
\section{Conclusion}
We recommend a square--root transform of the phylogenetic distance matrix for
all uses where phylogenetic relatedness is used as a proxy for current--day
functional disparity. There are some cases where the number of years of
evolutionary history in a place may be an interesting quantity in and of
itself \citep{purvis2000}. In those cases linear relatedness may still be of
interest; however, many ecological studies use evolutionary relatedness as a
proxy for trait dissimilarity and in these cases using relatedness linearly
will decrease the power of the investigation.
While we have made a statistical argument above, in conclusion we stress that
this is actually a conceptual point. We argue that conventional approaches over-weight long-ago
evolutionary time and under-weight recent evolution both conceptually and statistically, and in
doing so inadvertently limit the statistical power and success of efforts to leverage phylogenetic
information in ecological contexts. There are many other reasons why the mapping of
ecological process to phylogenetic community patterns may be inconclusive \citep{Mayfield2010, Godoy2014}; many of these issues are hard to address. Here, we have identified one problem---
the weighting of evolutionary history---where a simple
adjustment may help.
Of course, by using the square-root transformation we make the assumption that trait differences scale linearly with ecological fitness. While disentangling the ecological/evolutionary processes is somewhat intractable in this instance, this is at least a parsimonious assumption. Instead, justification for using more complex measures of functional distance (e.g. squared distance) in the context of ecological selection/assembly should be contingent on supporting theory. To our knowledge none exists. The magnitude of fitness-trait relationships has received some attention \citep{Kimball2011, Adler2013a} but explicitly exploring their scaling properties could well prove an invaluable area of future research.
In general, there needs to be a more nuanced use of evolutionary relatedness within community
ecology. By improving the connection between metrics within community phylogenetics and trait
evolution, we can increase the power and utility of using evolutionary relatedness to ask ecological questions.
This methodological update will not be a one-off: as our understanding of the processes and patterns in trait macro-evolution at large
scales grows \citep{omeara2012, pennell2013integrative}, the phylogenetic metrics used in contemporary ecology will need to be
continually updated.
\subsection*{Acknowledgements}
Thanks to Nathan Kraft, Rich FitzJohn, Rob Kooyman, Sandrine Pavoine and an anonymous reviewer for insightful comments.
\subsection*{Data accessibility}
R code to reproduce simulations provided in Appendix B.
\nocite{zanne2014, FitzJohn2012, Revell2012}
%\bibliographystyle{mee}
%\bibliography{bm_scaling}
|
{-# OPTIONS --without-K --safe #-}
-- The 'Trivial' instance, with a single arrow between objects
module Categories.Theory.Lawvere.Instance.Triv where
open import Data.Nat using (_*_)
open import Data.Unit.Polymorphic using (⊤; tt)
open import Relation.Binary.PropositionalEquality
using (_≡_; refl; isEquivalence)
open import Categories.Theory.Lawvere using (LawvereTheory)
Triv : ∀ {ℓ} → LawvereTheory ℓ ℓ
Triv = record
{ L = record
{ _⇒_ = λ _ _ → ⊤
; _≈_ = _≡_
; assoc = refl
; sym-assoc = refl
; identityˡ = refl
; identityʳ = refl
; identity² = refl
; equiv = isEquivalence
; ∘-resp-≈ = λ _ _ → refl
}
; T = record
{ terminal = record { ⊤ = 0 ; ⊤-is-terminal = record { ! = tt ; !-unique = λ _ → refl } }
; products = record
{ product = λ {m} {n} → record
{ A×B = m * n
; project₁ = refl
; project₂ = refl
; unique = λ _ _ → refl
}
}
}
; I = record
{ F₁ = λ _ → tt
; identity = refl
; homomorphism = refl
; F-resp-≈ = λ _ → refl
}
; CartF = record
{ F-resp-⊤ = record { ! = tt ; !-unique = λ _ → refl }
; F-resp-× = record { ⟨_,_⟩ = λ _ _ → tt ; project₁ = refl ; project₂ = refl ; unique = λ _ _ → refl }
}
}
|
/-
Copyright (c) 2020 Johan Commelin and Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin and Robert Y. Lewis
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.padics.padic_integers
import Mathlib.PostPort
universes u_1
namespace Mathlib
/-!
# Relating `ℤ_[p]` to `zmod (p ^ n)`
In this file we establish connections between the `p`-adic integers $\mathbb{Z}_p$
and the integers modulo powers of `p`, $\mathbb{Z}/p^n\mathbb{Z}$.
## Main declarations
We show that $\mathbb{Z}_p$ has a ring hom to $\mathbb{Z}/p^n\mathbb{Z}$ for each `n`.
The case for `n = 1` is handled separately, since it is used in the general construction
and we may want to use it without the `^1` getting in the way.
* `padic_int.to_zmod`: ring hom to `zmod p`
* `padic_int.to_zmod_pow`: ring hom to `zmod (p^n)`
* `padic_int.ker_to_zmod` / `padic_int.ker_to_zmod_pow`: the kernels of these maps are the ideals
generated by `p^n`
We also establish the universal property of $\mathbb{Z}_p$ as a projective limit.
Given a family of compatible ring homs $f_k : R \to \mathbb{Z}/p^n\mathbb{Z}$,
there is a unique limit $R \to \mathbb{Z}_p$.
* `padic_int.lift`: the limit function
* `padic_int.lift_spec` / `padic_int.lift_unique`: the universal property
## Implementation notes
The ring hom constructions go through an auxiliary constructor `padic_int.to_zmod_hom`,
which removes some boilerplate code.
-/
namespace padic_int
/-! ### Ring homomorphisms to `zmod p` and `zmod (p ^ n)` -/
/--
`mod_part p r` is an integer that satisfies
`∥(r - mod_part p r : ℚ_[p])∥ < 1` when `∥(r : ℚ_[p])∥ ≤ 1`,
see `padic_int.norm_sub_mod_part`.
It is the unique non-negative integer that is `< p` with this property.
(Note that this definition assumes `r : ℚ`.
See `padic_int.zmod_repr` for a version that takes values in `ℕ`
and works for arbitrary `x : ℤ_[p]`.) -/
def mod_part (p : ℕ) (r : ℚ) : ℤ := rat.num r * nat.gcd_a (rat.denom r) p % ↑p
theorem mod_part_lt_p {p : ℕ} [hp_prime : fact (nat.prime p)] (r : ℚ) : mod_part p r < ↑p := sorry
theorem mod_part_nonneg {p : ℕ} [hp_prime : fact (nat.prime p)] (r : ℚ) : 0 ≤ mod_part p r := sorry
theorem is_unit_denom {p : ℕ} [hp_prime : fact (nat.prime p)] (r : ℚ) (h : norm ↑r ≤ 1) :
is_unit ↑(rat.denom r) :=
sorry
theorem norm_sub_mod_part_aux {p : ℕ} [hp_prime : fact (nat.prime p)] (r : ℚ) (h : norm ↑r ≤ 1) :
↑p ∣ rat.num r - rat.num r * nat.gcd_a (rat.denom r) p % ↑p * ↑(rat.denom r) :=
sorry
theorem norm_sub_mod_part {p : ℕ} [hp_prime : fact (nat.prime p)] (r : ℚ) (h : norm ↑r ≤ 1) :
norm ({ val := ↑r, property := h } - ↑(mod_part p r)) < 1 :=
sorry
theorem exists_mem_range_of_norm_rat_le_one {p : ℕ} [hp_prime : fact (nat.prime p)] (r : ℚ)
(h : norm ↑r ≤ 1) : ∃ (n : ℤ), 0 ≤ n ∧ n < ↑p ∧ norm ({ val := ↑r, property := h } - ↑n) < 1 :=
Exists.intro (mod_part p r)
{ left := mod_part_nonneg r,
right := { left := mod_part_lt_p r, right := norm_sub_mod_part r h } }
theorem zmod_congr_of_sub_mem_span_aux {p : ℕ} [hp_prime : fact (nat.prime p)] (n : ℕ)
(x : padic_int p) (a : ℤ) (b : ℤ) (ha : x - ↑a ∈ ideal.span (singleton (↑p ^ n)))
(hb : x - ↑b ∈ ideal.span (singleton (↑p ^ n))) : ↑a = ↑b :=
sorry
theorem zmod_congr_of_sub_mem_span {p : ℕ} [hp_prime : fact (nat.prime p)] (n : ℕ) (x : padic_int p)
(a : ℕ) (b : ℕ) (ha : x - ↑a ∈ ideal.span (singleton (↑p ^ n)))
(hb : x - ↑b ∈ ideal.span (singleton (↑p ^ n))) : ↑a = ↑b :=
zmod_congr_of_sub_mem_span_aux n x (↑a) (↑b) ha hb
theorem zmod_congr_of_sub_mem_max_ideal {p : ℕ} [hp_prime : fact (nat.prime p)] (x : padic_int p)
(m : ℕ) (n : ℕ) (hm : x - ↑m ∈ local_ring.maximal_ideal (padic_int p))
(hn : x - ↑n ∈ local_ring.maximal_ideal (padic_int p)) : ↑m = ↑n :=
sorry
theorem exists_mem_range {p : ℕ} [hp_prime : fact (nat.prime p)] (x : padic_int p) :
∃ (n : ℕ), n < p ∧ x - ↑n ∈ local_ring.maximal_ideal (padic_int p) :=
sorry
/--
`zmod_repr x` is the unique natural number smaller than `p`
satisfying `∥(x - zmod_repr x : ℤ_[p])∥ < 1`.
-/
def zmod_repr {p : ℕ} [hp_prime : fact (nat.prime p)] (x : padic_int p) : ℕ :=
classical.some (exists_mem_range x)
theorem zmod_repr_spec {p : ℕ} [hp_prime : fact (nat.prime p)] (x : padic_int p) :
zmod_repr x < p ∧ x - ↑(zmod_repr x) ∈ local_ring.maximal_ideal (padic_int p) :=
classical.some_spec (exists_mem_range x)
theorem zmod_repr_lt_p {p : ℕ} [hp_prime : fact (nat.prime p)] (x : padic_int p) :
zmod_repr x < p :=
and.left (zmod_repr_spec x)
theorem sub_zmod_repr_mem {p : ℕ} [hp_prime : fact (nat.prime p)] (x : padic_int p) :
x - ↑(zmod_repr x) ∈ local_ring.maximal_ideal (padic_int p) :=
and.right (zmod_repr_spec x)
/--
`to_zmod_hom` is an auxiliary constructor for creating ring homs from `ℤ_[p]` to `zmod v`.
-/
def to_zmod_hom {p : ℕ} [hp_prime : fact (nat.prime p)] (v : ℕ) (f : padic_int p → ℕ)
(f_spec : ∀ (x : padic_int p), x - ↑(f x) ∈ ideal.span (singleton ↑v))
(f_congr :
∀ (x : padic_int p) (a b : ℕ),
x - ↑a ∈ ideal.span (singleton ↑v) → x - ↑b ∈ ideal.span (singleton ↑v) → ↑a = ↑b) :
padic_int p →+* zmod v :=
ring_hom.mk (fun (x : padic_int p) => ↑(f x)) sorry sorry sorry sorry
/--
`to_zmod` is a ring hom from `ℤ_[p]` to `zmod p`,
with the equality `to_zmod x = (zmod_repr x : zmod p)`.
-/
def to_zmod {p : ℕ} [hp_prime : fact (nat.prime p)] : padic_int p →+* zmod p :=
to_zmod_hom p zmod_repr sorry sorry
/--
`z - (to_zmod z : ℤ_[p])` is contained in the maximal ideal of `ℤ_[p]`, for every `z : ℤ_[p]`.
The coercion from `zmod p` to `ℤ_[p]` is `zmod.has_coe_t`,
which coerces `zmod p` into artibrary rings.
This is unfortunate, but a consequence of the fact that we allow `zmod p`
to coerce to rings of arbitrary characteristic, instead of only rings of characteristic `p`.
This coercion is only a ring homomorphism if it coerces into a ring whose characteristic divides
`p`. While this is not the case here we can still make use of the coercion.
-/
theorem to_zmod_spec {p : ℕ} [hp_prime : fact (nat.prime p)] (z : padic_int p) :
z - ↑(coe_fn to_zmod z) ∈ local_ring.maximal_ideal (padic_int p) :=
sorry
theorem ker_to_zmod {p : ℕ} [hp_prime : fact (nat.prime p)] :
ring_hom.ker to_zmod = local_ring.maximal_ideal (padic_int p) :=
sorry
/-- `appr n x` gives a value `v : ℕ` such that `x` and `↑v : ℤ_p` are congruent mod `p^n`.
See `appr_spec`. -/
def appr {p : ℕ} [hp_prime : fact (nat.prime p)] : padic_int p → ℕ → ℕ := sorry
theorem appr_lt {p : ℕ} [hp_prime : fact (nat.prime p)] (x : padic_int p) (n : ℕ) :
appr x n < p ^ n :=
sorry
theorem appr_mono {p : ℕ} [hp_prime : fact (nat.prime p)] (x : padic_int p) : monotone (appr x) :=
sorry
theorem dvd_appr_sub_appr {p : ℕ} [hp_prime : fact (nat.prime p)] (x : padic_int p) (m : ℕ) (n : ℕ)
(h : m ≤ n) : p ^ m ∣ appr x n - appr x m :=
sorry
theorem appr_spec {p : ℕ} [hp_prime : fact (nat.prime p)] (n : ℕ) (x : padic_int p) :
x - ↑(appr x n) ∈ ideal.span (singleton (↑p ^ n)) :=
sorry
/-- A ring hom from `ℤ_[p]` to `zmod (p^n)`, with underlying function `padic_int.appr n`. -/
def to_zmod_pow {p : ℕ} [hp_prime : fact (nat.prime p)] (n : ℕ) : padic_int p →+* zmod (p ^ n) :=
to_zmod_hom (p ^ n) (fun (x : padic_int p) => appr x n) sorry sorry
theorem ker_to_zmod_pow {p : ℕ} [hp_prime : fact (nat.prime p)] (n : ℕ) :
ring_hom.ker (to_zmod_pow n) = ideal.span (singleton (↑p ^ n)) :=
sorry
@[simp] theorem zmod_cast_comp_to_zmod_pow {p : ℕ} [hp_prime : fact (nat.prime p)] (m : ℕ) (n : ℕ)
(h : m ≤ n) :
ring_hom.comp (zmod.cast_hom (pow_dvd_pow p h) (zmod (p ^ m))) (to_zmod_pow n) =
to_zmod_pow m :=
sorry
@[simp] theorem cast_to_zmod_pow {p : ℕ} [hp_prime : fact (nat.prime p)] (m : ℕ) (n : ℕ) (h : m ≤ n)
(x : padic_int p) : ↑(coe_fn (to_zmod_pow n) x) = coe_fn (to_zmod_pow m) x :=
sorry
theorem dense_range_nat_cast {p : ℕ} [hp_prime : fact (nat.prime p)] : dense_range nat.cast := sorry
theorem dense_range_int_cast {p : ℕ} [hp_prime : fact (nat.prime p)] : dense_range int.cast := sorry
/-! ### Universal property as projective limit -/
/--
Given a family of ring homs `f : Π n : ℕ, R →+* zmod (p ^ n)`,
`nth_hom f r` is an integer-valued sequence
whose `n`th value is the unique integer `k` such that `0 ≤ k < p ^ n`
and `f n r = (k : zmod (p ^ n))`.
-/
def nth_hom {p : ℕ} {R : Type u_1} [comm_ring R] (f : (k : ℕ) → R →+* zmod (p ^ k)) (r : R) :
ℕ → ℤ :=
fun (n : ℕ) => ↑(zmod.val (coe_fn (f n) r))
@[simp] theorem nth_hom_zero {p : ℕ} {R : Type u_1} [comm_ring R]
(f : (k : ℕ) → R →+* zmod (p ^ k)) : nth_hom f 0 = 0 :=
sorry
theorem pow_dvd_nth_hom_sub {p : ℕ} [hp_prime : fact (nat.prime p)] {R : Type u_1} [comm_ring R]
{f : (k : ℕ) → R →+* zmod (p ^ k)}
(f_compat :
∀ (k1 k2 : ℕ) (hk : k1 ≤ k2),
ring_hom.comp (zmod.cast_hom (pow_dvd_pow p hk) (zmod (p ^ k1))) (f k2) = f k1)
(r : R) (i : ℕ) (j : ℕ) (h : i ≤ j) : ↑p ^ i ∣ nth_hom f r j - nth_hom f r i :=
sorry
theorem is_cau_seq_nth_hom {p : ℕ} [hp_prime : fact (nat.prime p)] {R : Type u_1} [comm_ring R]
{f : (k : ℕ) → R →+* zmod (p ^ k)}
(f_compat :
∀ (k1 k2 : ℕ) (hk : k1 ≤ k2),
ring_hom.comp (zmod.cast_hom (pow_dvd_pow p hk) (zmod (p ^ k1))) (f k2) = f k1)
(r : R) : is_cau_seq (padic_norm p) fun (n : ℕ) => ↑(nth_hom f r n) :=
sorry
/--
`nth_hom_seq f_compat r` bundles `padic_int.nth_hom f r`
as a Cauchy sequence of rationals with respect to the `p`-adic norm.
The `n`th value of the sequence is `((f n r).val : ℚ)`.
-/
def nth_hom_seq {p : ℕ} [hp_prime : fact (nat.prime p)] {R : Type u_1} [comm_ring R]
{f : (k : ℕ) → R →+* zmod (p ^ k)}
(f_compat :
∀ (k1 k2 : ℕ) (hk : k1 ≤ k2),
ring_hom.comp (zmod.cast_hom (pow_dvd_pow p hk) (zmod (p ^ k1))) (f k2) = f k1)
(r : R) : padic_seq p :=
{ val := fun (n : ℕ) => ↑(nth_hom f r n), property := is_cau_seq_nth_hom f_compat r }
theorem nth_hom_seq_one {p : ℕ} [hp_prime : fact (nat.prime p)] {R : Type u_1} [comm_ring R]
{f : (k : ℕ) → R →+* zmod (p ^ k)}
(f_compat :
∀ (k1 k2 : ℕ) (hk : k1 ≤ k2),
ring_hom.comp (zmod.cast_hom (pow_dvd_pow p hk) (zmod (p ^ k1))) (f k2) = f k1) :
nth_hom_seq f_compat 1 ≈ 1 :=
sorry
theorem nth_hom_seq_add {p : ℕ} [hp_prime : fact (nat.prime p)] {R : Type u_1} [comm_ring R]
{f : (k : ℕ) → R →+* zmod (p ^ k)}
(f_compat :
∀ (k1 k2 : ℕ) (hk : k1 ≤ k2),
ring_hom.comp (zmod.cast_hom (pow_dvd_pow p hk) (zmod (p ^ k1))) (f k2) = f k1)
(r : R) (s : R) :
nth_hom_seq f_compat (r + s) ≈ nth_hom_seq f_compat r + nth_hom_seq f_compat s :=
sorry
theorem nth_hom_seq_mul {p : ℕ} [hp_prime : fact (nat.prime p)] {R : Type u_1} [comm_ring R]
{f : (k : ℕ) → R →+* zmod (p ^ k)}
(f_compat :
∀ (k1 k2 : ℕ) (hk : k1 ≤ k2),
ring_hom.comp (zmod.cast_hom (pow_dvd_pow p hk) (zmod (p ^ k1))) (f k2) = f k1)
(r : R) (s : R) :
nth_hom_seq f_compat (r * s) ≈ nth_hom_seq f_compat r * nth_hom_seq f_compat s :=
sorry
/--
`lim_nth_hom f_compat r` is the limit of a sequence `f` of compatible ring homs `R →+* zmod (p^k)`.
This is itself a ring hom: see `padic_int.lift`.
-/
def lim_nth_hom {p : ℕ} [hp_prime : fact (nat.prime p)] {R : Type u_1} [comm_ring R]
{f : (k : ℕ) → R →+* zmod (p ^ k)}
(f_compat :
∀ (k1 k2 : ℕ) (hk : k1 ≤ k2),
ring_hom.comp (zmod.cast_hom (pow_dvd_pow p hk) (zmod (p ^ k1))) (f k2) = f k1)
(r : R) : padic_int p :=
of_int_seq (nth_hom f r) (is_cau_seq_nth_hom f_compat r)
theorem lim_nth_hom_spec {p : ℕ} [hp_prime : fact (nat.prime p)] {R : Type u_1} [comm_ring R]
{f : (k : ℕ) → R →+* zmod (p ^ k)}
(f_compat :
∀ (k1 k2 : ℕ) (hk : k1 ≤ k2),
ring_hom.comp (zmod.cast_hom (pow_dvd_pow p hk) (zmod (p ^ k1))) (f k2) = f k1)
(r : R) (ε : ℝ) :
0 < ε → ∃ (N : ℕ), ∀ (n : ℕ), n ≥ N → norm (lim_nth_hom f_compat r - ↑(nth_hom f r n)) < ε :=
sorry
theorem lim_nth_hom_zero {p : ℕ} [hp_prime : fact (nat.prime p)] {R : Type u_1} [comm_ring R]
{f : (k : ℕ) → R →+* zmod (p ^ k)}
(f_compat :
∀ (k1 k2 : ℕ) (hk : k1 ≤ k2),
ring_hom.comp (zmod.cast_hom (pow_dvd_pow p hk) (zmod (p ^ k1))) (f k2) = f k1) :
lim_nth_hom f_compat 0 = 0 :=
sorry
theorem lim_nth_hom_one {p : ℕ} [hp_prime : fact (nat.prime p)] {R : Type u_1} [comm_ring R]
{f : (k : ℕ) → R →+* zmod (p ^ k)}
(f_compat :
∀ (k1 k2 : ℕ) (hk : k1 ≤ k2),
ring_hom.comp (zmod.cast_hom (pow_dvd_pow p hk) (zmod (p ^ k1))) (f k2) = f k1) :
lim_nth_hom f_compat 1 = 1 :=
subtype.ext (quot.sound (nth_hom_seq_one f_compat))
theorem lim_nth_hom_add {p : ℕ} [hp_prime : fact (nat.prime p)] {R : Type u_1} [comm_ring R]
{f : (k : ℕ) → R →+* zmod (p ^ k)}
(f_compat :
∀ (k1 k2 : ℕ) (hk : k1 ≤ k2),
ring_hom.comp (zmod.cast_hom (pow_dvd_pow p hk) (zmod (p ^ k1))) (f k2) = f k1)
(r : R) (s : R) :
lim_nth_hom f_compat (r + s) = lim_nth_hom f_compat r + lim_nth_hom f_compat s :=
subtype.ext (quot.sound (nth_hom_seq_add f_compat r s))
theorem lim_nth_hom_mul {p : ℕ} [hp_prime : fact (nat.prime p)] {R : Type u_1} [comm_ring R]
{f : (k : ℕ) → R →+* zmod (p ^ k)}
(f_compat :
∀ (k1 k2 : ℕ) (hk : k1 ≤ k2),
ring_hom.comp (zmod.cast_hom (pow_dvd_pow p hk) (zmod (p ^ k1))) (f k2) = f k1)
(r : R) (s : R) :
lim_nth_hom f_compat (r * s) = lim_nth_hom f_compat r * lim_nth_hom f_compat s :=
subtype.ext (quot.sound (nth_hom_seq_mul f_compat r s))
-- TODO: generalize this to arbitrary complete discrete valuation rings
/--
`lift f_compat` is the limit of a sequence `f` of compatible ring homs `R →+* zmod (p^k)`,
with the equality `lift f_compat r = padic_int.lim_nth_hom f_compat r`.
-/
def lift {p : ℕ} [hp_prime : fact (nat.prime p)] {R : Type u_1} [comm_ring R]
{f : (k : ℕ) → R →+* zmod (p ^ k)}
(f_compat :
∀ (k1 k2 : ℕ) (hk : k1 ≤ k2),
ring_hom.comp (zmod.cast_hom (pow_dvd_pow p hk) (zmod (p ^ k1))) (f k2) = f k1) :
R →+* padic_int p :=
ring_hom.mk (lim_nth_hom f_compat) sorry sorry sorry sorry
theorem lift_sub_val_mem_span {p : ℕ} [hp_prime : fact (nat.prime p)] {R : Type u_1} [comm_ring R]
{f : (k : ℕ) → R →+* zmod (p ^ k)}
(f_compat :
∀ (k1 k2 : ℕ) (hk : k1 ≤ k2),
ring_hom.comp (zmod.cast_hom (pow_dvd_pow p hk) (zmod (p ^ k1))) (f k2) = f k1)
(r : R) (n : ℕ) :
coe_fn (lift f_compat) r - ↑(zmod.val (coe_fn (f n) r)) ∈ ideal.span (singleton (↑p ^ n)) :=
sorry
/--
One part of the universal property of `ℤ_[p]` as a projective limit.
See also `padic_int.lift_unique`.
-/
theorem lift_spec {p : ℕ} [hp_prime : fact (nat.prime p)] {R : Type u_1} [comm_ring R]
{f : (k : ℕ) → R →+* zmod (p ^ k)}
(f_compat :
∀ (k1 k2 : ℕ) (hk : k1 ≤ k2),
ring_hom.comp (zmod.cast_hom (pow_dvd_pow p hk) (zmod (p ^ k1))) (f k2) = f k1)
(n : ℕ) : ring_hom.comp (to_zmod_pow n) (lift f_compat) = f n :=
sorry
/--
One part of the universal property of `ℤ_[p]` as a projective limit.
See also `padic_int.lift_spec`.
-/
theorem lift_unique {p : ℕ} [hp_prime : fact (nat.prime p)] {R : Type u_1} [comm_ring R]
{f : (k : ℕ) → R →+* zmod (p ^ k)}
(f_compat :
∀ (k1 k2 : ℕ) (hk : k1 ≤ k2),
ring_hom.comp (zmod.cast_hom (pow_dvd_pow p hk) (zmod (p ^ k1))) (f k2) = f k1)
(g : R →+* padic_int p) (hg : ∀ (n : ℕ), ring_hom.comp (to_zmod_pow n) g = f n) :
lift f_compat = g :=
sorry
@[simp] theorem lift_self {p : ℕ} [hp_prime : fact (nat.prime p)] (z : padic_int p) :
coe_fn (lift zmod_cast_comp_to_zmod_pow) z = z :=
sorry
theorem ext_of_to_zmod_pow {p : ℕ} [hp_prime : fact (nat.prime p)] {x : padic_int p}
{y : padic_int p} : (∀ (n : ℕ), coe_fn (to_zmod_pow n) x = coe_fn (to_zmod_pow n) y) ↔ x = y :=
sorry
theorem to_zmod_pow_eq_iff_ext {p : ℕ} [hp_prime : fact (nat.prime p)] {R : Type u_1} [comm_ring R]
{g : R →+* padic_int p} {g' : R →+* padic_int p} :
(∀ (n : ℕ), ring_hom.comp (to_zmod_pow n) g = ring_hom.comp (to_zmod_pow n) g') ↔ g = g' :=
sorry
end Mathlib |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE UndecidableSuperClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE EmptyCase #-}
{-# LANGUAGE TypeApplications #-}
{-# OPTIONS_GHC -Wall #-}
{-# OPTIONS_GHC -Wno-deprecations #-} -- for errorWithStackTrace
-- | Miscellany
module ConCat.Misc where
import GHC.Types (Constraint)
-- import Control.Arrow ((&&&))
-- import Data.Type.Equality
import Data.Typeable (Typeable,TypeRep,typeRep,Proxy(..))
import Data.Data (Data)
import Data.Monoid (Endo(..))
import Data.Semigroup (Semigroup(..))
import Data.Complex (Complex)
import GHC.Generics hiding (R)
-- import Unsafe.Coerce (unsafeCoerce) -- for oops
import GHC.Stack (errorWithStackTrace) -- for oops
import GHC.TypeLits
import Control.Newtype.Generics
{--------------------------------------------------------------------
Type abbreviations
-------------------------------------------------------------------
-}
infixr 8 :^
infixl 7 :*
infixl 6 :+
infixr 1 :=>
type s :^ n = n -> s
type (:*) = (,)
type (:+) = Either
type (:=>) = (->)
{--------------------------------------------------------------------
Helpers for GHC.Generics
--------------------------------------------------------------------}
-- | Operate inside a Generic1
inGeneric1 :: (Generic1 f, Generic1 g) => (Rep1 f a -> Rep1 g b) -> (f a -> g b)
inGeneric1 = to1 <~ from1
{-# INLINE inGeneric1 #-}
-- | Apply a unary function within the 'Comp1' constructor.
inComp :: (g (f a) -> g' (f' a')) -> ((g :.: f) a -> (g' :.: f') a')
inComp = Comp1 <~ unComp1
{-# INLINE inComp #-}
-- | Apply a binary function within the 'Comp1' constructor.
inComp2 :: ( g (f a) -> g' (f' a') -> g'' (f'' a''))
-> ((g :.: f) a -> (g' :.: f') a' -> (g'' :.: f'') a'')
inComp2 = inComp <~ unComp1
{-# INLINE inComp2 #-}
-- TODO: phase out inComp and inComp2 in favor of inNew and inNew2.
absurdF :: V1 a -> b
absurdF = \ case
{-# INLINE absurdF #-}
-- infixr 1 +->
-- data (a +-> b) p = Fun1 { unFun1 :: a p -> b p }
-- -- TODO: resolve name conflict with tries. Using ":->:" for functors fits with
-- -- other type constructors in GHC.Generics.
-- instance Newtype ((a +-> b) t) where
-- type O ((a +-> b) t) = a t -> b t
-- pack = Fun1
-- unpack = unFun1
#if 0
{--------------------------------------------------------------------
Evaluation
--------------------------------------------------------------------}
-- class Evalable e where
-- type ValT e
-- eval :: e -> ValT e
class PrimBasics p where
unitP :: p ()
pairP :: p (a :=> b :=> a :* b)
class Evalable p where eval :: p a -> a
-- TODO: Are we still using PrimBasics or Evalable?
#endif
{--------------------------------------------------------------------
Other
--------------------------------------------------------------------}
type Unop a = a -> a
type Binop a = a -> Unop a
type Ternop a = a -> Binop a
infixl 1 <~
infixr 1 ~>
-- | Add pre- and post-processing
(~>) :: forall a b a' b'. (a' -> a) -> (b -> b') -> ((a -> b) -> (a' -> b'))
(f ~> h) g = h . g . f
-- (~>) = flip (<~)
{-# INLINE (~>) #-}
-- | Add post- and pre-processing
(<~) :: forall a b a' b'. (b -> b') -> (a' -> a) -> ((a -> b) -> (a' -> b'))
(h <~ f) g = h . g . f
{-# INLINE (<~) #-}
-- For SEC-style programming. I was using fmap instead, but my rules interfered.
result :: (b -> c) -> ((a -> b) -> (a -> c))
result = (.)
{-# INLINE result #-}
class Yes0
instance Yes0
class Yes1 a
instance Yes1 a
class Yes2 a b
instance Yes2 a b
-- | Compose list of unary transformations
compose :: Foldable f => f (Unop a) -> Unop a
compose = appEndo . foldMap Endo
-- compose = foldr (.) id
infixr 3 `xor`
xor :: Binop Bool
xor = (/=)
{-# NOINLINE xor #-}
newtype Parity = Parity { getParity :: Bool }
instance Newtype Parity where
type O Parity = Bool
pack = Parity
unpack (Parity x) = x
instance Semigroup Parity where
Parity a <> Parity b = Parity (a `xor` b)
instance Monoid Parity where
mempty = Parity False
mappend = (<>)
-- Parity a `mappend` Parity b = Parity (a `xor` b)
boolToInt :: Bool -> Int
boolToInt c = if c then 1 else 0
{-# INLINE boolToInt #-}
cond :: a -> a -> Bool -> a
cond t e i = if i then t else e
{-# INLINE cond #-} -- later INLINE?
{--------------------------------------------------------------------
Type level computations
--------------------------------------------------------------------}
infixr 3 &&
class (a,b) => a && b
instance (a,b) => a && b
-- Saying (b,a) instead of (a,b) causes Oks k [a,b,c] to expand in order, oddly.
-- TODO: investigate.
infixr 3 &+&
class (a t, b t) => (a &+& b) t
instance (a t, b t) => (a &+& b) t
class f b a => Flip f a b
instance f b a => Flip f a b
-- • Potential superclass cycle for ‘&&’
-- one of whose superclass constraints is headed by a type variable: ‘a’
-- Use UndecidableSuperClasses to accept this
-- Same for Flip
type family FoldrC op b0 as where
FoldrC op z '[] = z
FoldrC op z (a : as) = a `op` FoldrC op z as
type family MapC f us where
MapC f '[] = '[]
MapC f (u : us) = f u : MapC f us
-- type Comp g f u = g (f u)
-- -- Operator applied to too few arguments: :
-- type MapC' f us = FoldrC (Comp (':) f) '[] us
type AndC cs = FoldrC (&&) Yes0 cs
type AllC f us = AndC (MapC f us)
-- type family AndC' cs where
-- AndC' '[] = Yes0
-- AndC' (c : cs) = c && AndC' cs
-- type family AllC f as where
-- AllC f '[] = Yes0
-- AllC f (a : as) = f a && AllC f as
-- -- Operator applied to too few arguments: :
-- type as ++ bs = FoldrC (':) bs as
infixr 5 ++
type family as ++ bs where
'[] ++ bs = bs
(a : as) ++ bs = a : as ++ bs
type family CrossWith f as bs where
CrossWith f '[] bs = '[]
CrossWith f (a : as) bs = MapC (f a) bs ++ CrossWith f as bs
-- Illegal nested type family application ‘MapC (f a1) bs
-- ++ CrossWith f as bs’
-- (Use UndecidableInstances to permit this)
type AllC2 f as bs = AndC (CrossWith f as bs)
-- | Annotation for pseudo-function, i.e., defined by rules. During ccc
-- generation, don't split applications. TODO: maybe add an arity.
data PseudoFun = PseudoFun { pseudoArgs :: Int } deriving (Typeable,Data)
-- Alternatively, we could keep PseudoFun abstract:
-- pseudoFun :: Int -> PseudoFun
-- pseudoFun = PseudoFun
-- | Pseudo function to fool GHC's divergence checker.
oops :: String -> b
oops str = errorWithStackTrace ("Oops: "++str)
{-# NOINLINE oops #-}
-- In the use of ‘errorWithStackTrace’ (imported from GHC.Stack):
-- Deprecated: "'error' appends the call stack now"
-- When we use error, the divergence checker eliminates a lot of code early. An
-- alternative is unsafeCoerce, but it leads to terrible run-time errors. A safe
-- alternative seems to be errorWithStackTrace. Oddly, the doc for
-- errorWithStackTrace says "Deprecated: error appends the call stack now."
-- | Hack: delay inlining to thwart some of GHC's rewrites
delay :: a -> a
delay a = a
{-# INLINE [0] delay #-}
bottom :: a
-- bottom = error "bottom evaluated"
bottom = oops "bottom evaluated"
{-# NOINLINE bottom #-}
-- Convenient alternative to typeRep
typeR :: forall a. Typeable a => TypeRep
typeR = typeRep (Proxy :: Proxy a)
type R = Double -- Float
type C = Complex R
sqr :: Num a => a -> a
sqr a = a * a
{-# INLINE sqr #-}
magSqr :: Num a => a :* a -> a
magSqr (a,b) = sqr a + sqr b
{-# INLINE magSqr #-}
transpose :: (Traversable t, Applicative f) => t (f a) -> f (t a)
transpose = sequenceA
inTranspose :: (Applicative f, Traversable t, Applicative f', Traversable t')
=> (f (t a) -> t' (f' a)) -> (t (f a) -> f' (t' a))
inTranspose = transpose <~ transpose
{-# INLINE inTranspose #-}
-- inTranspose h = transpose . h . transpose
unzip :: Functor f => f (a :* b) -> f a :* f b
unzip ps = (fst <$> ps, snd <$> ps)
{-# INLINE unzip #-}
natValAt :: forall n. KnownNat n => Integer
natValAt = nat @n
-- Shorter name
nat :: forall n. KnownNat n => Integer
nat = natVal (Proxy @n)
{-# INLINE nat #-}
int :: forall n. KnownNat n => Int
int = fromIntegral (nat @n)
{-# INLINE int #-}
{--------------------------------------------------------------------
Newtype
--------------------------------------------------------------------}
-- See <https://github.com/jcristovao/newtype-generics/pull/5>
-- Type generalization of underF from newtype-generics.
underF :: (Newtype n, Newtype n', o' ~ O n', o ~ O n, Functor f, Functor g)
=> (o -> n) -> (f n -> g n') -> (f o -> g o')
underF _ f = fmap unpack . f . fmap pack
{-# INLINE underF #-}
-- Type generalization of overF from newtype-generics.
overF :: (Newtype n, Newtype n', o' ~ O n', o ~ O n, Functor f, Functor g)
=> (o -> n) -> (f o -> g o') -> (f n -> g n')
overF _ f = fmap pack . f . fmap unpack
{-# INLINE overF #-}
inNew :: (Newtype p, Newtype q) =>
(O p -> O q) -> (p -> q)
inNew = pack <~ unpack
{-# INLINE inNew #-}
inNew2 :: (Newtype p, Newtype q, Newtype r) =>
(O p -> O q -> O r) -> (p -> q -> r)
inNew2 = inNew <~ unpack
{-# INLINE inNew2 #-}
-- TODO: use inNew and inNew2 in place of ad hoc versions throughout.
exNew :: (Newtype p, Newtype q) =>
(p -> q) -> (O p -> O q)
exNew = unpack <~ pack
{-# INLINE exNew #-}
exNew2 :: (Newtype p, Newtype q, Newtype r) =>
(p -> q -> r) -> (O p -> O q -> O r)
exNew2 = exNew <~ pack
{-# INLINE exNew2 #-}
{--------------------------------------------------------------------
Constraint shorthands
--------------------------------------------------------------------}
#if 1
-- Experiment. Smaller Core?
type C1 (con :: u -> Constraint) a = con a
type C2 (con :: u -> Constraint) a b = (con a, con b)
type C3 (con :: u -> Constraint) a b c = (con a, con b, con c)
type C4 (con :: u -> Constraint) a b c d = (con a, con b, con c, con d)
type C5 (con :: u -> Constraint) a b c d e = (con a, con b, con c, con d, con e)
type C6 (con :: u -> Constraint) a b c d e f = (con a, con b, con c, con d, con e, con f)
#else
type C1 (con :: u -> Constraint) a = con a
type C2 con a b = (C1 con a, con b)
type C3 con a b c = (C2 con a b, con c)
type C4 con a b c d = (C2 con a b, C2 con c d)
type C5 con a b c d e = (C3 con a b c, C2 con d e)
type C6 con a b c d e f = (C3 con a b c, C3 con d e f)
#endif
|
= = Regulation = =
|
[STATEMENT]
lemma gen_build[autoref_rules]:
assumes PRIO_TAG_GEN_ALGO
assumes to_list: "SIDE_GEN_ALGO (is_set_to_list A Rs tol)"
assumes empty: "GEN_OP emp op_map_empty (\<langle>A, B\<rangle> Rm)"
assumes update: "GEN_OP upd op_map_update (A \<rightarrow> B \<rightarrow> \<langle>A, B\<rangle> Rm \<rightarrow> \<langle>A, B\<rangle> Rm)"
shows "(\<lambda> f X. gen_build tol upd emp f X, \<lambda> f X. (Some \<circ> f) |` X) \<in>
(A \<rightarrow> B) \<rightarrow> \<langle>A\<rangle> Rs \<rightarrow> \<langle>A, B\<rangle> Rm"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (gen_build tol upd emp, \<lambda>f. (|`) (Some \<circ> f)) \<in> (A \<rightarrow> B) \<rightarrow> \<langle>A\<rangle>Rs \<rightarrow> \<langle>A, B\<rangle>Rm
[PROOF STEP]
proof (intro fun_relI)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>a a' aa a'a. \<lbrakk>(a, a') \<in> A \<rightarrow> B; (aa, a'a) \<in> \<langle>A\<rangle>Rs\<rbrakk> \<Longrightarrow> (gen_build tol upd emp a aa, (Some \<circ> a') |` a'a) \<in> \<langle>A, B\<rangle>Rm
[PROOF STEP]
note [unfolded autoref_tag_defs, param] = empty update
[PROOF STATE]
proof (state)
this:
(emp, op_map_empty) \<in> \<langle>A, B\<rangle>Rm
(upd, op_map_update) \<in> A \<rightarrow> B \<rightarrow> \<langle>A, B\<rangle>Rm \<rightarrow> \<langle>A, B\<rangle>Rm
goal (1 subgoal):
1. \<And>a a' aa a'a. \<lbrakk>(a, a') \<in> A \<rightarrow> B; (aa, a'a) \<in> \<langle>A\<rangle>Rs\<rbrakk> \<Longrightarrow> (gen_build tol upd emp a aa, (Some \<circ> a') |` a'a) \<in> \<langle>A, B\<rangle>Rm
[PROOF STEP]
fix f g T S
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>a a' aa a'a. \<lbrakk>(a, a') \<in> A \<rightarrow> B; (aa, a'a) \<in> \<langle>A\<rangle>Rs\<rbrakk> \<Longrightarrow> (gen_build tol upd emp a aa, (Some \<circ> a') |` a'a) \<in> \<langle>A, B\<rangle>Rm
[PROOF STEP]
assume 1[param]: "(g, f) \<in> A \<rightarrow> B" "(T, S) \<in> \<langle>A\<rangle> Rs"
[PROOF STATE]
proof (state)
this:
(g, f) \<in> A \<rightarrow> B
(T, S) \<in> \<langle>A\<rangle>Rs
goal (1 subgoal):
1. \<And>a a' aa a'a. \<lbrakk>(a, a') \<in> A \<rightarrow> B; (aa, a'a) \<in> \<langle>A\<rangle>Rs\<rbrakk> \<Longrightarrow> (gen_build tol upd emp a aa, (Some \<circ> a') |` a'a) \<in> \<langle>A, B\<rangle>Rm
[PROOF STEP]
obtain tsl' where
[param]: "(tol T, tsl') \<in> \<langle>A\<rangle>list_rel"
and IT': "RETURN tsl' \<le> it_to_sorted_list (\<lambda>_ _. True) S"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>tsl'. \<lbrakk>(tol T, tsl') \<in> \<langle>A\<rangle>list_rel; RETURN tsl' \<le> it_to_sorted_list (\<lambda>_ _. True) S\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
using to_list[unfolded autoref_tag_defs is_set_to_list_def] 1(2)
[PROOF STATE]
proof (prove)
using this:
is_set_to_sorted_list (\<lambda>_ _. True) A Rs tol
(T, S) \<in> \<langle>A\<rangle>Rs
goal (1 subgoal):
1. (\<And>tsl'. \<lbrakk>(tol T, tsl') \<in> \<langle>A\<rangle>list_rel; RETURN tsl' \<le> it_to_sorted_list (\<lambda>_ _. True) S\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by (rule is_set_to_sorted_listE)
[PROOF STATE]
proof (state)
this:
(tol T, tsl') \<in> \<langle>A\<rangle>list_rel
RETURN tsl' \<le> it_to_sorted_list (\<lambda>_ _. True) S
goal (1 subgoal):
1. \<And>a a' aa a'a. \<lbrakk>(a, a') \<in> A \<rightarrow> B; (aa, a'a) \<in> \<langle>A\<rangle>Rs\<rbrakk> \<Longrightarrow> (gen_build tol upd emp a aa, (Some \<circ> a') |` a'a) \<in> \<langle>A, B\<rangle>Rm
[PROOF STEP]
from IT'
[PROOF STATE]
proof (chain)
picking this:
RETURN tsl' \<le> it_to_sorted_list (\<lambda>_ _. True) S
[PROOF STEP]
have 10: "S = set tsl'" "distinct tsl'"
[PROOF STATE]
proof (prove)
using this:
RETURN tsl' \<le> it_to_sorted_list (\<lambda>_ _. True) S
goal (1 subgoal):
1. S = set tsl' &&& distinct tsl'
[PROOF STEP]
unfolding it_to_sorted_list_def
[PROOF STATE]
proof (prove)
using this:
RETURN tsl' \<le> SPEC (\<lambda>l. distinct l \<and> S = set l \<and> sorted_wrt (\<lambda>_ _. True) l)
goal (1 subgoal):
1. S = set tsl' &&& distinct tsl'
[PROOF STEP]
by simp_all
[PROOF STATE]
proof (state)
this:
S = set tsl'
distinct tsl'
goal (1 subgoal):
1. \<And>a a' aa a'a. \<lbrakk>(a, a') \<in> A \<rightarrow> B; (aa, a'a) \<in> \<langle>A\<rangle>Rs\<rbrakk> \<Longrightarrow> (gen_build tol upd emp a aa, (Some \<circ> a') |` a'a) \<in> \<langle>A, B\<rangle>Rm
[PROOF STEP]
have "gen_build tol upd emp g T = fold (\<lambda> x. upd x (g x)) (tol T) emp"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. gen_build tol upd emp g T = fold (\<lambda>x. upd x (g x)) (tol T) emp
[PROOF STEP]
unfolding gen_build_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. fold (\<lambda>x. upd x (g x)) (tol T) emp = fold (\<lambda>x. upd x (g x)) (tol T) emp
[PROOF STEP]
by rule
[PROOF STATE]
proof (state)
this:
gen_build tol upd emp g T = fold (\<lambda>x. upd x (g x)) (tol T) emp
goal (1 subgoal):
1. \<And>a a' aa a'a. \<lbrakk>(a, a') \<in> A \<rightarrow> B; (aa, a'a) \<in> \<langle>A\<rangle>Rs\<rbrakk> \<Longrightarrow> (gen_build tol upd emp a aa, (Some \<circ> a') |` a'a) \<in> \<langle>A, B\<rangle>Rm
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
gen_build tol upd emp g T = fold (\<lambda>x. upd x (g x)) (tol T) emp
goal (1 subgoal):
1. \<And>a a' aa a'a. \<lbrakk>(a, a') \<in> A \<rightarrow> B; (aa, a'a) \<in> \<langle>A\<rangle>Rs\<rbrakk> \<Longrightarrow> (gen_build tol upd emp a aa, (Some \<circ> a') |` a'a) \<in> \<langle>A, B\<rangle>Rm
[PROOF STEP]
have "(\<dots>, fold (\<lambda> x. op_map_update x (f x)) tsl' op_map_empty) \<in> \<langle>A, B\<rangle> Rm"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (fold (\<lambda>x. upd x (g x)) (tol T) emp, fold (\<lambda>x. op_map_update x (f x)) tsl' op_map_empty) \<in> \<langle>A, B\<rangle>Rm
[PROOF STEP]
by parametricity
[PROOF STATE]
proof (state)
this:
(fold (\<lambda>x. upd x (g x)) (tol T) emp, fold (\<lambda>x. op_map_update x (f x)) tsl' op_map_empty) \<in> \<langle>A, B\<rangle>Rm
goal (1 subgoal):
1. \<And>a a' aa a'a. \<lbrakk>(a, a') \<in> A \<rightarrow> B; (aa, a'a) \<in> \<langle>A\<rangle>Rs\<rbrakk> \<Longrightarrow> (gen_build tol upd emp a aa, (Some \<circ> a') |` a'a) \<in> \<langle>A, B\<rangle>Rm
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
(fold (\<lambda>x. upd x (g x)) (tol T) emp, fold (\<lambda>x. op_map_update x (f x)) tsl' op_map_empty) \<in> \<langle>A, B\<rangle>Rm
goal (1 subgoal):
1. \<And>a a' aa a'a. \<lbrakk>(a, a') \<in> A \<rightarrow> B; (aa, a'a) \<in> \<langle>A\<rangle>Rs\<rbrakk> \<Longrightarrow> (gen_build tol upd emp a aa, (Some \<circ> a') |` a'a) \<in> \<langle>A, B\<rangle>Rm
[PROOF STEP]
have "fold (\<lambda> x. op_map_update x (f x)) tsl' m = m ++ (Some \<circ> f) |` S" for m
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. fold (\<lambda>x. op_map_update x (f x)) tsl' m = m ++ (Some \<circ> f) |` S
[PROOF STEP]
unfolding 10 op_map_update_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. fold (\<lambda>x m. m(x \<mapsto> f x)) tsl' m = m ++ (Some \<circ> f) |` set tsl'
[PROOF STEP]
by (induct tsl' arbitrary: m rule: rev_induct) (auto simp add: restrict_map_insert)
[PROOF STATE]
proof (state)
this:
fold (\<lambda>x. op_map_update x (f x)) tsl' ?m = ?m ++ (Some \<circ> f) |` S
goal (1 subgoal):
1. \<And>a a' aa a'a. \<lbrakk>(a, a') \<in> A \<rightarrow> B; (aa, a'a) \<in> \<langle>A\<rangle>Rs\<rbrakk> \<Longrightarrow> (gen_build tol upd emp a aa, (Some \<circ> a') |` a'a) \<in> \<langle>A, B\<rangle>Rm
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
fold (\<lambda>x. op_map_update x (f x)) tsl' ?m = ?m ++ (Some \<circ> f) |` S
goal (1 subgoal):
1. \<And>a a' aa a'a. \<lbrakk>(a, a') \<in> A \<rightarrow> B; (aa, a'a) \<in> \<langle>A\<rangle>Rs\<rbrakk> \<Longrightarrow> (gen_build tol upd emp a aa, (Some \<circ> a') |` a'a) \<in> \<langle>A, B\<rangle>Rm
[PROOF STEP]
have "op_map_empty ++ (Some \<circ> f) |` S = (Some \<circ> f) |` S"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. op_map_empty ++ (Some \<circ> f) |` S = (Some \<circ> f) |` S
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
op_map_empty ++ (Some \<circ> f) |` S = (Some \<circ> f) |` S
goal (1 subgoal):
1. \<And>a a' aa a'a. \<lbrakk>(a, a') \<in> A \<rightarrow> B; (aa, a'a) \<in> \<langle>A\<rangle>Rs\<rbrakk> \<Longrightarrow> (gen_build tol upd emp a aa, (Some \<circ> a') |` a'a) \<in> \<langle>A, B\<rangle>Rm
[PROOF STEP]
finally
[PROOF STATE]
proof (chain)
picking this:
(gen_build tol upd emp g T, (Some \<circ> f) |` S) \<in> \<langle>A, B\<rangle>Rm
[PROOF STEP]
show "(gen_build tol upd emp g T, (Some \<circ> f) |` S) \<in> \<langle>A, B\<rangle> Rm"
[PROOF STATE]
proof (prove)
using this:
(gen_build tol upd emp g T, (Some \<circ> f) |` S) \<in> \<langle>A, B\<rangle>Rm
goal (1 subgoal):
1. (gen_build tol upd emp g T, (Some \<circ> f) |` S) \<in> \<langle>A, B\<rangle>Rm
[PROOF STEP]
by this
[PROOF STATE]
proof (state)
this:
(gen_build tol upd emp g T, (Some \<circ> f) |` S) \<in> \<langle>A, B\<rangle>Rm
goal:
No subgoals!
[PROOF STEP]
qed |
\documentclass{scrartcl}
\usepackage{fullpage}
\usepackage{url}
\author{Luke Anderson, Jon Gjengset, Jeevana Inala, and Andrew Wang \\
\texttt{\{lukea,jfrg,jinala,wangaj\}@mit.edu}
}
\title{6.858 Project Proposal}
\subtitle{Concolic Execution for Django Applications}
\date{\today}
\begin{document}
\maketitle
\section{Project motivation}
Concolic execution systems give developers the power to verify crucial security
invariants in their applications. The third lab exercise in 6.858 uses the z3 solver to implement concolic
execution for the Zoobar python application. Unfortunately, the framework used
for the lab is written specifically for Zoobar, and is unlikely to be directly
compatible with other applications. We therefore wish to extend the lab
3 concolic execution implementation to one that operates on web applications
built on top of the popular Django framework.
\section{Deliverables}
\begin{enumerate}
\item A rewrite of the Zoobar web application in Django.
\item A modified version of Django that supports concolic execution.
\item A polished and fleshed-out version of the lab3 concolic execution
framework that supports Django web applications out of the box.
\item (\textit{Wishlist}) Django ORM support plugin/patch for the
Microsoft z3 solver.
\end{enumerate}
\section{Project stages}
First, we have to rebuild the Zoobar application functionality using the Django
framework. As Zoobar is a fairly standard web application, this is a relatively
small part of the project.
Next, we will instrument the Django source code so that it can support symbolic
execution of interesting input parameters. For most applications, this is
likely to be the request URL, the query parameters, the request type
(GET/POST/PUT/DELETE), and the cookie values.
After instrumenting Django, we will run the Zoobar application with concolic
execution, and make the modifications to the lab3 concolic execution framework
that are necessary to get it to run correctly on this new application.
If time allows, we also wish to implement support for the Django
Object-Relational Mapper (ORM) directly inside the z3 solver. This would allow
z3 to query the database directly for objects satisfying constraints (using
SQL) rather than relying on the developer enumerating all database records and
looking them up using native python operations as in Exercise 5. This should
substantially improve concolic execution time, and will make it much easier to
use our framework in complex applications. However, given the complexity and
magnitude of this task, we will only do it if the other components turn out to
be easier than expected and we are left with spare time.
\section{Challenges}
\begin{enumerate}
\item Cookies in Django contain session IDs that are then used to look
up the variables stored in that user's session. This is
substantially more complex than the Zoobar cookies which simply
included the username of the user that was logged in.
Supporting these kinds of session cookies is vital to being
able to test real web applications, and will likely be
non-trivial.
\item Modifying the lab3 concolic execution framework to support Django
applications will probably include extending the set of
supported operations supported quite substantially. This is
because Django and ``real'' web applications probably exercise
a larger subset of python operations.
\item The complexity of Django, and many applications running atop it,
means the state space can grow very large very quickly. It is
likely that we will need to find and implement optimizations in
the fuzzer that limit the concolic execution branching factor.
\item Extending z3 to have support for database queries directly
through the Django ORM requires digging through z3 to figure
out how to translate symbolic conditions into SQL clauses.
We will also need to find a way of inferring which symbolic
variables in conditions correspond to database objects, and
which are primitives (strings, ints, etc.). Solving this
problem is likely going to require deep-seated and non-trivial
changes to z3.
\end{enumerate}
\end{document}
|
(*<*)
theory Fsub
imports "../Nominal"
begin
(*>*)
text{* Authors: Christian Urban,
Benjamin Pierce,
Dimitrios Vytiniotis
Stephanie Weirich
Steve Zdancewic
Julien Narboux
Stefan Berghofer
with great help from Markus Wenzel. *}
section {* Types for Names, Nominal Datatype Declaration for Types and Terms *}
no_syntax
"_Map" :: "maplets => 'a ~=> 'b" ("(1[_])")
text {* The main point of this solution is to use names everywhere (be they bound,
binding or free). In System \FSUB{} there are two kinds of names corresponding to
type-variables and to term-variables. These two kinds of names are represented in
the nominal datatype package as atom-types @{text "tyvrs"} and @{text "vrs"}: *}
atom_decl tyvrs vrs
text{* There are numerous facts that come with this declaration: for example that
there are infinitely many elements in @{text "tyvrs"} and @{text "vrs"}. *}
text{* The constructors for types and terms in System \FSUB{} contain abstractions
over type-variables and term-variables. The nominal datatype package uses
@{text "\<guillemotleft>\<dots>\<guillemotright>\<dots>"} to indicate where abstractions occur. *}
nominal_datatype ty =
Tvar "tyvrs"
| Top
| Arrow "ty" "ty" (infixr "\<rightarrow>" 200)
| Forall "\<guillemotleft>tyvrs\<guillemotright>ty" "ty"
nominal_datatype trm =
Var "vrs"
| Abs "\<guillemotleft>vrs\<guillemotright>trm" "ty"
| TAbs "\<guillemotleft>tyvrs\<guillemotright>trm" "ty"
| App "trm" "trm" (infixl "\<cdot>" 200)
| TApp "trm" "ty" (infixl "\<cdot>\<^sub>\<tau>" 200)
text {* To be polite to the eye, some more familiar notation is introduced.
Because of the change in the order of arguments, one needs to use
translation rules, instead of syntax annotations at the term-constructors
as given above for @{term "Arrow"}. *}
abbreviation
Forall_syn :: "tyvrs \<Rightarrow> ty \<Rightarrow> ty \<Rightarrow> ty" ("(3\<forall>_<:_./ _)" [0, 0, 10] 10)
where
"\<forall>X<:T\<^sub>1. T\<^sub>2 \<equiv> ty.Forall X T\<^sub>2 T\<^sub>1"
abbreviation
Abs_syn :: "vrs \<Rightarrow> ty \<Rightarrow> trm \<Rightarrow> trm" ("(3\<lambda>_:_./ _)" [0, 0, 10] 10)
where
"\<lambda>x:T. t \<equiv> trm.Abs x t T"
abbreviation
TAbs_syn :: "tyvrs \<Rightarrow> ty \<Rightarrow> trm \<Rightarrow> trm" ("(3\<lambda>_<:_./ _)" [0, 0, 10] 10)
where
"\<lambda>X<:T. t \<equiv> trm.TAbs X t T"
text {* Again there are numerous facts that are proved automatically for @{typ "ty"}
and @{typ "trm"}: for example that the set of free variables, i.e.~the @{text "support"},
is finite. However note that nominal-datatype declarations do \emph{not} define
``classical" constructor-based datatypes, but rather define $\alpha$-equivalence
classes---we can for example show that $\alpha$-equivalent @{typ "ty"}s
and @{typ "trm"}s are equal: *}
lemma alpha_illustration:
shows "(\<forall>X<:T. Tvar X) = (\<forall>Y<:T. Tvar Y)"
and "(\<lambda>x:T. Var x) = (\<lambda>y:T. Var y)"
by (simp_all add: ty.inject trm.inject alpha calc_atm fresh_atm)
section {* SubTyping Contexts *}
nominal_datatype binding =
VarB vrs ty
| TVarB tyvrs ty
type_synonym env = "binding list"
text {* Typing contexts are represented as lists that ``grow" on the left; we
thereby deviating from the convention in the POPLmark-paper. The lists contain
pairs of type-variables and types (this is sufficient for Part 1A). *}
text {* In order to state validity-conditions for typing-contexts, the notion of
a @{text "dom"} of a typing-context is handy. *}
nominal_primrec
"tyvrs_of" :: "binding \<Rightarrow> tyvrs set"
where
"tyvrs_of (VarB x y) = {}"
| "tyvrs_of (TVarB x y) = {x}"
by auto
nominal_primrec
"vrs_of" :: "binding \<Rightarrow> vrs set"
where
"vrs_of (VarB x y) = {x}"
| "vrs_of (TVarB x y) = {}"
by auto
primrec
"ty_dom" :: "env \<Rightarrow> tyvrs set"
where
"ty_dom [] = {}"
| "ty_dom (X#\<Gamma>) = (tyvrs_of X)\<union>(ty_dom \<Gamma>)"
primrec
"trm_dom" :: "env \<Rightarrow> vrs set"
where
"trm_dom [] = {}"
| "trm_dom (X#\<Gamma>) = (vrs_of X)\<union>(trm_dom \<Gamma>)"
lemma vrs_of_eqvt[eqvt]:
fixes pi ::"tyvrs prm"
and pi'::"vrs prm"
shows "pi \<bullet>(tyvrs_of x) = tyvrs_of (pi\<bullet>x)"
and "pi'\<bullet>(tyvrs_of x) = tyvrs_of (pi'\<bullet>x)"
and "pi \<bullet>(vrs_of x) = vrs_of (pi\<bullet>x)"
and "pi'\<bullet>(vrs_of x) = vrs_of (pi'\<bullet>x)"
by (nominal_induct x rule: binding.strong_induct) (simp_all add: tyvrs_of.simps eqvts)
lemma doms_eqvt[eqvt]:
fixes pi::"tyvrs prm"
and pi'::"vrs prm"
shows "pi \<bullet>(ty_dom \<Gamma>) = ty_dom (pi\<bullet>\<Gamma>)"
and "pi'\<bullet>(ty_dom \<Gamma>) = ty_dom (pi'\<bullet>\<Gamma>)"
and "pi \<bullet>(trm_dom \<Gamma>) = trm_dom (pi\<bullet>\<Gamma>)"
and "pi'\<bullet>(trm_dom \<Gamma>) = trm_dom (pi'\<bullet>\<Gamma>)"
by (induct \<Gamma>) (simp_all add: eqvts)
lemma finite_vrs:
shows "finite (tyvrs_of x)"
and "finite (vrs_of x)"
by (nominal_induct rule:binding.strong_induct) auto
lemma finite_doms:
shows "finite (ty_dom \<Gamma>)"
and "finite (trm_dom \<Gamma>)"
by (induct \<Gamma>) (auto simp add: finite_vrs)
lemma ty_dom_supp:
shows "(supp (ty_dom \<Gamma>)) = (ty_dom \<Gamma>)"
and "(supp (trm_dom \<Gamma>)) = (trm_dom \<Gamma>)"
by (simp only: at_fin_set_supp at_tyvrs_inst at_vrs_inst finite_doms)+
lemma ty_dom_inclusion:
assumes a: "(TVarB X T)\<in>set \<Gamma>"
shows "X\<in>(ty_dom \<Gamma>)"
using a by (induct \<Gamma>) (auto)
lemma ty_binding_existence:
assumes "X \<in> (tyvrs_of a)"
shows "\<exists>T.(TVarB X T=a)"
using assms
by (nominal_induct a rule: binding.strong_induct) (auto)
lemma ty_dom_existence:
assumes a: "X\<in>(ty_dom \<Gamma>)"
shows "\<exists>T.(TVarB X T)\<in>set \<Gamma>"
using a
apply (induct \<Gamma>, auto)
apply (rename_tac a \<Gamma>')
apply (subgoal_tac "\<exists>T.(TVarB X T=a)")
apply (auto)
apply (auto simp add: ty_binding_existence)
done
lemma doms_append:
shows "ty_dom (\<Gamma>@\<Delta>) = ((ty_dom \<Gamma>) \<union> (ty_dom \<Delta>))"
and "trm_dom (\<Gamma>@\<Delta>) = ((trm_dom \<Gamma>) \<union> (trm_dom \<Delta>))"
by (induct \<Gamma>) (auto)
lemma ty_vrs_prm_simp:
fixes pi::"vrs prm"
and S::"ty"
shows "pi\<bullet>S = S"
by (induct S rule: ty.induct) (auto simp add: calc_atm)
lemma fresh_ty_dom_cons:
fixes X::"tyvrs"
shows "X\<sharp>(ty_dom (Y#\<Gamma>)) = (X\<sharp>(tyvrs_of Y) \<and> X\<sharp>(ty_dom \<Gamma>))"
apply (nominal_induct rule:binding.strong_induct)
apply (auto)
apply (simp add: fresh_def supp_def eqvts)
apply (simp add: fresh_fin_insert [OF pt_tyvrs_inst at_tyvrs_inst fs_tyvrs_inst] finite_doms)
apply (simp add: fresh_def supp_def eqvts)
apply (simp add: fresh_fin_insert [OF pt_tyvrs_inst at_tyvrs_inst fs_tyvrs_inst] finite_doms)+
done
lemma tyvrs_fresh:
fixes X::"tyvrs"
assumes "X \<sharp> a"
shows "X \<sharp> tyvrs_of a"
and "X \<sharp> vrs_of a"
using assms
apply (nominal_induct a rule:binding.strong_induct)
apply (auto)
apply (fresh_guess)+
done
lemma fresh_dom:
fixes X::"tyvrs"
assumes a: "X\<sharp>\<Gamma>"
shows "X\<sharp>(ty_dom \<Gamma>)"
using a
apply(induct \<Gamma>)
apply(simp add: fresh_set_empty)
apply(simp only: fresh_ty_dom_cons)
apply(auto simp add: fresh_prod fresh_list_cons tyvrs_fresh)
done
text {* Not all lists of type @{typ "env"} are well-formed. One condition
requires that in @{term "TVarB X S#\<Gamma>"} all free variables of @{term "S"} must be
in the @{term "ty_dom"} of @{term "\<Gamma>"}, that is @{term "S"} must be @{text "closed"}
in @{term "\<Gamma>"}. The set of free variables of @{term "S"} is the
@{text "support"} of @{term "S"}. *}
definition "closed_in" :: "ty \<Rightarrow> env \<Rightarrow> bool" ("_ closed'_in _" [100,100] 100) where
"S closed_in \<Gamma> \<equiv> (supp S)\<subseteq>(ty_dom \<Gamma>)"
lemma closed_in_eqvt[eqvt]:
fixes pi::"tyvrs prm"
assumes a: "S closed_in \<Gamma>"
shows "(pi\<bullet>S) closed_in (pi\<bullet>\<Gamma>)"
using a
proof -
from a have "pi\<bullet>(S closed_in \<Gamma>)" by (simp add: perm_bool)
then show "(pi\<bullet>S) closed_in (pi\<bullet>\<Gamma>)" by (simp add: closed_in_def eqvts)
qed
lemma tyvrs_vrs_prm_simp:
fixes pi::"vrs prm"
shows "tyvrs_of (pi\<bullet>a) = tyvrs_of a"
apply (nominal_induct rule:binding.strong_induct)
apply (simp_all add: eqvts)
apply (simp add: dj_perm_forget[OF dj_tyvrs_vrs])
done
lemma ty_vrs_fresh:
fixes x::"vrs"
and T::"ty"
shows "x \<sharp> T"
by (simp add: fresh_def supp_def ty_vrs_prm_simp)
lemma ty_dom_vrs_prm_simp:
fixes pi::"vrs prm"
and \<Gamma>::"env"
shows "(ty_dom (pi\<bullet>\<Gamma>)) = (ty_dom \<Gamma>)"
apply(induct \<Gamma>)
apply (simp add: eqvts)
apply(simp add: tyvrs_vrs_prm_simp)
done
lemma closed_in_eqvt'[eqvt]:
fixes pi::"vrs prm"
assumes a: "S closed_in \<Gamma>"
shows "(pi\<bullet>S) closed_in (pi\<bullet>\<Gamma>)"
using a
by (simp add: closed_in_def ty_dom_vrs_prm_simp ty_vrs_prm_simp)
lemma fresh_vrs_of:
fixes x::"vrs"
shows "x\<sharp>vrs_of b = x\<sharp>b"
by (nominal_induct b rule: binding.strong_induct)
(simp_all add: fresh_singleton fresh_set_empty ty_vrs_fresh fresh_atm)
lemma fresh_trm_dom:
fixes x::"vrs"
shows "x\<sharp> trm_dom \<Gamma> = x\<sharp>\<Gamma>"
by (induct \<Gamma>)
(simp_all add: fresh_set_empty fresh_list_cons
fresh_fin_union [OF pt_vrs_inst at_vrs_inst fs_vrs_inst]
finite_doms finite_vrs fresh_vrs_of fresh_list_nil)
lemma closed_in_fresh: "(X::tyvrs) \<sharp> ty_dom \<Gamma> \<Longrightarrow> T closed_in \<Gamma> \<Longrightarrow> X \<sharp> T"
by (auto simp add: closed_in_def fresh_def ty_dom_supp)
text {* Now validity of a context is a straightforward inductive definition. *}
inductive
valid_rel :: "env \<Rightarrow> bool" ("\<turnstile> _ ok" [100] 100)
where
valid_nil[simp]: "\<turnstile> [] ok"
| valid_consT[simp]: "\<lbrakk>\<turnstile> \<Gamma> ok; X\<sharp>(ty_dom \<Gamma>); T closed_in \<Gamma>\<rbrakk> \<Longrightarrow> \<turnstile> (TVarB X T#\<Gamma>) ok"
| valid_cons [simp]: "\<lbrakk>\<turnstile> \<Gamma> ok; x\<sharp>(trm_dom \<Gamma>); T closed_in \<Gamma>\<rbrakk> \<Longrightarrow> \<turnstile> (VarB x T#\<Gamma>) ok"
equivariance valid_rel
declare binding.inject [simp add]
declare trm.inject [simp add]
inductive_cases validE[elim]:
"\<turnstile> (TVarB X T#\<Gamma>) ok"
"\<turnstile> (VarB x T#\<Gamma>) ok"
"\<turnstile> (b#\<Gamma>) ok"
declare binding.inject [simp del]
declare trm.inject [simp del]
lemma validE_append:
assumes a: "\<turnstile> (\<Delta>@\<Gamma>) ok"
shows "\<turnstile> \<Gamma> ok"
using a
proof (induct \<Delta>)
case (Cons a \<Gamma>')
then show ?case
by (nominal_induct a rule:binding.strong_induct)
(auto elim: validE)
qed (auto)
lemma replace_type:
assumes a: "\<turnstile> (\<Delta>@(TVarB X T)#\<Gamma>) ok"
and b: "S closed_in \<Gamma>"
shows "\<turnstile> (\<Delta>@(TVarB X S)#\<Gamma>) ok"
using a b
proof(induct \<Delta>)
case Nil
then show ?case by (auto elim: validE intro: valid_cons simp add: doms_append closed_in_def)
next
case (Cons a \<Gamma>')
then show ?case
by (nominal_induct a rule:binding.strong_induct)
(auto elim: validE intro!: valid_cons simp add: doms_append closed_in_def)
qed
text {* Well-formed contexts have a unique type-binding for a type-variable. *}
lemma uniqueness_of_ctxt:
fixes \<Gamma>::"env"
assumes a: "\<turnstile> \<Gamma> ok"
and b: "(TVarB X T)\<in>set \<Gamma>"
and c: "(TVarB X S)\<in>set \<Gamma>"
shows "T=S"
using a b c
proof (induct)
case (valid_consT \<Gamma> X' T')
moreover
{ fix \<Gamma>'::"env"
assume a: "X'\<sharp>(ty_dom \<Gamma>')"
have "\<not>(\<exists>T.(TVarB X' T)\<in>(set \<Gamma>'))" using a
proof (induct \<Gamma>')
case (Cons Y \<Gamma>')
thus "\<not> (\<exists>T.(TVarB X' T)\<in>set(Y#\<Gamma>'))"
by (simp add: fresh_ty_dom_cons
fresh_fin_union[OF pt_tyvrs_inst at_tyvrs_inst fs_tyvrs_inst]
finite_vrs finite_doms,
auto simp add: fresh_atm fresh_singleton)
qed (simp)
}
ultimately show "T=S" by (auto simp add: binding.inject)
qed (auto)
lemma uniqueness_of_ctxt':
fixes \<Gamma>::"env"
assumes a: "\<turnstile> \<Gamma> ok"
and b: "(VarB x T)\<in>set \<Gamma>"
and c: "(VarB x S)\<in>set \<Gamma>"
shows "T=S"
using a b c
proof (induct)
case (valid_cons \<Gamma> x' T')
moreover
{ fix \<Gamma>'::"env"
assume a: "x'\<sharp>(trm_dom \<Gamma>')"
have "\<not>(\<exists>T.(VarB x' T)\<in>(set \<Gamma>'))" using a
proof (induct \<Gamma>')
case (Cons y \<Gamma>')
thus "\<not> (\<exists>T.(VarB x' T)\<in>set(y#\<Gamma>'))"
by (simp add: fresh_fin_union[OF pt_vrs_inst at_vrs_inst fs_vrs_inst]
finite_vrs finite_doms,
auto simp add: fresh_atm fresh_singleton)
qed (simp)
}
ultimately show "T=S" by (auto simp add: binding.inject)
qed (auto)
section {* Size and Capture-Avoiding Substitution for Types *}
nominal_primrec
size_ty :: "ty \<Rightarrow> nat"
where
"size_ty (Tvar X) = 1"
| "size_ty (Top) = 1"
| "size_ty (T1 \<rightarrow> T2) = (size_ty T1) + (size_ty T2) + 1"
| "X \<sharp> T1 \<Longrightarrow> size_ty (\<forall>X<:T1. T2) = (size_ty T1) + (size_ty T2) + 1"
apply (finite_guess)+
apply (rule TrueI)+
apply (simp add: fresh_nat)
apply (fresh_guess)+
done
nominal_primrec
subst_ty :: "ty \<Rightarrow> tyvrs \<Rightarrow> ty \<Rightarrow> ty" ("_[_ \<mapsto> _]\<^sub>\<tau>" [300, 0, 0] 300)
where
"(Tvar X)[Y \<mapsto> T]\<^sub>\<tau> = (if X=Y then T else Tvar X)"
| "(Top)[Y \<mapsto> T]\<^sub>\<tau> = Top"
| "(T\<^sub>1 \<rightarrow> T\<^sub>2)[Y \<mapsto> T]\<^sub>\<tau> = T\<^sub>1[Y \<mapsto> T]\<^sub>\<tau> \<rightarrow> T\<^sub>2[Y \<mapsto> T]\<^sub>\<tau>"
| "X\<sharp>(Y,T,T\<^sub>1) \<Longrightarrow> (\<forall>X<:T\<^sub>1. T\<^sub>2)[Y \<mapsto> T]\<^sub>\<tau> = (\<forall>X<:T\<^sub>1[Y \<mapsto> T]\<^sub>\<tau>. T\<^sub>2[Y \<mapsto> T]\<^sub>\<tau>)"
apply (finite_guess)+
apply (rule TrueI)+
apply (simp add: abs_fresh)
apply (fresh_guess)+
done
lemma subst_eqvt[eqvt]:
fixes pi::"tyvrs prm"
and T::"ty"
shows "pi\<bullet>(T[X \<mapsto> T']\<^sub>\<tau>) = (pi\<bullet>T)[(pi\<bullet>X) \<mapsto> (pi\<bullet>T')]\<^sub>\<tau>"
by (nominal_induct T avoiding: X T' rule: ty.strong_induct)
(perm_simp add: fresh_bij)+
lemma subst_eqvt'[eqvt]:
fixes pi::"vrs prm"
and T::"ty"
shows "pi\<bullet>(T[X \<mapsto> T']\<^sub>\<tau>) = (pi\<bullet>T)[(pi\<bullet>X) \<mapsto> (pi\<bullet>T')]\<^sub>\<tau>"
by (nominal_induct T avoiding: X T' rule: ty.strong_induct)
(perm_simp add: fresh_left)+
lemma type_subst_fresh:
fixes X::"tyvrs"
assumes "X\<sharp>T" and "X\<sharp>P"
shows "X\<sharp>T[Y \<mapsto> P]\<^sub>\<tau>"
using assms
by (nominal_induct T avoiding: X Y P rule:ty.strong_induct)
(auto simp add: abs_fresh)
lemma fresh_type_subst_fresh:
assumes "X\<sharp>T'"
shows "X\<sharp>T[X \<mapsto> T']\<^sub>\<tau>"
using assms
by (nominal_induct T avoiding: X T' rule: ty.strong_induct)
(auto simp add: fresh_atm abs_fresh fresh_nat)
lemma type_subst_identity:
"X\<sharp>T \<Longrightarrow> T[X \<mapsto> U]\<^sub>\<tau> = T"
by (nominal_induct T avoiding: X U rule: ty.strong_induct)
(simp_all add: fresh_atm abs_fresh)
lemma type_substitution_lemma:
"X \<noteq> Y \<Longrightarrow> X\<sharp>L \<Longrightarrow> M[X \<mapsto> N]\<^sub>\<tau>[Y \<mapsto> L]\<^sub>\<tau> = M[Y \<mapsto> L]\<^sub>\<tau>[X \<mapsto> N[Y \<mapsto> L]\<^sub>\<tau>]\<^sub>\<tau>"
by (nominal_induct M avoiding: X Y N L rule: ty.strong_induct)
(auto simp add: type_subst_fresh type_subst_identity)
lemma type_subst_rename:
"Y\<sharp>T \<Longrightarrow> ([(Y,X)]\<bullet>T)[Y \<mapsto> U]\<^sub>\<tau> = T[X \<mapsto> U]\<^sub>\<tau>"
by (nominal_induct T avoiding: X Y U rule: ty.strong_induct)
(simp_all add: fresh_atm calc_atm abs_fresh fresh_aux)
nominal_primrec
subst_tyb :: "binding \<Rightarrow> tyvrs \<Rightarrow> ty \<Rightarrow> binding" ("_[_ \<mapsto> _]\<^sub>b" [100,100,100] 100)
where
"(TVarB X U)[Y \<mapsto> T]\<^sub>b = TVarB X (U[Y \<mapsto> T]\<^sub>\<tau>)"
| "(VarB X U)[Y \<mapsto> T]\<^sub>b = VarB X (U[Y \<mapsto> T]\<^sub>\<tau>)"
by auto
lemma binding_subst_fresh:
fixes X::"tyvrs"
assumes "X\<sharp>a"
and "X\<sharp>P"
shows "X\<sharp>a[Y \<mapsto> P]\<^sub>b"
using assms
by (nominal_induct a rule: binding.strong_induct)
(auto simp add: type_subst_fresh)
lemma binding_subst_identity:
shows "X\<sharp>B \<Longrightarrow> B[X \<mapsto> U]\<^sub>b = B"
by (induct B rule: binding.induct)
(simp_all add: fresh_atm type_subst_identity)
primrec subst_tyc :: "env \<Rightarrow> tyvrs \<Rightarrow> ty \<Rightarrow> env" ("_[_ \<mapsto> _]\<^sub>e" [100,100,100] 100) where
"([])[Y \<mapsto> T]\<^sub>e= []"
| "(B#\<Gamma>)[Y \<mapsto> T]\<^sub>e = (B[Y \<mapsto> T]\<^sub>b)#(\<Gamma>[Y \<mapsto> T]\<^sub>e)"
lemma ctxt_subst_fresh':
fixes X::"tyvrs"
assumes "X\<sharp>\<Gamma>"
and "X\<sharp>P"
shows "X\<sharp>\<Gamma>[Y \<mapsto> P]\<^sub>e"
using assms
by (induct \<Gamma>)
(auto simp add: fresh_list_cons binding_subst_fresh)
lemma ctxt_subst_mem_TVarB: "TVarB X T \<in> set \<Gamma> \<Longrightarrow> TVarB X (T[Y \<mapsto> U]\<^sub>\<tau>) \<in> set (\<Gamma>[Y \<mapsto> U]\<^sub>e)"
by (induct \<Gamma>) auto
lemma ctxt_subst_mem_VarB: "VarB x T \<in> set \<Gamma> \<Longrightarrow> VarB x (T[Y \<mapsto> U]\<^sub>\<tau>) \<in> set (\<Gamma>[Y \<mapsto> U]\<^sub>e)"
by (induct \<Gamma>) auto
lemma ctxt_subst_identity: "X\<sharp>\<Gamma> \<Longrightarrow> \<Gamma>[X \<mapsto> U]\<^sub>e = \<Gamma>"
by (induct \<Gamma>) (simp_all add: fresh_list_cons binding_subst_identity)
lemma ctxt_subst_append: "(\<Delta> @ \<Gamma>)[X \<mapsto> T]\<^sub>e = \<Delta>[X \<mapsto> T]\<^sub>e @ \<Gamma>[X \<mapsto> T]\<^sub>e"
by (induct \<Delta>) simp_all
nominal_primrec
subst_trm :: "trm \<Rightarrow> vrs \<Rightarrow> trm \<Rightarrow> trm" ("_[_ \<mapsto> _]" [300, 0, 0] 300)
where
"(Var x)[y \<mapsto> t'] = (if x=y then t' else (Var x))"
| "(t1 \<cdot> t2)[y \<mapsto> t'] = t1[y \<mapsto> t'] \<cdot> t2[y \<mapsto> t']"
| "(t \<cdot>\<^sub>\<tau> T)[y \<mapsto> t'] = t[y \<mapsto> t'] \<cdot>\<^sub>\<tau> T"
| "X\<sharp>(T,t') \<Longrightarrow> (\<lambda>X<:T. t)[y \<mapsto> t'] = (\<lambda>X<:T. t[y \<mapsto> t'])"
| "x\<sharp>(y,t') \<Longrightarrow> (\<lambda>x:T. t)[y \<mapsto> t'] = (\<lambda>x:T. t[y \<mapsto> t'])"
apply(finite_guess)+
apply(rule TrueI)+
apply(simp add: abs_fresh)+
apply(fresh_guess add: ty_vrs_fresh abs_fresh)+
done
lemma subst_trm_fresh_tyvar:
fixes X::"tyvrs"
shows "X\<sharp>t \<Longrightarrow> X\<sharp>u \<Longrightarrow> X\<sharp>t[x \<mapsto> u]"
by (nominal_induct t avoiding: x u rule: trm.strong_induct)
(auto simp add: trm.fresh abs_fresh)
lemma subst_trm_fresh_var:
"x\<sharp>u \<Longrightarrow> x\<sharp>t[x \<mapsto> u]"
by (nominal_induct t avoiding: x u rule: trm.strong_induct)
(simp_all add: abs_fresh fresh_atm ty_vrs_fresh)
lemma subst_trm_eqvt[eqvt]:
fixes pi::"tyvrs prm"
and t::"trm"
shows "pi\<bullet>(t[x \<mapsto> u]) = (pi\<bullet>t)[(pi\<bullet>x) \<mapsto> (pi\<bullet>u)]"
by (nominal_induct t avoiding: x u rule: trm.strong_induct)
(perm_simp add: fresh_left)+
lemma subst_trm_eqvt'[eqvt]:
fixes pi::"vrs prm"
and t::"trm"
shows "pi\<bullet>(t[x \<mapsto> u]) = (pi\<bullet>t)[(pi\<bullet>x) \<mapsto> (pi\<bullet>u)]"
by (nominal_induct t avoiding: x u rule: trm.strong_induct)
(perm_simp add: fresh_left)+
lemma subst_trm_rename:
"y\<sharp>t \<Longrightarrow> ([(y, x)] \<bullet> t)[y \<mapsto> u] = t[x \<mapsto> u]"
by (nominal_induct t avoiding: x y u rule: trm.strong_induct)
(simp_all add: fresh_atm calc_atm abs_fresh fresh_aux ty_vrs_fresh perm_fresh_fresh)
nominal_primrec (freshness_context: "T2::ty")
subst_trm_ty :: "trm \<Rightarrow> tyvrs \<Rightarrow> ty \<Rightarrow> trm" ("_[_ \<mapsto>\<^sub>\<tau> _]" [300, 0, 0] 300)
where
"(Var x)[Y \<mapsto>\<^sub>\<tau> T2] = Var x"
| "(t1 \<cdot> t2)[Y \<mapsto>\<^sub>\<tau> T2] = t1[Y \<mapsto>\<^sub>\<tau> T2] \<cdot> t2[Y \<mapsto>\<^sub>\<tau> T2]"
| "(t1 \<cdot>\<^sub>\<tau> T)[Y \<mapsto>\<^sub>\<tau> T2] = t1[Y \<mapsto>\<^sub>\<tau> T2] \<cdot>\<^sub>\<tau> T[Y \<mapsto> T2]\<^sub>\<tau>"
| "X\<sharp>(Y,T,T2) \<Longrightarrow> (\<lambda>X<:T. t)[Y \<mapsto>\<^sub>\<tau> T2] = (\<lambda>X<:T[Y \<mapsto> T2]\<^sub>\<tau>. t[Y \<mapsto>\<^sub>\<tau> T2])"
| "(\<lambda>x:T. t)[Y \<mapsto>\<^sub>\<tau> T2] = (\<lambda>x:T[Y \<mapsto> T2]\<^sub>\<tau>. t[Y \<mapsto>\<^sub>\<tau> T2])"
apply(finite_guess)+
apply(rule TrueI)+
apply(simp add: abs_fresh ty_vrs_fresh)+
apply(simp add: type_subst_fresh)
apply(fresh_guess add: ty_vrs_fresh abs_fresh)+
done
lemma subst_trm_ty_fresh:
fixes X::"tyvrs"
shows "X\<sharp>t \<Longrightarrow> X\<sharp>T \<Longrightarrow> X\<sharp>t[Y \<mapsto>\<^sub>\<tau> T]"
by (nominal_induct t avoiding: Y T rule: trm.strong_induct)
(auto simp add: abs_fresh type_subst_fresh)
lemma subst_trm_ty_fresh':
"X\<sharp>T \<Longrightarrow> X\<sharp>t[X \<mapsto>\<^sub>\<tau> T]"
by (nominal_induct t avoiding: X T rule: trm.strong_induct)
(simp_all add: abs_fresh fresh_type_subst_fresh fresh_atm)
lemma subst_trm_ty_eqvt[eqvt]:
fixes pi::"tyvrs prm"
and t::"trm"
shows "pi\<bullet>(t[X \<mapsto>\<^sub>\<tau> T]) = (pi\<bullet>t)[(pi\<bullet>X) \<mapsto>\<^sub>\<tau> (pi\<bullet>T)]"
by (nominal_induct t avoiding: X T rule: trm.strong_induct)
(perm_simp add: fresh_bij subst_eqvt)+
lemma subst_trm_ty_eqvt'[eqvt]:
fixes pi::"vrs prm"
and t::"trm"
shows "pi\<bullet>(t[X \<mapsto>\<^sub>\<tau> T]) = (pi\<bullet>t)[(pi\<bullet>X) \<mapsto>\<^sub>\<tau> (pi\<bullet>T)]"
by (nominal_induct t avoiding: X T rule: trm.strong_induct)
(perm_simp add: fresh_left subst_eqvt')+
lemma subst_trm_ty_rename:
"Y\<sharp>t \<Longrightarrow> ([(Y, X)] \<bullet> t)[Y \<mapsto>\<^sub>\<tau> U] = t[X \<mapsto>\<^sub>\<tau> U]"
by (nominal_induct t avoiding: X Y U rule: trm.strong_induct)
(simp_all add: fresh_atm calc_atm abs_fresh fresh_aux type_subst_rename)
section {* Subtyping-Relation *}
text {* The definition for the subtyping-relation follows quite closely what is written
in the POPLmark-paper, except for the premises dealing with well-formed contexts and
the freshness constraint @{term "X\<sharp>\<Gamma>"} in the @{text "S_Forall"}-rule. (The freshness
constraint is specific to the \emph{nominal approach}. Note, however, that the constraint
does \emph{not} make the subtyping-relation ``partial"\ldots because we work over
$\alpha$-equivalence classes.) *}
inductive
subtype_of :: "env \<Rightarrow> ty \<Rightarrow> ty \<Rightarrow> bool" ("_\<turnstile>_<:_" [100,100,100] 100)
where
SA_Top[intro]: "\<lbrakk>\<turnstile> \<Gamma> ok; S closed_in \<Gamma>\<rbrakk> \<Longrightarrow> \<Gamma> \<turnstile> S <: Top"
| SA_refl_TVar[intro]: "\<lbrakk>\<turnstile> \<Gamma> ok; X \<in> ty_dom \<Gamma>\<rbrakk>\<Longrightarrow> \<Gamma> \<turnstile> Tvar X <: Tvar X"
| SA_trans_TVar[intro]: "\<lbrakk>(TVarB X S) \<in> set \<Gamma>; \<Gamma> \<turnstile> S <: T\<rbrakk> \<Longrightarrow> \<Gamma> \<turnstile> (Tvar X) <: T"
| SA_arrow[intro]: "\<lbrakk>\<Gamma> \<turnstile> T\<^sub>1 <: S\<^sub>1; \<Gamma> \<turnstile> S\<^sub>2 <: T\<^sub>2\<rbrakk> \<Longrightarrow> \<Gamma> \<turnstile> (S\<^sub>1 \<rightarrow> S\<^sub>2) <: (T\<^sub>1 \<rightarrow> T\<^sub>2)"
| SA_all[intro]: "\<lbrakk>\<Gamma> \<turnstile> T\<^sub>1 <: S\<^sub>1; ((TVarB X T\<^sub>1)#\<Gamma>) \<turnstile> S\<^sub>2 <: T\<^sub>2\<rbrakk> \<Longrightarrow> \<Gamma> \<turnstile> (\<forall>X<:S\<^sub>1. S\<^sub>2) <: (\<forall>X<:T\<^sub>1. T\<^sub>2)"
lemma subtype_implies_ok:
fixes X::"tyvrs"
assumes a: "\<Gamma> \<turnstile> S <: T"
shows "\<turnstile> \<Gamma> ok"
using a by (induct) (auto)
lemma subtype_implies_closed:
assumes a: "\<Gamma> \<turnstile> S <: T"
shows "S closed_in \<Gamma> \<and> T closed_in \<Gamma>"
using a
proof (induct)
case (SA_Top \<Gamma> S)
have "Top closed_in \<Gamma>" by (simp add: closed_in_def ty.supp)
moreover
have "S closed_in \<Gamma>" by fact
ultimately show "S closed_in \<Gamma> \<and> Top closed_in \<Gamma>" by simp
next
case (SA_trans_TVar X S \<Gamma> T)
have "(TVarB X S)\<in>set \<Gamma>" by fact
hence "X \<in> ty_dom \<Gamma>" by (rule ty_dom_inclusion)
hence "(Tvar X) closed_in \<Gamma>" by (simp add: closed_in_def ty.supp supp_atm)
moreover
have "S closed_in \<Gamma> \<and> T closed_in \<Gamma>" by fact
hence "T closed_in \<Gamma>" by force
ultimately show "(Tvar X) closed_in \<Gamma> \<and> T closed_in \<Gamma>" by simp
qed (auto simp add: closed_in_def ty.supp supp_atm abs_supp)
lemma subtype_implies_fresh:
fixes X::"tyvrs"
assumes a1: "\<Gamma> \<turnstile> S <: T"
and a2: "X\<sharp>\<Gamma>"
shows "X\<sharp>S \<and> X\<sharp>T"
proof -
from a1 have "\<turnstile> \<Gamma> ok" by (rule subtype_implies_ok)
with a2 have "X\<sharp>ty_dom(\<Gamma>)" by (simp add: fresh_dom)
moreover
from a1 have "S closed_in \<Gamma> \<and> T closed_in \<Gamma>" by (rule subtype_implies_closed)
hence "supp S \<subseteq> ((supp (ty_dom \<Gamma>))::tyvrs set)"
and "supp T \<subseteq> ((supp (ty_dom \<Gamma>))::tyvrs set)" by (simp_all add: ty_dom_supp closed_in_def)
ultimately show "X\<sharp>S \<and> X\<sharp>T" by (force simp add: supp_prod fresh_def)
qed
lemma valid_ty_dom_fresh:
fixes X::"tyvrs"
assumes valid: "\<turnstile> \<Gamma> ok"
shows "X\<sharp>(ty_dom \<Gamma>) = X\<sharp>\<Gamma>"
using valid
apply induct
apply (simp add: fresh_list_nil fresh_set_empty)
apply (simp_all add: binding.fresh fresh_list_cons
fresh_fin_insert [OF pt_tyvrs_inst at_tyvrs_inst fs_tyvrs_inst] finite_doms fresh_atm)
apply (auto simp add: closed_in_fresh)
done
equivariance subtype_of
nominal_inductive subtype_of
apply (simp_all add: abs_fresh)
apply (fastforce simp add: valid_ty_dom_fresh dest: subtype_implies_ok)
apply (force simp add: closed_in_fresh dest: subtype_implies_closed subtype_implies_ok)+
done
section {* Reflexivity of Subtyping *}
lemma subtype_reflexivity:
assumes a: "\<turnstile> \<Gamma> ok"
and b: "T closed_in \<Gamma>"
shows "\<Gamma> \<turnstile> T <: T"
using a b
proof(nominal_induct T avoiding: \<Gamma> rule: ty.strong_induct)
case (Forall X T\<^sub>1 T\<^sub>2)
have ih_T\<^sub>1: "\<And>\<Gamma>. \<lbrakk>\<turnstile> \<Gamma> ok; T\<^sub>1 closed_in \<Gamma>\<rbrakk> \<Longrightarrow> \<Gamma> \<turnstile> T\<^sub>1 <: T\<^sub>1" by fact
have ih_T\<^sub>2: "\<And>\<Gamma>. \<lbrakk>\<turnstile> \<Gamma> ok; T\<^sub>2 closed_in \<Gamma>\<rbrakk> \<Longrightarrow> \<Gamma> \<turnstile> T\<^sub>2 <: T\<^sub>2" by fact
have fresh_cond: "X\<sharp>\<Gamma>" by fact
hence fresh_ty_dom: "X\<sharp>(ty_dom \<Gamma>)" by (simp add: fresh_dom)
have "(\<forall>X<:T\<^sub>2. T\<^sub>1) closed_in \<Gamma>" by fact
hence closed\<^sub>T2: "T\<^sub>2 closed_in \<Gamma>" and closed\<^sub>T1: "T\<^sub>1 closed_in ((TVarB X T\<^sub>2)#\<Gamma>)"
by (auto simp add: closed_in_def ty.supp abs_supp)
have ok: "\<turnstile> \<Gamma> ok" by fact
hence ok': "\<turnstile> ((TVarB X T\<^sub>2)#\<Gamma>) ok" using closed\<^sub>T2 fresh_ty_dom by simp
have "\<Gamma> \<turnstile> T\<^sub>2 <: T\<^sub>2" using ih_T\<^sub>2 closed\<^sub>T2 ok by simp
moreover
have "((TVarB X T\<^sub>2)#\<Gamma>) \<turnstile> T\<^sub>1 <: T\<^sub>1" using ih_T\<^sub>1 closed\<^sub>T1 ok' by simp
ultimately show "\<Gamma> \<turnstile> (\<forall>X<:T\<^sub>2. T\<^sub>1) <: (\<forall>X<:T\<^sub>2. T\<^sub>1)" using fresh_cond
by (simp add: subtype_of.SA_all)
qed (auto simp add: closed_in_def ty.supp supp_atm)
lemma subtype_reflexivity_semiautomated:
assumes a: "\<turnstile> \<Gamma> ok"
and b: "T closed_in \<Gamma>"
shows "\<Gamma> \<turnstile> T <: T"
using a b
apply(nominal_induct T avoiding: \<Gamma> rule: ty.strong_induct)
apply(auto simp add: ty.supp abs_supp supp_atm closed_in_def)
--{* Too bad that this instantiation cannot be found automatically by
\isakeyword{auto}; \isakeyword{blast} would find it if we had not used
an explicit definition for @{text "closed_in_def"}. *}
apply(drule_tac x="(TVarB tyvrs ty2)#\<Gamma>" in meta_spec)
apply(force dest: fresh_dom simp add: closed_in_def)
done
section {* Weakening *}
text {* In order to prove weakening we introduce the notion of a type-context extending
another. This generalization seems to make the proof for weakening to be
smoother than if we had strictly adhered to the version in the POPLmark-paper. *}
definition extends :: "env \<Rightarrow> env \<Rightarrow> bool" ("_ extends _" [100,100] 100) where
"\<Delta> extends \<Gamma> \<equiv> \<forall>X Q. (TVarB X Q)\<in>set \<Gamma> \<longrightarrow> (TVarB X Q)\<in>set \<Delta>"
lemma extends_ty_dom:
assumes a: "\<Delta> extends \<Gamma>"
shows "ty_dom \<Gamma> \<subseteq> ty_dom \<Delta>"
using a
apply (auto simp add: extends_def)
apply (drule ty_dom_existence)
apply (force simp add: ty_dom_inclusion)
done
lemma extends_closed:
assumes a1: "T closed_in \<Gamma>"
and a2: "\<Delta> extends \<Gamma>"
shows "T closed_in \<Delta>"
using a1 a2
by (auto dest: extends_ty_dom simp add: closed_in_def)
lemma extends_memb:
assumes a: "\<Delta> extends \<Gamma>"
and b: "(TVarB X T) \<in> set \<Gamma>"
shows "(TVarB X T) \<in> set \<Delta>"
using a b by (simp add: extends_def)
lemma weakening:
assumes a: "\<Gamma> \<turnstile> S <: T"
and b: "\<turnstile> \<Delta> ok"
and c: "\<Delta> extends \<Gamma>"
shows "\<Delta> \<turnstile> S <: T"
using a b c
proof (nominal_induct \<Gamma> S T avoiding: \<Delta> rule: subtype_of.strong_induct)
case (SA_Top \<Gamma> S)
have lh_drv_prem: "S closed_in \<Gamma>" by fact
have "\<turnstile> \<Delta> ok" by fact
moreover
have "\<Delta> extends \<Gamma>" by fact
hence "S closed_in \<Delta>" using lh_drv_prem by (simp only: extends_closed)
ultimately show "\<Delta> \<turnstile> S <: Top" by force
next
case (SA_trans_TVar X S \<Gamma> T)
have lh_drv_prem: "(TVarB X S) \<in> set \<Gamma>" by fact
have ih: "\<And>\<Delta>. \<turnstile> \<Delta> ok \<Longrightarrow> \<Delta> extends \<Gamma> \<Longrightarrow> \<Delta> \<turnstile> S <: T" by fact
have ok: "\<turnstile> \<Delta> ok" by fact
have extends: "\<Delta> extends \<Gamma>" by fact
have "(TVarB X S) \<in> set \<Delta>" using lh_drv_prem extends by (simp only: extends_memb)
moreover
have "\<Delta> \<turnstile> S <: T" using ok extends ih by simp
ultimately show "\<Delta> \<turnstile> Tvar X <: T" using ok by force
next
case (SA_refl_TVar \<Gamma> X)
have lh_drv_prem: "X \<in> ty_dom \<Gamma>" by fact
have "\<turnstile> \<Delta> ok" by fact
moreover
have "\<Delta> extends \<Gamma>" by fact
hence "X \<in> ty_dom \<Delta>" using lh_drv_prem by (force dest: extends_ty_dom)
ultimately show "\<Delta> \<turnstile> Tvar X <: Tvar X" by force
next
case (SA_arrow \<Gamma> T\<^sub>1 S\<^sub>1 S\<^sub>2 T\<^sub>2) thus "\<Delta> \<turnstile> S\<^sub>1 \<rightarrow> S\<^sub>2 <: T\<^sub>1 \<rightarrow> T\<^sub>2" by blast
next
case (SA_all \<Gamma> T\<^sub>1 S\<^sub>1 X S\<^sub>2 T\<^sub>2)
have fresh_cond: "X\<sharp>\<Delta>" by fact
hence fresh_dom: "X\<sharp>(ty_dom \<Delta>)" by (simp add: fresh_dom)
have ih\<^sub>1: "\<And>\<Delta>. \<turnstile> \<Delta> ok \<Longrightarrow> \<Delta> extends \<Gamma> \<Longrightarrow> \<Delta> \<turnstile> T\<^sub>1 <: S\<^sub>1" by fact
have ih\<^sub>2: "\<And>\<Delta>. \<turnstile> \<Delta> ok \<Longrightarrow> \<Delta> extends ((TVarB X T\<^sub>1)#\<Gamma>) \<Longrightarrow> \<Delta> \<turnstile> S\<^sub>2 <: T\<^sub>2" by fact
have lh_drv_prem: "\<Gamma> \<turnstile> T\<^sub>1 <: S\<^sub>1" by fact
hence closed\<^sub>T1: "T\<^sub>1 closed_in \<Gamma>" by (simp add: subtype_implies_closed)
have ok: "\<turnstile> \<Delta> ok" by fact
have ext: "\<Delta> extends \<Gamma>" by fact
have "T\<^sub>1 closed_in \<Delta>" using ext closed\<^sub>T1 by (simp only: extends_closed)
hence "\<turnstile> ((TVarB X T\<^sub>1)#\<Delta>) ok" using fresh_dom ok by force
moreover
have "((TVarB X T\<^sub>1)#\<Delta>) extends ((TVarB X T\<^sub>1)#\<Gamma>)" using ext by (force simp add: extends_def)
ultimately have "((TVarB X T\<^sub>1)#\<Delta>) \<turnstile> S\<^sub>2 <: T\<^sub>2" using ih\<^sub>2 by simp
moreover
have "\<Delta> \<turnstile> T\<^sub>1 <: S\<^sub>1" using ok ext ih\<^sub>1 by simp
ultimately show "\<Delta> \<turnstile> (\<forall>X<:S\<^sub>1. S\<^sub>2) <: (\<forall>X<:T\<^sub>1. T\<^sub>2)" using ok by (force intro: SA_all)
qed
text {* In fact all ``non-binding" cases can be solved automatically: *}
lemma weakening_more_automated:
assumes a: "\<Gamma> \<turnstile> S <: T"
and b: "\<turnstile> \<Delta> ok"
and c: "\<Delta> extends \<Gamma>"
shows "\<Delta> \<turnstile> S <: T"
using a b c
proof (nominal_induct \<Gamma> S T avoiding: \<Delta> rule: subtype_of.strong_induct)
case (SA_all \<Gamma> T\<^sub>1 S\<^sub>1 X S\<^sub>2 T\<^sub>2)
have fresh_cond: "X\<sharp>\<Delta>" by fact
hence fresh_dom: "X\<sharp>(ty_dom \<Delta>)" by (simp add: fresh_dom)
have ih\<^sub>1: "\<And>\<Delta>. \<turnstile> \<Delta> ok \<Longrightarrow> \<Delta> extends \<Gamma> \<Longrightarrow> \<Delta> \<turnstile> T\<^sub>1 <: S\<^sub>1" by fact
have ih\<^sub>2: "\<And>\<Delta>. \<turnstile> \<Delta> ok \<Longrightarrow> \<Delta> extends ((TVarB X T\<^sub>1)#\<Gamma>) \<Longrightarrow> \<Delta> \<turnstile> S\<^sub>2 <: T\<^sub>2" by fact
have lh_drv_prem: "\<Gamma> \<turnstile> T\<^sub>1 <: S\<^sub>1" by fact
hence closed\<^sub>T1: "T\<^sub>1 closed_in \<Gamma>" by (simp add: subtype_implies_closed)
have ok: "\<turnstile> \<Delta> ok" by fact
have ext: "\<Delta> extends \<Gamma>" by fact
have "T\<^sub>1 closed_in \<Delta>" using ext closed\<^sub>T1 by (simp only: extends_closed)
hence "\<turnstile> ((TVarB X T\<^sub>1)#\<Delta>) ok" using fresh_dom ok by force
moreover
have "((TVarB X T\<^sub>1)#\<Delta>) extends ((TVarB X T\<^sub>1)#\<Gamma>)" using ext by (force simp add: extends_def)
ultimately have "((TVarB X T\<^sub>1)#\<Delta>) \<turnstile> S\<^sub>2 <: T\<^sub>2" using ih\<^sub>2 by simp
moreover
have "\<Delta> \<turnstile> T\<^sub>1 <: S\<^sub>1" using ok ext ih\<^sub>1 by simp
ultimately show "\<Delta> \<turnstile> (\<forall>X<:S\<^sub>1. S\<^sub>2) <: (\<forall>X<:T\<^sub>1. T\<^sub>2)" using ok by (force intro: SA_all)
qed (blast intro: extends_closed extends_memb dest: extends_ty_dom)+
section {* Transitivity and Narrowing *}
text {* Some inversion lemmas that are needed in the transitivity and narrowing proof.*}
declare ty.inject [simp add]
inductive_cases S_TopE: "\<Gamma> \<turnstile> Top <: T"
inductive_cases S_ArrowE_left: "\<Gamma> \<turnstile> S\<^sub>1 \<rightarrow> S\<^sub>2 <: T"
declare ty.inject [simp del]
lemma S_ForallE_left:
shows "\<lbrakk>\<Gamma> \<turnstile> (\<forall>X<:S\<^sub>1. S\<^sub>2) <: T; X\<sharp>\<Gamma>; X\<sharp>S\<^sub>1; X\<sharp>T\<rbrakk>
\<Longrightarrow> T = Top \<or> (\<exists>T\<^sub>1 T\<^sub>2. T = (\<forall>X<:T\<^sub>1. T\<^sub>2) \<and> \<Gamma> \<turnstile> T\<^sub>1 <: S\<^sub>1 \<and> ((TVarB X T\<^sub>1)#\<Gamma>) \<turnstile> S\<^sub>2 <: T\<^sub>2)"
apply(erule subtype_of.strong_cases[where X="X"])
apply(auto simp add: abs_fresh ty.inject alpha)
done
text {* Next we prove the transitivity and narrowing for the subtyping-relation.
The POPLmark-paper says the following:
\begin{quote}
\begin{lemma}[Transitivity and Narrowing] \
\begin{enumerate}
\item If @{term "\<Gamma> \<turnstile> S<:Q"} and @{term "\<Gamma> \<turnstile> Q<:T"}, then @{term "\<Gamma> \<turnstile> S<:T"}.
\item If @{text "\<Gamma>,X<:Q,\<Delta> \<turnstile> M<:N"} and @{term "\<Gamma> \<turnstile> P<:Q"} then @{text "\<Gamma>,X<:P,\<Delta> \<turnstile> M<:N"}.
\end{enumerate}
\end{lemma}
The two parts are proved simultaneously, by induction on the size
of @{term "Q"}. The argument for part (2) assumes that part (1) has
been established already for the @{term "Q"} in question; part (1) uses
part (2) only for strictly smaller @{term "Q"}.
\end{quote}
For the induction on the size of @{term "Q"}, we use the induction-rule
@{text "measure_induct_rule"}:
\begin{center}
@{thm measure_induct_rule[of "size_ty",no_vars]}
\end{center}
That means in order to show a property @{term "P a"} for all @{term "a"},
the induct-rule requires to prove that for all @{term x} @{term "P x"} holds using the
assumption that for all @{term y} whose size is strictly smaller than
that of @{term x} the property @{term "P y"} holds. *}
lemma
shows subtype_transitivity: "\<Gamma>\<turnstile>S<:Q \<Longrightarrow> \<Gamma>\<turnstile>Q<:T \<Longrightarrow> \<Gamma>\<turnstile>S<:T"
and subtype_narrow: "(\<Delta>@[(TVarB X Q)]@\<Gamma>)\<turnstile>M<:N \<Longrightarrow> \<Gamma>\<turnstile>P<:Q \<Longrightarrow> (\<Delta>@[(TVarB X P)]@\<Gamma>)\<turnstile>M<:N"
proof (induct Q arbitrary: \<Gamma> S T \<Delta> X P M N taking: "size_ty" rule: measure_induct_rule)
case (less Q)
have IH_trans:
"\<And>Q' \<Gamma> S T. \<lbrakk>size_ty Q' < size_ty Q; \<Gamma>\<turnstile>S<:Q'; \<Gamma>\<turnstile>Q'<:T\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile>S<:T" by fact
have IH_narrow:
"\<And>Q' \<Delta> \<Gamma> X M N P. \<lbrakk>size_ty Q' < size_ty Q; (\<Delta>@[(TVarB X Q')]@\<Gamma>)\<turnstile>M<:N; \<Gamma>\<turnstile>P<:Q'\<rbrakk>
\<Longrightarrow> (\<Delta>@[(TVarB X P)]@\<Gamma>)\<turnstile>M<:N" by fact
{ fix \<Gamma> S T
have "\<lbrakk>\<Gamma> \<turnstile> S <: Q; \<Gamma> \<turnstile> Q <: T\<rbrakk> \<Longrightarrow> \<Gamma> \<turnstile> S <: T"
proof (induct \<Gamma> S Q\<equiv>Q rule: subtype_of.induct)
case (SA_Top \<Gamma> S)
then have rh_drv: "\<Gamma> \<turnstile> Top <: T" by simp
then have T_inst: "T = Top" by (auto elim: S_TopE)
from `\<turnstile> \<Gamma> ok` and `S closed_in \<Gamma>`
have "\<Gamma> \<turnstile> S <: Top" by auto
then show "\<Gamma> \<turnstile> S <: T" using T_inst by simp
next
case (SA_trans_TVar Y U \<Gamma>)
then have IH_inner: "\<Gamma> \<turnstile> U <: T" by simp
have "(TVarB Y U) \<in> set \<Gamma>" by fact
with IH_inner show "\<Gamma> \<turnstile> Tvar Y <: T" by auto
next
case (SA_refl_TVar \<Gamma> X)
then show "\<Gamma> \<turnstile> Tvar X <: T" by simp
next
case (SA_arrow \<Gamma> Q\<^sub>1 S\<^sub>1 S\<^sub>2 Q\<^sub>2)
then have rh_drv: "\<Gamma> \<turnstile> Q\<^sub>1 \<rightarrow> Q\<^sub>2 <: T" by simp
from `Q\<^sub>1 \<rightarrow> Q\<^sub>2 = Q`
have Q\<^sub>12_less: "size_ty Q\<^sub>1 < size_ty Q" "size_ty Q\<^sub>2 < size_ty Q" by auto
have lh_drv_prm\<^sub>1: "\<Gamma> \<turnstile> Q\<^sub>1 <: S\<^sub>1" by fact
have lh_drv_prm\<^sub>2: "\<Gamma> \<turnstile> S\<^sub>2 <: Q\<^sub>2" by fact
from rh_drv have "T=Top \<or> (\<exists>T\<^sub>1 T\<^sub>2. T=T\<^sub>1\<rightarrow>T\<^sub>2 \<and> \<Gamma>\<turnstile>T\<^sub>1<:Q\<^sub>1 \<and> \<Gamma>\<turnstile>Q\<^sub>2<:T\<^sub>2)"
by (auto elim: S_ArrowE_left)
moreover
have "S\<^sub>1 closed_in \<Gamma>" and "S\<^sub>2 closed_in \<Gamma>"
using lh_drv_prm\<^sub>1 lh_drv_prm\<^sub>2 by (simp_all add: subtype_implies_closed)
hence "(S\<^sub>1 \<rightarrow> S\<^sub>2) closed_in \<Gamma>" by (simp add: closed_in_def ty.supp)
moreover
have "\<turnstile> \<Gamma> ok" using rh_drv by (rule subtype_implies_ok)
moreover
{ assume "\<exists>T\<^sub>1 T\<^sub>2. T = T\<^sub>1\<rightarrow>T\<^sub>2 \<and> \<Gamma> \<turnstile> T\<^sub>1 <: Q\<^sub>1 \<and> \<Gamma> \<turnstile> Q\<^sub>2 <: T\<^sub>2"
then obtain T\<^sub>1 T\<^sub>2
where T_inst: "T = T\<^sub>1 \<rightarrow> T\<^sub>2"
and rh_drv_prm\<^sub>1: "\<Gamma> \<turnstile> T\<^sub>1 <: Q\<^sub>1"
and rh_drv_prm\<^sub>2: "\<Gamma> \<turnstile> Q\<^sub>2 <: T\<^sub>2" by force
from IH_trans[of "Q\<^sub>1"]
have "\<Gamma> \<turnstile> T\<^sub>1 <: S\<^sub>1" using Q\<^sub>12_less rh_drv_prm\<^sub>1 lh_drv_prm\<^sub>1 by simp
moreover
from IH_trans[of "Q\<^sub>2"]
have "\<Gamma> \<turnstile> S\<^sub>2 <: T\<^sub>2" using Q\<^sub>12_less rh_drv_prm\<^sub>2 lh_drv_prm\<^sub>2 by simp
ultimately have "\<Gamma> \<turnstile> S\<^sub>1 \<rightarrow> S\<^sub>2 <: T\<^sub>1 \<rightarrow> T\<^sub>2" by auto
then have "\<Gamma> \<turnstile> S\<^sub>1 \<rightarrow> S\<^sub>2 <: T" using T_inst by simp
}
ultimately show "\<Gamma> \<turnstile> S\<^sub>1 \<rightarrow> S\<^sub>2 <: T" by blast
next
case (SA_all \<Gamma> Q\<^sub>1 S\<^sub>1 X S\<^sub>2 Q\<^sub>2)
then have rh_drv: "\<Gamma> \<turnstile> (\<forall>X<:Q\<^sub>1. Q\<^sub>2) <: T" by simp
have lh_drv_prm\<^sub>1: "\<Gamma> \<turnstile> Q\<^sub>1 <: S\<^sub>1" by fact
have lh_drv_prm\<^sub>2: "((TVarB X Q\<^sub>1)#\<Gamma>) \<turnstile> S\<^sub>2 <: Q\<^sub>2" by fact
then have "X\<sharp>\<Gamma>" by (force dest: subtype_implies_ok simp add: valid_ty_dom_fresh)
then have fresh_cond: "X\<sharp>\<Gamma>" "X\<sharp>Q\<^sub>1" "X\<sharp>T" using rh_drv lh_drv_prm\<^sub>1
by (simp_all add: subtype_implies_fresh)
from rh_drv
have "T = Top \<or>
(\<exists>T\<^sub>1 T\<^sub>2. T = (\<forall>X<:T\<^sub>1. T\<^sub>2) \<and> \<Gamma> \<turnstile> T\<^sub>1 <: Q\<^sub>1 \<and> ((TVarB X T\<^sub>1)#\<Gamma>) \<turnstile> Q\<^sub>2 <: T\<^sub>2)"
using fresh_cond by (simp add: S_ForallE_left)
moreover
have "S\<^sub>1 closed_in \<Gamma>" and "S\<^sub>2 closed_in ((TVarB X Q\<^sub>1)#\<Gamma>)"
using lh_drv_prm\<^sub>1 lh_drv_prm\<^sub>2 by (simp_all add: subtype_implies_closed)
then have "(\<forall>X<:S\<^sub>1. S\<^sub>2) closed_in \<Gamma>" by (force simp add: closed_in_def ty.supp abs_supp)
moreover
have "\<turnstile> \<Gamma> ok" using rh_drv by (rule subtype_implies_ok)
moreover
{ assume "\<exists>T\<^sub>1 T\<^sub>2. T=(\<forall>X<:T\<^sub>1. T\<^sub>2) \<and> \<Gamma>\<turnstile>T\<^sub>1<:Q\<^sub>1 \<and> ((TVarB X T\<^sub>1)#\<Gamma>)\<turnstile>Q\<^sub>2<:T\<^sub>2"
then obtain T\<^sub>1 T\<^sub>2
where T_inst: "T = (\<forall>X<:T\<^sub>1. T\<^sub>2)"
and rh_drv_prm\<^sub>1: "\<Gamma> \<turnstile> T\<^sub>1 <: Q\<^sub>1"
and rh_drv_prm\<^sub>2:"((TVarB X T\<^sub>1)#\<Gamma>) \<turnstile> Q\<^sub>2 <: T\<^sub>2" by force
have "(\<forall>X<:Q\<^sub>1. Q\<^sub>2) = Q" by fact
then have Q\<^sub>12_less: "size_ty Q\<^sub>1 < size_ty Q" "size_ty Q\<^sub>2 < size_ty Q"
using fresh_cond by auto
from IH_trans[of "Q\<^sub>1"]
have "\<Gamma> \<turnstile> T\<^sub>1 <: S\<^sub>1" using lh_drv_prm\<^sub>1 rh_drv_prm\<^sub>1 Q\<^sub>12_less by blast
moreover
from IH_narrow[of "Q\<^sub>1" "[]"]
have "((TVarB X T\<^sub>1)#\<Gamma>) \<turnstile> S\<^sub>2 <: Q\<^sub>2" using Q\<^sub>12_less lh_drv_prm\<^sub>2 rh_drv_prm\<^sub>1 by simp
with IH_trans[of "Q\<^sub>2"]
have "((TVarB X T\<^sub>1)#\<Gamma>) \<turnstile> S\<^sub>2 <: T\<^sub>2" using Q\<^sub>12_less rh_drv_prm\<^sub>2 by simp
ultimately have "\<Gamma> \<turnstile> (\<forall>X<:S\<^sub>1. S\<^sub>2) <: (\<forall>X<:T\<^sub>1. T\<^sub>2)"
using fresh_cond by (simp add: subtype_of.SA_all)
hence "\<Gamma> \<turnstile> (\<forall>X<:S\<^sub>1. S\<^sub>2) <: T" using T_inst by simp
}
ultimately show "\<Gamma> \<turnstile> (\<forall>X<:S\<^sub>1. S\<^sub>2) <: T" by blast
qed
} note transitivity_lemma = this
{ --{* The transitivity proof is now by the auxiliary lemma. *}
case 1
from `\<Gamma> \<turnstile> S <: Q` and `\<Gamma> \<turnstile> Q <: T`
show "\<Gamma> \<turnstile> S <: T" by (rule transitivity_lemma)
next
case 2
from `(\<Delta>@[(TVarB X Q)]@\<Gamma>) \<turnstile> M <: N`
and `\<Gamma> \<turnstile> P<:Q`
show "(\<Delta>@[(TVarB X P)]@\<Gamma>) \<turnstile> M <: N"
proof (induct "\<Delta>@[(TVarB X Q)]@\<Gamma>" M N arbitrary: \<Gamma> X \<Delta> rule: subtype_of.induct)
case (SA_Top S \<Gamma> X \<Delta>)
from `\<Gamma> \<turnstile> P <: Q`
have "P closed_in \<Gamma>" by (simp add: subtype_implies_closed)
with `\<turnstile> (\<Delta>@[(TVarB X Q)]@\<Gamma>) ok` have "\<turnstile> (\<Delta>@[(TVarB X P)]@\<Gamma>) ok"
by (simp add: replace_type)
moreover
from `S closed_in (\<Delta>@[(TVarB X Q)]@\<Gamma>)` have "S closed_in (\<Delta>@[(TVarB X P)]@\<Gamma>)"
by (simp add: closed_in_def doms_append)
ultimately show "(\<Delta>@[(TVarB X P)]@\<Gamma>) \<turnstile> S <: Top" by (simp add: subtype_of.SA_Top)
next
case (SA_trans_TVar Y S N \<Gamma> X \<Delta>)
then have IH_inner: "(\<Delta>@[(TVarB X P)]@\<Gamma>) \<turnstile> S <: N"
and lh_drv_prm: "(TVarB Y S) \<in> set (\<Delta>@[(TVarB X Q)]@\<Gamma>)"
and rh_drv: "\<Gamma> \<turnstile> P<:Q"
and ok\<^sub>Q: "\<turnstile> (\<Delta>@[(TVarB X Q)]@\<Gamma>) ok" by (simp_all add: subtype_implies_ok)
then have ok\<^sub>P: "\<turnstile> (\<Delta>@[(TVarB X P)]@\<Gamma>) ok" by (simp add: subtype_implies_ok)
show "(\<Delta>@[(TVarB X P)]@\<Gamma>) \<turnstile> Tvar Y <: N"
proof (cases "X=Y")
case False
have "X\<noteq>Y" by fact
hence "(TVarB Y S)\<in>set (\<Delta>@[(TVarB X P)]@\<Gamma>)" using lh_drv_prm by (simp add:binding.inject)
with IH_inner show "(\<Delta>@[(TVarB X P)]@\<Gamma>) \<turnstile> Tvar Y <: N" by (simp add: subtype_of.SA_trans_TVar)
next
case True
have memb\<^sub>XQ: "(TVarB X Q)\<in>set (\<Delta>@[(TVarB X Q)]@\<Gamma>)" by simp
have memb\<^sub>XP: "(TVarB X P)\<in>set (\<Delta>@[(TVarB X P)]@\<Gamma>)" by simp
have eq: "X=Y" by fact
hence "S=Q" using ok\<^sub>Q lh_drv_prm memb\<^sub>XQ by (simp only: uniqueness_of_ctxt)
hence "(\<Delta>@[(TVarB X P)]@\<Gamma>) \<turnstile> Q <: N" using IH_inner by simp
moreover
have "(\<Delta>@[(TVarB X P)]@\<Gamma>) extends \<Gamma>" by (simp add: extends_def)
hence "(\<Delta>@[(TVarB X P)]@\<Gamma>) \<turnstile> P <: Q" using rh_drv ok\<^sub>P by (simp only: weakening)
ultimately have "(\<Delta>@[(TVarB X P)]@\<Gamma>) \<turnstile> P <: N" by (simp add: transitivity_lemma)
then show "(\<Delta>@[(TVarB X P)]@\<Gamma>) \<turnstile> Tvar Y <: N" using memb\<^sub>XP eq by auto
qed
next
case (SA_refl_TVar Y \<Gamma> X \<Delta>)
from `\<Gamma> \<turnstile> P <: Q`
have "P closed_in \<Gamma>" by (simp add: subtype_implies_closed)
with `\<turnstile> (\<Delta>@[(TVarB X Q)]@\<Gamma>) ok` have "\<turnstile> (\<Delta>@[(TVarB X P)]@\<Gamma>) ok"
by (simp add: replace_type)
moreover
from `Y \<in> ty_dom (\<Delta>@[(TVarB X Q)]@\<Gamma>)` have "Y \<in> ty_dom (\<Delta>@[(TVarB X P)]@\<Gamma>)"
by (simp add: doms_append)
ultimately show "(\<Delta>@[(TVarB X P)]@\<Gamma>) \<turnstile> Tvar Y <: Tvar Y" by (simp add: subtype_of.SA_refl_TVar)
next
case (SA_arrow S\<^sub>1 Q\<^sub>1 Q\<^sub>2 S\<^sub>2 \<Gamma> X \<Delta>)
then show "(\<Delta>@[(TVarB X P)]@\<Gamma>) \<turnstile> Q\<^sub>1 \<rightarrow> Q\<^sub>2 <: S\<^sub>1 \<rightarrow> S\<^sub>2" by blast
next
case (SA_all T\<^sub>1 S\<^sub>1 Y S\<^sub>2 T\<^sub>2 \<Gamma> X \<Delta>)
have IH_inner\<^sub>1: "(\<Delta>@[(TVarB X P)]@\<Gamma>) \<turnstile> T\<^sub>1 <: S\<^sub>1"
and IH_inner\<^sub>2: "(((TVarB Y T\<^sub>1)#\<Delta>)@[(TVarB X P)]@\<Gamma>) \<turnstile> S\<^sub>2 <: T\<^sub>2"
by (fastforce intro: SA_all)+
then show "(\<Delta>@[(TVarB X P)]@\<Gamma>) \<turnstile> (\<forall>Y<:S\<^sub>1. S\<^sub>2) <: (\<forall>Y<:T\<^sub>1. T\<^sub>2)" by auto
qed
}
qed
section {* Typing *}
inductive
typing :: "env \<Rightarrow> trm \<Rightarrow> ty \<Rightarrow> bool" ("_ \<turnstile> _ : _" [60,60,60] 60)
where
T_Var[intro]: "\<lbrakk> VarB x T \<in> set \<Gamma>; \<turnstile> \<Gamma> ok \<rbrakk> \<Longrightarrow> \<Gamma> \<turnstile> Var x : T"
| T_App[intro]: "\<lbrakk> \<Gamma> \<turnstile> t\<^sub>1 : T\<^sub>1 \<rightarrow> T\<^sub>2; \<Gamma> \<turnstile> t\<^sub>2 : T\<^sub>1 \<rbrakk> \<Longrightarrow> \<Gamma> \<turnstile> t\<^sub>1 \<cdot> t\<^sub>2 : T\<^sub>2"
| T_Abs[intro]: "\<lbrakk> VarB x T\<^sub>1 # \<Gamma> \<turnstile> t\<^sub>2 : T\<^sub>2 \<rbrakk> \<Longrightarrow> \<Gamma> \<turnstile> (\<lambda>x:T\<^sub>1. t\<^sub>2) : T\<^sub>1 \<rightarrow> T\<^sub>2"
| T_Sub[intro]: "\<lbrakk> \<Gamma> \<turnstile> t : S; \<Gamma> \<turnstile> S <: T \<rbrakk> \<Longrightarrow> \<Gamma> \<turnstile> t : T"
| T_TAbs[intro]:"\<lbrakk> TVarB X T\<^sub>1 # \<Gamma> \<turnstile> t\<^sub>2 : T\<^sub>2 \<rbrakk> \<Longrightarrow> \<Gamma> \<turnstile> (\<lambda>X<:T\<^sub>1. t\<^sub>2) : (\<forall>X<:T\<^sub>1. T\<^sub>2)"
| T_TApp[intro]:"\<lbrakk>X\<sharp>(\<Gamma>,t\<^sub>1,T\<^sub>2); \<Gamma> \<turnstile> t\<^sub>1 : (\<forall>X<:T\<^sub>11. T\<^sub>12); \<Gamma> \<turnstile> T\<^sub>2 <: T\<^sub>11\<rbrakk> \<Longrightarrow> \<Gamma> \<turnstile> t\<^sub>1 \<cdot>\<^sub>\<tau> T\<^sub>2 : (T\<^sub>12[X \<mapsto> T\<^sub>2]\<^sub>\<tau>)"
equivariance typing
lemma better_T_TApp:
assumes H1: "\<Gamma> \<turnstile> t\<^sub>1 : (\<forall>X<:T11. T12)"
and H2: "\<Gamma> \<turnstile> T2 <: T11"
shows "\<Gamma> \<turnstile> t\<^sub>1 \<cdot>\<^sub>\<tau> T2 : (T12[X \<mapsto> T2]\<^sub>\<tau>)"
proof -
obtain Y::tyvrs where Y: "Y \<sharp> (X, T12, \<Gamma>, t\<^sub>1, T2)"
by (rule exists_fresh) (rule fin_supp)
then have "Y \<sharp> (\<Gamma>, t\<^sub>1, T2)" by simp
moreover from Y have "(\<forall>X<:T11. T12) = (\<forall>Y<:T11. [(Y, X)] \<bullet> T12)"
by (auto simp add: ty.inject alpha' fresh_prod fresh_atm)
with H1 have "\<Gamma> \<turnstile> t\<^sub>1 : (\<forall>Y<:T11. [(Y, X)] \<bullet> T12)" by simp
ultimately have "\<Gamma> \<turnstile> t\<^sub>1 \<cdot>\<^sub>\<tau> T2 : (([(Y, X)] \<bullet> T12)[Y \<mapsto> T2]\<^sub>\<tau>)" using H2
by (rule T_TApp)
with Y show ?thesis by (simp add: type_subst_rename)
qed
lemma typing_ok:
assumes "\<Gamma> \<turnstile> t : T"
shows "\<turnstile> \<Gamma> ok"
using assms by (induct) (auto)
nominal_inductive typing
by (auto dest!: typing_ok intro: closed_in_fresh fresh_dom type_subst_fresh
simp: abs_fresh fresh_type_subst_fresh ty_vrs_fresh valid_ty_dom_fresh fresh_trm_dom)
lemma ok_imp_VarB_closed_in:
assumes ok: "\<turnstile> \<Gamma> ok"
shows "VarB x T \<in> set \<Gamma> \<Longrightarrow> T closed_in \<Gamma>" using ok
by induct (auto simp add: binding.inject closed_in_def)
lemma tyvrs_of_subst: "tyvrs_of (B[X \<mapsto> T]\<^sub>b) = tyvrs_of B"
by (nominal_induct B rule: binding.strong_induct) simp_all
lemma ty_dom_subst: "ty_dom (\<Gamma>[X \<mapsto> T]\<^sub>e) = ty_dom \<Gamma>"
by (induct \<Gamma>) (simp_all add: tyvrs_of_subst)
lemma vrs_of_subst: "vrs_of (B[X \<mapsto> T]\<^sub>b) = vrs_of B"
by (nominal_induct B rule: binding.strong_induct) simp_all
lemma trm_dom_subst: "trm_dom (\<Gamma>[X \<mapsto> T]\<^sub>e) = trm_dom \<Gamma>"
by (induct \<Gamma>) (simp_all add: vrs_of_subst)
lemma subst_closed_in:
"T closed_in (\<Delta> @ TVarB X S # \<Gamma>) \<Longrightarrow> U closed_in \<Gamma> \<Longrightarrow> T[X \<mapsto> U]\<^sub>\<tau> closed_in (\<Delta>[X \<mapsto> U]\<^sub>e @ \<Gamma>)"
apply (nominal_induct T avoiding: X U \<Gamma> rule: ty.strong_induct)
apply (simp add: closed_in_def ty.supp supp_atm doms_append ty_dom_subst)
apply blast
apply (simp add: closed_in_def ty.supp)
apply (simp add: closed_in_def ty.supp)
apply (simp add: closed_in_def ty.supp abs_supp)
apply (drule_tac x = X in meta_spec)
apply (drule_tac x = U in meta_spec)
apply (drule_tac x = "(TVarB tyvrs ty2) # \<Gamma>" in meta_spec)
apply (simp add: doms_append ty_dom_subst)
apply blast
done
lemmas subst_closed_in' = subst_closed_in [where \<Delta>="[]", simplified]
lemma typing_closed_in:
assumes "\<Gamma> \<turnstile> t : T"
shows "T closed_in \<Gamma>"
using assms
proof induct
case (T_Var x T \<Gamma>)
from `\<turnstile> \<Gamma> ok` and `VarB x T \<in> set \<Gamma>`
show ?case by (rule ok_imp_VarB_closed_in)
next
case (T_App \<Gamma> t\<^sub>1 T\<^sub>1 T\<^sub>2 t\<^sub>2)
then show ?case by (auto simp add: ty.supp closed_in_def)
next
case (T_Abs x T\<^sub>1 \<Gamma> t\<^sub>2 T\<^sub>2)
from `VarB x T\<^sub>1 # \<Gamma> \<turnstile> t\<^sub>2 : T\<^sub>2`
have "T\<^sub>1 closed_in \<Gamma>" by (auto dest: typing_ok)
with T_Abs show ?case by (auto simp add: ty.supp closed_in_def)
next
case (T_Sub \<Gamma> t S T)
from `\<Gamma> \<turnstile> S <: T` show ?case by (simp add: subtype_implies_closed)
next
case (T_TAbs X T\<^sub>1 \<Gamma> t\<^sub>2 T\<^sub>2)
from `TVarB X T\<^sub>1 # \<Gamma> \<turnstile> t\<^sub>2 : T\<^sub>2`
have "T\<^sub>1 closed_in \<Gamma>" by (auto dest: typing_ok)
with T_TAbs show ?case by (auto simp add: ty.supp closed_in_def abs_supp)
next
case (T_TApp X \<Gamma> t\<^sub>1 T2 T11 T12)
then have "T12 closed_in (TVarB X T11 # \<Gamma>)"
by (auto simp add: closed_in_def ty.supp abs_supp)
moreover from T_TApp have "T2 closed_in \<Gamma>"
by (simp add: subtype_implies_closed)
ultimately show ?case by (rule subst_closed_in')
qed
subsection {* Evaluation *}
inductive
val :: "trm \<Rightarrow> bool"
where
Abs[intro]: "val (\<lambda>x:T. t)"
| TAbs[intro]: "val (\<lambda>X<:T. t)"
equivariance val
inductive_cases val_inv_auto[elim]:
"val (Var x)"
"val (t1 \<cdot> t2)"
"val (t1 \<cdot>\<^sub>\<tau> t2)"
inductive
eval :: "trm \<Rightarrow> trm \<Rightarrow> bool" ("_ \<longmapsto> _" [60,60] 60)
where
E_Abs : "\<lbrakk> x \<sharp> v\<^sub>2; val v\<^sub>2 \<rbrakk> \<Longrightarrow> (\<lambda>x:T\<^sub>11. t\<^sub>12) \<cdot> v\<^sub>2 \<longmapsto> t\<^sub>12[x \<mapsto> v\<^sub>2]"
| E_App1 [intro]: "t \<longmapsto> t' \<Longrightarrow> t \<cdot> u \<longmapsto> t' \<cdot> u"
| E_App2 [intro]: "\<lbrakk> val v; t \<longmapsto> t' \<rbrakk> \<Longrightarrow> v \<cdot> t \<longmapsto> v \<cdot> t'"
| E_TAbs : "X \<sharp> (T\<^sub>11, T\<^sub>2) \<Longrightarrow> (\<lambda>X<:T\<^sub>11. t\<^sub>12) \<cdot>\<^sub>\<tau> T\<^sub>2 \<longmapsto> t\<^sub>12[X \<mapsto>\<^sub>\<tau> T\<^sub>2]"
| E_TApp [intro]: "t \<longmapsto> t' \<Longrightarrow> t \<cdot>\<^sub>\<tau> T \<longmapsto> t' \<cdot>\<^sub>\<tau> T"
lemma better_E_Abs[intro]:
assumes H: "val v2"
shows "(\<lambda>x:T11. t12) \<cdot> v2 \<longmapsto> t12[x \<mapsto> v2]"
proof -
obtain y::vrs where y: "y \<sharp> (x, t12, v2)" by (rule exists_fresh) (rule fin_supp)
then have "y \<sharp> v2" by simp
then have "(\<lambda>y:T11. [(y, x)] \<bullet> t12) \<cdot> v2 \<longmapsto> ([(y, x)] \<bullet> t12)[y \<mapsto> v2]" using H
by (rule E_Abs)
moreover from y have "(\<lambda>x:T11. t12) \<cdot> v2 = (\<lambda>y:T11. [(y, x)] \<bullet> t12) \<cdot> v2"
by (auto simp add: trm.inject alpha' fresh_prod fresh_atm)
ultimately have "(\<lambda>x:T11. t12) \<cdot> v2 \<longmapsto> ([(y, x)] \<bullet> t12)[y \<mapsto> v2]"
by simp
with y show ?thesis by (simp add: subst_trm_rename)
qed
lemma better_E_TAbs[intro]: "(\<lambda>X<:T11. t12) \<cdot>\<^sub>\<tau> T2 \<longmapsto> t12[X \<mapsto>\<^sub>\<tau> T2]"
proof -
obtain Y::tyvrs where Y: "Y \<sharp> (X, t12, T11, T2)" by (rule exists_fresh) (rule fin_supp)
then have "Y \<sharp> (T11, T2)" by simp
then have "(\<lambda>Y<:T11. [(Y, X)] \<bullet> t12) \<cdot>\<^sub>\<tau> T2 \<longmapsto> ([(Y, X)] \<bullet> t12)[Y \<mapsto>\<^sub>\<tau> T2]"
by (rule E_TAbs)
moreover from Y have "(\<lambda>X<:T11. t12) \<cdot>\<^sub>\<tau> T2 = (\<lambda>Y<:T11. [(Y, X)] \<bullet> t12) \<cdot>\<^sub>\<tau> T2"
by (auto simp add: trm.inject alpha' fresh_prod fresh_atm)
ultimately have "(\<lambda>X<:T11. t12) \<cdot>\<^sub>\<tau> T2 \<longmapsto> ([(Y, X)] \<bullet> t12)[Y \<mapsto>\<^sub>\<tau> T2]"
by simp
with Y show ?thesis by (simp add: subst_trm_ty_rename)
qed
equivariance eval
nominal_inductive eval
by (simp_all add: abs_fresh ty_vrs_fresh subst_trm_fresh_tyvar
subst_trm_fresh_var subst_trm_ty_fresh')
inductive_cases eval_inv_auto[elim]:
"Var x \<longmapsto> t'"
"(\<lambda>x:T. t) \<longmapsto> t'"
"(\<lambda>X<:T. t) \<longmapsto> t'"
lemma ty_dom_cons:
shows "ty_dom (\<Gamma>@[VarB X Q]@\<Delta>) = ty_dom (\<Gamma>@\<Delta>)"
by (induct \<Gamma>) (auto)
lemma closed_in_cons:
assumes "S closed_in (\<Gamma> @ VarB X Q # \<Delta>)"
shows "S closed_in (\<Gamma>@\<Delta>)"
using assms ty_dom_cons closed_in_def by auto
lemma closed_in_weaken: "T closed_in (\<Delta> @ \<Gamma>) \<Longrightarrow> T closed_in (\<Delta> @ B # \<Gamma>)"
by (auto simp add: closed_in_def doms_append)
lemma closed_in_weaken': "T closed_in \<Gamma> \<Longrightarrow> T closed_in (\<Delta> @ \<Gamma>)"
by (auto simp add: closed_in_def doms_append)
lemma valid_subst:
assumes ok: "\<turnstile> (\<Delta> @ TVarB X Q # \<Gamma>) ok"
and closed: "P closed_in \<Gamma>"
shows "\<turnstile> (\<Delta>[X \<mapsto> P]\<^sub>e @ \<Gamma>) ok" using ok closed
apply (induct \<Delta>)
apply simp_all
apply (erule validE)
apply assumption
apply (erule validE)
apply simp
apply (rule valid_consT)
apply assumption
apply (simp add: doms_append ty_dom_subst)
apply (simp add: fresh_fin_insert [OF pt_tyvrs_inst at_tyvrs_inst fs_tyvrs_inst] finite_doms)
apply (rule_tac S=Q in subst_closed_in')
apply (simp add: closed_in_def doms_append ty_dom_subst)
apply (simp add: closed_in_def doms_append)
apply blast
apply simp
apply (rule valid_cons)
apply assumption
apply (simp add: doms_append trm_dom_subst)
apply (rule_tac S=Q in subst_closed_in')
apply (simp add: closed_in_def doms_append ty_dom_subst)
apply (simp add: closed_in_def doms_append)
apply blast
done
lemma ty_dom_vrs:
shows "ty_dom (G @ [VarB x Q] @ D) = ty_dom (G @ D)"
by (induct G) (auto)
lemma valid_cons':
assumes "\<turnstile> (\<Gamma> @ VarB x Q # \<Delta>) ok"
shows "\<turnstile> (\<Gamma> @ \<Delta>) ok"
using assms
proof (induct "\<Gamma> @ VarB x Q # \<Delta>" arbitrary: \<Gamma> \<Delta>)
case valid_nil
have "[] = \<Gamma> @ VarB x Q # \<Delta>" by fact
then have "False" by auto
then show ?case by auto
next
case (valid_consT G X T)
then show ?case
proof (cases \<Gamma>)
case Nil
with valid_consT show ?thesis by simp
next
case (Cons b bs)
with valid_consT
have "\<turnstile> (bs @ \<Delta>) ok" by simp
moreover from Cons and valid_consT have "X \<sharp> ty_dom (bs @ \<Delta>)"
by (simp add: doms_append)
moreover from Cons and valid_consT have "T closed_in (bs @ \<Delta>)"
by (simp add: closed_in_def doms_append)
ultimately have "\<turnstile> (TVarB X T # bs @ \<Delta>) ok"
by (rule valid_rel.valid_consT)
with Cons and valid_consT show ?thesis by simp
qed
next
case (valid_cons G x T)
then show ?case
proof (cases \<Gamma>)
case Nil
with valid_cons show ?thesis by simp
next
case (Cons b bs)
with valid_cons
have "\<turnstile> (bs @ \<Delta>) ok" by simp
moreover from Cons and valid_cons have "x \<sharp> trm_dom (bs @ \<Delta>)"
by (simp add: doms_append finite_doms
fresh_fin_insert [OF pt_vrs_inst at_vrs_inst fs_vrs_inst])
moreover from Cons and valid_cons have "T closed_in (bs @ \<Delta>)"
by (simp add: closed_in_def doms_append)
ultimately have "\<turnstile> (VarB x T # bs @ \<Delta>) ok"
by (rule valid_rel.valid_cons)
with Cons and valid_cons show ?thesis by simp
qed
qed
text {* A.5(6) *}
lemma type_weaken:
assumes "(\<Delta>@\<Gamma>) \<turnstile> t : T"
and "\<turnstile> (\<Delta> @ B # \<Gamma>) ok"
shows "(\<Delta> @ B # \<Gamma>) \<turnstile> t : T"
using assms
proof(nominal_induct "\<Delta> @ \<Gamma>" t T avoiding: \<Delta> \<Gamma> B rule: typing.strong_induct)
case (T_Var x T)
then show ?case by auto
next
case (T_App X t\<^sub>1 T\<^sub>2 T\<^sub>11 T\<^sub>12)
then show ?case by force
next
case (T_Abs y T\<^sub>1 t\<^sub>2 T\<^sub>2 \<Delta> \<Gamma>)
then have "VarB y T\<^sub>1 # \<Delta> @ \<Gamma> \<turnstile> t\<^sub>2 : T\<^sub>2" by simp
then have closed: "T\<^sub>1 closed_in (\<Delta> @ \<Gamma>)"
by (auto dest: typing_ok)
have "\<turnstile> (VarB y T\<^sub>1 # \<Delta> @ B # \<Gamma>) ok"
apply (rule valid_cons)
apply (rule T_Abs)
apply (simp add: doms_append
fresh_fin_insert [OF pt_vrs_inst at_vrs_inst fs_vrs_inst]
fresh_fin_union [OF pt_vrs_inst at_vrs_inst fs_vrs_inst]
finite_doms finite_vrs fresh_vrs_of T_Abs fresh_trm_dom)
apply (rule closed_in_weaken)
apply (rule closed)
done
then have "\<turnstile> ((VarB y T\<^sub>1 # \<Delta>) @ B # \<Gamma>) ok" by simp
with _ have "(VarB y T\<^sub>1 # \<Delta>) @ B # \<Gamma> \<turnstile> t\<^sub>2 : T\<^sub>2"
by (rule T_Abs) simp
then have "VarB y T\<^sub>1 # \<Delta> @ B # \<Gamma> \<turnstile> t\<^sub>2 : T\<^sub>2" by simp
then show ?case by (rule typing.T_Abs)
next
case (T_Sub t S T \<Delta> \<Gamma>)
from refl and `\<turnstile> (\<Delta> @ B # \<Gamma>) ok`
have "\<Delta> @ B # \<Gamma> \<turnstile> t : S" by (rule T_Sub)
moreover from `(\<Delta> @ \<Gamma>)\<turnstile>S<:T` and `\<turnstile> (\<Delta> @ B # \<Gamma>) ok`
have "(\<Delta> @ B # \<Gamma>)\<turnstile>S<:T"
by (rule weakening) (simp add: extends_def T_Sub)
ultimately show ?case by (rule typing.T_Sub)
next
case (T_TAbs X T\<^sub>1 t\<^sub>2 T\<^sub>2 \<Delta> \<Gamma>)
from `TVarB X T\<^sub>1 # \<Delta> @ \<Gamma> \<turnstile> t\<^sub>2 : T\<^sub>2`
have closed: "T\<^sub>1 closed_in (\<Delta> @ \<Gamma>)"
by (auto dest: typing_ok)
have "\<turnstile> (TVarB X T\<^sub>1 # \<Delta> @ B # \<Gamma>) ok"
apply (rule valid_consT)
apply (rule T_TAbs)
apply (simp add: doms_append
fresh_fin_insert [OF pt_tyvrs_inst at_tyvrs_inst fs_tyvrs_inst]
fresh_fin_union [OF pt_tyvrs_inst at_tyvrs_inst fs_tyvrs_inst]
finite_doms finite_vrs tyvrs_fresh T_TAbs fresh_dom)
apply (rule closed_in_weaken)
apply (rule closed)
done
then have "\<turnstile> ((TVarB X T\<^sub>1 # \<Delta>) @ B # \<Gamma>) ok" by simp
with _ have "(TVarB X T\<^sub>1 # \<Delta>) @ B # \<Gamma> \<turnstile> t\<^sub>2 : T\<^sub>2"
by (rule T_TAbs) simp
then have "TVarB X T\<^sub>1 # \<Delta> @ B # \<Gamma> \<turnstile> t\<^sub>2 : T\<^sub>2" by simp
then show ?case by (rule typing.T_TAbs)
next
case (T_TApp X t\<^sub>1 T2 T11 T12 \<Delta> \<Gamma>)
have "\<Delta> @ B # \<Gamma> \<turnstile> t\<^sub>1 : (\<forall>X<:T11. T12)"
by (rule T_TApp refl)+
moreover from `(\<Delta> @ \<Gamma>)\<turnstile>T2<:T11` and `\<turnstile> (\<Delta> @ B # \<Gamma>) ok`
have "(\<Delta> @ B # \<Gamma>)\<turnstile>T2<:T11"
by (rule weakening) (simp add: extends_def T_TApp)
ultimately show ?case by (rule better_T_TApp)
qed
lemma type_weaken':
"\<Gamma> \<turnstile> t : T \<Longrightarrow> \<turnstile> (\<Delta>@\<Gamma>) ok \<Longrightarrow> (\<Delta>@\<Gamma>) \<turnstile> t : T"
apply (induct \<Delta>)
apply simp_all
apply (erule validE)
apply (insert type_weaken [of "[]", simplified])
apply simp_all
done
text {* A.6 *}
lemma strengthening:
assumes "(\<Gamma> @ VarB x Q # \<Delta>) \<turnstile> S <: T"
shows "(\<Gamma>@\<Delta>) \<turnstile> S <: T"
using assms
proof (induct "\<Gamma> @ VarB x Q # \<Delta>" S T arbitrary: \<Gamma>)
case (SA_Top S)
then have "\<turnstile> (\<Gamma> @ \<Delta>) ok" by (auto dest: valid_cons')
moreover have "S closed_in (\<Gamma> @ \<Delta>)" using SA_Top by (auto dest: closed_in_cons)
ultimately show ?case using subtype_of.SA_Top by auto
next
case (SA_refl_TVar X)
from `\<turnstile> (\<Gamma> @ VarB x Q # \<Delta>) ok`
have h1:"\<turnstile> (\<Gamma> @ \<Delta>) ok" by (auto dest: valid_cons')
have "X \<in> ty_dom (\<Gamma> @ VarB x Q # \<Delta>)" using SA_refl_TVar by auto
then have h2:"X \<in> ty_dom (\<Gamma> @ \<Delta>)" using ty_dom_vrs by auto
show ?case using h1 h2 by auto
next
case (SA_all T1 S1 X S2 T2)
have h1:"((TVarB X T1 # \<Gamma>) @ \<Delta>)\<turnstile>S2<:T2" by (fastforce intro: SA_all)
have h2:"(\<Gamma> @ \<Delta>)\<turnstile>T1<:S1" using SA_all by auto
then show ?case using h1 h2 by auto
qed (auto)
lemma narrow_type: -- {* A.7 *}
assumes H: "\<Delta> @ (TVarB X Q) # \<Gamma> \<turnstile> t : T"
shows "\<Gamma> \<turnstile> P <: Q \<Longrightarrow> \<Delta> @ (TVarB X P) # \<Gamma> \<turnstile> t : T"
using H
proof (nominal_induct "\<Delta> @ (TVarB X Q) # \<Gamma>" t T avoiding: P arbitrary: \<Delta> rule: typing.strong_induct)
case (T_Var x T P D)
then have "VarB x T \<in> set (D @ TVarB X P # \<Gamma>)"
and "\<turnstile> (D @ TVarB X P # \<Gamma>) ok"
by (auto intro: replace_type dest!: subtype_implies_closed)
then show ?case by auto
next
case (T_App t1 T1 T2 t2 P D)
then show ?case by force
next
case (T_Abs x T1 t2 T2 P D)
then show ?case by (fastforce dest: typing_ok)
next
case (T_Sub t S T P D)
then show ?case using subtype_narrow by fastforce
next
case (T_TAbs X' T1 t2 T2 P D)
then show ?case by (fastforce dest: typing_ok)
next
case (T_TApp X' t1 T2 T11 T12 P D)
then have "D @ TVarB X P # \<Gamma> \<turnstile> t1 : Forall X' T12 T11" by fastforce
moreover have "(D @ [TVarB X Q] @ \<Gamma>) \<turnstile> T2<:T11" using T_TApp by auto
then have "(D @ [TVarB X P] @ \<Gamma>) \<turnstile> T2<:T11" using `\<Gamma>\<turnstile>P<:Q`
by (rule subtype_narrow)
moreover from T_TApp have "X' \<sharp> (D @ TVarB X P # \<Gamma>, t1, T2)"
by (simp add: fresh_list_append fresh_list_cons fresh_prod)
ultimately show ?case by auto
qed
subsection {* Substitution lemmas *}
subsubsection {* Substition Preserves Typing *}
theorem subst_type: -- {* A.8 *}
assumes H: "(\<Delta> @ (VarB x U) # \<Gamma>) \<turnstile> t : T"
shows "\<Gamma> \<turnstile> u : U \<Longrightarrow> \<Delta> @ \<Gamma> \<turnstile> t[x \<mapsto> u] : T" using H
proof (nominal_induct "\<Delta> @ (VarB x U) # \<Gamma>" t T avoiding: x u arbitrary: \<Delta> rule: typing.strong_induct)
case (T_Var y T x u D)
show ?case
proof (cases "x = y")
assume eq:"x=y"
then have "T=U" using T_Var uniqueness_of_ctxt' by auto
then show ?case using eq T_Var
by (auto intro: type_weaken' dest: valid_cons')
next
assume "x\<noteq>y"
then show ?case using T_Var
by (auto simp add:binding.inject dest: valid_cons')
qed
next
case (T_App t1 T1 T2 t2 x u D)
then show ?case by force
next
case (T_Abs y T1 t2 T2 x u D)
then show ?case by force
next
case (T_Sub t S T x u D)
then have "D @ \<Gamma> \<turnstile> t[x \<mapsto> u] : S" by auto
moreover have "(D @ \<Gamma>) \<turnstile> S<:T" using T_Sub by (auto dest: strengthening)
ultimately show ?case by auto
next
case (T_TAbs X T1 t2 T2 x u D)
from `TVarB X T1 # D @ VarB x U # \<Gamma> \<turnstile> t2 : T2` have "X \<sharp> T1"
by (auto simp add: valid_ty_dom_fresh dest: typing_ok intro!: closed_in_fresh)
with `X \<sharp> u` and T_TAbs show ?case by fastforce
next
case (T_TApp X t1 T2 T11 T12 x u D)
then have "(D@\<Gamma>) \<turnstile>T2<:T11" using T_TApp by (auto dest: strengthening)
then show "((D @ \<Gamma>) \<turnstile> ((t1 \<cdot>\<^sub>\<tau> T2)[x \<mapsto> u]) : (T12[X \<mapsto> T2]\<^sub>\<tau>))" using T_TApp
by (force simp add: fresh_prod fresh_list_append fresh_list_cons subst_trm_fresh_tyvar)
qed
subsubsection {* Type Substitution Preserves Subtyping *}
lemma substT_subtype: -- {* A.10 *}
assumes H: "(\<Delta> @ ((TVarB X Q) # \<Gamma>)) \<turnstile> S <: T"
shows "\<Gamma> \<turnstile> P <: Q \<Longrightarrow> (\<Delta>[X \<mapsto> P]\<^sub>e @ \<Gamma>) \<turnstile> S[X \<mapsto> P]\<^sub>\<tau> <: T[X \<mapsto> P]\<^sub>\<tau>"
using H
proof (nominal_induct "\<Delta> @ TVarB X Q # \<Gamma>" S T avoiding: X P arbitrary: \<Delta> rule: subtype_of.strong_induct)
case (SA_Top S X P D)
then have "\<turnstile> (D @ TVarB X Q # \<Gamma>) ok" by simp
moreover have closed: "P closed_in \<Gamma>" using SA_Top subtype_implies_closed by auto
ultimately have "\<turnstile> (D[X \<mapsto> P]\<^sub>e @ \<Gamma>) ok" by (rule valid_subst)
moreover from SA_Top have "S closed_in (D @ TVarB X Q # \<Gamma>)" by simp
then have "S[X \<mapsto> P]\<^sub>\<tau> closed_in (D[X \<mapsto> P]\<^sub>e @ \<Gamma>)" using closed by (rule subst_closed_in)
ultimately show ?case by auto
next
case (SA_trans_TVar Y S T X P D)
have h:"(D @ TVarB X Q # \<Gamma>)\<turnstile>S<:T" by fact
then have ST: "(D[X \<mapsto> P]\<^sub>e @ \<Gamma>) \<turnstile> S[X \<mapsto> P]\<^sub>\<tau> <: T[X \<mapsto> P]\<^sub>\<tau>" using SA_trans_TVar by auto
from h have G_ok: "\<turnstile> (D @ TVarB X Q # \<Gamma>) ok" by (rule subtype_implies_ok)
from G_ok and SA_trans_TVar have X_\<Gamma>_ok: "\<turnstile> (TVarB X Q # \<Gamma>) ok"
by (auto intro: validE_append)
show "(D[X \<mapsto> P]\<^sub>e @ \<Gamma>) \<turnstile> Tvar Y[X \<mapsto> P]\<^sub>\<tau><:T[X \<mapsto> P]\<^sub>\<tau>"
proof (cases "X = Y")
assume eq: "X = Y"
from eq and SA_trans_TVar have "TVarB Y Q \<in> set (D @ TVarB X Q # \<Gamma>)" by simp
with G_ok have QS: "Q = S" using `TVarB Y S \<in> set (D @ TVarB X Q # \<Gamma>)`
by (rule uniqueness_of_ctxt)
from X_\<Gamma>_ok have "X \<sharp> ty_dom \<Gamma>" and "Q closed_in \<Gamma>" by auto
then have XQ: "X \<sharp> Q" by (rule closed_in_fresh)
note `\<Gamma>\<turnstile>P<:Q`
moreover from ST have "\<turnstile> (D[X \<mapsto> P]\<^sub>e @ \<Gamma>) ok" by (rule subtype_implies_ok)
moreover have "(D[X \<mapsto> P]\<^sub>e @ \<Gamma>) extends \<Gamma>" by (simp add: extends_def)
ultimately have "(D[X \<mapsto> P]\<^sub>e @ \<Gamma>) \<turnstile> P<:Q" by (rule weakening)
with QS have "(D[X \<mapsto> P]\<^sub>e @ \<Gamma>) \<turnstile> P<:S" by simp
moreover from XQ and ST and QS have "(D[X \<mapsto> P]\<^sub>e @ \<Gamma>) \<turnstile> S<:T[X \<mapsto> P]\<^sub>\<tau>"
by (simp add: type_subst_identity)
ultimately have "(D[X \<mapsto> P]\<^sub>e @ \<Gamma>) \<turnstile> P<:T[X \<mapsto> P]\<^sub>\<tau>"
by (rule subtype_transitivity)
with eq show ?case by simp
next
assume neq: "X \<noteq> Y"
with SA_trans_TVar have "TVarB Y S \<in> set D \<or> TVarB Y S \<in> set \<Gamma>"
by (simp add: binding.inject)
then show ?case
proof
assume "TVarB Y S \<in> set D"
then have "TVarB Y (S[X \<mapsto> P]\<^sub>\<tau>) \<in> set (D[X \<mapsto> P]\<^sub>e)"
by (rule ctxt_subst_mem_TVarB)
then have "TVarB Y (S[X \<mapsto> P]\<^sub>\<tau>) \<in> set (D[X \<mapsto> P]\<^sub>e @ \<Gamma>)" by simp
with neq and ST show ?thesis by auto
next
assume Y: "TVarB Y S \<in> set \<Gamma>"
from X_\<Gamma>_ok have "X \<sharp> ty_dom \<Gamma>" and "\<turnstile> \<Gamma> ok" by auto
then have "X \<sharp> \<Gamma>" by (simp add: valid_ty_dom_fresh)
with Y have "X \<sharp> S"
by (induct \<Gamma>) (auto simp add: fresh_list_nil fresh_list_cons)
with ST have "(D[X \<mapsto> P]\<^sub>e @ \<Gamma>)\<turnstile>S<:T[X \<mapsto> P]\<^sub>\<tau>"
by (simp add: type_subst_identity)
moreover from Y have "TVarB Y S \<in> set (D[X \<mapsto> P]\<^sub>e @ \<Gamma>)" by simp
ultimately show ?thesis using neq by auto
qed
qed
next
case (SA_refl_TVar Y X P D)
note `\<turnstile> (D @ TVarB X Q # \<Gamma>) ok`
moreover from SA_refl_TVar have closed: "P closed_in \<Gamma>"
by (auto dest: subtype_implies_closed)
ultimately have ok: "\<turnstile> (D[X \<mapsto> P]\<^sub>e @ \<Gamma>) ok" using valid_subst by auto
from closed have closed': "P closed_in (D[X \<mapsto> P]\<^sub>e @ \<Gamma>)"
by (simp add: closed_in_weaken')
show ?case
proof (cases "X = Y")
assume "X = Y"
with closed' and ok show ?thesis
by (auto intro: subtype_reflexivity)
next
assume neq: "X \<noteq> Y"
with SA_refl_TVar have "Y \<in> ty_dom (D[X \<mapsto> P]\<^sub>e @ \<Gamma>)"
by (simp add: ty_dom_subst doms_append)
with neq and ok show ?thesis by auto
qed
next
case (SA_arrow T1 S1 S2 T2 X P D)
then have h1:"(D[X \<mapsto> P]\<^sub>e @ \<Gamma>)\<turnstile>T1[X \<mapsto> P]\<^sub>\<tau><:S1[X \<mapsto> P]\<^sub>\<tau>" using SA_arrow by auto
from SA_arrow have h2:"(D[X \<mapsto> P]\<^sub>e @ \<Gamma>)\<turnstile>S2[X \<mapsto> P]\<^sub>\<tau><:T2[X \<mapsto> P]\<^sub>\<tau>" using SA_arrow by auto
show ?case using subtype_of.SA_arrow h1 h2 by auto
next
case (SA_all T1 S1 Y S2 T2 X P D)
then have Y: "Y \<sharp> ty_dom (D @ TVarB X Q # \<Gamma>)"
by (auto dest: subtype_implies_ok intro: fresh_dom)
moreover from SA_all have "S1 closed_in (D @ TVarB X Q # \<Gamma>)"
by (auto dest: subtype_implies_closed)
ultimately have S1: "Y \<sharp> S1" by (rule closed_in_fresh)
from SA_all have "T1 closed_in (D @ TVarB X Q # \<Gamma>)"
by (auto dest: subtype_implies_closed)
with Y have T1: "Y \<sharp> T1" by (rule closed_in_fresh)
with SA_all and S1 show ?case by force
qed
subsubsection {* Type Substitution Preserves Typing *}
theorem substT_type: -- {* A.11 *}
assumes H: "(D @ TVarB X Q # G) \<turnstile> t : T"
shows "G \<turnstile> P <: Q \<Longrightarrow>
(D[X \<mapsto> P]\<^sub>e @ G) \<turnstile> t[X \<mapsto>\<^sub>\<tau> P] : T[X \<mapsto> P]\<^sub>\<tau>" using H
proof (nominal_induct "D @ TVarB X Q # G" t T avoiding: X P arbitrary: D rule: typing.strong_induct)
case (T_Var x T X P D')
have "G\<turnstile>P<:Q" by fact
then have "P closed_in G" using subtype_implies_closed by auto
moreover note `\<turnstile> (D' @ TVarB X Q # G) ok`
ultimately have "\<turnstile> (D'[X \<mapsto> P]\<^sub>e @ G) ok" using valid_subst by auto
moreover note `VarB x T \<in> set (D' @ TVarB X Q # G)`
then have "VarB x T \<in> set D' \<or> VarB x T \<in> set G" by simp
then have "(VarB x (T[X \<mapsto> P]\<^sub>\<tau>)) \<in> set (D'[X \<mapsto> P]\<^sub>e @ G)"
proof
assume "VarB x T \<in> set D'"
then have "VarB x (T[X \<mapsto> P]\<^sub>\<tau>) \<in> set (D'[X \<mapsto> P]\<^sub>e)"
by (rule ctxt_subst_mem_VarB)
then show ?thesis by simp
next
assume x: "VarB x T \<in> set G"
from T_Var have ok: "\<turnstile> G ok" by (auto dest: subtype_implies_ok)
then have "X \<sharp> ty_dom G" using T_Var by (auto dest: validE_append)
with ok have "X \<sharp> G" by (simp add: valid_ty_dom_fresh)
moreover from x have "VarB x T \<in> set (D' @ G)" by simp
then have "VarB x (T[X \<mapsto> P]\<^sub>\<tau>) \<in> set ((D' @ G)[X \<mapsto> P]\<^sub>e)"
by (rule ctxt_subst_mem_VarB)
ultimately show ?thesis
by (simp add: ctxt_subst_append ctxt_subst_identity)
qed
ultimately show ?case by auto
next
case (T_App t1 T1 T2 t2 X P D')
then have "D'[X \<mapsto> P]\<^sub>e @ G \<turnstile> t1[X \<mapsto>\<^sub>\<tau> P] : (T1 \<rightarrow> T2)[X \<mapsto> P]\<^sub>\<tau>" by auto
moreover from T_App have "D'[X \<mapsto> P]\<^sub>e @ G \<turnstile> t2[X \<mapsto>\<^sub>\<tau> P] : T1[X \<mapsto> P]\<^sub>\<tau>" by auto
ultimately show ?case by auto
next
case (T_Abs x T1 t2 T2 X P D')
then show ?case by force
next
case (T_Sub t S T X P D')
then show ?case using substT_subtype by force
next
case (T_TAbs X' T1 t2 T2 X P D')
then have "X' \<sharp> ty_dom (D' @ TVarB X Q # G)"
and "T1 closed_in (D' @ TVarB X Q # G)"
by (auto dest: typing_ok)
then have "X' \<sharp> T1" by (rule closed_in_fresh)
with T_TAbs show ?case by force
next
case (T_TApp X' t1 T2 T11 T12 X P D')
then have "X' \<sharp> ty_dom (D' @ TVarB X Q # G)"
by (simp add: fresh_dom)
moreover from T_TApp have "T11 closed_in (D' @ TVarB X Q # G)"
by (auto dest: subtype_implies_closed)
ultimately have X': "X' \<sharp> T11" by (rule closed_in_fresh)
from T_TApp have "D'[X \<mapsto> P]\<^sub>e @ G \<turnstile> t1[X \<mapsto>\<^sub>\<tau> P] : (\<forall>X'<:T11. T12)[X \<mapsto> P]\<^sub>\<tau>"
by simp
with X' and T_TApp show ?case
by (auto simp add: fresh_atm type_substitution_lemma
fresh_list_append fresh_list_cons
ctxt_subst_fresh' type_subst_fresh subst_trm_ty_fresh
intro: substT_subtype)
qed
lemma Abs_type: -- {* A.13(1) *}
assumes H: "\<Gamma> \<turnstile> (\<lambda>x:S. s) : T"
and H': "\<Gamma> \<turnstile> T <: U \<rightarrow> U'"
and H'': "x \<sharp> \<Gamma>"
obtains S' where "\<Gamma> \<turnstile> U <: S"
and "(VarB x S) # \<Gamma> \<turnstile> s : S'"
and "\<Gamma> \<turnstile> S' <: U'"
using H H' H''
proof (nominal_induct \<Gamma> t \<equiv> "\<lambda>x:S. s" T avoiding: x arbitrary: U U' S s rule: typing.strong_induct)
case (T_Abs y T\<^sub>1 \<Gamma> t\<^sub>2 T\<^sub>2)
from `\<Gamma> \<turnstile> T\<^sub>1 \<rightarrow> T\<^sub>2 <: U \<rightarrow> U'`
obtain ty1: "\<Gamma> \<turnstile> U <: S" and ty2: "\<Gamma> \<turnstile> T\<^sub>2 <: U'" using T_Abs
by cases (simp_all add: ty.inject trm.inject alpha fresh_atm)
from T_Abs have "VarB y S # \<Gamma> \<turnstile> [(y, x)] \<bullet> s : T\<^sub>2"
by (simp add: trm.inject alpha fresh_atm)
then have "[(y, x)] \<bullet> (VarB y S # \<Gamma>) \<turnstile> [(y, x)] \<bullet> [(y, x)] \<bullet> s : [(y, x)] \<bullet> T\<^sub>2"
by (rule typing.eqvt)
moreover from T_Abs have "y \<sharp> \<Gamma>"
by (auto dest!: typing_ok simp add: fresh_trm_dom)
ultimately have "VarB x S # \<Gamma> \<turnstile> s : T\<^sub>2" using T_Abs
by (perm_simp add: ty_vrs_prm_simp)
with ty1 show ?case using ty2 by (rule T_Abs)
next
case (T_Sub \<Gamma> t S T)
then show ?case using subtype_transitivity by blast
qed simp_all
lemma subtype_reflexivity_from_typing:
assumes "\<Gamma> \<turnstile> t : T"
shows "\<Gamma> \<turnstile> T <: T"
using assms subtype_reflexivity typing_ok typing_closed_in by simp
lemma Abs_type':
assumes H: "\<Gamma> \<turnstile> (\<lambda>x:S. s) : U \<rightarrow> U'"
and H': "x \<sharp> \<Gamma>"
obtains S'
where "\<Gamma> \<turnstile> U <: S"
and "(VarB x S) # \<Gamma> \<turnstile> s : S'"
and "\<Gamma> \<turnstile> S' <: U'"
using H subtype_reflexivity_from_typing [OF H] H'
by (rule Abs_type)
lemma TAbs_type: -- {* A.13(2) *}
assumes H: "\<Gamma> \<turnstile> (\<lambda>X<:S. s) : T"
and H': "\<Gamma> \<turnstile> T <: (\<forall>X<:U. U')"
and fresh: "X \<sharp> \<Gamma>" "X \<sharp> S" "X \<sharp> U"
obtains S'
where "\<Gamma> \<turnstile> U <: S"
and "(TVarB X U # \<Gamma>) \<turnstile> s : S'"
and "(TVarB X U # \<Gamma>) \<turnstile> S' <: U'"
using H H' fresh
proof (nominal_induct \<Gamma> t \<equiv> "\<lambda>X<:S. s" T avoiding: X U U' S arbitrary: s rule: typing.strong_induct)
case (T_TAbs Y T\<^sub>1 \<Gamma> t\<^sub>2 T\<^sub>2)
from `TVarB Y T\<^sub>1 # \<Gamma> \<turnstile> t\<^sub>2 : T\<^sub>2` have Y: "Y \<sharp> \<Gamma>"
by (auto dest!: typing_ok simp add: valid_ty_dom_fresh)
from `Y \<sharp> U'` and `Y \<sharp> X`
have "(\<forall>X<:U. U') = (\<forall>Y<:U. [(Y, X)] \<bullet> U')"
by (simp add: ty.inject alpha' fresh_atm)
with T_TAbs have "\<Gamma> \<turnstile> (\<forall>Y<:S. T\<^sub>2) <: (\<forall>Y<:U. [(Y, X)] \<bullet> U')" by (simp add: trm.inject)
then obtain ty1: "\<Gamma> \<turnstile> U <: S" and ty2: "(TVarB Y U # \<Gamma>) \<turnstile> T\<^sub>2 <: ([(Y, X)] \<bullet> U')" using T_TAbs Y
by (cases rule: subtype_of.strong_cases [where X=Y]) (simp_all add: ty.inject alpha abs_fresh)
note ty1
moreover from T_TAbs have "TVarB Y S # \<Gamma> \<turnstile> ([(Y, X)] \<bullet> s) : T\<^sub>2"
by (simp add: trm.inject alpha fresh_atm)
then have "[(Y, X)] \<bullet> (TVarB Y S # \<Gamma>) \<turnstile> [(Y, X)] \<bullet> [(Y, X)] \<bullet> s : [(Y, X)] \<bullet> T\<^sub>2"
by (rule typing.eqvt)
with `X \<sharp> \<Gamma>` `X \<sharp> S` Y `Y \<sharp> S` have "TVarB X S # \<Gamma> \<turnstile> s : [(Y, X)] \<bullet> T\<^sub>2"
by perm_simp
then have "TVarB X U # \<Gamma> \<turnstile> s : [(Y, X)] \<bullet> T\<^sub>2" using ty1
by (rule narrow_type [of "[]", simplified])
moreover from ty2 have "([(Y, X)] \<bullet> (TVarB Y U # \<Gamma>)) \<turnstile> ([(Y, X)] \<bullet> T\<^sub>2) <: ([(Y, X)] \<bullet> [(Y, X)] \<bullet> U')"
by (rule subtype_of.eqvt)
with `X \<sharp> \<Gamma>` `X \<sharp> U` Y `Y \<sharp> U` have "(TVarB X U # \<Gamma>) \<turnstile> ([(Y, X)] \<bullet> T\<^sub>2) <: U'"
by perm_simp
ultimately show ?case by (rule T_TAbs)
next
case (T_Sub \<Gamma> t S T)
then show ?case using subtype_transitivity by blast
qed simp_all
lemma TAbs_type':
assumes H: "\<Gamma> \<turnstile> (\<lambda>X<:S. s) : (\<forall>X<:U. U')"
and fresh: "X \<sharp> \<Gamma>" "X \<sharp> S" "X \<sharp> U"
obtains S'
where "\<Gamma> \<turnstile> U <: S"
and "(TVarB X U # \<Gamma>) \<turnstile> s : S'"
and "(TVarB X U # \<Gamma>) \<turnstile> S' <: U'"
using H subtype_reflexivity_from_typing [OF H] fresh
by (rule TAbs_type)
theorem preservation: -- {* A.20 *}
assumes H: "\<Gamma> \<turnstile> t : T"
shows "t \<longmapsto> t' \<Longrightarrow> \<Gamma> \<turnstile> t' : T" using H
proof (nominal_induct avoiding: t' rule: typing.strong_induct)
case (T_App \<Gamma> t\<^sub>1 T\<^sub>11 T\<^sub>12 t\<^sub>2 t')
obtain x::vrs where x_fresh: "x \<sharp> (\<Gamma>, t\<^sub>1 \<cdot> t\<^sub>2, t')"
by (rule exists_fresh) (rule fin_supp)
obtain X::tyvrs where "X \<sharp> (t\<^sub>1 \<cdot> t\<^sub>2, t')"
by (rule exists_fresh) (rule fin_supp)
with `t\<^sub>1 \<cdot> t\<^sub>2 \<longmapsto> t'` show ?case
proof (cases rule: eval.strong_cases [where x=x and X=X])
case (E_Abs v\<^sub>2 T\<^sub>11' t\<^sub>12)
with T_App and x_fresh have h: "\<Gamma> \<turnstile> (\<lambda>x:T\<^sub>11'. t\<^sub>12) : T\<^sub>11 \<rightarrow> T\<^sub>12"
by (simp add: trm.inject fresh_prod)
moreover from x_fresh have "x \<sharp> \<Gamma>" by simp
ultimately obtain S'
where T\<^sub>11: "\<Gamma> \<turnstile> T\<^sub>11 <: T\<^sub>11'"
and t\<^sub>12: "(VarB x T\<^sub>11') # \<Gamma> \<turnstile> t\<^sub>12 : S'"
and S': "\<Gamma> \<turnstile> S' <: T\<^sub>12"
by (rule Abs_type') blast
from `\<Gamma> \<turnstile> t\<^sub>2 : T\<^sub>11`
have "\<Gamma> \<turnstile> t\<^sub>2 : T\<^sub>11'" using T\<^sub>11 by (rule T_Sub)
with t\<^sub>12 have "\<Gamma> \<turnstile> t\<^sub>12[x \<mapsto> t\<^sub>2] : S'"
by (rule subst_type [where \<Delta>="[]", simplified])
hence "\<Gamma> \<turnstile> t\<^sub>12[x \<mapsto> t\<^sub>2] : T\<^sub>12" using S' by (rule T_Sub)
with E_Abs and x_fresh show ?thesis by (simp add: trm.inject fresh_prod)
next
case (E_App1 t''' t'' u)
hence "t\<^sub>1 \<longmapsto> t''" by (simp add:trm.inject)
hence "\<Gamma> \<turnstile> t'' : T\<^sub>11 \<rightarrow> T\<^sub>12" by (rule T_App)
hence "\<Gamma> \<turnstile> t'' \<cdot> t\<^sub>2 : T\<^sub>12" using `\<Gamma> \<turnstile> t\<^sub>2 : T\<^sub>11`
by (rule typing.T_App)
with E_App1 show ?thesis by (simp add:trm.inject)
next
case (E_App2 v t''' t'')
hence "t\<^sub>2 \<longmapsto> t''" by (simp add:trm.inject)
hence "\<Gamma> \<turnstile> t'' : T\<^sub>11" by (rule T_App)
with T_App(1) have "\<Gamma> \<turnstile> t\<^sub>1 \<cdot> t'' : T\<^sub>12"
by (rule typing.T_App)
with E_App2 show ?thesis by (simp add:trm.inject)
qed (simp_all add: fresh_prod)
next
case (T_TApp X \<Gamma> t\<^sub>1 T\<^sub>2 T\<^sub>11 T\<^sub>12 t')
obtain x::vrs where "x \<sharp> (t\<^sub>1 \<cdot>\<^sub>\<tau> T\<^sub>2, t')"
by (rule exists_fresh) (rule fin_supp)
with `t\<^sub>1 \<cdot>\<^sub>\<tau> T\<^sub>2 \<longmapsto> t'`
show ?case
proof (cases rule: eval.strong_cases [where X=X and x=x])
case (E_TAbs T\<^sub>11' T\<^sub>2' t\<^sub>12)
with T_TApp have "\<Gamma> \<turnstile> (\<lambda>X<:T\<^sub>11'. t\<^sub>12) : (\<forall>X<:T\<^sub>11. T\<^sub>12)" and "X \<sharp> \<Gamma>" and "X \<sharp> T\<^sub>11'"
by (simp_all add: trm.inject)
moreover from `\<Gamma>\<turnstile>T\<^sub>2<:T\<^sub>11` and `X \<sharp> \<Gamma>` have "X \<sharp> T\<^sub>11"
by (blast intro: closed_in_fresh fresh_dom dest: subtype_implies_closed)
ultimately obtain S'
where "TVarB X T\<^sub>11 # \<Gamma> \<turnstile> t\<^sub>12 : S'"
and "(TVarB X T\<^sub>11 # \<Gamma>) \<turnstile> S' <: T\<^sub>12"
by (rule TAbs_type') blast
hence "TVarB X T\<^sub>11 # \<Gamma> \<turnstile> t\<^sub>12 : T\<^sub>12" by (rule T_Sub)
hence "\<Gamma> \<turnstile> t\<^sub>12[X \<mapsto>\<^sub>\<tau> T\<^sub>2] : T\<^sub>12[X \<mapsto> T\<^sub>2]\<^sub>\<tau>" using `\<Gamma> \<turnstile> T\<^sub>2 <: T\<^sub>11`
by (rule substT_type [where D="[]", simplified])
with T_TApp and E_TAbs show ?thesis by (simp add: trm.inject)
next
case (E_TApp t''' t'' T)
from E_TApp have "t\<^sub>1 \<longmapsto> t''" by (simp add: trm.inject)
then have "\<Gamma> \<turnstile> t'' : (\<forall>X<:T\<^sub>11. T\<^sub>12)" by (rule T_TApp)
then have "\<Gamma> \<turnstile> t'' \<cdot>\<^sub>\<tau> T\<^sub>2 : T\<^sub>12[X \<mapsto> T\<^sub>2]\<^sub>\<tau>" using `\<Gamma> \<turnstile> T\<^sub>2 <: T\<^sub>11`
by (rule better_T_TApp)
with E_TApp show ?thesis by (simp add: trm.inject)
qed (simp_all add: fresh_prod)
next
case (T_Sub \<Gamma> t S T t')
have "t \<longmapsto> t'" by fact
hence "\<Gamma> \<turnstile> t' : S" by (rule T_Sub)
moreover have "\<Gamma> \<turnstile> S <: T" by fact
ultimately show ?case by (rule typing.T_Sub)
qed (auto)
lemma Fun_canonical: -- {* A.14(1) *}
assumes ty: "[] \<turnstile> v : T\<^sub>1 \<rightarrow> T\<^sub>2"
shows "val v \<Longrightarrow> \<exists>x t S. v = (\<lambda>x:S. t)" using ty
proof (induct "[]::env" v "T\<^sub>1 \<rightarrow> T\<^sub>2" arbitrary: T\<^sub>1 T\<^sub>2)
case (T_Sub t S)
from `[] \<turnstile> S <: T\<^sub>1 \<rightarrow> T\<^sub>2`
obtain S\<^sub>1 S\<^sub>2 where S: "S = S\<^sub>1 \<rightarrow> S\<^sub>2"
by cases (auto simp add: T_Sub)
then show ?case using `val t` by (rule T_Sub)
qed (auto)
lemma TyAll_canonical: -- {* A.14(3) *}
fixes X::tyvrs
assumes ty: "[] \<turnstile> v : (\<forall>X<:T\<^sub>1. T\<^sub>2)"
shows "val v \<Longrightarrow> \<exists>X t S. v = (\<lambda>X<:S. t)" using ty
proof (induct "[]::env" v "\<forall>X<:T\<^sub>1. T\<^sub>2" arbitrary: X T\<^sub>1 T\<^sub>2)
case (T_Sub t S)
from `[] \<turnstile> S <: (\<forall>X<:T\<^sub>1. T\<^sub>2)`
obtain X S\<^sub>1 S\<^sub>2 where S: "S = (\<forall>X<:S\<^sub>1. S\<^sub>2)"
by cases (auto simp add: T_Sub)
then show ?case using T_Sub by auto
qed (auto)
theorem progress:
assumes "[] \<turnstile> t : T"
shows "val t \<or> (\<exists>t'. t \<longmapsto> t')"
using assms
proof (induct "[]::env" t T)
case (T_App t\<^sub>1 T\<^sub>11 T\<^sub>12 t\<^sub>2)
hence "val t\<^sub>1 \<or> (\<exists>t'. t\<^sub>1 \<longmapsto> t')" by simp
thus ?case
proof
assume t\<^sub>1_val: "val t\<^sub>1"
with T_App obtain x t3 S where t\<^sub>1: "t\<^sub>1 = (\<lambda>x:S. t3)"
by (auto dest!: Fun_canonical)
from T_App have "val t\<^sub>2 \<or> (\<exists>t'. t\<^sub>2 \<longmapsto> t')" by simp
thus ?case
proof
assume "val t\<^sub>2"
with t\<^sub>1 have "t\<^sub>1 \<cdot> t\<^sub>2 \<longmapsto> t3[x \<mapsto> t\<^sub>2]" by auto
thus ?case by auto
next
assume "\<exists>t'. t\<^sub>2 \<longmapsto> t'"
then obtain t' where "t\<^sub>2 \<longmapsto> t'" by auto
with t\<^sub>1_val have "t\<^sub>1 \<cdot> t\<^sub>2 \<longmapsto> t\<^sub>1 \<cdot> t'" by auto
thus ?case by auto
qed
next
assume "\<exists>t'. t\<^sub>1 \<longmapsto> t'"
then obtain t' where "t\<^sub>1 \<longmapsto> t'" by auto
hence "t\<^sub>1 \<cdot> t\<^sub>2 \<longmapsto> t' \<cdot> t\<^sub>2" by auto
thus ?case by auto
qed
next
case (T_TApp X t\<^sub>1 T\<^sub>2 T\<^sub>11 T\<^sub>12)
hence "val t\<^sub>1 \<or> (\<exists>t'. t\<^sub>1 \<longmapsto> t')" by simp
thus ?case
proof
assume "val t\<^sub>1"
with T_TApp obtain x t S where "t\<^sub>1 = (\<lambda>x<:S. t)"
by (auto dest!: TyAll_canonical)
hence "t\<^sub>1 \<cdot>\<^sub>\<tau> T\<^sub>2 \<longmapsto> t[x \<mapsto>\<^sub>\<tau> T\<^sub>2]" by auto
thus ?case by auto
next
assume "\<exists>t'. t\<^sub>1 \<longmapsto> t'" thus ?case by auto
qed
qed (auto)
end
|
"""
FAD(seqs; alpha = 0.01, neigh_thresh = 1.0,method = 2,err_rate=0.02, phreds = nothing)
Exploits abundance and neighborhood information to denoise sequences without clustering
on consensus calls. Primarily designed for short amplicons, high quality sequences,
and good read-per-template coverage
"""
function FAD(seqs; alpha = 0.01, neigh_thresh = 1.0,method = 2,err_rate=0.02, phreds = nothing)
if !(method in [1,2,3])
warn("Please pick a method in 1,2,3")
return [],[]
end
#Method list:
#1: No statistical considerations. All smaller relatives get eaten.
#2: Use Poisson test to decide to add not-too-small relatives back in.
#3: Use homopolymer test to skew Poisson rate for adding smaller relatives back in.
#Need to mod this to work for .fasta files. Perhaps use the number of pairs to approximate the number of error free sequences.
if phreds != nothing
#seqs, phreds , _ = read_fastq(fn, seqtype=String);
noises = [mean(phred_to_p(i)) for i in phreds];
#Calculate the expected proportion of sequences that are error free.
expected_zero_errors = mean([pdf(Poisson(noises[i]*length(seqs[i])),0) for i in 1:length(seqs)]);
else
warn("Switching to method 1, phreds missing")
method = 1
end
counts = countmap(seqs);
seq_keys = keys(counts);
seq_freqs_all = reverse(sort([(counts[k],k,kmer_count(k,6)) for k in seq_keys]));
seq_freqs = seq_freqs_all[[k[1]>=2 for k in seq_freqs_all]];
if length(seq_freqs) > 0
current_set = [seq_freqs[1]];
for i in 2:length(seq_freqs)
dists = [corrected_kmer_dist_full(k[3],seq_freqs[i][3]) for k in current_set]
neighbour_set = dists.<=neigh_thresh
#if no neighbours within radius, add to current_set
if sum(neighbour_set)==0
push!(current_set,seq_freqs[i])
else
if method == 2
inds = collect(1:length(current_set))[neighbour_set]
best = indmax(current_set[inds])
p_val = (1-cdf(Poisson((current_set[inds][best][1]/expected_zero_errors)*err_rate),seq_freqs[i][1]))*length(seq_freqs[i][2])
if p_val < alpha
push!(current_set,seq_freqs[i])
end
end
#Using same as above. Will add in homopolymer test.
if method == 3
#Need to look through all inds. For each, calculate p-value. Take the largest p-value. If that is <thresh, then keep cluster.
#This will use a regular error rate if HP==false, but a much larger error rate if HP==true.
inds = collect(1:length(current_set))[neighbour_set]
best = indmax(current_set[inds])
p_val = (1-cdf(Poisson((current_set[inds][best][1]/expected_zero_errors)*err_rate),seq_freqs[i][1]))*length(seq_freqs[i][2])
if p_val < alpha
push!(current_set,seq_freqs[i])
end
end
end
end
println("Using ",100*sum([k[1] for k in current_set])/length(seqs),"% of reads. If this is lower than 5%, use RAD instead.")
frequencies = zeros(length(current_set))
for s in seq_freqs_all
dists = [corrected_kmer_dist_full(k[3],s[3],k=5) for k in current_set]
frequencies[indmin(dists)] += s[1]
end
return [k[2] for k in current_set],frequencies
else #catching the condition where there are no duplicates
warn("Failing completely. Use RAD instead.")
return [],[]
end
end
|
[STATEMENT]
lemma to_bl_unfold:
\<open>to_bl w = rev (map (bit w) [0..<LENGTH('a)])\<close> for w :: \<open>'a::len word\<close>
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. to_bl w = rev (map (bit w) [0..<LENGTH('a)])
[PROOF STEP]
by (simp add: map_bit_interval_eq takefill_bintrunc to_bl_def flip: bin_to_bl_def) |
The closure of a set is empty if and only if the set is empty. |
import Language.Reflection
%language ElabReflection
elabTry : Elab ()
elabTry
= try (declare `[ x : 94
x = 94 ])
(declare `[ x : Int
x = 94 ])
%runElab elabTry
|
module Fancy_Ops
{-
This includes some work done on having more of a well-typed feel to the
Operational semantics for FLK. It wound up being farely complicated, and
ruined some of the untyped feel of the semantics, so now it is over here.
-}
import Data.SortedMap
Ident : Type
Ident = String
data Op2 : Type -> Type -> Type where
Plus : Op2 Nat Nat
Minus : Op2 Nat Nat
Times : Op2 Nat Nat
LThan : Op2 Nat Bool
GThan : Op2 Nat Bool
LEThan : Op2 Nat Bool
GEThan : Op2 Nat Bool
EQual : Op2 inT outT
NEqual : Op2 inT outT
data Op1 : Type -> Type -> Type where
Not : Op1 Bool Bool
data Status = Inter | Done | Lam
mutual
Env : Type
Env = SortedMap Ident (Exp Done)
data Exp : Status -> Type where
App : Exp a -> Exp b -> Exp Inter
Abs : Ident -> Exp a -> Exp Lam
Rec : Ident -> Exp a -> Exp Done
If : Exp a -> Exp b -> Exp c -> Exp Inter
Prim1 : Op1 w x -> Exp a -> Exp Inter
Prim2 : Op2 w x -> Exp a -> Exp b -> Exp Inter
N : Nat -> Exp Done
B : Bool -> Exp Done
Clos : Env -> Exp Lam -> Exp Done
Id : Ident -> Exp Inter
total
tView : (n : Exp Done) -> Type
tView (Rec _ _) = {a : Type} -> {b : Type} -> (a -> b)
tView (N _) = Nat
tView (B _) = Bool
tView (Clos _ _) = {a : Type} -> {b : Type} -> (a -> b)
total
calc1 : (x : Exp Done) -> (op : Op1 a b) -> (tView x = a) -> (y ** tView y = b)
calc1 (B x) Not prf = let b = B (not x) in (b ** Refl)
calc1 (Rec x y) Not prf = ?h7_1
calc1 (N k) Not prf = absurd (t prf)
where t : (Nat = Bool) -> Void
calc1 (Clos x y) Not prf = ?h1_4
|
%==================================================================
% General Data File
% Title: TETREAHEDRA
% Units: SI
% Dimensions: 3D
% Type of problem: Plane_Stress
% Type of Phisics: ELASTIC
% Micro/Macro: MACRO
%
%==================================================================
%% Data
Data_prb = {
'TETRAHEDRA';
'SI';
'3D';
'Plane_Stress';
'ELASTIC';
'MACRO';
};
%% Coordinates
% Node X Y Z
coord = [
1 2 0 1
2 2 0 0.5
3 2 0.5 1
4 2 0.5 0.5
5 2 0 0
6 2 1 1
7 1 0 1
8 1 0 0.5
9 1 0.5 1
10 2 1 0.5
11 2 0.5 0
12 1 0.5 0.5
13 2 1 0
14 1 0 0
15 1 1 1
16 1 0.5 0
17 1 1 0.5
18 1 1 0
19 0 0 1
20 0 0 0.5
21 0 0.5 1
22 0 0.5 0.5
23 0 1 1
24 0 0 0
25 0 0.5 0
26 0 1 0.5
27 0 1 0
];
%% Conectivities
% Element Node(1) Node(2) Node(3) Node(4) Material
connec = [
1 10 17 12 6 0
2 6 10 4 12 0
3 15 9 12 6 0
4 6 3 9 12 0
5 6 15 17 12 0
6 3 4 12 6 0
7 11 16 12 13 0
8 13 11 4 12 0
9 18 17 12 13 0
10 13 10 17 12 0
11 13 18 16 12 0
12 10 4 12 13 0
13 9 21 23 12 0
14 12 9 15 23 0
15 22 26 23 12 0
16 12 17 26 23 0
17 12 22 21 23 0
18 17 15 23 12 0
19 17 26 27 12 0
20 12 17 18 27 0
21 22 25 27 12 0
22 12 16 25 27 0
23 12 22 26 27 0
24 16 18 27 12 0
25 3 9 12 1 0
26 1 3 4 12 0
27 7 8 12 1 0
28 1 2 8 12 0
29 1 7 9 12 0
30 2 4 12 1 0
31 2 8 12 5 0
32 5 2 4 12 0
33 14 16 12 5 0
34 5 11 16 12 0
35 5 14 8 12 0
36 11 4 12 5 0
37 8 20 19 12 0
38 12 8 7 19 0
39 22 21 19 12 0
40 12 9 21 19 0
41 12 22 20 19 0
42 9 7 19 12 0
43 16 25 24 12 0
44 12 16 14 24 0
45 22 20 24 12 0
46 12 8 20 24 0
47 12 22 25 24 0
48 8 14 24 12 0
];
%% Variable Prescribed
% Node Dimension Value
dirichlet_data = [
19 1 0
19 2 0
19 3 0
20 1 0
20 2 0
20 3 0
21 1 0
21 2 0
21 3 0
22 1 0
22 2 0
22 3 0
23 1 0
23 2 0
23 3 0
24 1 0
24 2 0
24 3 0
25 1 0
25 2 0
25 3 0
26 1 0
26 2 0
26 3 0
27 1 0
27 2 0
27 3 0
];
%% Force Prescribed
% Node Dimension Value
pointload_complete = [
4 1 0
4 2 -1
];
%% Volumetric Force
% Element Dim Force_Dim
Vol_force = [
];
%% Group Elements
% Element Group_num
Group = [
];
%% Initial Holes
% Elements that are considered holes initially
% Element
Initial_holes = [
];
%% Boundary Elements
% Elements that can not be removed
% Element
Boundary_elements = [
];
%% Micro gauss post
%
% Element
Micro_gauss_post = [
];
%% Micro Slave-Master
% Nodes that are Slaves
% Nodes Value (1-Slave,0-Master)
Micro_slave = [
];
%% Nodes solid
% Nodes that must remain
% Nodes
nodesolid = unique(pointload_complete(:,1));
%% External border Elements
% Detect the elements that define the edge of the domain
% Element Node(1) Node(2)
External_border_elements = [
];
%% External border Nodes
% Detect the nodes that define the edge of the domain
% Node
External_border_nodes = [
];
%% Materials
% Materials that have been used
% Material_Num Mat_density Young_Modulus Poisson
Materials = [
];
|
module stateDependentObjects where
open import Size renaming (Size to AgdaSize)
open import Agda.Builtin.Equality
open import Data.Nat.Base as N hiding (_⊔_)
open import Data.Product
open import Data.Vec as Vec using (Vec; []; _∷_; head; tail)
open import Function
open import NativeIO
open import Relation.Binary.PropositionalEquality
open import interactiveProgramsAgda
-- open import SizedIO.Base
{- State dependent interfaces, objects -}
record Interfaceˢ : Set₁ where
field Stateˢ : Set
Methodˢ : (s : Stateˢ) → Set
Resultˢ : (s : Stateˢ) → (m : Methodˢ s) → Set
nextˢ : (s : Stateˢ) → (m : Methodˢ s) → (r : Resultˢ s m)
→ Stateˢ
open Interfaceˢ public
{- State-Dependent Objects -}
record Objectˢ (I : Interfaceˢ) (s : Stateˢ I) : Set where
coinductive
field objectMethod : (m : Methodˢ I s) →
Σ[ r ∈ Resultˢ I s m ] Objectˢ I (nextˢ I s m r)
open Objectˢ public
record IOObjectˢ (Iᵢₒ : IOInterface) (I : Interfaceˢ) (s : Stateˢ I) : Set where
coinductive
field method : (m : Methodˢ I s) →
IO Iᵢₒ ∞ (Σ[ r ∈ Resultˢ I s m ] IOObjectˢ Iᵢₒ I (nextˢ I s m r))
{- Example of a Stack -}
StackStateˢ : Set
StackStateˢ = ℕ
data StackMethodˢ (A : Set) : (n : StackStateˢ) → Set where
push : ∀ {n} → A → StackMethodˢ A n
pop : ∀ {n} → StackMethodˢ A (suc n)
StackResultˢ : (A : Set) → (s : StackStateˢ) → StackMethodˢ A s → Set
StackResultˢ A _ (push _) = Unit
StackResultˢ A _ pop = A
stackNextˢ : ∀ A n (m : StackMethodˢ A n) (r : StackResultˢ A n m) → StackStateˢ
stackNextˢ A n (push x) r = suc n
stackNextˢ A (suc n) pop r = n
StackInterfaceˢ : (A : Set) → Interfaceˢ
Stateˢ (StackInterfaceˢ A) = StackStateˢ
Methodˢ (StackInterfaceˢ A) = StackMethodˢ A
Resultˢ (StackInterfaceˢ A) = StackResultˢ A
nextˢ (StackInterfaceˢ A) = stackNextˢ A
stack : ∀{A}{n : ℕ} (as : Vec A n) → Objectˢ (StackInterfaceˢ A) n
objectMethod (stack as) (push a) = _ , stack (a ∷ as)
objectMethod (stack (a ∷ as)) pop = a , stack as
{- Reasoning about Stateful Objects -}
{- Bisimiliarity -}
module Bisim (I : Interfaceˢ)
(let S = Stateˢ I) (let M = Methodˢ I) (let R = Resultˢ I)
(let next = nextˢ I) (let O = Objectˢ I)
where
data ΣR {A : Set} {B : A → Set} (R : ∀{a} (b b' : B a) → Set)
: (p p' : Σ A B) → Set
where
eqΣ : ∀{a}{b b' : B a} → R b b' → ΣR R (a , b) (a , b')
record _≅_ {s : S} (o o' : O s) : Set where
coinductive
field bisimMethod : (m : M s) →
ΣR (_≅_) (objectMethod o m) (objectMethod o' m)
open _≅_ public
refl≅ : ∀{s} (o : O s) → o ≅ o
bisimMethod (refl≅ o) m = let (r , o') = objectMethod o m
in eqΣ (refl≅ o')
module _ {E : Set} where
private
I = StackInterfaceˢ E
S = Stateˢ I
O = Objectˢ I
open Bisim I
{- Verifying Stack laws -}
pop-after-push : ∀{n} {v : Vec E n} {e : E} →
let st = stack v
(_ , st₁) = objectMethod st (push e)
(e₂ , st₂) = objectMethod st₁ pop
in (e ≡ e₂) × (st ≅ st₂)
pop-after-push = refl , refl≅ _
push-after-pop : ∀{n} {v : Vec E n} {e : E} →
let st = stack (e ∷ v)
(e₁ , st₁) = objectMethod st pop
(_ , st₂) = objectMethod st₁ (push e₁)
in st ≅ st₂
push-after-pop = refl≅ _
{- Bisimilarity of different stack implementations -}
stackFState = ℕ → E
pushStackF : E → stackFState → stackFState
pushStackF e f = λ { 0 → e ;
(suc m) → f m}
popStackFe : stackFState → E
popStackFe f = f 0
popStackFf : stackFState → stackFState
popStackFf f = f ∘ suc
tabulate : ∀ (n : ℕ) → stackFState → Vec E n
tabulate 0 f = []
tabulate (suc n) f = popStackFe f ∷ tabulate n (popStackFf f)
stackF : ∀ (n : ℕ) (f : ℕ → E) → Objectˢ (StackInterfaceˢ E) n
objectMethod (stackF n f) (push e) = _ ,
stackF (suc n) (pushStackF e f)
objectMethod (stackF (suc n) f) pop = popStackFe f ,
stackF n (popStackFf f)
impl-bisim : ∀{n f} v (p : tabulate n f ≡ v) → stackF n f ≅ stack v
bisimMethod (impl-bisim v p) (push e) =
eqΣ (impl-bisim (e ∷ v) (cong (_∷_ e) p))
bisimMethod (impl-bisim (e ∷ v) p) pop rewrite cong head p =
eqΣ (impl-bisim v (cong tail p))
|
example (p q : Prop) (hp : p) (hq : q) : p ∧ q :=
by split; assumption
|
/-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
! This file was ported from Lean 3 source module analysis.box_integral.partition.basic
! leanprover-community/mathlib commit 84dc0bd6619acaea625086d6f53cb35cdd554219
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Algebra.BigOperators.Option
import Mathbin.Analysis.BoxIntegral.Box.Basic
/-!
# Partitions of rectangular boxes in `ℝⁿ`
In this file we define (pre)partitions of rectangular boxes in `ℝⁿ`. A partition of a box `I` in
`ℝⁿ` (see `box_integral.prepartition` and `box_integral.prepartition.is_partition`) is a finite set
of pairwise disjoint boxes such that their union is exactly `I`. We use `boxes : finset (box ι)` to
store the set of boxes.
Many lemmas about box integrals deal with pairwise disjoint collections of subboxes, so we define a
structure `box_integral.prepartition (I : box_integral.box ι)` that stores a collection of boxes
such that
* each box `J ∈ boxes` is a subbox of `I`;
* the boxes are pairwise disjoint as sets in `ℝⁿ`.
Then we define a predicate `box_integral.prepartition.is_partition`; `π.is_partition` means that the
boxes of `π` actually cover the whole `I`. We also define some operations on prepartitions:
* `box_integral.partition.bUnion`: split each box of a partition into smaller boxes;
* `box_integral.partition.restrict`: restrict a partition to a smaller box.
We also define a `semilattice_inf` structure on `box_integral.partition I` for all
`I : box_integral.box ι`.
## Tags
rectangular box, partition
-/
open Set Finset Function
open Classical NNReal BigOperators
noncomputable section
namespace BoxIntegral
variable {ι : Type _}
/-- A prepartition of `I : box_integral.box ι` is a finite set of pairwise disjoint subboxes of
`I`. -/
structure Prepartition (I : Box ι) where
boxes : Finset (Box ι)
le_of_mem' : ∀ J ∈ boxes, J ≤ I
PairwiseDisjoint : Set.Pairwise (↑boxes) (Disjoint on (coe : Box ι → Set (ι → ℝ)))
#align box_integral.prepartition BoxIntegral.Prepartition
namespace Prepartition
variable {I J J₁ J₂ : Box ι} (π : Prepartition I) {π₁ π₂ : Prepartition I} {x : ι → ℝ}
instance : Membership (Box ι) (Prepartition I) :=
⟨fun J π => J ∈ π.boxes⟩
@[simp]
theorem mem_boxes : J ∈ π.boxes ↔ J ∈ π :=
Iff.rfl
#align box_integral.prepartition.mem_boxes BoxIntegral.Prepartition.mem_boxes
@[simp]
theorem mem_mk {s h₁ h₂} : J ∈ (mk s h₁ h₂ : Prepartition I) ↔ J ∈ s :=
Iff.rfl
#align box_integral.prepartition.mem_mk BoxIntegral.Prepartition.mem_mk
theorem disjoint_coe_of_mem (h₁ : J₁ ∈ π) (h₂ : J₂ ∈ π) (h : J₁ ≠ J₂) :
Disjoint (J₁ : Set (ι → ℝ)) J₂ :=
π.PairwiseDisjoint h₁ h₂ h
#align box_integral.prepartition.disjoint_coe_of_mem BoxIntegral.Prepartition.disjoint_coe_of_mem
theorem eq_of_mem_of_mem (h₁ : J₁ ∈ π) (h₂ : J₂ ∈ π) (hx₁ : x ∈ J₁) (hx₂ : x ∈ J₂) : J₁ = J₂ :=
by_contra fun H => (π.disjoint_coe_of_mem h₁ h₂ H).le_bot ⟨hx₁, hx₂⟩
#align box_integral.prepartition.eq_of_mem_of_mem BoxIntegral.Prepartition.eq_of_mem_of_mem
theorem eq_of_le_of_le (h₁ : J₁ ∈ π) (h₂ : J₂ ∈ π) (hle₁ : J ≤ J₁) (hle₂ : J ≤ J₂) : J₁ = J₂ :=
π.eq_of_mem_of_mem h₁ h₂ (hle₁ J.upper_mem) (hle₂ J.upper_mem)
#align box_integral.prepartition.eq_of_le_of_le BoxIntegral.Prepartition.eq_of_le_of_le
theorem eq_of_le (h₁ : J₁ ∈ π) (h₂ : J₂ ∈ π) (hle : J₁ ≤ J₂) : J₁ = J₂ :=
π.eq_of_le_of_le h₁ h₂ le_rfl hle
#align box_integral.prepartition.eq_of_le BoxIntegral.Prepartition.eq_of_le
theorem le_of_mem (hJ : J ∈ π) : J ≤ I :=
π.le_of_mem' J hJ
#align box_integral.prepartition.le_of_mem BoxIntegral.Prepartition.le_of_mem
theorem lower_le_lower (hJ : J ∈ π) : I.lower ≤ J.lower :=
Box.antitone_lower (π.le_of_mem hJ)
#align box_integral.prepartition.lower_le_lower BoxIntegral.Prepartition.lower_le_lower
theorem upper_le_upper (hJ : J ∈ π) : J.upper ≤ I.upper :=
Box.monotone_upper (π.le_of_mem hJ)
#align box_integral.prepartition.upper_le_upper BoxIntegral.Prepartition.upper_le_upper
theorem injective_boxes : Function.Injective (boxes : Prepartition I → Finset (Box ι)) :=
by
rintro ⟨s₁, h₁, h₁'⟩ ⟨s₂, h₂, h₂'⟩ (rfl : s₁ = s₂)
rfl
#align box_integral.prepartition.injective_boxes BoxIntegral.Prepartition.injective_boxes
@[ext]
theorem ext (h : ∀ J, J ∈ π₁ ↔ J ∈ π₂) : π₁ = π₂ :=
injective_boxes <| Finset.ext h
#align box_integral.prepartition.ext BoxIntegral.Prepartition.ext
/-- The singleton prepartition `{J}`, `J ≤ I`. -/
@[simps]
def single (I J : Box ι) (h : J ≤ I) : Prepartition I :=
⟨{J}, by simpa, by simp⟩
#align box_integral.prepartition.single BoxIntegral.Prepartition.single
@[simp]
theorem mem_single {J'} (h : J ≤ I) : J' ∈ single I J h ↔ J' = J :=
mem_singleton
#align box_integral.prepartition.mem_single BoxIntegral.Prepartition.mem_single
/-- We say that `π ≤ π'` if each box of `π` is a subbox of some box of `π'`. -/
instance : LE (Prepartition I) :=
⟨fun π π' => ∀ ⦃I⦄, I ∈ π → ∃ I' ∈ π', I ≤ I'⟩
instance : PartialOrder (Prepartition I)
where
le := (· ≤ ·)
le_refl π I hI := ⟨I, hI, le_rfl⟩
le_trans π₁ π₂ π₃ h₁₂ h₂₃ I₁ hI₁ :=
let ⟨I₂, hI₂, hI₁₂⟩ := h₁₂ hI₁
let ⟨I₃, hI₃, hI₂₃⟩ := h₂₃ hI₂
⟨I₃, hI₃, hI₁₂.trans hI₂₃⟩
le_antisymm :=
by
suffices : ∀ {π₁ π₂ : prepartition I}, π₁ ≤ π₂ → π₂ ≤ π₁ → π₁.boxes ⊆ π₂.boxes
exact fun π₁ π₂ h₁ h₂ => injective_boxes (subset.antisymm (this h₁ h₂) (this h₂ h₁))
intro π₁ π₂ h₁ h₂ J hJ
rcases h₁ hJ with ⟨J', hJ', hle⟩; rcases h₂ hJ' with ⟨J'', hJ'', hle'⟩
obtain rfl : J = J''; exact π₁.eq_of_le hJ hJ'' (hle.trans hle')
obtain rfl : J' = J; exact le_antisymm ‹_› ‹_›
assumption
instance : OrderTop (Prepartition I)
where
top := single I I le_rfl
le_top π J hJ := ⟨I, by simp, π.le_of_mem hJ⟩
instance : OrderBot (Prepartition I)
where
bot := ⟨∅, fun J hJ => False.elim hJ, fun J hJ => False.elim hJ⟩
bot_le π J hJ := False.elim hJ
instance : Inhabited (Prepartition I) :=
⟨⊤⟩
theorem le_def : π₁ ≤ π₂ ↔ ∀ J ∈ π₁, ∃ J' ∈ π₂, J ≤ J' :=
Iff.rfl
#align box_integral.prepartition.le_def BoxIntegral.Prepartition.le_def
@[simp]
theorem mem_top : J ∈ (⊤ : Prepartition I) ↔ J = I :=
mem_singleton
#align box_integral.prepartition.mem_top BoxIntegral.Prepartition.mem_top
@[simp]
theorem top_boxes : (⊤ : Prepartition I).boxes = {I} :=
rfl
#align box_integral.prepartition.top_boxes BoxIntegral.Prepartition.top_boxes
@[simp]
theorem not_mem_bot : J ∉ (⊥ : Prepartition I) :=
id
#align box_integral.prepartition.not_mem_bot BoxIntegral.Prepartition.not_mem_bot
@[simp]
theorem bot_boxes : (⊥ : Prepartition I).boxes = ∅ :=
rfl
#align box_integral.prepartition.bot_boxes BoxIntegral.Prepartition.bot_boxes
/-- An auxiliary lemma used to prove that the same point can't belong to more than
`2 ^ fintype.card ι` closed boxes of a prepartition. -/
theorem injOn_setOf_mem_icc_setOf_lower_eq (x : ι → ℝ) :
InjOn (fun J : Box ι => { i | J.lower i = x i }) { J | J ∈ π ∧ x ∈ J.Icc } :=
by
rintro J₁ ⟨h₁, hx₁⟩ J₂ ⟨h₂, hx₂⟩ (H : { i | J₁.lower i = x i } = { i | J₂.lower i = x i })
suffices ∀ i, (Ioc (J₁.lower i) (J₁.upper i) ∩ Ioc (J₂.lower i) (J₂.upper i)).Nonempty
by
choose y hy₁ hy₂
exact π.eq_of_mem_of_mem h₁ h₂ hy₁ hy₂
intro i
simp only [Set.ext_iff, mem_set_of_eq] at H
cases' (hx₁.1 i).eq_or_lt with hi₁ hi₁
· have hi₂ : J₂.lower i = x i := (H _).1 hi₁
have H₁ : x i < J₁.upper i := by simpa only [hi₁] using J₁.lower_lt_upper i
have H₂ : x i < J₂.upper i := by simpa only [hi₂] using J₂.lower_lt_upper i
rw [Ioc_inter_Ioc, hi₁, hi₂, sup_idem, Set.nonempty_Ioc]
exact lt_min H₁ H₂
· have hi₂ : J₂.lower i < x i := (hx₂.1 i).lt_of_ne (mt (H _).2 hi₁.ne)
exact ⟨x i, ⟨hi₁, hx₁.2 i⟩, ⟨hi₂, hx₂.2 i⟩⟩
#align box_integral.prepartition.inj_on_set_of_mem_Icc_set_of_lower_eq BoxIntegral.Prepartition.injOn_setOf_mem_icc_setOf_lower_eq
/-- The set of boxes of a prepartition that contain `x` in their closures has cardinality
at most `2 ^ fintype.card ι`. -/
theorem card_filter_mem_icc_le [Fintype ι] (x : ι → ℝ) :
(π.boxes.filterₓ fun J : Box ι => x ∈ J.Icc).card ≤ 2 ^ Fintype.card ι :=
by
rw [← Fintype.card_set]
refine'
Finset.card_le_card_of_inj_on (fun J : box ι => { i | J.lower i = x i })
(fun _ _ => Finset.mem_univ _) _
simpa only [Finset.mem_filter] using π.inj_on_set_of_mem_Icc_set_of_lower_eq x
#align box_integral.prepartition.card_filter_mem_Icc_le BoxIntegral.Prepartition.card_filter_mem_icc_le
/-- Given a prepartition `π : box_integral.prepartition I`, `π.Union` is the part of `I` covered by
the boxes of `π`. -/
protected def union : Set (ι → ℝ) :=
⋃ J ∈ π, ↑J
#align box_integral.prepartition.Union BoxIntegral.Prepartition.union
theorem union_def : π.unionᵢ = ⋃ J ∈ π, ↑J :=
rfl
#align box_integral.prepartition.Union_def BoxIntegral.Prepartition.union_def
theorem union_def' : π.unionᵢ = ⋃ J ∈ π.boxes, ↑J :=
rfl
#align box_integral.prepartition.Union_def' BoxIntegral.Prepartition.union_def'
@[simp]
theorem mem_union : x ∈ π.unionᵢ ↔ ∃ J ∈ π, x ∈ J :=
Set.mem_unionᵢ₂
#align box_integral.prepartition.mem_Union BoxIntegral.Prepartition.mem_union
@[simp]
theorem union_single (h : J ≤ I) : (single I J h).unionᵢ = J := by simp [Union_def]
#align box_integral.prepartition.Union_single BoxIntegral.Prepartition.union_single
@[simp]
theorem union_top : (⊤ : Prepartition I).unionᵢ = I := by simp [prepartition.Union]
#align box_integral.prepartition.Union_top BoxIntegral.Prepartition.union_top
@[simp]
theorem union_eq_empty : π₁.unionᵢ = ∅ ↔ π₁ = ⊥ := by
simp [← injective_boxes.eq_iff, Finset.ext_iff, prepartition.Union, imp_false]
#align box_integral.prepartition.Union_eq_empty BoxIntegral.Prepartition.union_eq_empty
@[simp]
theorem union_bot : (⊥ : Prepartition I).unionᵢ = ∅ :=
union_eq_empty.2 rfl
#align box_integral.prepartition.Union_bot BoxIntegral.Prepartition.union_bot
theorem subset_union (h : J ∈ π) : ↑J ⊆ π.unionᵢ :=
subset_bunionᵢ_of_mem h
#align box_integral.prepartition.subset_Union BoxIntegral.Prepartition.subset_union
theorem union_subset : π.unionᵢ ⊆ I :=
unionᵢ₂_subset π.le_of_mem'
#align box_integral.prepartition.Union_subset BoxIntegral.Prepartition.union_subset
@[mono]
theorem union_mono (h : π₁ ≤ π₂) : π₁.unionᵢ ⊆ π₂.unionᵢ := fun x hx =>
let ⟨J₁, hJ₁, hx⟩ := π₁.mem_unionᵢ.1 hx
let ⟨J₂, hJ₂, hle⟩ := h hJ₁
π₂.mem_unionᵢ.2 ⟨J₂, hJ₂, hle hx⟩
#align box_integral.prepartition.Union_mono BoxIntegral.Prepartition.union_mono
theorem disjoint_boxes_of_disjoint_union (h : Disjoint π₁.unionᵢ π₂.unionᵢ) :
Disjoint π₁.boxes π₂.boxes :=
Finset.disjoint_left.2 fun J h₁ h₂ =>
Disjoint.le_bot (h.mono (π₁.subset_unionᵢ h₁) (π₂.subset_unionᵢ h₂)) ⟨J.upper_mem, J.upper_mem⟩
#align box_integral.prepartition.disjoint_boxes_of_disjoint_Union BoxIntegral.Prepartition.disjoint_boxes_of_disjoint_union
theorem le_iff_nonempty_imp_le_and_union_subset :
π₁ ≤ π₂ ↔
(∀ J ∈ π₁, ∀ J' ∈ π₂, (J ∩ J' : Set (ι → ℝ)).Nonempty → J ≤ J') ∧ π₁.unionᵢ ⊆ π₂.unionᵢ :=
by
fconstructor
· refine' fun H => ⟨fun J hJ J' hJ' Hne => _, Union_mono H⟩
rcases H hJ with ⟨J'', hJ'', Hle⟩
rcases Hne with ⟨x, hx, hx'⟩
rwa [π₂.eq_of_mem_of_mem hJ' hJ'' hx' (Hle hx)]
· rintro ⟨H, HU⟩ J hJ
simp only [Set.subset_def, mem_Union] at HU
rcases HU J.upper ⟨J, hJ, J.upper_mem⟩ with ⟨J₂, hJ₂, hx⟩
exact ⟨J₂, hJ₂, H _ hJ _ hJ₂ ⟨_, J.upper_mem, hx⟩⟩
#align box_integral.prepartition.le_iff_nonempty_imp_le_and_Union_subset BoxIntegral.Prepartition.le_iff_nonempty_imp_le_and_union_subset
theorem eq_of_boxes_subset_union_superset (h₁ : π₁.boxes ⊆ π₂.boxes) (h₂ : π₂.unionᵢ ⊆ π₁.unionᵢ) :
π₁ = π₂ :=
(le_antisymm fun J hJ => ⟨J, h₁ hJ, le_rfl⟩) <|
le_iff_nonempty_imp_le_and_union_subset.2
⟨fun J₁ hJ₁ J₂ hJ₂ Hne =>
(π₂.eq_of_mem_of_mem hJ₁ (h₁ hJ₂) Hne.choose_spec.1 Hne.choose_spec.2).le, h₂⟩
#align box_integral.prepartition.eq_of_boxes_subset_Union_superset BoxIntegral.Prepartition.eq_of_boxes_subset_union_superset
/-- Given a prepartition `π` of a box `I` and a collection of prepartitions `πi J` of all boxes
`J ∈ π`, returns the prepartition of `I` into the union of the boxes of all `πi J`.
Though we only use the values of `πi` on the boxes of `π`, we require `πi` to be a globally defined
function. -/
@[simps]
def bUnion (πi : ∀ J : Box ι, Prepartition J) : Prepartition I
where
boxes := π.boxes.bunionᵢ fun J => (πi J).boxes
le_of_mem' J hJ :=
by
simp only [Finset.mem_bunionᵢ, exists_prop, mem_boxes] at hJ
rcases hJ with ⟨J', hJ', hJ⟩
exact ((πi J').le_of_mem hJ).trans (π.le_of_mem hJ')
PairwiseDisjoint :=
by
simp only [Set.Pairwise, Finset.mem_coe, Finset.mem_bunionᵢ]
rintro J₁' ⟨J₁, hJ₁, hJ₁'⟩ J₂' ⟨J₂, hJ₂, hJ₂'⟩ Hne
rw [Function.onFun, Set.disjoint_left]
rintro x hx₁ hx₂; apply Hne
obtain rfl : J₁ = J₂
exact π.eq_of_mem_of_mem hJ₁ hJ₂ ((πi J₁).le_of_mem hJ₁' hx₁) ((πi J₂).le_of_mem hJ₂' hx₂)
exact (πi J₁).eq_of_mem_of_mem hJ₁' hJ₂' hx₁ hx₂
#align box_integral.prepartition.bUnion BoxIntegral.Prepartition.bUnion
variable {πi πi₁ πi₂ : ∀ J : Box ι, Prepartition J}
@[simp]
theorem mem_bUnion : J ∈ π.bunionᵢ πi ↔ ∃ J' ∈ π, J ∈ πi J' := by simp [bUnion]
#align box_integral.prepartition.mem_bUnion BoxIntegral.Prepartition.mem_bUnion
theorem bUnion_le (πi : ∀ J, Prepartition J) : π.bunionᵢ πi ≤ π := fun J hJ =>
let ⟨J', hJ', hJ⟩ := π.mem_bunionᵢ.1 hJ
⟨J', hJ', (πi J').le_of_mem hJ⟩
#align box_integral.prepartition.bUnion_le BoxIntegral.Prepartition.bUnion_le
@[simp]
theorem bUnion_top : (π.bunionᵢ fun _ => ⊤) = π :=
by
ext
simp
#align box_integral.prepartition.bUnion_top BoxIntegral.Prepartition.bUnion_top
@[congr]
theorem bUnion_congr (h : π₁ = π₂) (hi : ∀ J ∈ π₁, πi₁ J = πi₂ J) :
π₁.bunionᵢ πi₁ = π₂.bunionᵢ πi₂ := by
subst π₂
ext J
simp (config := { contextual := true }) [hi]
#align box_integral.prepartition.bUnion_congr BoxIntegral.Prepartition.bUnion_congr
theorem bUnion_congr_of_le (h : π₁ = π₂) (hi : ∀ J ≤ I, πi₁ J = πi₂ J) :
π₁.bunionᵢ πi₁ = π₂.bunionᵢ πi₂ :=
bUnion_congr h fun J hJ => hi J (π₁.le_of_mem hJ)
#align box_integral.prepartition.bUnion_congr_of_le BoxIntegral.Prepartition.bUnion_congr_of_le
@[simp]
theorem union_bUnion (πi : ∀ J : Box ι, Prepartition J) :
(π.bunionᵢ πi).unionᵢ = ⋃ J ∈ π, (πi J).unionᵢ := by simp [prepartition.Union]
#align box_integral.prepartition.Union_bUnion BoxIntegral.Prepartition.union_bUnion
@[simp]
theorem sum_bunionᵢ_boxes {M : Type _} [AddCommMonoid M] (π : Prepartition I)
(πi : ∀ J, Prepartition J) (f : Box ι → M) :
(∑ J in π.boxes.bunionᵢ fun J => (πi J).boxes, f J) =
∑ J in π.boxes, ∑ J' in (πi J).boxes, f J' :=
by
refine' Finset.sum_bunionᵢ fun J₁ h₁ J₂ h₂ hne => Finset.disjoint_left.2 fun J' h₁' h₂' => _
exact hne (π.eq_of_le_of_le h₁ h₂ ((πi J₁).le_of_mem h₁') ((πi J₂).le_of_mem h₂'))
#align box_integral.prepartition.sum_bUnion_boxes BoxIntegral.Prepartition.sum_bunionᵢ_boxes
/-- Given a box `J ∈ π.bUnion πi`, returns the box `J' ∈ π` such that `J ∈ πi J'`.
For `J ∉ π.bUnion πi`, returns `I`. -/
def bUnionIndex (πi : ∀ J, Prepartition J) (J : Box ι) : Box ι :=
if hJ : J ∈ π.bunionᵢ πi then (π.mem_bunionᵢ.1 hJ).some else I
#align box_integral.prepartition.bUnion_index BoxIntegral.Prepartition.bUnionIndex
theorem bUnionIndex_mem (hJ : J ∈ π.bunionᵢ πi) : π.bUnionIndex πi J ∈ π :=
by
rw [bUnion_index, dif_pos hJ]
exact (π.mem_bUnion.1 hJ).choose_spec.fst
#align box_integral.prepartition.bUnion_index_mem BoxIntegral.Prepartition.bUnionIndex_mem
theorem bUnionIndex_le (πi : ∀ J, Prepartition J) (J : Box ι) : π.bUnionIndex πi J ≤ I :=
by
by_cases hJ : J ∈ π.bUnion πi
· exact π.le_of_mem (π.bUnion_index_mem hJ)
· rw [bUnion_index, dif_neg hJ]
exact le_rfl
#align box_integral.prepartition.bUnion_index_le BoxIntegral.Prepartition.bUnionIndex_le
theorem mem_bUnionIndex (hJ : J ∈ π.bunionᵢ πi) : J ∈ πi (π.bUnionIndex πi J) := by
convert(π.mem_bUnion.1 hJ).choose_spec.snd <;> exact dif_pos hJ
#align box_integral.prepartition.mem_bUnion_index BoxIntegral.Prepartition.mem_bUnionIndex
theorem le_bUnionIndex (hJ : J ∈ π.bunionᵢ πi) : J ≤ π.bUnionIndex πi J :=
le_of_mem _ (π.mem_bUnionIndex hJ)
#align box_integral.prepartition.le_bUnion_index BoxIntegral.Prepartition.le_bUnionIndex
/-- Uniqueness property of `box_integral.partition.bUnion_index`. -/
theorem bUnionIndex_of_mem (hJ : J ∈ π) {J'} (hJ' : J' ∈ πi J) : π.bUnionIndex πi J' = J :=
have : J' ∈ π.bunionᵢ πi := π.mem_bunionᵢ.2 ⟨J, hJ, hJ'⟩
π.eq_of_le_of_le (π.bUnionIndex_mem this) hJ (π.le_bUnionIndex this) (le_of_mem _ hJ')
#align box_integral.prepartition.bUnion_index_of_mem BoxIntegral.Prepartition.bUnionIndex_of_mem
theorem bUnion_assoc (πi : ∀ J, Prepartition J) (πi' : Box ι → ∀ J : Box ι, Prepartition J) :
(π.bunionᵢ fun J => (πi J).bunionᵢ (πi' J)) =
(π.bunionᵢ πi).bunionᵢ fun J => πi' (π.bUnionIndex πi J) J :=
by
ext J
simp only [mem_bUnion, exists_prop]
fconstructor
· rintro ⟨J₁, hJ₁, J₂, hJ₂, hJ⟩
refine' ⟨J₂, ⟨J₁, hJ₁, hJ₂⟩, _⟩
rwa [π.bUnion_index_of_mem hJ₁ hJ₂]
· rintro ⟨J₁, ⟨J₂, hJ₂, hJ₁⟩, hJ⟩
refine' ⟨J₂, hJ₂, J₁, hJ₁, _⟩
rwa [π.bUnion_index_of_mem hJ₂ hJ₁] at hJ
#align box_integral.prepartition.bUnion_assoc BoxIntegral.Prepartition.bUnion_assoc
/-- Create a `box_integral.prepartition` from a collection of possibly empty boxes by filtering out
the empty one if it exists. -/
def ofWithBot (boxes : Finset (WithBot (Box ι)))
(le_of_mem : ∀ J ∈ boxes, (J : WithBot (Box ι)) ≤ I)
(pairwise_disjoint : Set.Pairwise (boxes : Set (WithBot (Box ι))) Disjoint) : Prepartition I
where
boxes := boxes.eraseNone
le_of_mem' J hJ := by
rw [mem_erase_none] at hJ
simpa only [WithBot.some_eq_coe, WithBot.coe_le_coe] using le_of_mem _ hJ
PairwiseDisjoint J₁ h₁ J₂ h₂ hne :=
by
simp only [mem_coe, mem_erase_none] at h₁ h₂
exact box.disjoint_coe.1 (pairwise_disjoint h₁ h₂ (mt Option.some_inj.1 hne))
#align box_integral.prepartition.of_with_bot BoxIntegral.Prepartition.ofWithBot
@[simp]
theorem mem_ofWithBot {boxes : Finset (WithBot (Box ι))} {h₁ h₂} :
J ∈ (ofWithBot boxes h₁ h₂ : Prepartition I) ↔ (J : WithBot (Box ι)) ∈ boxes :=
mem_eraseNone
#align box_integral.prepartition.mem_of_with_bot BoxIntegral.Prepartition.mem_ofWithBot
@[simp]
theorem union_ofWithBot (boxes : Finset (WithBot (Box ι)))
(le_of_mem : ∀ J ∈ boxes, (J : WithBot (Box ι)) ≤ I)
(pairwise_disjoint : Set.Pairwise (boxes : Set (WithBot (Box ι))) Disjoint) :
(ofWithBot boxes le_of_mem pairwise_disjoint).unionᵢ = ⋃ J ∈ boxes, ↑J :=
by
suffices (⋃ (J : box ι) (hJ : ↑J ∈ boxes), ↑J) = ⋃ J ∈ boxes, ↑J by
simpa [of_with_bot, prepartition.Union]
simp only [← box.bUnion_coe_eq_coe, @Union_comm _ _ (box ι), @Union_comm _ _ (@Eq _ _ _),
Union_Union_eq_right]
#align box_integral.prepartition.Union_of_with_bot BoxIntegral.Prepartition.union_ofWithBot
theorem ofWithBot_le {boxes : Finset (WithBot (Box ι))}
{le_of_mem : ∀ J ∈ boxes, (J : WithBot (Box ι)) ≤ I}
{pairwise_disjoint : Set.Pairwise (boxes : Set (WithBot (Box ι))) Disjoint}
(H : ∀ J ∈ boxes, J ≠ ⊥ → ∃ J' ∈ π, J ≤ ↑J') :
ofWithBot boxes le_of_mem pairwise_disjoint ≤ π :=
by
have : ∀ J : Box ι, ↑J ∈ boxes → ∃ J' ∈ π, J ≤ J' := fun J hJ => by
simpa only [WithBot.coe_le_coe] using H J hJ WithBot.coe_ne_bot
simpa [of_with_bot, le_def]
#align box_integral.prepartition.of_with_bot_le BoxIntegral.Prepartition.ofWithBot_le
theorem le_ofWithBot {boxes : Finset (WithBot (Box ι))}
{le_of_mem : ∀ J ∈ boxes, (J : WithBot (Box ι)) ≤ I}
{pairwise_disjoint : Set.Pairwise (boxes : Set (WithBot (Box ι))) Disjoint}
(H : ∀ J ∈ π, ∃ J' ∈ boxes, ↑J ≤ J') : π ≤ ofWithBot boxes le_of_mem pairwise_disjoint :=
by
intro J hJ
rcases H J hJ with ⟨J', J'mem, hle⟩
lift J' to box ι using ne_bot_of_le_ne_bot WithBot.coe_ne_bot hle
exact ⟨J', mem_of_with_bot.2 J'mem, WithBot.coe_le_coe.1 hle⟩
#align box_integral.prepartition.le_of_with_bot BoxIntegral.Prepartition.le_ofWithBot
theorem ofWithBot_mono {boxes₁ : Finset (WithBot (Box ι))}
{le_of_mem₁ : ∀ J ∈ boxes₁, (J : WithBot (Box ι)) ≤ I}
{pairwise_disjoint₁ : Set.Pairwise (boxes₁ : Set (WithBot (Box ι))) Disjoint}
{boxes₂ : Finset (WithBot (Box ι))} {le_of_mem₂ : ∀ J ∈ boxes₂, (J : WithBot (Box ι)) ≤ I}
{pairwise_disjoint₂ : Set.Pairwise (boxes₂ : Set (WithBot (Box ι))) Disjoint}
(H : ∀ J ∈ boxes₁, J ≠ ⊥ → ∃ J' ∈ boxes₂, J ≤ J') :
ofWithBot boxes₁ le_of_mem₁ pairwise_disjoint₁ ≤
ofWithBot boxes₂ le_of_mem₂ pairwise_disjoint₂ :=
le_ofWithBot _ fun J hJ => H J (mem_ofWithBot.1 hJ) WithBot.coe_ne_bot
#align box_integral.prepartition.of_with_bot_mono BoxIntegral.Prepartition.ofWithBot_mono
theorem sum_ofWithBot {M : Type _} [AddCommMonoid M] (boxes : Finset (WithBot (Box ι)))
(le_of_mem : ∀ J ∈ boxes, (J : WithBot (Box ι)) ≤ I)
(pairwise_disjoint : Set.Pairwise (boxes : Set (WithBot (Box ι))) Disjoint) (f : Box ι → M) :
(∑ J in (ofWithBot boxes le_of_mem pairwise_disjoint).boxes, f J) =
∑ J in boxes, Option.elim' 0 f J :=
Finset.sum_eraseNone _ _
#align box_integral.prepartition.sum_of_with_bot BoxIntegral.Prepartition.sum_ofWithBot
/-- Restrict a prepartition to a box. -/
def restrict (π : Prepartition I) (J : Box ι) : Prepartition J :=
ofWithBot (π.boxes.image fun J' => J ⊓ J')
(fun J' hJ' => by
rcases Finset.mem_image.1 hJ' with ⟨J', -, rfl⟩
exact inf_le_left)
(by
simp only [Set.Pairwise, on_fun, Finset.mem_coe, Finset.mem_image]
rintro _ ⟨J₁, h₁, rfl⟩ _ ⟨J₂, h₂, rfl⟩ Hne
have : J₁ ≠ J₂ := by
rintro rfl
exact Hne rfl
exact ((box.disjoint_coe.2 <| π.disjoint_coe_of_mem h₁ h₂ this).inf_left' _).inf_right' _)
#align box_integral.prepartition.restrict BoxIntegral.Prepartition.restrict
@[simp]
theorem mem_restrict : J₁ ∈ π.restrict J ↔ ∃ J' ∈ π, (J₁ : WithBot (Box ι)) = J ⊓ J' := by
simp [restrict, eq_comm]
#align box_integral.prepartition.mem_restrict BoxIntegral.Prepartition.mem_restrict
theorem mem_restrict' : J₁ ∈ π.restrict J ↔ ∃ J' ∈ π, (J₁ : Set (ι → ℝ)) = J ∩ J' := by
simp only [mem_restrict, ← box.with_bot_coe_inj, box.coe_inf, box.coe_coe]
#align box_integral.prepartition.mem_restrict' BoxIntegral.Prepartition.mem_restrict'
@[mono]
theorem restrict_mono {π₁ π₂ : Prepartition I} (Hle : π₁ ≤ π₂) : π₁.restrict J ≤ π₂.restrict J :=
by
refine' of_with_bot_mono fun J₁ hJ₁ hne => _
rw [Finset.mem_image] at hJ₁; rcases hJ₁ with ⟨J₁, hJ₁, rfl⟩
rcases Hle hJ₁ with ⟨J₂, hJ₂, hle⟩
exact ⟨_, Finset.mem_image_of_mem _ hJ₂, inf_le_inf_left _ <| WithBot.coe_le_coe.2 hle⟩
#align box_integral.prepartition.restrict_mono BoxIntegral.Prepartition.restrict_mono
theorem monotone_restrict : Monotone fun π : Prepartition I => restrict π J := fun π₁ π₂ =>
restrict_mono
#align box_integral.prepartition.monotone_restrict BoxIntegral.Prepartition.monotone_restrict
/-- Restricting to a larger box does not change the set of boxes. We cannot claim equality
of prepartitions because they have different types. -/
theorem restrict_boxes_of_le (π : Prepartition I) (h : I ≤ J) : (π.restrict J).boxes = π.boxes :=
by
simp only [restrict, of_with_bot, erase_none_eq_bUnion]
refine' finset.image_bUnion.trans _
refine' (Finset.bunionᵢ_congr rfl _).trans Finset.bunionᵢ_singleton_eq_self
intro J' hJ'
rw [inf_of_le_right, ← WithBot.some_eq_coe, Option.toFinset_some]
exact WithBot.coe_le_coe.2 ((π.le_of_mem hJ').trans h)
#align box_integral.prepartition.restrict_boxes_of_le BoxIntegral.Prepartition.restrict_boxes_of_le
@[simp]
theorem restrict_self : π.restrict I = π :=
injective_boxes <| restrict_boxes_of_le π le_rfl
#align box_integral.prepartition.restrict_self BoxIntegral.Prepartition.restrict_self
@[simp]
theorem union_restrict : (π.restrict J).unionᵢ = J ∩ π.unionᵢ := by
simp [restrict, ← inter_Union, ← Union_def]
#align box_integral.prepartition.Union_restrict BoxIntegral.Prepartition.union_restrict
@[simp]
theorem restrict_bUnion (πi : ∀ J, Prepartition J) (hJ : J ∈ π) :
(π.bunionᵢ πi).restrict J = πi J :=
by
refine' (eq_of_boxes_subset_Union_superset (fun J₁ h₁ => _) _).symm
· refine' (mem_restrict _).2 ⟨J₁, π.mem_bUnion.2 ⟨J, hJ, h₁⟩, (inf_of_le_right _).symm⟩
exact WithBot.coe_le_coe.2 (le_of_mem _ h₁)
· simp only [Union_restrict, Union_bUnion, Set.subset_def, Set.mem_inter_iff, Set.mem_unionᵢ]
rintro x ⟨hxJ, J₁, h₁, hx⟩
obtain rfl : J = J₁
exact π.eq_of_mem_of_mem hJ h₁ hxJ (Union_subset _ hx)
exact hx
#align box_integral.prepartition.restrict_bUnion BoxIntegral.Prepartition.restrict_bUnion
theorem bUnion_le_iff {πi : ∀ J, Prepartition J} {π' : Prepartition I} :
π.bunionᵢ πi ≤ π' ↔ ∀ J ∈ π, πi J ≤ π'.restrict J :=
by
fconstructor <;> intro H J hJ
· rw [← π.restrict_bUnion πi hJ]
exact restrict_mono H
· rw [mem_bUnion] at hJ
rcases hJ with ⟨J₁, h₁, hJ⟩
rcases H J₁ h₁ hJ with ⟨J₂, h₂, Hle⟩
rcases π'.mem_restrict.mp h₂ with ⟨J₃, h₃, H⟩
exact ⟨J₃, h₃, Hle.trans <| WithBot.coe_le_coe.1 <| H.trans_le inf_le_right⟩
#align box_integral.prepartition.bUnion_le_iff BoxIntegral.Prepartition.bUnion_le_iff
theorem le_bUnion_iff {πi : ∀ J, Prepartition J} {π' : Prepartition I} :
π' ≤ π.bunionᵢ πi ↔ π' ≤ π ∧ ∀ J ∈ π, π'.restrict J ≤ πi J :=
by
refine' ⟨fun H => ⟨H.trans (π.bUnion_le πi), fun J hJ => _⟩, _⟩
· rw [← π.restrict_bUnion πi hJ]
exact restrict_mono H
· rintro ⟨H, Hi⟩ J' hJ'
rcases H hJ' with ⟨J, hJ, hle⟩
have : J' ∈ π'.restrict J :=
π'.mem_restrict.2 ⟨J', hJ', (inf_of_le_right <| WithBot.coe_le_coe.2 hle).symm⟩
rcases Hi J hJ this with ⟨Ji, hJi, hlei⟩
exact ⟨Ji, π.mem_bUnion.2 ⟨J, hJ, hJi⟩, hlei⟩
#align box_integral.prepartition.le_bUnion_iff BoxIntegral.Prepartition.le_bUnion_iff
instance : Inf (Prepartition I) :=
⟨fun π₁ π₂ => π₁.bunionᵢ fun J => π₂.restrict J⟩
theorem inf_def (π₁ π₂ : Prepartition I) : π₁ ⊓ π₂ = π₁.bunionᵢ fun J => π₂.restrict J :=
rfl
#align box_integral.prepartition.inf_def BoxIntegral.Prepartition.inf_def
@[simp]
theorem mem_inf {π₁ π₂ : Prepartition I} :
J ∈ π₁ ⊓ π₂ ↔ ∃ J₁ ∈ π₁, ∃ J₂ ∈ π₂, (J : WithBot (Box ι)) = J₁ ⊓ J₂ := by
simp only [inf_def, mem_bUnion, mem_restrict]
#align box_integral.prepartition.mem_inf BoxIntegral.Prepartition.mem_inf
@[simp]
theorem union_inf (π₁ π₂ : Prepartition I) : (π₁ ⊓ π₂).unionᵢ = π₁.unionᵢ ∩ π₂.unionᵢ := by
simp only [inf_def, Union_bUnion, Union_restrict, ← Union_inter, ← Union_def]
#align box_integral.prepartition.Union_inf BoxIntegral.Prepartition.union_inf
instance : SemilatticeInf (Prepartition I) :=
{ Prepartition.hasInf,
Prepartition.partialOrder with
inf_le_left := fun π₁ π₂ => π₁.bUnion_le _
inf_le_right := fun π₁ π₂ => (bUnion_le_iff _).2 fun J hJ => le_rfl
le_inf := fun π π₁ π₂ h₁ h₂ => π₁.le_bUnion_iff.2 ⟨h₁, fun J hJ => restrict_mono h₂⟩ }
/-- The prepartition with boxes `{J ∈ π | p J}`. -/
@[simps]
def filter (π : Prepartition I) (p : Box ι → Prop) : Prepartition I
where
boxes := π.boxes.filterₓ p
le_of_mem' J hJ := π.le_of_mem (mem_filter.1 hJ).1
PairwiseDisjoint J₁ h₁ J₂ h₂ := π.disjoint_coe_of_mem (mem_filter.1 h₁).1 (mem_filter.1 h₂).1
#align box_integral.prepartition.filter BoxIntegral.Prepartition.filter
@[simp]
theorem mem_filter {p : Box ι → Prop} : J ∈ π.filterₓ p ↔ J ∈ π ∧ p J :=
Finset.mem_filter
#align box_integral.prepartition.mem_filter BoxIntegral.Prepartition.mem_filter
theorem filter_le (π : Prepartition I) (p : Box ι → Prop) : π.filterₓ p ≤ π := fun J hJ =>
let ⟨hπ, hp⟩ := π.mem_filter.1 hJ
⟨J, hπ, le_rfl⟩
#align box_integral.prepartition.filter_le BoxIntegral.Prepartition.filter_le
theorem filter_of_true {p : Box ι → Prop} (hp : ∀ J ∈ π, p J) : π.filterₓ p = π :=
by
ext J
simpa using hp J
#align box_integral.prepartition.filter_of_true BoxIntegral.Prepartition.filter_of_true
@[simp]
theorem filter_true : (π.filterₓ fun _ => True) = π :=
π.filter_of_true fun _ _ => trivial
#align box_integral.prepartition.filter_true BoxIntegral.Prepartition.filter_true
@[simp]
theorem union_filter_not (π : Prepartition I) (p : Box ι → Prop) :
(π.filterₓ fun J => ¬p J).unionᵢ = π.unionᵢ \ (π.filterₓ p).unionᵢ :=
by
simp only [prepartition.Union]
convert(@Set.bunionᵢ_diff_bunionᵢ_eq _ (box ι) π.boxes (π.filter p).boxes coe _).symm
· ext (J x)
simp (config := { contextual := true })
· convert π.pairwise_disjoint
simp
#align box_integral.prepartition.Union_filter_not BoxIntegral.Prepartition.union_filter_not
theorem sum_fiberwise {α M} [AddCommMonoid M] (π : Prepartition I) (f : Box ι → α) (g : Box ι → M) :
(∑ y in π.boxes.image f, ∑ J in (π.filterₓ fun J => f J = y).boxes, g J) =
∑ J in π.boxes, g J :=
by convert sum_fiberwise_of_maps_to (fun _ => Finset.mem_image_of_mem f) g
#align box_integral.prepartition.sum_fiberwise BoxIntegral.Prepartition.sum_fiberwise
/-- Union of two disjoint prepartitions. -/
@[simps]
def disjUnion (π₁ π₂ : Prepartition I) (h : Disjoint π₁.unionᵢ π₂.unionᵢ) : Prepartition I
where
boxes := π₁.boxes ∪ π₂.boxes
le_of_mem' J hJ := (Finset.mem_union.1 hJ).elim π₁.le_of_mem π₂.le_of_mem
PairwiseDisjoint :=
suffices ∀ J₁ ∈ π₁, ∀ J₂ ∈ π₂, J₁ ≠ J₂ → Disjoint (J₁ : Set (ι → ℝ)) J₂ by
simpa [pairwise_union_of_symmetric (symmetric_disjoint.comap _), pairwise_disjoint]
fun J₁ h₁ J₂ h₂ _ => h.mono (π₁.subset_unionᵢ h₁) (π₂.subset_unionᵢ h₂)
#align box_integral.prepartition.disj_union BoxIntegral.Prepartition.disjUnion
@[simp]
theorem mem_disjUnion (H : Disjoint π₁.unionᵢ π₂.unionᵢ) :
J ∈ π₁.disjUnion π₂ H ↔ J ∈ π₁ ∨ J ∈ π₂ :=
Finset.mem_union
#align box_integral.prepartition.mem_disj_union BoxIntegral.Prepartition.mem_disjUnion
@[simp]
theorem union_disjUnion (h : Disjoint π₁.unionᵢ π₂.unionᵢ) :
(π₁.disjUnion π₂ h).unionᵢ = π₁.unionᵢ ∪ π₂.unionᵢ := by
simp [disj_union, prepartition.Union, Union_or, Union_union_distrib]
#align box_integral.prepartition.Union_disj_union BoxIntegral.Prepartition.union_disjUnion
@[simp]
theorem sum_disj_union_boxes {M : Type _} [AddCommMonoid M] (h : Disjoint π₁.unionᵢ π₂.unionᵢ)
(f : Box ι → M) :
(∑ J in π₁.boxes ∪ π₂.boxes, f J) = (∑ J in π₁.boxes, f J) + ∑ J in π₂.boxes, f J :=
sum_union <| disjoint_boxes_of_disjoint_union h
#align box_integral.prepartition.sum_disj_union_boxes BoxIntegral.Prepartition.sum_disj_union_boxes
section Distortion
variable [Fintype ι]
/-- The distortion of a prepartition is the maximum of the distortions of the boxes of this
prepartition. -/
def distortion : ℝ≥0 :=
π.boxes.sup Box.distortion
#align box_integral.prepartition.distortion BoxIntegral.Prepartition.distortion
theorem distortion_le_of_mem (h : J ∈ π) : J.distortion ≤ π.distortion :=
le_sup h
#align box_integral.prepartition.distortion_le_of_mem BoxIntegral.Prepartition.distortion_le_of_mem
theorem distortion_le_iff {c : ℝ≥0} : π.distortion ≤ c ↔ ∀ J ∈ π, Box.distortion J ≤ c :=
Finset.sup_le_iff
#align box_integral.prepartition.distortion_le_iff BoxIntegral.Prepartition.distortion_le_iff
theorem distortion_bUnion (π : Prepartition I) (πi : ∀ J, Prepartition J) :
(π.bunionᵢ πi).distortion = π.boxes.sup fun J => (πi J).distortion :=
sup_bunionᵢ _ _
#align box_integral.prepartition.distortion_bUnion BoxIntegral.Prepartition.distortion_bUnion
@[simp]
theorem distortion_disjUnion (h : Disjoint π₁.unionᵢ π₂.unionᵢ) :
(π₁.disjUnion π₂ h).distortion = max π₁.distortion π₂.distortion :=
sup_union
#align box_integral.prepartition.distortion_disj_union BoxIntegral.Prepartition.distortion_disjUnion
theorem distortion_of_const {c} (h₁ : π.boxes.Nonempty) (h₂ : ∀ J ∈ π, Box.distortion J = c) :
π.distortion = c :=
(sup_congr rfl h₂).trans (sup_const h₁ _)
#align box_integral.prepartition.distortion_of_const BoxIntegral.Prepartition.distortion_of_const
@[simp]
theorem distortion_top (I : Box ι) : distortion (⊤ : Prepartition I) = I.distortion :=
sup_singleton
#align box_integral.prepartition.distortion_top BoxIntegral.Prepartition.distortion_top
@[simp]
theorem distortion_bot (I : Box ι) : distortion (⊥ : Prepartition I) = 0 :=
sup_empty
#align box_integral.prepartition.distortion_bot BoxIntegral.Prepartition.distortion_bot
end Distortion
/-- A prepartition `π` of `I` is a partition if the boxes of `π` cover the whole `I`. -/
def IsPartition (π : Prepartition I) :=
∀ x ∈ I, ∃ J ∈ π, x ∈ J
#align box_integral.prepartition.is_partition BoxIntegral.Prepartition.IsPartition
theorem isPartition_iff_union_eq {π : Prepartition I} : π.IsPartition ↔ π.unionᵢ = I := by
simp_rw [is_partition, Set.Subset.antisymm_iff, π.Union_subset, true_and_iff, Set.subset_def,
mem_Union, box.mem_coe]
#align box_integral.prepartition.is_partition_iff_Union_eq BoxIntegral.Prepartition.isPartition_iff_union_eq
@[simp]
theorem isPartition_single_iff (h : J ≤ I) : IsPartition (single I J h) ↔ J = I := by
simp [is_partition_iff_Union_eq]
#align box_integral.prepartition.is_partition_single_iff BoxIntegral.Prepartition.isPartition_single_iff
theorem isPartitionTop (I : Box ι) : IsPartition (⊤ : Prepartition I) := fun x hx =>
⟨I, mem_top.2 rfl, hx⟩
#align box_integral.prepartition.is_partition_top BoxIntegral.Prepartition.isPartitionTop
namespace IsPartition
variable {π}
theorem union_eq (h : π.IsPartition) : π.unionᵢ = I :=
isPartition_iff_union_eq.1 h
#align box_integral.prepartition.is_partition.Union_eq BoxIntegral.Prepartition.IsPartition.union_eq
theorem union_subset (h : π.IsPartition) (π₁ : Prepartition I) : π₁.unionᵢ ⊆ π.unionᵢ :=
h.unionᵢ_eq.symm ▸ π₁.unionᵢ_subset
#align box_integral.prepartition.is_partition.Union_subset BoxIntegral.Prepartition.IsPartition.union_subset
/- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (J «expr ∈ » π) -/
protected theorem existsUnique (h : π.IsPartition) (hx : x ∈ I) : ∃! (J : _)(_ : J ∈ π), x ∈ J :=
by
rcases h x hx with ⟨J, h, hx⟩
exact ExistsUnique.intro₂ J h hx fun J' h' hx' => π.eq_of_mem_of_mem h' h hx' hx
#align box_integral.prepartition.is_partition.exists_unique BoxIntegral.Prepartition.IsPartition.existsUnique
theorem nonempty_boxes (h : π.IsPartition) : π.boxes.Nonempty :=
let ⟨J, hJ, _⟩ := h _ I.upper_mem
⟨J, hJ⟩
#align box_integral.prepartition.is_partition.nonempty_boxes BoxIntegral.Prepartition.IsPartition.nonempty_boxes
theorem eq_of_boxes_subset (h₁ : π₁.IsPartition) (h₂ : π₁.boxes ⊆ π₂.boxes) : π₁ = π₂ :=
eq_of_boxes_subset_union_superset h₂ <| h₁.unionᵢ_subset _
#align box_integral.prepartition.is_partition.eq_of_boxes_subset BoxIntegral.Prepartition.IsPartition.eq_of_boxes_subset
theorem le_iff (h : π₂.IsPartition) :
π₁ ≤ π₂ ↔ ∀ J ∈ π₁, ∀ J' ∈ π₂, (J ∩ J' : Set (ι → ℝ)).Nonempty → J ≤ J' :=
le_iff_nonempty_imp_le_and_union_subset.trans <| and_iff_left <| h.unionᵢ_subset _
#align box_integral.prepartition.is_partition.le_iff BoxIntegral.Prepartition.IsPartition.le_iff
protected theorem bUnion (h : IsPartition π) (hi : ∀ J ∈ π, IsPartition (πi J)) :
IsPartition (π.bunionᵢ πi) := fun x hx =>
let ⟨J, hJ, hxi⟩ := h x hx
let ⟨Ji, hJi, hx⟩ := hi J hJ x hxi
⟨Ji, π.mem_bunionᵢ.2 ⟨J, hJ, hJi⟩, hx⟩
#align box_integral.prepartition.is_partition.bUnion BoxIntegral.Prepartition.IsPartition.bUnion
protected theorem restrict (h : IsPartition π) (hJ : J ≤ I) : IsPartition (π.restrict J) :=
isPartition_iff_union_eq.2 <| by simp [h.Union_eq, hJ]
#align box_integral.prepartition.is_partition.restrict BoxIntegral.Prepartition.IsPartition.restrict
protected theorem inf (h₁ : IsPartition π₁) (h₂ : IsPartition π₂) : IsPartition (π₁ ⊓ π₂) :=
isPartition_iff_union_eq.2 <| by simp [h₁.Union_eq, h₂.Union_eq]
#align box_integral.prepartition.is_partition.inf BoxIntegral.Prepartition.IsPartition.inf
end IsPartition
theorem union_bUnion_partition (h : ∀ J ∈ π, (πi J).IsPartition) :
(π.bunionᵢ πi).unionᵢ = π.unionᵢ :=
(union_bUnion _ _).trans <|
unionᵢ_congr_of_surjective id surjective_id fun J =>
unionᵢ_congr_of_surjective id surjective_id fun hJ => (h J hJ).unionᵢ_eq
#align box_integral.prepartition.Union_bUnion_partition BoxIntegral.Prepartition.union_bUnion_partition
theorem isPartitionDisjUnionOfEqDiff (h : π₂.unionᵢ = I \ π₁.unionᵢ) :
IsPartition (π₁.disjUnion π₂ <| h.symm ▸ disjoint_sdiff_self_right) :=
isPartition_iff_union_eq.2 <| (union_disjUnion _).trans <| by simp [h, π₁.Union_subset]
#align box_integral.prepartition.is_partition_disj_union_of_eq_diff BoxIntegral.Prepartition.isPartitionDisjUnionOfEqDiff
end Prepartition
end BoxIntegral
|
module HankelTransform where
import Control.Parallel.Strategies
import Data.Array.Repa as R
import Data.Complex as C
import Data.List as L
import Data.Vector.Storable as VS
import Data.Vector.Unboxed as VU
import Graphics.Rendering.Chart.Backend.Cairo
import Graphics.Rendering.Chart.Easy
import Numeric.GSL.Special.Bessel
import System.Directory
import System.Environment
import System.FilePath
import Text.Printf
import Utils.BLAS
import Utils.List
import Utils.Parallel
main = do
args@(nStr:deltaXStr:deltaRStr:radiusXStr:radiusRStr:_) <- getArgs
let n = read nStr :: Int
deltaX = read deltaXStr :: Double
deltaR = read deltaRStr :: Double
radiusX = read radiusXStr :: Double
radiusR = read radiusRStr :: Double
folderPath = "output/test/HankelTransform"
createDirectoryIfMissing True folderPath
let numR = round $ radiusR / deltaR :: Int
numX = round $ radiusX / deltaX :: Int
func r =
if r >= 1
then 1 / r
else 1 / r
fr =
parMap
rdeepseq
(\r -> func r * r)
[fromIntegral r * deltaR | r <- [1 .. numR]]
besselArrayR =
fromFunction (Z :. numX :. numR) $ \(Z :. x :. r) ->
deltaR *
bessel_Jn
(fromIntegral n)
((fromIntegral x + 1) * deltaX * (fromIntegral r + 1) * deltaR)
besselArray <- computeUnboxedP besselArrayR
let besselVec = VU.convert . toUnboxed $ besselArray
frVec = VS.fromList fr
xs <- VS.toList <$> gemmBLAS numX 1 numR besselVec frVec
toFile def (folderPath </> "HankelTransform.png") $ do
layout_title .=
printf "N = %d RadiusR = %.2f RadiusX = %.2f" n radiusR radiusX
plot (line "" [L.zip [fromIntegral i * deltaX | i <- [1 .. numX]] xs])
|
theory Unified_PW_Impl
imports Refine_Imperative_HOL.IICF Unified_PW_Hashing Heap_Hash_Map
begin
subsection \<open>Implementation on Lists\<close>
(* XXX Move *)
context notes [split!] = list.split begin
sepref_decl_op list_hdtl: "\<lambda> (x # xs) \<Rightarrow> (x, xs)" :: "[\<lambda>l. l\<noteq>[]]\<^sub>f \<langle>A\<rangle>list_rel \<rightarrow> A \<times>\<^sub>r \<langle>A\<rangle>list_rel"
by auto
end
context Worklist_Map2_Defs
begin
definition trace where
"trace \<equiv> \<lambda>type a. RETURN ()"
definition
"explored_string = ''Explored''"
definition
"final_string = ''Final''"
definition
"added_string = ''Add''"
definition
"subsumed_string = ''Subsumed''"
definition
"empty_string = ''Empty''"
lemma add_pw'_map2_alt_def:
"add_pw'_map2 passed wait a = do {
trace explored_string a;
nfoldli (succs a) (\<lambda>(_, _, brk). \<not>brk)
(\<lambda>a (passed, wait, _).
do {
RETURN (
if empty a then
(passed, wait, False)
else if F' a then (passed, wait, True)
else
let
k = key a;
(v, passed) = op_map_extract k passed
in
case v of
None \<Rightarrow> (passed(k \<mapsto> {COPY a}), a # wait, False) |
Some passed' \<Rightarrow>
if \<exists> x \<in> passed'. a \<unlhd> x then
(passed(k \<mapsto> passed'), wait, False)
else
(passed(k \<mapsto> (insert (COPY a) passed')), a # wait, False)
)
}
)
(passed,wait,False)
}"
unfolding add_pw'_map2_def id_def op_map_extract_def trace_def
supply [simp del] = map_upd_eq_restrict
apply simp
apply (fo_rule fun_cong)
apply (fo_rule arg_cong)
apply (rule ext)+
by (auto 4 3 simp: Let_def split: option.split)
lemma add_pw'_map2_full_trace_def:
"add_pw'_map2 passed wait a = do {
trace explored_string a;
nfoldli (succs a) (\<lambda>(_, _, brk). \<not>brk)
(\<lambda>a (passed, wait, _).
do {
if empty a then
do {trace empty_string a; RETURN (passed, wait, False)}
else if F' a then do {trace final_string a; RETURN (passed, wait, True)}
else
let
k = key a;
(v, passed) = op_map_extract k passed
in
case v of
None \<Rightarrow> do {trace added_string a; RETURN (passed(k \<mapsto> {COPY a}), a # wait, False)} |
Some passed' \<Rightarrow>
if \<exists> x \<in> passed'. a \<unlhd> x then
do {trace subsumed_string a; RETURN (passed(k \<mapsto> passed'), wait, False)}
else do {
trace added_string a;
RETURN (passed(k \<mapsto> (insert (COPY a) passed')), a # wait, False)
}
}
)
(passed,wait,False)
}"
unfolding add_pw'_map2_alt_def
unfolding trace_def
apply (simp add:)
apply (fo_rule fun_cong)
apply (fo_rule arg_cong)
apply (rule ext)+
apply (auto simp add: Let_def split: option.split)
done
end
locale Worklist_Map2_Impl =
Worklist4_Impl + Worklist_Map2_Impl_Defs + Worklist_Map2 +
fixes K
assumes [sepref_fr_rules]: "(keyi,RETURN o PR_CONST key) \<in> A\<^sup>k \<rightarrow>\<^sub>a K"
assumes [sepref_fr_rules]: "(copyi, RETURN o COPY) \<in> A\<^sup>k \<rightarrow>\<^sub>a A"
assumes [sepref_fr_rules]: "(uncurry tracei,uncurry trace) \<in> id_assn\<^sup>k *\<^sub>a A\<^sup>k \<rightarrow>\<^sub>a id_assn"
assumes pure_K: "is_pure K"
assumes left_unique_K: "IS_LEFT_UNIQUE (the_pure K)"
assumes right_unique_K: "IS_RIGHT_UNIQUE (the_pure K)"
begin
sepref_register
"PR_CONST a\<^sub>0" "PR_CONST F'" "PR_CONST (\<unlhd>)" "PR_CONST succs" "PR_CONST empty" "PR_CONST key"
"PR_CONST F" trace
lemma take_from_list_alt_def:
"take_from_list xs = do {_ \<leftarrow> ASSERT (xs \<noteq> []); RETURN (hd_tl xs)}"
unfolding take_from_list_def by (auto simp: pw_eq_iff refine_pw_simps)
lemma [safe_constraint_rules]: "CN_FALSE is_pure A \<Longrightarrow> is_pure A" by simp
lemmas [sepref_fr_rules] = hd_tl_hnr
lemmas [safe_constraint_rules] = pure_K left_unique_K right_unique_K
lemma [sepref_import_param]:
"(explored_string, explored_string) \<in> Id"
"(subsumed_string, subsumed_string) \<in> Id"
"(added_string, added_string) \<in> Id"
"(final_string, final_string) \<in> Id"
"(empty_string, empty_string) \<in> Id"
unfolding
explored_string_def subsumed_string_def added_string_def final_string_def empty_string_def
by simp+
lemmas [sepref_opt_simps] =
explored_string_def
subsumed_string_def
added_string_def
final_string_def
empty_string_def
sepref_thm pw_algo_map2_impl is
"uncurry0 (do {(r, p) \<leftarrow> pw_algo_map2; RETURN r})" :: "unit_assn\<^sup>k \<rightarrow>\<^sub>a bool_assn"
unfolding pw_algo_map2_def add_pw'_map2_full_trace_def PR_CONST_def TRACE'_def[symmetric]
supply [[goals_limit = 1]]
supply conv_to_is_Nil[simp]
unfolding fold_lso_bex
unfolding take_from_list_alt_def
apply (rewrite in "{a\<^sub>0}" lso_fold_custom_empty)
unfolding hm.hms_fold_custom_empty
apply (rewrite in "[a\<^sub>0]" HOL_list.fold_custom_empty)
apply (rewrite in "{}" lso_fold_custom_empty)
unfolding F_split (* XXX Why? F only appears in the invariant *)
by sepref
concrete_definition (in -) pw_impl
for Lei a\<^sub>0i Fi succsi emptyi
uses Worklist_Map2_Impl.pw_algo_map2_impl.refine_raw is "(uncurry0 ?f,_)\<in>_"
end \<comment> \<open>Worklist Map2 Impl\<close>
locale Worklist_Map2_Impl_finite = Worklist_Map2_Impl + Worklist_Map2_finite
begin
(* XXX Missing review from Peter *)
lemma pw_algo_map2_correct':
"(do {(r, p) \<leftarrow> pw_algo_map2; RETURN r}) \<le> SPEC (\<lambda>brk. brk = F_reachable)"
using pw_algo_map2_correct
apply auto
apply (cases pw_algo_map2)
apply simp
apply simp
unfolding RETURN_def
apply auto
subgoal for X
apply (cases "do {(r, p) \<leftarrow> RES X; RES {r}}")
apply simp
apply (subst (asm) Refine_Basic.bind_def)
apply force
subgoal premises prems for X'
proof -
have "r = F_reachable" if "(r, p) \<in> X" for r p
using that prems(1) by auto
then show ?thesis
by (auto simp: pw_le_iff refine_pw_simps)
qed
done
done
lemma pw_impl_hnr_F_reachable:
"(uncurry0 (pw_impl keyi copyi tracei Lei a\<^sub>0i Fi succsi emptyi), uncurry0 (RETURN F_reachable))
\<in> unit_assn\<^sup>k \<rightarrow>\<^sub>a bool_assn"
using
pw_impl.refine[
OF Worklist_Map2_Impl_axioms,
FCOMP pw_algo_map2_correct'[THEN Id_SPEC_refine, THEN nres_relI]
]
by (simp add: RETURN_def)
end
locale Worklist_Map2_Hashable =
Worklist_Map2_Impl_finite
begin
sepref_decl_op F_reachable :: "bool_rel" .
lemma [def_pat_rules]: "F_reachable \<equiv> op_F_reachable" by simp
lemma hnr_op_F_reachable:
assumes "GEN_ALGO a\<^sub>0i (\<lambda>a\<^sub>0i. (uncurry0 a\<^sub>0i, uncurry0 (RETURN a\<^sub>0)) \<in> unit_assn\<^sup>k \<rightarrow>\<^sub>a A)"
assumes "GEN_ALGO Fi (\<lambda>Fi. (Fi,RETURN o F') \<in> A\<^sup>k \<rightarrow>\<^sub>a bool_assn)"
assumes "GEN_ALGO Lei (\<lambda>Lei. (uncurry Lei,uncurry (RETURN oo (\<unlhd>))) \<in> A\<^sup>k *\<^sub>a A\<^sup>k \<rightarrow>\<^sub>a bool_assn)"
assumes "GEN_ALGO succsi (\<lambda>succsi. (succsi,RETURN o succs) \<in> A\<^sup>k \<rightarrow>\<^sub>a list_assn A)"
assumes "GEN_ALGO emptyi (\<lambda>Fi. (Fi,RETURN o empty) \<in> A\<^sup>k \<rightarrow>\<^sub>a bool_assn)"
assumes [sepref_fr_rules]: "(keyi,RETURN o PR_CONST key) \<in> A\<^sup>k \<rightarrow>\<^sub>a K"
assumes [sepref_fr_rules]: "(copyi, RETURN o COPY) \<in> A\<^sup>k \<rightarrow>\<^sub>a A"
shows
"(uncurry0 (pw_impl keyi copyi tracei Lei a\<^sub>0i Fi succsi emptyi),
uncurry0 (RETURN (PR_CONST op_F_reachable)))
\<in> unit_assn\<^sup>k \<rightarrow>\<^sub>a bool_assn"
proof -
from assms interpret
Worklist_Map2_Impl
E a\<^sub>0 F "(\<preceq>)" succs empty "(\<unlhd>)" F' A succsi a\<^sub>0i Fi Lei emptyi key keyi copyi
by (unfold_locales; simp add: GEN_ALGO_def)
from pw_impl_hnr_F_reachable show ?thesis by simp
qed
sepref_decl_impl hnr_op_F_reachable .
end \<comment> \<open>Worklist Map 2\<close>
end \<comment> \<open>End of Theory\<close> |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "parmt_utils.h"
#ifdef PARMT_USE_INTEL
#include <mkl_lapacke.h>
#include <mkl_cblas.h>
#else
#include <lapacke.h>
#include <cblas.h>
#endif
#include "iscl/array/array.h"
#include "iscl/memory/memory.h"
#include "iscl/random/random.h"
#include "iscl/signal/convolve.h"
int parmt_utils_getEffectiveRank(const double relError,
const struct parmtNoiseBasis_struct basis)
{
double frac;
int i, rank;
rank = 1;
for (i=1; i<basis.nvals; i++)
{
// Modification of Demmel 3.9.3 to deal with sqrt(eig)
if (100.0*pow(basis.sqrtEvals[i], 2)/pow(basis.sqrtEvals[0], 2) < relError)
{
rank = i;
break;
}
}
return rank;
}
int parmt_utils_makeKLNoise(const int rank,
const int npts,
const struct parmtNoiseBasis_struct basis,
double *__restrict__ xn)
{
double *r, xscal;
int ir, ierr, ldz, rankUse;
if (rank < 1 || npts < 1 || basis.npts != npts || xn == NULL)
{
if (rank < 1){fprintf(stderr, "%s: rank is too small\n", __func__);}
if (npts < 1){fprintf(stderr, "%s: no points\n", __func__);}
if (basis.npts != npts)
{
fprintf(stderr, "%s: npts != basis.npts\n", __func__);
}
if (xn == NULL){fprintf(stderr, "%s: error x is NULL\n", __func__);}
return -1;
}
rankUse = MAX(1, MIN(basis.nvals, rank));
ldz = basis.lde;
r = random_rand64f(rankUse, &ierr);
array_zeros64f_work(npts, xn);
for (ir=0; ir<rank; ir++)
{
xscal = r[ir]*basis.sqrtEvals[ir];
printf("%f %f\n", r[ir], basis.sqrtEvals[ir]);
cblas_daxpy(npts, xscal, &basis.evects[ir*ldz], 1, xn, 1);
}
memory_free64f(&r);
return 0;
}
//============================================================================//
/*!
* @brief Releases memory on the noise basis struture
*
* @param[out] basis on exit all memory has been released and all variables
* set to NULL or 0.
*
* @author Ben Baker
*
* @copyright ISTI distributed under Apache 2
*
*/
int parmt_utils_freeNoiseBasis(struct parmtNoiseBasis_struct *basis)
{
memory_free64f(&basis->sqrtEvals);
memory_free64f(&basis->evects);
memset(basis, 0, sizeof(struct parmtNoiseBasis_struct));
return 0;
}
//============================================================================//
/*!
* @brief Computes the eigenvectors and eigenvalues of the noise
* autocorrelation matrix which will be further used in the
* Karhunen-Loeve expansion.
*
* @param[in] npts number of data points
* @param[in] data noise signal from which to compute noise basis.
*
* @param[out] basis on successful exit contains the eigendecomposition
* of the autocorrelation noise matrix for use in the KL
* expansion.
*
* @result 0 indicates success
*
* @author Ben Baker
*
* @copyright ISTI distributed under Apache 2
*
*/
int parmt_utils_getNoiseBasis64f(const int npts,
const double *__restrict__ data,
struct parmtNoiseBasis_struct *basis)
{
double *C, *CtC, *s, xnorm;
int i, ierr, j, ldc, ldctc, m, n, nrows;
const enum corrMatrixType_enum type = CORRMTX_AUTOCORRELATION;
//------------------------------------------------------------------------//
//
// error checking
ierr = 0;
memset(basis, 0, sizeof(struct parmtNoiseBasis_struct));
if (npts < 1 || data == NULL)
{
if (npts < 1)
{
fprintf(stderr, "%s: No points in noise signal\n", __func__);
}
if (data == NULL)
{
fprintf(stderr, "%s; Noise signal is NULL\n", __func__);
}
return -1;
}
C = NULL;
CtC = NULL;
// Normalize the noise energy in the noise signal
xnorm = cblas_dnrm2(npts, data, 1);
if (fabs(xnorm) < 1.e-15)
{
fprintf(stderr, "%s: Error division by zero\n", __func__);
return -1;
}
xnorm = 1.0/xnorm;
s = array_copy64f(npts, data, &ierr);
cblas_dscal(npts, xnorm, s, 1);
// Figure out the size of the noise correlation matrix
n = npts;
m = npts - 1;
ldc = n;
if (type == CORRMTX_AUTOCORRELATION)
{
nrows = n + m;
C = memory_calloc64f(ldc*nrows);
}
else
{
fprintf(stderr, "%s: Invalid correlation matrix type\n", __func__);
return -1;
}
ldctc = n;
CtC = memory_calloc64f(n*n);
// Compute the correlation matrix and C'C
ierr = convolve_corrmtx64f_work(npts, s,
m, ldc, C,
type, true, ldctc, CtC);
if (ierr != 0)
{
fprintf(stderr, "%s: Failed to compute correlation matrix\n", __func__);
goto ERROR;
}
ierr = parmt_utils_getNoiseBasisFromCtC64f(npts, ldctc, CtC, basis);
if (ierr != 0)
{
fprintf(stderr, "%s: Failed to compute noise basis\n", __func__);
}
ERROR:;
memory_free64f(&C);
memory_free64f(&CtC);
return ierr;
}
int parmt_utils_getNoiseBasisFromCtC64f(const int npts, const int ldctc,
const double *__restrict__ CtC,
struct parmtNoiseBasis_struct *basis)
{
double *CtCw, *w;
int ierr, i, info, j;
ierr = 0;
memset(basis, 0, sizeof(struct parmtNoiseBasis_struct));
CtCw = memory_calloc64f(npts*ldctc);
for (i=0; i<npts; i++)
{
cblas_dcopy(npts, &CtC[i*ldctc], 1, &CtCw[i*ldctc], 1);
}
// Compute the eigendecompsition of the symmetric matrix
w = memory_calloc64f(npts);
info = LAPACKE_dsyev(LAPACK_ROW_MAJOR, 'V', 'U', npts, CtCw, ldctc, w);
if (info != 0)
{
ierr = 1;
if (info > 0)
{
fprintf(stderr, "%s: Failure to converge on %d'th element\n",
__func__, info);
}
else
{
fprintf(stderr, "%s: %d'th parameter is invalid\n", __func__, info);
}
goto ERROR;
}
// Set the basis
basis->lde = npts;
basis->nvals = npts;
basis->npts = npts;
basis->sqrtEvals = memory_calloc64f(basis->nvals);
basis->evects = memory_calloc64f(basis->lde*basis->nvals);
// Put into descending order
for (i=0; i<npts; i++)
{
basis->sqrtEvals[i] = sqrt(w[npts-1-i]);
}
// Copy corresponding eigenvectors in descending order
for (j=0; j<npts; j++)
{
for (i=0; i<npts; i++)
{
basis->evects[j*basis->lde+i] = CtCw[i*ldctc+(npts-1-j)];
}
}
ERROR:;
memory_free64f(&w);
memory_free64f(&CtCw);
return ierr;
}
|
function legendre_set_test ( )
%*****************************************************************************80
%
%% LEGENDRE_SET_TEST tests LEGENDRE_SET.
%
% Licensing:
%
% This code is distributed under the GNU LGPL license.
%
% Modified:
%
% 16 November 2014
%
% Author:
%
% John Burkardt
%
fprintf ( 1, '\n' );
fprintf ( 1, 'LEGENDRE_SET_TEST\n' );
fprintf ( 1, ' LEGENDRE_SET returns points and weights of \n' );
fprintf ( 1, ' Gauss-Legendre quadrature rules.\n' );
fprintf ( 1, '\n' );
fprintf ( 1, ' N 1 X^4 Runge\n' );
fprintf ( 1, '\n' );
for n = 1 : 10
[ x, w ] = legendre_set ( n );
e1 = sum ( w(1:n,1) );
e2 = w(1:n,1)' * x(1:n,1).^4;
e3 = w(1:n,1)' * ( 1.0 ./ ( 1.0 + 25.0 * x(1:n,1).^2 ) );
fprintf ( 1, ' %2d %14.6g %14.6g %14.6g\n', n, e1, e2, e3 );
end
return
end
|
State Before: α : Type u_1
inst✝ : OrderedAddCommGroup α
a b c : α
⊢ -Ioc a b = Ico (-b) (-a) State After: no goals Tactic: simp [← Ioi_inter_Iic, ← Ici_inter_Iio, inter_comm] |
# Dates
xd <- as.Date("2016-11-16")
print(xd)
weekdays(xd)
xd+7
xd + 0:6
weekdays(xd + 0:6)
xm <- seq(xd, by = "2 months", length.out = 6)
xm
months(xm)
quarters(xm)
nd <- "Nov 17, 2016" # this line and below useful for data transforms
newdate <- as.Date(nd, format="%b %d, %Y")
paste("Original date: ",nd," Converted to R: ",newdate) # useful for combining values for display
#
#
# Time
test <- "June 29, 1958, 20:17:39"
test.fmt <- "%B %d, %Y, %H:%M:%S"
xct = as.POSIXct(test, format=test.fmt, tz="UTC")
xct
format(xct, "%d/%m/%y")
format(xct, "%M minutes past %I %p, on %d %B %Y")
xct + 7*86400
xct + 3*60*60
xct - 7*86400
xct
|
#ifndef _PARAMETERS_H_
#define _PARAMETERS_H_
#include <string>
#include <fstream>
#include <iostream>
#include <cstdlib>
#include "../Headers/voxel.h"
#include <math.h>
#include <gsl/gsl_rng.h>
using namespace std;
class Parameters{
//Atributs
public:
int it; //Contador
int nt; // Nombre de passos total
int ntout; // Nombre de pasos per l'output
int neq; //Number of equations
float dt; // Pas de temps
float t;
string Dir_Output;
string Dir_Input;
string NumPar_Dat;
string Data_Dat;
string Init_Cond_Dat;
int nNodes;
int nNodes_inh;
string Kex_Dat;
string Kin_Dat;
float ** Kex; //Coupling matrix for excitatory population
float ** Kin; //Coupling matrix for inhibitory population
voxel * V; //Voxel
ofstream fout_data;
ofstream fout_init_cond;
public:
Parameters();
~Parameters();
//Mètodes
void Read_Kex_Dat(void);
void Read_Kin_Dat(void);
void RefreshDelay(void);
void Read_NumPar_Dat(void);
void WriteData();
void WriteInitialConditions(int);
void openfiles();
void closefiles();
//private:
};
#endif
|
! { dg-do run }
program save_1
implicit none
integer i
integer foo1, foo2, foo3, foo4
do i=1,10
if (foo1().ne.i) then
call abort
end if
if (foo2().ne.i) then
call abort
end if
if (foo3().ne.i) then
call abort
end if
if (foo4().ne.i) then
call abort
end if
end do
end program save_1
integer function foo1 ()
integer j
save
save ! { dg-warning "Blanket SAVE" }
data j /0/
j = j + 1
foo1 = j
end function foo1
integer function foo2 ()
integer j
save j
save j ! { dg-warning "Duplicate SAVE" }
data j /0/
j = j + 1
foo2 = j
end function foo2
integer function foo3 ()
integer j ! { dg-warning "Duplicate SAVE" }
save
save j ! { dg-warning "SAVE statement" }
data j /0/
j = j + 1
foo3 = j
end function foo3
integer function foo4 ()
integer j ! { dg-warning "Duplicate SAVE" }
save j
save
data j /0/
j = j + 1
foo4 = j
end function foo4
|
# simbMoments
*simbMoments* determines a system of equations corresponding to the first and second moments of the population observations. The process to find each moment is quite similar to the way it was done to find the system of differential equations using *simbODE*. The equations are sympy objects which one can manipulate to compute some statistics from the whole population. The implemented function just determines upon the second moment. The first moment is equivalent to the mean behavior of the system output, while the second expresses the cross dependence of the species and is equivalent to the variance of the system output.
```
#libraries required
import numpy as np
import sympy as sp
```
**Defines System Properties**
```
#molecular species
species = ['x1', 'x2']
species = sp.var(species)
#system input
inp = ['u']
uh = sp.var(inp)
ruh = 0 #reaction affected by input (0 = 1st reaction)
#reagent and product matrices
reactants = np.array([[0, 1, 1, 0],
[0, 0, 0, 1]])
products = np.array([[1, 0, 1, 0],
[0, 0, 1, 0]])
#kinetic parameters
pars = ['c1', 'c2', 'c3', 'c4']
parsValues = sp.var(pars)
#to replace kinetic parameters for numeric values, uncomment the next line
#and comment the two previous ones
#parsValues = [4.0, 0.010, 1.0, 0.006]
```
**Pre-processing of the System**. From previous defined information determines stoichiometric matrix and propensity vector. These arrays are used to compute
the moments of the system.
```
#stoichiometric matrix
V = products - reactants
#pre-propensity function
aPro = parsValues
aPro[ruh] = aPro[ruh]*uh[0] #Attaches system input
#system dimentions
Sn, Rm = V.shape
#propensity function vector
for r in range(0,Rm):
for s in range(0, Sn):
#determines propensity vector expressions
for a in range(0, reactants[s,r]):
aPro[r] *= species[s]
#end for a
#end for s
#end for r
print("Stoichimotric Matrix:\n", V)
print("Propensity Function Vector:", aPro)
```
Stoichimotric Matrix:
[[ 1 -1 0 0]
[ 0 0 1 -1]]
Propensity Function Vector: [c1*u, c2*x1, c3*x1, c4*x2]
**Computes Moments Equations**. Each species has its own first moment equation and second orden moment equation. The second moment is found for itself and crossed with other species.
*First Moment*
```
#System of First Moment Equations
odeX = []
for s in range(0,Sn):
temp = 0
#Determines Defferential Equations
for r in range(0, Rm):
temp += V[s,r]*aPro[r]
#end for r
#Set of Differential Equations
odeX.append(temp)
#end for s
```
*Second Order Moment*
```
#System of Second Order Equations
ode2m = []
name2m = []
nameODE = species
odeTotal = odeX
for s1 in range(0, Sn):
for s2 in range(0, Sn):
#Determines second order expression
temp = 0
for r in range(0,Rm):
temp += (V[s1,r]*aPro[r]*species[s2] + V[s2,r]*aPro[r]*species[s1] \
+ V[s1,r]*V[s2,r]*aPro[r])
#end for r
#set of second order moment equations
if temp not in ode2m:
ode2m.append(temp)
odeTotal.append(temp)
#end if temp
#variable names of second order species
if (species[s1]*species[s2]) not in name2m:
name2m.append(species[s1]*species[s2])
nameODE.append(species[s1]*species[s2])
#end if species s1*s2
#end for s2
#end for s1
```
Some processing of the determined data to make easy posterior manipulation
```
#replaces variable names
dxName = []
dxODE = []
for exp in odeTotal:
#at each expression searches for the variable names to replaces them
#for a nickname "dx#"
for j in range(0,len(nameODE)):
name = sp.var('dx' + str(len(nameODE)-j))
exp = exp.subs(nameODE[len(nameODE)-j-1],name)
#stores nicknames
if name not in dxName:
dxName.append(name)
#end if name
#end for j
dxODE.append(exp)
#end for exp
dxName.reverse()
```
```
#Shows sistem of differential equations determined
for k in range(0,len(odeTotal)):
print(f'd{nameODE[k]}/dt:', odeTotal[k])
# print(f'd({dxName[k]})/dt:', dxODE[k])
# print('\n')
#end for k
```
dx1/dt: c1*u - c2*x1
dx2/dt: c3*x1 - c4*x2
dx1**2/dt: 2*c1*u*x1 + c1*u - 2*c2*x1**2 + c2*x1
dx1*x2/dt: c1*u*x2 - c2*x1*x2 + c3*x1**2 - c4*x1*x2
dx2**2/dt: 2*c3*x1*x2 + c3*x1 - 2*c4*x2**2 + c4*x2
|
########################################################################
#
# A stat
StatQtile <- ggproto(
"StatQtile", Stat, required_aes = c("x", "y"),
compute_group = function(data, scales, upper, lower) {
data %>%
group_by(x) %>%
summarise(ymax=quantile(y, upper),
ymin=quantile(y, lower),
y=median(y))
}
)
stat_qtile <- function(mapping = NULL, data = NULL, geom = "smooth",
position = "identity", na.rm = FALSE, show.legend = NA,
inherit.aes = TRUE, upper=0.95, lower=0.05, ...) {
layer(
stat = StatQtile, data = data, mapping = mapping, geom = geom,
position = position, show.legend = show.legend, inherit.aes = inherit.aes,
params = list(na.rm = na.rm, upper=upper, lower=lower, se=TRUE, ...)
)
}
|
function [Gausspoint,Gaussweight] = GaussQuadrature(ngl)
%-------------------------------------------------------------------
% Purpose:
% determine the integration points and weighting coefficients
% of Gauss-Legendre quadrature for two-dimensional integration
%
% Synopsis:
% [point,weight]=GaussQuadrature(nglx,ngly)
%
% Variable Description:
% ngl - number of integration points
% point - vector containing integration points
% weight - vector containing weighting coefficients
%-------------------------------------------------------------------
% initialization
Gausspoint=zeros(ngl,1);
Gaussweight=zeros(ngl,1);
% corresponding integration points and weights
% 2-point quadrature rule
Gausspoint(1)=-0.577350269189626;
Gausspoint(2)=-Gausspoint(1);
Gaussweight(1)=1.0;
Gaussweight(2)=Gaussweight(1); |
import data.real.basic
import data.polynomial.basic
import data.polynomial.eval
theorem exo (f: polynomial real):
let f_fun (x: real) := polynomial.eval x f in
(forall (a b c: real), a*b + b*c + c*a = 0 -> f_fun(a - b) + f_fun(b - c) + f_fun(c - a) = 2*f_fun(a + b + c))
<-> (exists c1 c2, forall x, f_fun x = c1 * x^4 + c2 * x^2)
:=
sorry |
myTestRule {
# Input parameters are:
# Source data object file path
# Destination object path
# Output parameter is:
# Status
# Output from running the example is
# File /tempZone/home/rods/put_test.txt copied to /tempZone/home/rods/SaveVersions
msiStoreVersionWithTS(*SourceFile,*DestPath,*Status);
writeLine("stdout","File *SourceFile copied to *DestPath");
}
INPUT *SourceFile="/tempZone/home/rods/put_test.txt", *DestPath="/tempZone/home/rods/SaveVersions"
OUTPUT ruleExecOut
|
Require Import PocklingtonRefl.
Open Local Scope positive_scope.
Lemma prime14139308836963 : prime 14139308836963.
Proof.
apply (Pocklington_refl
(Pock_certif 14139308836963 2 ((10607, 1)::(2,1)::nil) 6921)
((Proof_certif 10607 prime10607) ::
(Proof_certif 2 prime2) ::
nil)).
vm_cast_no_check (refl_equal true).
Qed.
Lemma prime6789012345678901234567903: prime 6789012345678901234567903.
apply (Pocklington_refl
(SPock_certif
6789012345678901234567903
2
((14139308836963, 1)::nil))
( (Proof_certif 14139308836963 prime14139308836963) :: nil)).
vm_cast_no_check (refl_equal true).
Time Qed.
|
program data12
integer x(10)
complex z(10)
C Complex value is coerced to integer and this should not be
C interpreted as eight values: 1 1 1 2 1 1 1 2!
c data (x(i), i = 1, 2) /2*(3*1,2)/
c data (z(i), i = 1, 2) /2*(3*1,2)/
data (x(i), i = 1, 2) /2*(3,2)/
data (z(i), i = 1, 2) /2*(3,2)/
print *, (x(i), i = 1, 8)
print *, (z(i), i = 1, 8)
end
|
library(shiny)
library(qvalue, lib.loc= .libPaths()[1])
library(shiny)
library(shinythemes)
library(shinyjs)
library(markdown)
library(DT)
library(shinyjqui)###need to upload package to server
library(shinycssloaders)
options(shiny.maxRequestSize=300*1024^2)
files <- list.files("data")
shinyUI(fluidPage(
tags$head(
tags$head(includeScript("google-analytics.js")),
tags$link(rel="stylesheet", type="text/css",href="style.css"),
tags$script(type="text/javascript", src = "md5.js"),
tags$script('!function(d,s,id){var js,fjs=d.getElementsByTagName(s) [0],p=/^http:/.test(d.location)?\'http\':\'https\';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");')
),
useShinyjs(),
uiOutput("app"),
# Application title
headerPanel(
list(tags$head(tags$style("body {background-color: white; }")),
"FDRCLIM", HTML('<img src="picture2.png", height="100px",
style="float:left"/>','<p style="color:grey"> FDR control of ExG associations </p>' ))
),
theme = shinytheme("journal") ,
jqui_draggabled( sidebarPanel(
selectInput('file', 'Choose ExG association', setNames(files, files)),
tags$hr(),
checkboxInput('header', 'Header', TRUE),
wellPanel(a(h4('Please cite us in any publication that utilizes information from Arabidopsis CLIMtools:'), href = "https://www.nature.com/articles/s41559-018-0754-5", h6('Ferrero-Serrano, Á & Assmann SM. Phenotypic and genome-wide association with the local environment of Arabidopsis. Nature Ecology & Evolution. doi: 10.1038/s41559-018-0754-5 (2019)' ))),
wellPanel(
p( strong( HTML("π<sub>0</sub>"), "estimate inputs")),
selectInput("pi0method", p("Choose a", HTML("π<sub>0</sub>"), "method:"),
choices = c("smoother", "bootstrap")),
sliderInput(inputId = "lambda", label = p(HTML("λ"),"range"),
min = 0, max = 1, value = c(0, 0.95), step = 0.01),
numericInput("step", p(HTML("λ"),"step size:"), 0.05),
numericInput("sdf", "smooth df:", 3.0),
checkboxInput(inputId = "pi0log", label = p(HTML("π<sub>0</sub>"), "smoother log"), value = FALSE)
),
wellPanel(
p(strong("Local FDR inputs")),
selectInput("transf", "Choose a transformation method:",
choices = c("probit", "logit")),
checkboxInput(inputId = "trunc", label = "truncate local FDR values", value = TRUE),
checkboxInput(inputId = "mono", label = "monotone", value = TRUE),
numericInput("adj", "adjust:", 1.5),
numericInput("eps", "threshold:", 10^-8)
),
wellPanel(
p(strong("Output")),
sliderInput("fdr",
"FDR level:",
step = 0.01,
value = 0.05,
min = 0,
max = 1),
checkboxInput(inputId = "pfdr", label = "pfdr", value = FALSE)
), wellPanel(a("Tweets by @ClimTools", class="twitter-timeline"
, href = "https://twitter.com/ClimTools"), style = "overflow-y:scroll; max-height: 1000px"
),h6('Contact us: [email protected]'))
),
mainPanel(
###add code to get rid of error messages on the app.
tags$style(type="text/css",
".shiny-output-error { visibility: hidden; }",
".shiny-output-error:before { visibility: hidden; }"
),
tabsetPanel(id="tabSelected",
tabPanel("About", h4("Using the App"), uiOutput("about"), h4("References"), uiOutput("ref")),
# tabPanel("Figures", h4("Plot"), plotOutput("qvaluePlot"), h4("Histogram"), plotOutput("qvalueHist"), h4("Summary"), verbatimTextOutput("summary") ),
tabPanel("Figures", uiOutput("subTabs")),
tabPanel("Help", uiOutput("help")))
)
))
|
## Copyright (c) 2018-2021, Carnegie Mellon University
## See LICENSE for details
Class(WarpXOpts, FFTXConvOpts, rec(
tags := [],
operations := rec(Print := s -> Print("<FFTX WarpX options record>"))
));
warpxOpts := function(arg) # specific to WarpX size 100...
local opts, rfs;
rfs := Copy(RulesFuncSimp);
Unbind(rfs.rules.TensorIdId);
opts := Copy(WarpXOpts);
opts.breakdownRules.Circulant := [Circulant_PRDFT_FDataNT];
opts.breakdownRules.PRDFT := List([PRDFT1_Base1, PRDFT1_Base2, CopyFields(PRDFT1_CT,
rec(allChildren := P ->Filtered(PRDFT1_CT.allChildren(P), i->When(P[1] = 100, Cols(i[1]) = 4, true)))),
PRDFT_PD], _noT);
opts.breakdownRules.IPRDFT := List([ IPRDFT1_Base1, IPRDFT1_Base2, IPRDFT1_CT, IPRDFT_PD ], _noT);
opts.breakdownRules.PRDFT3 := List([ PRDFT3_Base1, PRDFT3_Base2, PRDFT3_CT ], _noT);
opts.breakdownRules.IPRDFT2 := List([ IPRDFT2_Base1, IPRDFT2_Base2, IPRDFT2_CT ], _noT);
opts.breakdownRules.DFT := [ DFT_Base,
CopyFields(DFT_CT, rec(children := nt ->Filtered(DFT_CT.children(nt), i->When(nt.params[1] = 100, Cols(i[1]) = 4, true)))),
DFT_PD ];
opts.breakdownRules.TTensorInd := [dsA_base, L_dsA_L_base, dsA_L_base, L_dsA_base];
opts.breakdownRules.MDDFT := [ MDDFT_Base, MDDFT_RowCol ];
opts.breakdownRules.TL := [L_base];
opts.breakdownRules.TSparseMat := [ TSparseMat_base ];
opts.globalUnrolling := 23;
opts.codegen := CopyFields( MultiPtrCodegenMixin, spiral.libgen.VecRecCodegen);
opts.sumsgen.IterHStack := MultiPtrSumsgenMixin.IterHStack;
opts.preProcess := t -> ApplyStrategy(t,
[ RulesFFTXPromoteWarpX1,
MergedRuleSet(rfs, RulesSums, RulesFFTXPromoteWarpX2),
RulesFFTXPromoteNT,
MergedRuleSet(rfs, RulesSums, RulesFFTXPromoteWarpX3) ],
BUA, opts);
opts.useDeref := false;
# for debugging...
opts.generateInitFunc := false;
# opts.codegen := DefaultCodegen;
opts.arrayBufModifier := "";
opts.arrayDataModifier := "static";
return opts;
end;
warpxConf := rec(
defaultName := "defaultWarpXConf",
defaultOpts := (arg) >> rec(useWarpX := true),
confHandler := warpxOpts
);
fftx.FFTXGlobals.registerConf(warpxConf);
|
/-
Copyright (c) 2023 Kevin Buzzard. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author : Jason Kexing Ying, Kevin Buzzard
-/
import tactic -- imports all the Lean tactics
import measure_theory.integral.bochner
--import probability.martingale.basic -- note to self: surely too much
/-
# Measures
Recall that Lean calls a space equipped with
a sigma algebra a "measurable_space". We will go with this language
and call sets in the sigma algebra "measurable sets".
Given a measurable space, a *measure* on the measurable space is a function from
the measurable sets to `[0,∞]` which is countably additive (i.e.,
the measure of a countable disjoint union of measurable sets is the sum of the measures).
This is not the *definition* of a measure in Lean, but it is mathematically equivalent to the
definition.
For what it's worth, the actual definition of a measure in Lean is this: an `outer_measure`
on a type `α` is this:
```
structure outer_measure (α : Type*) :=
(measure_of : set α → ℝ≥0∞)
(empty : measure_of ∅ = 0)
(mono : ∀{s₁ s₂}, s₁ ⊆ s₂ → measure_of s₁ ≤ measure_of s₂)
(Union_nat : ∀(s:ℕ → set α), measure_of (⋃i, s i) ≤ ∑'i, measure_of (s i))
```
So it attaches an element of `[0,∞]` to *every* subset of α, satisfying some natural axioms;
note in particular it is countably *sub*additive, meaning that the measure of a countable
union of open sets, even if they're pairwise disjoint, is only assumed to be at most the sum of the measures.
And if `α` has a measurable space structure then a measure on `α` is an outer measure satisfying
some axioms, which boil down to "the restriction of the outer measure is a measure on the measurable
sets, and the extension of this measure to an outer measure agrees with the outer measure we started with".
The advantage of doing it this way is that given a measure, we can evaluate it on *any* subset
(getting the outer measure of the subset) rather than having to supply a proof that the subset
is measurable. This coincides with Lean's "make functions total" philosophy (the same reason that 1/0=0).
-/
open filter
open_locale nnreal ennreal measure_theory big_operators topological_space
-- note to self: removed `probability_theory`
namespace measure_theory
-- Let Ω be a set equipped with a sigma algebra.
variables {Ω : Type} [measurable_space Ω]
-- Now let's add a measure `μ` on `Ω`
variables {μ : measure Ω}
/-
Try proving the following:
-/
example (S T : set Ω) (hS : μ S ≠ ∞) (hT : measurable_set T) :
μ (S ∪ T) = μ S + μ T - μ (S ∩ T) :=
begin
rw ← measure_union_add_inter S hT,
rw ennreal.add_sub_cancel_right,
apply ne_top_of_le_ne_top hS,
apply outer_measure.mono,
exact set.inter_subset_left S T,
end
/-
*Remark*: while proving the above, you might have noticed I've added the
condition `hS` (think about what is a + ∞ - ∞). In particular, subtraction in
extended non-negative reals (`ℝ≥0∞`) might not be what you expect,
e.g. 1 - 2 = 0 in `ℝ≥0∞`. For this reason, the above lemma is better phrased as
`μ (S ∪ T) + μ (S ∩ T) = μ S + μ T` for which we can omit the condition `hS`.
-/
/-!
## Measurable functions
So far we've worked in the space `Ω` though with all mathematical objects, we
want to map between them. In measure theory, the correct notion of maps is
measurable functions. If you have seen continuity in topology, they are quite
similar, namely, a function `f` between two measurable spaces is said to be
measurable if the preimages of all measurable sets along `f` is measurable.
-/
/-
If you go to the definition of measurable you will find what you expect.
However, of course, measure theory in Lean is a bit more complicated. As we
shall see, in contrast to maths, there are 3 additional notions of measurability
in mathlib. These are:
- `ae_measurable`
- `strongly_measurable`
- `ae_strongly_measurable`
The reasons for their existence is technical but TLDR: `ae_foo f` is the predicate
that `f` is almost everywhere equal to some function satisfying `foo` (see the
a.e. filter section) while `strongly_measurable f` is saying `f` is the limit
of a sequence of simple functions.
Alongside `measurable`, we also see them quite often in the mathlib, although
all you have to know is in most cases (range is metrizable and second-countable),
`measurable` and `strongly_measurable` are equivalent.
-/
example : measurable (id : Ω → Ω) :=
begin
intros U hU,
exact hU,
end
example {X Y Z : Type} [measurable_space X] [measurable_space Y] [measurable_space Z]
(f : X → Y) (g : Y → Z) (hg : measurable g) (hf : measurable f) :
measurable (g ∘ f) :=
begin
intros U hU,
replace hg := hg hU,
exact hf hg,
end
/-!
## Integration
One of the primary motivations of measure theory is to introduce a more
satisfactory theory of integration. If you recall the definition of the
Darboux-Riemann integral, we cannot integrate the indicator function of
`ℚ ∩ [0, 1]` despite, intuitively, the set of rationals in the unit interval
is much "smaller" (rationals is countable while the irrationals are not.
In contrast, measure theory allows us to construct the Lebesgue integral
which can deal with integrals such as this one.
Lean uses a even more general notion of integration known as Bochner integration
which allows us to integrate Banach-space valued functions. Its construction
is similar to the Lebesgue integral.
Read page 5-6 of https://arxiv.org/pdf/2102.07636.pdf
if you want to know the details.
-/
-- Suppose now `X` is another measurable space
variables {X : Type} [measurable_space X]
-- and suppose it's also a Banach space (i.e. a vector space and a complete metric space)
variables [normed_add_comm_group X] [normed_space ℝ X] [complete_space X]
-- If `f : Ω → X` is a function, then the integral of `f` is written as
-- `∫ x, f x ∂μ`. If you want to integrate over the set `s : set Ω` then write
-- `∫ x in s, f x ∂μ`.
-- Try looking in mathlib
example {f g : Ω → X} (hf : integrable f μ) (hg : integrable g μ) :
∫ x, f x + g x ∂μ = ∫ x, f x ∂μ + ∫ x, g x ∂μ :=
begin
apply integral_add hf hg,
end
example (a : X) (s : set Ω) : ∫ x in s, a ∂μ = (μ s).to_real • a :=
begin
rw integral_const,
congr' 2,
rw measure.restrict_apply,
{ simp },
{ simp },
end
-- Harder
example {f : Ω → ℝ} (hf : measurable f) (hint : integrable f μ)
(hμ : 0 < μ {ω | 0 < f ω}) :
(0 : ℝ) < ∫ ω in {ω | 0 < f ω}, f ω ∂μ :=
begin
sorry
end
/-
*Remark* It's a common myth that Lebesgue integration is strictly better than
the Darboux-Riemann integral. This is true for integration on bounded intervals
though it is not true when considering improper integrals. A common example
for this is, while `∫ x in [0, ∞), sin x / x dx` is Darboux-Riemann integrable
(in fact it equals `π / 2`) it is not Lebesgue integrable as
`∫ x in [0, ∞), |sin x / x| dx = ∞`.
-/
/-!
## ae filter
Now we have come to a very important section of working with measure theory
in Lean.
In measure theory we have a notion known as almost everywhere (a.e.). In
probability this is known as almost surely however we will stick with
almost everywhere in this project. Namely, a predicate `P` on `Ω` is said to
be true almost everywhere if the set for which `P` holds is co-null, i.e.
`μ {ω : Ω | P ω}ᶜ = 0`.
As examples, we say:
- given functions `f, g`, `f` equals `g` a.e. if `μ {ω : Ω | f ω ≠ g ω} = 0`;
- `f` is less equal to `g` a.e. if `μ {ω : Ω | ¬ f ω ≤ g ω} = 0` etc.
Often, showing that a property holds a.e. is the best we can do in
measure/probability theory.
In Lean, the notion of a.e. is handled by the `measure.ae` filter.
Let's construct that filter ourselves.
-/
example (X : Type) [measurable_space X] (μ : measure X) : filter X :=
{ sets := {U | μ Uᶜ = 0},
univ_sets := begin
simp only [set.mem_set_of_eq, set.compl_univ, measure_empty],
end,
sets_of_superset := begin
rintro S T (hS : μ Sᶜ = 0) hST,
change μ Tᶜ = 0,
apply measure_mono_null _ hS,
exact set.compl_subset_compl.mpr hST,
end,
inter_sets := begin
intros S T hS hT,
rw set.mem_set_of at hS hT ⊢,
rw set.compl_inter,
rw ← le_zero_iff,
apply le_trans (measure_union_le _ _),
rw [hS, hT],
norm_num,
end }
-- say `f` and `g` are measurable functions `Ω → X`
variables (f g : Ω → X)
-- The following is a proposition that `f` and `g` are almost everywhere equal
-- it's **not** a proof that `f` and `g` are a.e. equal but simply a statement
example : Prop := ∀ᵐ ω ∂μ, f ω = g ω
-- Here's another example on how to state `f` is almost everywhere less equal
-- than `g`
-- To be able to formulate this we need a notion of inequality on `X` so we
-- will add the `has_le` instance on `X`, i.e. equip `X` with a inequality
example [has_le X] : Prop := ∀ᵐ ω ∂μ, f ω ≤ g ω
-- Since the above two cases come up quite often, there are special notations
-- for them. See if you can guess what they mean
example : Prop := f =ᵐ[μ] g
example [has_le X] : Prop := f ≤ᵐ[μ] g
-- In general, if `P : Ω → Prop` is a predicate on `Ω`, we write `∀ᵐ ω ∂μ, P ω`
-- for the statement that `P` holds a.e.
example (P : Ω → Prop) : Prop := ∀ᵐ ω ∂μ, P ω
-- Sanity check: the above notation actually means what we think
example (P : Ω → Prop) : (∀ᵐ ω ∂μ, P ω) ↔ μ {ω | P ω}ᶜ = 0 :=
begin
refl,
end
-- Heres a more convoluted example. See if you can figure what it means
example (f : ℕ → Ω → ℝ) (s : set Ω) :=
∀ᵐ ω ∂μ.restrict s, ∃ l : ℝ, tendsto (λ n, f n ω) at_top (𝓝 l)
-- Now to do some exercises: you will need to dig into the source code to see
-- what the definitions are and search for helpful lemmas
-- *Hint*: try out the `measurability` tactic. It should be able to solve simple
-- goals of the form `measurable_set s` and `measurable f`
example (s : set Ω) (f g : Ω → ℝ)
(hf : measurable f) (hg : measurable g) (hfg : ∀ ω ∈ s, f ω = g ω) :
f =ᵐ[μ.restrict s] g :=
begin
unfold eventually_eq filter.eventually,
rw mem_ae_iff,
rw measure.restrict_apply,
{ convert measure_empty,
rw set.eq_empty_iff_forall_not_mem,
rintro x ⟨hx1, hx2⟩,
apply hx1,
apply hfg _ hx2, },
{ measurability, },
end
example (f g h : Ω → ℝ) (h₁ : f ≤ᵐ[μ] g) (h₂ : f ≤ᵐ[μ] h) :
2 * f ≤ᵐ[μ] g + h :=
begin
convert eventually_le.add_le_add h₁ h₂,
rw two_mul,
end
example (f g : Ω → ℝ) (h : f =ᵐ[μ] g) (hg : ∀ᵐ ω ∂μ, 2 * g ω + 1 ≤ 0) :
∀ᵐ ω ∂μ, f ω ≤ -1/2 :=
begin
filter_upwards [h, hg],
rintro a ha hg,
rw ha,
linarith,
end
example (f g : ℕ → Ω → ℝ) (a b : ℝ)
(hf : ∀ᵐ ω ∂μ, tendsto (λ n, f n ω) at_top (𝓝 a))
(hg : ∀ᵐ ω ∂μ, tendsto (λ n, g n ω) at_top (𝓝 b)) :
∀ᵐ ω ∂μ, tendsto (λ n, f n ω + g n ω) at_top (𝓝 (a + b)) :=
begin
filter_upwards [hf, hg],
intros ω h1 h2,
convert tendsto.comp tendsto_add _, swap, exact (λ n, (f n ω, g n ω)), refl,
{ apply_instance, },
rw nhds_prod_eq,
rw tendsto_prod_iff',
exact ⟨h1, h2⟩,
end
/-
I hope that you found the above examples slightly annoying, especially the
third example: why can't we just `rw h`?! Of course, while we often do do so on
paper, rigourously, such a rewrite require some logic. Luckily, what we normally
do on paper is most often ok and we would like to do so in Lean as well. While
we can't directly rewrite almost everywhere equalities, we have the next best
thing: the `filter_upwards` tactic. See the tactic documentation here:
https://leanprover-community.github.io/mathlib_docs/tactics.html#filter_upwards
The `filter_upwards` tactic is much more powerful than simply rewritting a.e.
equalities and is helpful in many situtations, e.g. the above second, third
and fourth examples are all easily solvable with this tactic. Let us see how
it works in action.
-/
-- Hover over each line and see how the goal changes
example (f₁ f₂ g₁ g₂ : Ω → ℝ) (h₁ : f₁ ≤ᵐ[μ] g₁) (h₂ : f₂ ≤ᵐ[μ] g₂) :
f₁ + f₂ ≤ᵐ[μ] g₁ + g₂ :=
begin
filter_upwards [h₁, h₂],
intros ω hω₁ hω₂,
exact add_le_add hω₁ hω₂,
end
-- Heres an even shorter proof using additional parameters of `filter_upwards`
example (f₁ f₂ g₁ g₂ : Ω → ℝ) (h₁ : f₁ ≤ᵐ[μ] g₁) (h₂ : f₂ ≤ᵐ[μ] g₂) :
f₁ + f₂ ≤ᵐ[μ] g₁ + g₂ :=
begin
filter_upwards[h₁, h₂] with ω hω₁ hω₂ using add_le_add hω₁ hω₂,
end
/-
Intuitively, what `filter_upwards` is doing is simply exploiting the fact that
the intersection of two full measure sets (i.e. complements are null) is also
a set of full measure. Thus, it suffices to work in their intersection instead.
Now, try the above examples again using the `filter_upwards` tactic.
-/
end measure_theory |
If $x$ and $x'$ are both related to $y$ by the Euclidean relation, then $x + x'$ is related to $y$ by the Euclidean relation. |
/-
Copyright (c) 2021 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import data.sigma.basic
import order.rel_classes
/-!
# Lexicographic order on a sigma type
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This defines the lexicographical order of two arbitrary relations on a sigma type and proves some
lemmas about `psigma.lex`, which is defined in core Lean.
Given a relation in the index type and a relation on each summand, the lexicographical order on the
sigma type relates `a` and `b` if their summands are related or they are in the same summand and
related by the summand's relation.
## See also
Related files are:
* `data.finset.colex`: Colexicographic order on finite sets.
* `data.list.lex`: Lexicographic order on lists.
* `data.sigma.order`: Lexicographic order on `Σ i, α i` per say.
* `data.psigma.order`: Lexicographic order on `Σ' i, α i`.
* `data.prod.lex`: Lexicographic order on `α × β`. Can be thought of as the special case of
`sigma.lex` where all summands are the same
-/
namespace sigma
variables {ι : Type*} {α : ι → Type*} {r r₁ r₂ : ι → ι → Prop} {s s₁ s₂ : Π i, α i → α i → Prop}
{a b : Σ i, α i}
/-- The lexicographical order on a sigma type. It takes in a relation on the index type and a
relation for each summand. `a` is related to `b` iff their summands are related or they are in the
same summand and are related through the summand's relation. -/
inductive lex (r : ι → ι → Prop) (s : Π i, α i → α i → Prop) : Π a b : Σ i, α i, Prop
| left {i j : ι} (a : α i) (b : α j) : r i j → lex ⟨i, a⟩ ⟨j, b⟩
| right {i : ι} (a b : α i) : s i a b → lex ⟨i, a⟩ ⟨i, b⟩
lemma lex_iff : lex r s a b ↔ r a.1 b.1 ∨ ∃ h : a.1 = b.1, s _ (h.rec a.2) b.2 :=
begin
split,
{ rintro (⟨a, b, hij⟩ | ⟨a, b, hab⟩),
{ exact or.inl hij },
{ exact or.inr ⟨rfl, hab⟩ } },
{ obtain ⟨i, a⟩ := a,
obtain ⟨j, b⟩ := b,
dsimp only,
rintro (h | ⟨rfl, h⟩),
{ exact lex.left _ _ h },
{ exact lex.right _ _ h } }
end
instance lex.decidable (r : ι → ι → Prop) (s : Π i, α i → α i → Prop) [decidable_eq ι]
[decidable_rel r] [Π i, decidable_rel (s i)] :
decidable_rel (lex r s) :=
λ a b, decidable_of_decidable_of_iff infer_instance lex_iff.symm
lemma lex.mono (hr : ∀ a b, r₁ a b → r₂ a b) (hs : ∀ i a b, s₁ i a b → s₂ i a b) {a b : Σ i, α i}
(h : lex r₁ s₁ a b) :
lex r₂ s₂ a b :=
begin
obtain (⟨a, b, hij⟩ | ⟨a, b, hab⟩) := h,
{ exact lex.left _ _ (hr _ _ hij) },
{ exact lex.right _ _ (hs _ _ _ hab) }
end
lemma lex.mono_left (hr : ∀ a b, r₁ a b → r₂ a b) {a b : Σ i, α i} (h : lex r₁ s a b) :
lex r₂ s a b :=
h.mono hr $ λ _ _ _, id
lemma lex.mono_right (hs : ∀ i a b, s₁ i a b → s₂ i a b) {a b : Σ i, α i} (h : lex r s₁ a b) :
lex r s₂ a b :=
h.mono (λ _ _, id) hs
instance [Π i, is_refl (α i) (s i)] : is_refl _ (lex r s) := ⟨λ ⟨i, a⟩, lex.right _ _ $ refl _⟩
instance [is_irrefl ι r] [Π i, is_irrefl (α i) (s i)] : is_irrefl _ (lex r s) :=
⟨begin
rintro _ (⟨a, b, hi⟩ | ⟨a, b, ha⟩),
{ exact irrefl _ hi },
{ exact irrefl _ ha }
end⟩
instance [is_trans ι r] [Π i, is_trans (α i) (s i)] : is_trans _ (lex r s) :=
⟨begin
rintro _ _ _ (⟨a, b, hij⟩ | ⟨a, b, hab⟩) (⟨_, c, hk⟩ | ⟨_, c, hc⟩),
{ exact lex.left _ _ (trans hij hk) },
{ exact lex.left _ _ hij },
{ exact lex.left _ _ hk },
{ exact lex.right _ _ (trans hab hc) }
end⟩
instance [is_symm ι r] [Π i, is_symm (α i) (s i)] : is_symm _ (lex r s) :=
⟨begin
rintro _ _ (⟨a, b, hij⟩ | ⟨a, b, hab⟩),
{ exact lex.left _ _ (symm hij) },
{ exact lex.right _ _ (symm hab) }
end⟩
local attribute [instance] is_asymm.is_irrefl
instance [is_asymm ι r] [Π i, is_antisymm (α i) (s i)] : is_antisymm _ (lex r s) :=
⟨begin
rintro _ _ (⟨a, b, hij⟩ | ⟨a, b, hab⟩) (⟨_, _, hji⟩ | ⟨_, _, hba⟩),
{ exact (asymm hij hji).elim },
{ exact (irrefl _ hij).elim },
{ exact (irrefl _ hji).elim },
{ exact ext rfl (heq_of_eq $ antisymm hab hba) }
end⟩
instance [is_trichotomous ι r] [Π i, is_total (α i) (s i)] : is_total _ (lex r s) :=
⟨begin
rintro ⟨i, a⟩ ⟨j, b⟩,
obtain hij | rfl | hji := trichotomous_of r i j,
{ exact or.inl (lex.left _ _ hij) },
{ obtain hab | hba := total_of (s i) a b,
{ exact or.inl (lex.right _ _ hab) },
{ exact or.inr (lex.right _ _ hba) } },
{ exact or.inr (lex.left _ _ hji) }
end⟩
instance [is_trichotomous ι r] [Π i, is_trichotomous (α i) (s i)] : is_trichotomous _ (lex r s) :=
⟨begin
rintro ⟨i, a⟩ ⟨j, b⟩,
obtain hij | rfl | hji := trichotomous_of r i j,
{ exact or.inl (lex.left _ _ hij) },
{ obtain hab | rfl | hba := trichotomous_of (s i) a b,
{ exact or.inl (lex.right _ _ hab) },
{ exact or.inr (or.inl rfl) },
{ exact or.inr (or.inr $ lex.right _ _ hba) } },
{ exact or.inr (or.inr $ lex.left _ _ hji) }
end⟩
end sigma
/-! ### `psigma` -/
namespace psigma
variables {ι : Sort*} {α : ι → Sort*} {r r₁ r₂ : ι → ι → Prop} {s s₁ s₂ : Π i, α i → α i → Prop}
lemma lex_iff {a b : Σ' i, α i} : lex r s a b ↔ r a.1 b.1 ∨ ∃ h : a.1 = b.1, s _ (h.rec a.2) b.2 :=
begin
split,
{ rintro (⟨a, b, hij⟩ | ⟨i, hab⟩),
{ exact or.inl hij },
{ exact or.inr ⟨rfl, hab⟩ } },
{ obtain ⟨i, a⟩ := a,
obtain ⟨j, b⟩ := b,
dsimp only,
rintro (h | ⟨rfl, h⟩),
{ exact lex.left _ _ h },
{ exact lex.right _ h } }
end
instance lex.decidable (r : ι → ι → Prop) (s : Π i, α i → α i → Prop) [decidable_eq ι]
[decidable_rel r] [Π i, decidable_rel (s i)] :
decidable_rel (lex r s) :=
λ a b, decidable_of_decidable_of_iff infer_instance lex_iff.symm
lemma lex.mono {r₁ r₂ : ι → ι → Prop} {s₁ s₂ : Π i, α i → α i → Prop}
(hr : ∀ a b, r₁ a b → r₂ a b) (hs : ∀ i a b, s₁ i a b → s₂ i a b) {a b : Σ' i, α i}
(h : lex r₁ s₁ a b) :
lex r₂ s₂ a b :=
begin
obtain (⟨a, b, hij⟩ | ⟨i, hab⟩) := h,
{ exact lex.left _ _ (hr _ _ hij) },
{ exact lex.right _ (hs _ _ _ hab) }
end
lemma lex.mono_left {r₁ r₂ : ι → ι → Prop} {s : Π i, α i → α i → Prop}
(hr : ∀ a b, r₁ a b → r₂ a b) {a b : Σ' i, α i} (h : lex r₁ s a b) :
lex r₂ s a b :=
h.mono hr $ λ _ _ _, id
lemma lex.mono_right {r : ι → ι → Prop} {s₁ s₂ : Π i, α i → α i → Prop}
(hs : ∀ i a b, s₁ i a b → s₂ i a b) {a b : Σ' i, α i} (h : lex r s₁ a b) :
lex r s₂ a b :=
h.mono (λ _ _, id) hs
end psigma
|
```python
from kanren import run, var, fact
import kanren.assoccomm as la
# 足し算(add)と掛け算(mul)
# addとmulはルールの名前なだけ
add = 'addition'
mul = 'multiplication'
# 足し算、掛け算は交換法則(commutative)、結合法則(associative)を持つ事をfactを使って宣言する
# 交換法則とは、入れ替えても結果が変わらない事。足し算も掛け算も入れ替えても答えは変わらない
# 結合法則とは、カッコの位置を変えても変わらない事。足し算だけの式、掛け算だけの式はカッコの位置が変わっても答えは変わらない
# 交換法則も結合法則も文字列をどう扱うかといったルールでも使える
fact(la.commutative, mul)
fact(la.commutative, add)
fact(la.associative, mul)
fact(la.associative, add)
a, b, c = var('a'), var('b'), var('c')
expression_orig = (add, (mul, 3, -2), (mul, (add, 1, (mul, 2, 3)), -1))
expression1 = (add, (mul, (add, 1, (mul, 2, a)), b), (mul, 3, c))
expression2 = (add, (mul, 3, c), (mul, b, (add, (mul, 2, a), 1)))
expression3 = (add, (add, (mul, (mul, 2, a), b), b), (mul, 3, c))
```
この式を例に
$$
expression\_orig = 3 \times (-2) + (1 + 2 \times 3) \times (-1)
$$
変数で置き換えた式を照合する
$$
\begin{align}
&expression1 = (1 + 2 \times a) \times b + 3 \times c\\
&expression2 = c \times 3 + b \times (2 \times a + 1)\\
&expression3 = (((2 \times a) \times b) + b) + 3 \times c
\end{align}
$$
expression1〜3は数学的に同じ式
```python
print(run(0, (a, b, c), la.eq_assoccomm(expression1, expression_orig)))
print(run(0, (a, b, c), la.eq_assoccomm(expression2, expression_orig)))
print(run(0, (a, b, c), la.eq_assoccomm(expression3, expression_orig)))
```
((3, -1, -2),)
((3, -1, -2),)
()
1番目と2番目の式は一緒。3番目は構造的に異なる(らしい)
run(答えの個数, (欲しい答えの変数),
分配法則を定義していないから??
`eq_assoccomm`が分からん。。。
|
-- |
-- Tests for data serialization instances
module Tests.Serialization where
import Data.Binary (Binary,decode,encode)
import Data.Aeson (FromJSON,ToJSON,Result(..),toJSON,fromJSON)
import Data.Typeable
import Statistics.Distribution.Beta (BetaDistribution)
import Statistics.Distribution.Binomial (BinomialDistribution)
import Statistics.Distribution.CauchyLorentz
import Statistics.Distribution.ChiSquared (ChiSquared)
import Statistics.Distribution.Exponential (ExponentialDistribution)
import Statistics.Distribution.FDistribution (FDistribution)
import Statistics.Distribution.Gamma (GammaDistribution)
import Statistics.Distribution.Geometric
import Statistics.Distribution.Hypergeometric
import Statistics.Distribution.Laplace (LaplaceDistribution)
import Statistics.Distribution.Normal (NormalDistribution)
import Statistics.Distribution.Poisson (PoissonDistribution)
import Statistics.Distribution.StudentT
import Statistics.Distribution.Transform (LinearTransform)
import Statistics.Distribution.Uniform (UniformDistribution)
import Statistics.Types
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.QuickCheck (testProperty)
import Test.QuickCheck as QC
import Tests.Helpers
import Tests.Orphanage ()
tests :: TestTree
tests = testGroup "Test for data serialization"
[ serializationTests (T :: T (CL Float))
, serializationTests (T :: T (CL Double))
, serializationTests (T :: T (PValue Float))
, serializationTests (T :: T (PValue Double))
, serializationTests (T :: T (NormalErr Double))
, serializationTests (T :: T (ConfInt Double))
, serializationTests' "T (Estimate NormalErr Double)" (T :: T (Estimate NormalErr Double))
, serializationTests' "T (Estimate ConfInt Double)" (T :: T (Estimate ConfInt Double))
, serializationTests (T :: T (LowerLimit Double))
, serializationTests (T :: T (UpperLimit Double))
-- Distributions
, serializationTests (T :: T BetaDistribution )
, serializationTests (T :: T CauchyDistribution )
, serializationTests (T :: T ChiSquared )
, serializationTests (T :: T ExponentialDistribution )
, serializationTests (T :: T GammaDistribution )
, serializationTests (T :: T LaplaceDistribution )
, serializationTests (T :: T NormalDistribution )
, serializationTests (T :: T UniformDistribution )
, serializationTests (T :: T StudentT )
, serializationTests (T :: T (LinearTransform NormalDistribution))
, serializationTests (T :: T FDistribution )
, serializationTests (T :: T BinomialDistribution )
, serializationTests (T :: T GeometricDistribution )
, serializationTests (T :: T GeometricDistribution0 )
, serializationTests (T :: T HypergeometricDistribution )
, serializationTests (T :: T PoissonDistribution )
]
serializationTests
:: (Eq a, Typeable a, Binary a, Show a, Read a, ToJSON a, FromJSON a, Arbitrary a)
=> T a -> TestTree
serializationTests t = serializationTests' (typeName t) t
-- Not all types are Typeable, unfortunately
serializationTests'
:: (Eq a, Binary a, Show a, Read a, ToJSON a, FromJSON a, Arbitrary a)
=> String -> T a -> TestTree
serializationTests' name t = testGroup ("Tests for: " ++ name)
[ testProperty "show/read" (p_showRead t)
, testProperty "binary" (p_binary t)
, testProperty "aeson" (p_aeson t)
]
p_binary :: (Eq a, Binary a) => T a -> a -> Bool
p_binary _ a = a == (decode . encode) a
p_showRead :: (Eq a, Read a, Show a) => T a -> a -> Bool
p_showRead _ a = a == (read . show) a
p_aeson :: (Eq a, ToJSON a, FromJSON a) => T a -> a -> Bool
p_aeson _ a = Data.Aeson.Success a == (fromJSON . toJSON) a
|
// Copyright (c) 2007-2014 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#if !defined(HPX_PARALLEL_DETAIL_IS_NEGATIVE_JUL_2014_01_0148PM)
#define HPX_PARALLEL_DETAIL_IS_NEGATIVE_JUL_2014_01_0148PM
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_signed.hpp>
#include <boost/type_traits/is_unsigned.hpp>
namespace hpx { namespace parallel { HPX_INLINE_NAMESPACE(v1) { namespace detail
{
// main template represents non-integral types (raises error)
template <typename Size, typename Enable = void>
struct is_negative;
// signed integral values may be negative
template <typename Size>
struct is_negative<Size,
typename boost::enable_if<boost::is_signed<Size> >::type>
{
static bool call(Size const& size) { return size < 0; }
};
// unsigned integral values are never negative
template <typename Size>
struct is_negative<Size,
typename boost::enable_if<boost::is_unsigned<Size> >::type>
{
static bool call(Size const&) { return false; }
};
}}}}
#endif
|
! 6.2a в учебнике
program ex_6_2a
implicit none
integer, parameter :: R_ = 16
real(R_), parameter :: PI = 4*ATAN(1.0)
real(R_) :: x = 0, numerator = 0, currentElement = 0, currentSum = 0, newSum = 0, numeratorDiff = 0
integer :: In = 0, Out = 0, denominator = 0, i = 0, denominator_fact = 0, denominator_mul = 0
character(*), parameter :: output_file = "output.txt", input_file = "../data/input.txt"
open (file=input_file, newunit=In)
read(In,*) x
close (In)
currentElement = 1
numerator = 1
denominator = 1
denominator_fact = 1
numeratorDiff = x**2
do while (denominator > 0)
i = i + 1
newSum = currentSum + currentElement
currentSum = newSum
numerator = - numerator * numeratorDiff
denominator_fact = denominator_fact * i
denominator_mul = (2 * i) + 1
denominator = denominator_fact * denominator_mul
currentElement = numerator / denominator
enddo
open (file=output_file, newunit=Out)
write(Out, '(f5.2,a,f5.2)') (2 * x) / sqrt(PI) * currentSum, ' ~' , erf(x)
close (Out)
end program ex_6_2a
|
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE EmptyCase #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveGeneric #-}
-- {-# OPTIONS_GHC -O -ddump-rule-firings #-}
-- | Provides the class `ParamSet` which is used to represent the set of
-- parameters of a particular model. The goal of SGD is then to find the
-- parameter values which minimize a given objective function.
module Numeric.SGD.ParamSet
(
-- * Class
ParamSet(..)
-- * Generics
, GPMap
, GAdd
, GSub
, GDiv
, GMul
, GNorm2
) where
import GHC.Generics
import GHC.TypeNats (KnownNat)
import Prelude hiding (div)
import qualified Data.Map.Strict as M
import qualified Numeric.LinearAlgebra.Static as LA
-- | Class of types that can be treated as parameter sets. It provides basic
-- element-wise operations (addition, multiplication, mapping) which are
-- required to perform stochastic gradient descent. Many of the operations
-- (`add`, `mul`, `sub`, `div`, etc.) have the same interpretation and follow
-- the same laws (e.g. associativity) as the corresponding operations in `Num`
-- and `Fractional`.
--
-- `zero` takes a parameter set as argument and "zero out"'s all its elements
-- (as in the backprop library). This allows instances for `Maybe`, `M.Map`,
-- etc., where the structure of the parameter set is dynamic. This leads to
-- the following property:
--
-- @add (zero x) x = x@
--
-- However, `zero` does not have to obey @(add (zero x) y = y)@.
--
-- A `ParamSet` can be also seen as a (structured) vector, hence `pmap` and
-- `norm_2`. The latter is not strictly necessary to perform SGD, but it is
-- useful to control the training process.
--
-- `pmap` should obey the following law:
--
-- @pmap id x = x@
--
-- If you leave the body of an instance declaration blank, GHC Generics will be
-- used to derive instances if the type has a single constructor and each field
-- is an instance of `ParamSet`.
class ParamSet a where
-- | Element-wise mapping
pmap :: (Double -> Double) -> a -> a
-- | Zero-out all elements
zero :: a -> a
zero = pmap (const 0.0)
-- -- | Element-wise negation
-- neg :: a -> a
-- neg = pmap (\x -> -x)
-- | Element-wise addition
add :: a -> a -> a
-- | Elementi-wise substruction
sub :: a -> a -> a
-- | Element-wise multiplication
mul :: a -> a -> a
-- | Element-wise division
div :: a -> a -> a
-- | L2 norm
norm_2 :: a -> Double
-- default zero :: (Generic a, GZero (Rep a)) => a -> a
-- zero = genericZero
-- {-# INLINE zero #-}
default pmap
:: (Generic a, GPMap (Rep a))
=> (Double -> Double) -> a -> a
pmap = genericPMap
{-# INLINE pmap #-}
default add :: (Generic a, GAdd (Rep a)) => a -> a -> a
add = genericAdd
{-# INLINE add #-}
default sub :: (Generic a, GSub (Rep a)) => a -> a -> a
sub = genericSub
{-# INLINE sub #-}
default mul :: (Generic a, GMul (Rep a)) => a -> a -> a
mul = genericMul
{-# INLINE mul #-}
default div :: (Generic a, GDiv (Rep a)) => a -> a -> a
div = genericDiv
{-# INLINE div #-}
default norm_2 :: (Generic a, GNorm2 (Rep a)) => a -> Double
norm_2 = genericNorm2
{-# INLINE norm_2 #-}
{-# RULES
"ParamSet pmap/pmap" forall f g p. pmap f (pmap g p) = pmap (f . g) p
#-}
-- {-# RULES
-- "ParamSet pmap/add/pmap" forall f g p h q.
-- pmap f (add (pmap g p) (pmap h q))
-- = add (pmap (f . g) p) (pmap (f . h) q)
-- #-}
-- -- | 'add' using GHC Generics; works if all fields are instances of
-- -- 'ParamSet', but only for values with single constructors.
-- genericZero :: (Generic a, GZero (Rep a)) => a -> a
-- genericZero x = to $ gzero (from x)
-- {-# INLINE genericZero #-}
-- | 'add' using GHC Generics; works if all fields are instances of
-- 'ParamSet', but only for values with single constructors.
genericAdd :: (Generic a, GAdd (Rep a)) => a -> a -> a
genericAdd x y = to $ gadd (from x) (from y)
{-# INLINE genericAdd #-}
-- | 'sub' using GHC Generics; works if all fields are instances of
-- 'ParamSet', but only for values with single constructors.
genericSub :: (Generic a, GSub (Rep a)) => a -> a -> a
genericSub x y = to $ gsub (from x) (from y)
{-# INLINE genericSub #-}
-- | 'div' using GHC Generics; works if all fields are instances of
-- 'ParamSet', but only for values with single constructors.
genericDiv :: (Generic a, GDiv (Rep a)) => a -> a -> a
genericDiv x y = to $ gdiv (from x) (from y)
{-# INLINE genericDiv #-}
-- | 'mul' using GHC Generics; works if all fields are instances of
-- 'ParamSet', but only for values with single constructors.
genericMul :: (Generic a, GMul (Rep a)) => a -> a -> a
genericMul x y = to $ gmul (from x) (from y)
{-# INLINE genericMul #-}
-- | 'norm_2' using GHC Generics; works if all fields are instances of
-- 'ParamSet', but only for values with single constructors.
genericNorm2 :: (Generic a, GNorm2 (Rep a)) => a -> Double
genericNorm2 x = gnorm_2 (from x)
{-# INLINE genericNorm2 #-}
-- | 'pmap' using GHC Generics; works if all fields are instances of
-- 'ParamSet', but only for values with single constructors.
genericPMap :: (Generic a, GPMap (Rep a)) => (Double -> Double) -> a -> a
genericPMap f x = to $ gpmap f (from x)
{-# INLINE genericPMap #-}
--------------------------------------------------
-- Generics
--
-- Partially borrowed from the backprop library
--------------------------------------------------
-- -- | Helper class for automatically deriving 'add' using GHC Generics.
-- class GZero f where
-- gzero :: f t -> f t
--
-- instance ParamSet p => GZero (K1 i p) where
-- gzero (K1 x) = K1 (zero x)
-- {-# INLINE gzero #-}
--
-- instance (GZero f, GZero g) => GZero (f :*: g) where
-- gzero (x1 :*: y1) = x2 :*: y2
-- where
-- !x2 = gzero x1
-- !y2 = gzero y1
-- {-# INLINE gzero #-}
--
-- instance GZero V1 where
-- gzero = \case {}
-- {-# INLINE gzero #-}
--
-- instance GZero U1 where
-- gzero _ = U1
-- {-# INLINE gzero #-}
--
-- instance GZero f => GZero (M1 i c f) where
-- gzero (M1 x) = M1 (gzero x)
-- {-# INLINE gzero #-}
--
-- -- instance GZero f => GZero (f :.: g) where
-- -- gzero = Comp1 gzero
-- -- {-# INLINE gzero #-}
-- | Helper class for automatically deriving 'add' using GHC Generics.
class GAdd f where
gadd :: f t -> f t -> f t
instance ParamSet a => GAdd (K1 i a) where
gadd (K1 x) (K1 y) = K1 (add x y)
{-# INLINE gadd #-}
instance (GAdd f, GAdd g) => GAdd (f :*: g) where
gadd (x1 :*: y1) (x2 :*: y2) = x3 :*: y3
where
!x3 = gadd x1 x2
!y3 = gadd y1 y2
{-# INLINE gadd #-}
instance GAdd V1 where
gadd = \case {}
{-# INLINE gadd #-}
instance GAdd U1 where
gadd _ _ = U1
{-# INLINE gadd #-}
instance GAdd f => GAdd (M1 i c f) where
gadd (M1 x) (M1 y) = M1 (gadd x y)
{-# INLINE gadd #-}
-- instance GAdd f => GAdd (f :.: g) where
-- gadd (Comp1 x) (Comp1 y) = Comp1 (gadd x y)
-- {-# INLINE gadd #-}
-- | Helper class for automatically deriving 'sub' using GHC Generics.
class GSub f where
gsub :: f t -> f t -> f t
instance ParamSet a => GSub (K1 i a) where
gsub (K1 x) (K1 y) = K1 (sub x y)
{-# INLINE gsub #-}
instance (GSub f, GSub g) => GSub (f :*: g) where
gsub (x1 :*: y1) (x2 :*: y2) = x3 :*: y3
where
!x3 = gsub x1 x2
!y3 = gsub y1 y2
{-# INLINE gsub #-}
instance GSub V1 where
gsub = \case {}
{-# INLINE gsub #-}
instance GSub U1 where
gsub _ _ = U1
{-# INLINE gsub #-}
instance GSub f => GSub (M1 i c f) where
gsub (M1 x) (M1 y) = M1 (gsub x y)
{-# INLINE gsub #-}
-- instance GSub f => GSub (f :.: g) where
-- gsub (Comp1 x) (Comp1 y) = Comp1 (gsub x y)
-- {-# INLINE gsub #-}
-- | Helper class for automatically deriving 'mul' using GHC Generics.
class GMul f where
gmul :: f t -> f t -> f t
instance ParamSet a => GMul (K1 i a) where
gmul (K1 x) (K1 y) = K1 (mul x y)
{-# INLINE gmul #-}
instance (GMul f, GMul g) => GMul (f :*: g) where
gmul (x1 :*: y1) (x2 :*: y2) = x3 :*: y3
where
!x3 = gmul x1 x2
!y3 = gmul y1 y2
{-# INLINE gmul #-}
instance GMul V1 where
gmul = \case {}
{-# INLINE gmul #-}
instance GMul U1 where
gmul _ _ = U1
{-# INLINE gmul #-}
instance GMul f => GMul (M1 i c f) where
gmul (M1 x) (M1 y) = M1 (gmul x y)
{-# INLINE gmul #-}
-- instance GMul f => GMul (f :.: g) where
-- gmul (Comp1 x) (Comp1 y) = Comp1 (gmul x y)
-- {-# INLINE gmul #-}
-- | Helper class for automatically deriving 'div' using GHC Generics.
class GDiv f where
gdiv :: f t -> f t -> f t
instance ParamSet a => GDiv (K1 i a) where
gdiv (K1 x) (K1 y) = K1 (div x y)
{-# INLINE gdiv #-}
instance (GDiv f, GDiv g) => GDiv (f :*: g) where
gdiv (x1 :*: y1) (x2 :*: y2) = x3 :*: y3
where
!x3 = gdiv x1 x2
!y3 = gdiv y1 y2
{-# INLINE gdiv #-}
instance GDiv V1 where
gdiv = \case {}
{-# INLINE gdiv #-}
instance GDiv U1 where
gdiv _ _ = U1
{-# INLINE gdiv #-}
instance GDiv f => GDiv (M1 i c f) where
gdiv (M1 x) (M1 y) = M1 (gdiv x y)
{-# INLINE gdiv #-}
-- instance GDiv f => GDiv (f :.: g) where
-- gdiv (Comp1 x) (Comp1 y) = Comp1 (gdiv x y)
-- {-# INLINE gdiv #-}
-- | Helper class for automatically deriving 'norm_2' using GHC Generics.
class GNorm2 f where
gnorm_2 :: f t -> Double
instance ParamSet a => GNorm2 (K1 i a) where
gnorm_2 (K1 x) = norm_2 x
{-# INLINE gnorm_2 #-}
instance (GNorm2 f, GNorm2 g) => GNorm2 (f :*: g) where
gnorm_2 (x1 :*: y1) =
sqrt ((x2 ^ (2 :: Int)) + (y2 ^ (2 :: Int)))
where
!x2 = gnorm_2 x1
!y2 = gnorm_2 y1
{-# INLINE gnorm_2 #-}
instance GNorm2 V1 where
gnorm_2 = \case {}
{-# INLINE gnorm_2 #-}
instance GNorm2 U1 where
gnorm_2 _ = 0
{-# INLINE gnorm_2 #-}
instance GNorm2 f => GNorm2 (M1 i c f) where
gnorm_2 (M1 x) = gnorm_2 x
{-# INLINE gnorm_2 #-}
-- -- TODO: Make sure this makes sense
-- instance GNorm2 f => GNorm2 (f :.: g) where
-- gnorm_2 (Comp1 x) = gnorm_2 x
-- {-# INLINE gnorm_2 #-}
-- | Helper class for automatically deriving 'pmap' using GHC Generics.
class GPMap f where
gpmap :: (Double -> Double) -> f t -> f t
instance ParamSet a => GPMap (K1 i a) where
gpmap f (K1 x) = K1 (pmap f x)
{-# INLINE gpmap #-}
instance (GPMap f, GPMap g) => GPMap (f :*: g) where
gpmap f (x1 :*: y1) = x2 :*: y2
where
!x2 = gpmap f x1
!y2 = gpmap f y1
{-# INLINE gpmap #-}
instance GPMap V1 where
gpmap _ = \case {}
{-# INLINE gpmap #-}
instance GPMap U1 where
gpmap _ _ = U1
{-# INLINE gpmap #-}
instance GPMap f => GPMap (M1 i c f) where
gpmap f (M1 x) = M1 (gpmap f x)
{-# INLINE gpmap #-}
-- instance GPMap f => GPMap (f :.: g) where
-- gpmap f (Comp1 x) = Comp1 (gpmap f x)
-- {-# INLINE gpmap #-}
--------------------------------------------------
-- Basic instances
--------------------------------------------------
instance ParamSet Double where
zero = const 0
pmap = id
add = (+)
sub = (-)
mul = (*)
div = (/)
norm_2 = abs
instance (ParamSet a, ParamSet b) => ParamSet (a, b) where
pmap f (x, y) = (pmap f x, pmap f y)
add (x1, y1) (x2, y2) = (x1 `add` x2, y1 `add` y2)
sub (x1, y1) (x2, y2) = (x1 `sub` x2, y1 `sub` y2)
mul (x1, y1) (x2, y2) = (x1 `mul` x2, y1 `mul` y2)
div (x1, y1) (x2, y2) = (x1 `div` x2, y1 `div` y2)
norm_2 (x, y)
= sqrt . sum . map ((^(2::Int)))
$ [norm_2 x, norm_2 y]
instance (KnownNat n) => ParamSet (LA.R n) where
zero = const 0
pmap = LA.dvmap
add = (+)
sub = (-)
mul = (*)
div = (/)
norm_2 = LA.norm_2
instance (KnownNat n, KnownNat m) => ParamSet (LA.L n m) where
zero = const 0
pmap = LA.dmmap
add = (+)
sub = (-)
mul = (*)
div = (/)
norm_2 = LA.norm_2
-- | `Nothing` represents a deactivated parameter set component. If `Nothing`
-- is given as an argument to one of the `ParamSet` operations, the result is
-- `Nothing` as well.
--
-- This differs from the corresponding instance in the backprop library, where
-- `Nothing` is equivalent to `Just 0`. However, the implementation below
-- seems to correspond adequately enough to the notion that a particular
-- component is either active or not in both the parameter set and the
-- gradient, hence it doesn't make sense to combine `Just` with `Nothing`.
instance (ParamSet a) => ParamSet (Maybe a) where
zero = fmap zero
pmap = fmap . pmap
add (Just x) (Just y) = Just (add x y)
add _ _ = Nothing
sub (Just x) (Just y) = Just (sub x y)
sub _ _ = Nothing
mul (Just x) (Just y) = Just (mul x y)
mul _ _ = Nothing
div (Just x) (Just y) = Just (div x y)
div _ _ = Nothing
norm_2 = maybe 0 norm_2
-- | A map with different parameter sets (of the same type) assigned to the
-- individual keys.
--
-- When combining two maps with different sets of keys, only their intersection
-- is preserved.
instance (Ord k, ParamSet a) => ParamSet (M.Map k a) where
zero = fmap zero
pmap f = fmap (pmap f)
add = M.intersectionWith add
sub = M.intersectionWith sub
mul= M.intersectionWith mul
div= M.intersectionWith div
norm_2 = sqrt . sum . map ((^(2::Int)) . norm_2) . M.elems
|
!* Copyright (c) 1997, NVIDIA CORPORATION. All rights reserved.
!*
!* Licensed under the Apache License, Version 2.0 (the "License");
!* you may not use this file except in compliance with the License.
!* You may obtain a copy of the License at
!*
!* http://www.apache.org/licenses/LICENSE-2.0
!*
!* Unless required by applicable law or agreed to in writing, software
!* distributed under the License is distributed on an "AS IS" BASIS,
!* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
!* See the License for the specific language governing permissions and
!* limitations under the License.
!
! Derived types
program p
type test
integer,dimension(:,:),pointer:: mem
end type
integer results(9), expect(9)
data expect /4,5,6,7,99,9,10,99,12/
type(test)::a
allocate(a%mem(1:3,1:3))
do i = 1,3
do j = 1,3
a%mem(i,j) = i+j*3
enddo
enddo
where(a%mem(1,:).gt.5)
a%mem(2,:) = 99
endwhere
do i = 1,3
do j = 1,3
k = i+(j-1)*3
results(k) = a%mem(i,j)
enddo
enddo
call check( results, expect, 9)
end
|
Late night meeting reviewing details and duties for Pageant of Hope. These true beauties really know how to spend their Friday night. How blessed we are that Samantha is right there with them and how unconditionally loving they are to her. What a great weekend this is going to be!!!! |
/-
Copyright (c) 2021 Kexing Ying. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kexing Ying
! This file was ported from Lean 3 source module probability.density
! leanprover-community/mathlib commit 17ef379e997badd73e5eabb4d38f11919ab3c4b3
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.MeasureTheory.Decomposition.RadonNikodym
import Mathbin.MeasureTheory.Measure.Lebesgue
/-!
# Probability density function
This file defines the probability density function of random variables, by which we mean
measurable functions taking values in a Borel space. In particular, a measurable function `f`
is said to the probability density function of a random variable `X` if for all measurable
sets `S`, `ℙ(X ∈ S) = ∫ x in S, f x dx`. Probability density functions are one way of describing
the distribution of a random variable, and are useful for calculating probabilities and
finding moments (although the latter is better achieved with moment generating functions).
This file also defines the continuous uniform distribution and proves some properties about
random variables with this distribution.
## Main definitions
* `measure_theory.has_pdf` : A random variable `X : Ω → E` is said to `has_pdf` with
respect to the measure `ℙ` on `Ω` and `μ` on `E` if there exists a measurable function `f`
such that the push-forward measure of `ℙ` along `X` equals `μ.with_density f`.
* `measure_theory.pdf` : If `X` is a random variable that `has_pdf X ℙ μ`, then `pdf X`
is the measurable function `f` such that the push-forward measure of `ℙ` along `X` equals
`μ.with_density f`.
* `measure_theory.pdf.uniform` : A random variable `X` is said to follow the uniform
distribution if it has a constant probability density function with a compact, non-null support.
## Main results
* `measure_theory.pdf.integral_fun_mul_eq_integral` : Law of the unconscious statistician,
i.e. if a random variable `X : Ω → E` has pdf `f`, then `𝔼(g(X)) = ∫ x, g x * f x dx` for
all measurable `g : E → ℝ`.
* `measure_theory.pdf.integral_mul_eq_integral` : A real-valued random variable `X` with
pdf `f` has expectation `∫ x, x * f x dx`.
* `measure_theory.pdf.uniform.integral_eq` : If `X` follows the uniform distribution with
its pdf having support `s`, then `X` has expectation `(λ s)⁻¹ * ∫ x in s, x dx` where `λ`
is the Lebesgue measure.
## TODOs
Ultimately, we would also like to define characteristic functions to describe distributions as
it exists for all random variables. However, to define this, we will need Fourier transforms
which we currently do not have.
-/
noncomputable section
open Classical MeasureTheory NNReal ENNReal
namespace MeasureTheory
open TopologicalSpace MeasureTheory.Measure
variable {Ω E : Type _} [MeasurableSpace E]
/-- A random variable `X : Ω → E` is said to `has_pdf` with respect to the measure `ℙ` on `Ω` and
`μ` on `E` if there exists a measurable function `f` such that the push-forward measure of `ℙ`
along `X` equals `μ.with_density f`. -/
class HasPdf {m : MeasurableSpace Ω} (X : Ω → E) (ℙ : Measure Ω)
(μ : Measure E := by exact MeasureTheory.MeasureSpace.volume) : Prop where
pdf' : Measurable X ∧ ∃ f : E → ℝ≥0∞, Measurable f ∧ map X ℙ = μ.withDensity f
#align measure_theory.has_pdf MeasureTheory.HasPdf
@[measurability]
theorem HasPdf.measurable {m : MeasurableSpace Ω} (X : Ω → E) (ℙ : Measure Ω)
(μ : Measure E := by exact MeasureTheory.MeasureSpace.volume) [hX : HasPdf X ℙ μ] :
Measurable X :=
hX.pdf'.1
#align measure_theory.has_pdf.measurable MeasureTheory.HasPdf.measurable
/-- If `X` is a random variable that `has_pdf X ℙ μ`, then `pdf X` is the measurable function `f`
such that the push-forward measure of `ℙ` along `X` equals `μ.with_density f`. -/
def pdf {m : MeasurableSpace Ω} (X : Ω → E) (ℙ : Measure Ω)
(μ : Measure E := by exact MeasureTheory.MeasureSpace.volume) :=
if hX : HasPdf X ℙ μ then Classical.choose hX.pdf'.2 else 0
#align measure_theory.pdf MeasureTheory.pdf
theorem pdf_undef {m : MeasurableSpace Ω} {ℙ : Measure Ω} {μ : Measure E} {X : Ω → E}
(h : ¬HasPdf X ℙ μ) : pdf X ℙ μ = 0 := by simp only [pdf, dif_neg h]
#align measure_theory.pdf_undef MeasureTheory.pdf_undef
theorem hasPdfOfPdfNeZero {m : MeasurableSpace Ω} {ℙ : Measure Ω} {μ : Measure E} {X : Ω → E}
(h : pdf X ℙ μ ≠ 0) : HasPdf X ℙ μ := by
by_contra hpdf
rw [pdf, dif_neg hpdf] at h
exact hpdf (False.ndrec (has_pdf X ℙ μ) (h rfl))
#align measure_theory.has_pdf_of_pdf_ne_zero MeasureTheory.hasPdfOfPdfNeZero
theorem pdf_eq_zero_of_not_measurable {m : MeasurableSpace Ω} {ℙ : Measure Ω} {μ : Measure E}
{X : Ω → E} (hX : ¬Measurable X) : pdf X ℙ μ = 0 :=
pdf_undef fun hpdf => hX hpdf.pdf'.1
#align measure_theory.pdf_eq_zero_of_not_measurable MeasureTheory.pdf_eq_zero_of_not_measurable
theorem measurable_of_pdf_ne_zero {m : MeasurableSpace Ω} {ℙ : Measure Ω} {μ : Measure E}
(X : Ω → E) (h : pdf X ℙ μ ≠ 0) : Measurable X :=
by
by_contra hX
exact h (pdf_eq_zero_of_not_measurable hX)
#align measure_theory.measurable_of_pdf_ne_zero MeasureTheory.measurable_of_pdf_ne_zero
@[measurability]
theorem measurable_pdf {m : MeasurableSpace Ω} (X : Ω → E) (ℙ : Measure Ω)
(μ : Measure E := by exact MeasureTheory.MeasureSpace.volume) : Measurable (pdf X ℙ μ) :=
by
by_cases hX : has_pdf X ℙ μ
· rw [pdf, dif_pos hX]
exact (Classical.choose_spec hX.pdf'.2).1
· rw [pdf, dif_neg hX]
exact measurable_zero
#align measure_theory.measurable_pdf MeasureTheory.measurable_pdf
theorem map_eq_withDensity_pdf {m : MeasurableSpace Ω} (X : Ω → E) (ℙ : Measure Ω)
(μ : Measure E := by exact MeasureTheory.MeasureSpace.volume) [hX : HasPdf X ℙ μ] :
Measure.map X ℙ = μ.withDensity (pdf X ℙ μ) :=
by
rw [pdf, dif_pos hX]
exact (Classical.choose_spec hX.pdf'.2).2
#align measure_theory.map_eq_with_density_pdf MeasureTheory.map_eq_withDensity_pdf
theorem map_eq_set_lintegral_pdf {m : MeasurableSpace Ω} (X : Ω → E) (ℙ : Measure Ω)
(μ : Measure E := by exact MeasureTheory.MeasureSpace.volume) [hX : HasPdf X ℙ μ] {s : Set E}
(hs : MeasurableSet s) : Measure.map X ℙ s = ∫⁻ x in s, pdf X ℙ μ x ∂μ := by
rw [← with_density_apply _ hs, map_eq_with_density_pdf X ℙ μ]
#align measure_theory.map_eq_set_lintegral_pdf MeasureTheory.map_eq_set_lintegral_pdf
namespace Pdf
variable {m : MeasurableSpace Ω} {ℙ : Measure Ω} {μ : Measure E}
theorem lintegral_eq_measure_univ {X : Ω → E} [HasPdf X ℙ μ] :
(∫⁻ x, pdf X ℙ μ x ∂μ) = ℙ Set.univ := by
rw [← set_lintegral_univ, ← map_eq_set_lintegral_pdf X ℙ μ MeasurableSet.univ,
measure.map_apply (has_pdf.measurable X ℙ μ) MeasurableSet.univ, Set.preimage_univ]
#align measure_theory.pdf.lintegral_eq_measure_univ MeasureTheory.pdf.lintegral_eq_measure_univ
theorem ae_lt_top [IsFiniteMeasure ℙ] {μ : Measure E} {X : Ω → E} : ∀ᵐ x ∂μ, pdf X ℙ μ x < ∞ :=
by
by_cases hpdf : has_pdf X ℙ μ
· haveI := hpdf
refine' ae_lt_top (measurable_pdf X ℙ μ) _
rw [lintegral_eq_measure_univ]
exact (measure_lt_top _ _).Ne
· rw [pdf, dif_neg hpdf]
exact Filter.eventually_of_forall fun x => WithTop.zero_lt_top
#align measure_theory.pdf.ae_lt_top MeasureTheory.pdf.ae_lt_top
theorem ofReal_toReal_ae_eq [IsFiniteMeasure ℙ] {X : Ω → E} :
(fun x => ENNReal.ofReal (pdf X ℙ μ x).toReal) =ᵐ[μ] pdf X ℙ μ :=
ofReal_toReal_ae_eq ae_lt_top
#align measure_theory.pdf.of_real_to_real_ae_eq MeasureTheory.pdf.ofReal_toReal_ae_eq
theorem integrable_iff_integrable_mul_pdf [IsFiniteMeasure ℙ] {X : Ω → E} [HasPdf X ℙ μ] {f : E → ℝ}
(hf : Measurable f) :
Integrable (fun x => f (X x)) ℙ ↔ Integrable (fun x => f x * (pdf X ℙ μ x).toReal) μ :=
by
rw [← integrable_map_measure hf.ae_strongly_measurable (has_pdf.measurable X ℙ μ).AeMeasurable,
map_eq_with_density_pdf X ℙ μ, integrable_with_density_iff (measurable_pdf _ _ _) ae_lt_top]
infer_instance
#align measure_theory.pdf.integrable_iff_integrable_mul_pdf MeasureTheory.pdf.integrable_iff_integrable_mul_pdf
/-- **The Law of the Unconscious Statistician**: Given a random variable `X` and a measurable
function `f`, `f ∘ X` is a random variable with expectation `∫ x, f x * pdf X ∂μ`
where `μ` is a measure on the codomain of `X`. -/
theorem integral_fun_mul_eq_integral [IsFiniteMeasure ℙ] {X : Ω → E} [HasPdf X ℙ μ] {f : E → ℝ}
(hf : Measurable f) : (∫ x, f x * (pdf X ℙ μ x).toReal ∂μ) = ∫ x, f (X x) ∂ℙ :=
by
by_cases hpdf : integrable (fun x => f x * (pdf X ℙ μ x).toReal) μ
· rw [← integral_map (has_pdf.measurable X ℙ μ).AeMeasurable hf.ae_strongly_measurable,
map_eq_with_density_pdf X ℙ μ, integral_eq_lintegral_pos_part_sub_lintegral_neg_part hpdf,
integral_eq_lintegral_pos_part_sub_lintegral_neg_part,
lintegral_with_density_eq_lintegral_mul _ (measurable_pdf X ℙ μ) hf.neg.ennreal_of_real,
lintegral_with_density_eq_lintegral_mul _ (measurable_pdf X ℙ μ) hf.ennreal_of_real]
· congr 2
· have :
∀ x,
ENNReal.ofReal (f x * (pdf X ℙ μ x).toReal) =
ENNReal.ofReal (pdf X ℙ μ x).toReal * ENNReal.ofReal (f x) :=
by
intro x
rw [mul_comm, ENNReal.ofReal_mul ENNReal.toReal_nonneg]
simp_rw [this]
exact lintegral_congr_ae (Filter.EventuallyEq.mul of_real_to_real_ae_eq (ae_eq_refl _))
· have :
∀ x,
ENNReal.ofReal (-(f x * (pdf X ℙ μ x).toReal)) =
ENNReal.ofReal (pdf X ℙ μ x).toReal * ENNReal.ofReal (-f x) :=
by
intro x
rw [neg_mul_eq_neg_mul, mul_comm, ENNReal.ofReal_mul ENNReal.toReal_nonneg]
simp_rw [this]
exact lintegral_congr_ae (Filter.EventuallyEq.mul of_real_to_real_ae_eq (ae_eq_refl _))
· refine' ⟨hf.ae_strongly_measurable, _⟩
rw [has_finite_integral,
lintegral_with_density_eq_lintegral_mul _ (measurable_pdf _ _ _)
hf.nnnorm.coe_nnreal_ennreal]
have :
(fun x => (pdf X ℙ μ * fun x => ↑‖f x‖₊) x) =ᵐ[μ] fun x => ‖f x * (pdf X ℙ μ x).toReal‖₊ :=
by
simp_rw [← smul_eq_mul, nnnorm_smul, ENNReal.coe_mul]
rw [smul_eq_mul, mul_comm]
refine' Filter.EventuallyEq.mul (ae_eq_refl _) (ae_eq_trans of_real_to_real_ae_eq.symm _)
convert ae_eq_refl _
ext1 x
exact Real.ennnorm_eq_ofReal ENNReal.toReal_nonneg
rw [lintegral_congr_ae this]
exact hpdf.2
· rw [integral_undef hpdf, integral_undef]
rwa [← integrable_iff_integrable_mul_pdf hf] at hpdf
all_goals infer_instance
#align measure_theory.pdf.integral_fun_mul_eq_integral MeasureTheory.pdf.integral_fun_mul_eq_integral
theorem mapAbsolutelyContinuous {X : Ω → E} [HasPdf X ℙ μ] : map X ℙ ≪ μ :=
by
rw [map_eq_with_density_pdf X ℙ μ]
exact with_density_absolutely_continuous _ _
#align measure_theory.pdf.map_absolutely_continuous MeasureTheory.pdf.mapAbsolutelyContinuous
/-- A random variable that `has_pdf` is quasi-measure preserving. -/
theorem toQuasiMeasurePreserving {X : Ω → E} [HasPdf X ℙ μ] : QuasiMeasurePreserving X ℙ μ :=
{ Measurable := HasPdf.measurable X ℙ μ
AbsolutelyContinuous := mapAbsolutelyContinuous }
#align measure_theory.pdf.to_quasi_measure_preserving MeasureTheory.pdf.toQuasiMeasurePreserving
theorem haveLebesgueDecompositionOfHasPdf {X : Ω → E} [hX' : HasPdf X ℙ μ] :
(map X ℙ).HaveLebesgueDecomposition μ :=
⟨⟨⟨0, pdf X ℙ μ⟩, by
simp only [zero_add, measurable_pdf X ℙ μ, true_and_iff, mutually_singular.zero_left,
map_eq_with_density_pdf X ℙ μ]⟩⟩
#align measure_theory.pdf.have_lebesgue_decomposition_of_has_pdf MeasureTheory.pdf.haveLebesgueDecompositionOfHasPdf
theorem hasPdf_iff {X : Ω → E} :
HasPdf X ℙ μ ↔ Measurable X ∧ (map X ℙ).HaveLebesgueDecomposition μ ∧ map X ℙ ≪ μ :=
by
constructor
· intro hX'
exact ⟨hX'.pdf'.1, have_lebesgue_decomposition_of_has_pdf, map_absolutely_continuous⟩
· rintro ⟨hX, h_decomp, h⟩
haveI := h_decomp
refine' ⟨⟨hX, (measure.map X ℙ).rnDeriv μ, measurable_rn_deriv _ _, _⟩⟩
rwa [with_density_rn_deriv_eq]
#align measure_theory.pdf.has_pdf_iff MeasureTheory.pdf.hasPdf_iff
theorem hasPdf_iff_of_measurable {X : Ω → E} (hX : Measurable X) :
HasPdf X ℙ μ ↔ (map X ℙ).HaveLebesgueDecomposition μ ∧ map X ℙ ≪ μ :=
by
rw [has_pdf_iff]
simp only [hX, true_and_iff]
#align measure_theory.pdf.has_pdf_iff_of_measurable MeasureTheory.pdf.hasPdf_iff_of_measurable
section
variable {F : Type _} [MeasurableSpace F] {ν : Measure F}
/-- A random variable that `has_pdf` transformed under a `quasi_measure_preserving`
map also `has_pdf` if `(map g (map X ℙ)).have_lebesgue_decomposition μ`.
`quasi_measure_preserving_has_pdf'` is more useful in the case we are working with a
probability measure and a real-valued random variable. -/
theorem quasiMeasurePreservingHasPdf {X : Ω → E} [HasPdf X ℙ μ] {g : E → F}
(hg : QuasiMeasurePreserving g μ ν) (hmap : (map g (map X ℙ)).HaveLebesgueDecomposition ν) :
HasPdf (g ∘ X) ℙ ν :=
by
rw [has_pdf_iff, ← map_map hg.measurable (has_pdf.measurable X ℙ μ)]
refine' ⟨hg.measurable.comp (has_pdf.measurable X ℙ μ), hmap, _⟩
rw [map_eq_with_density_pdf X ℙ μ]
refine' absolutely_continuous.mk fun s hsm hs => _
rw [map_apply hg.measurable hsm, with_density_apply _ (hg.measurable hsm)]
have := hg.absolutely_continuous hs
rw [map_apply hg.measurable hsm] at this
exact set_lintegral_measure_zero _ _ this
#align measure_theory.pdf.quasi_measure_preserving_has_pdf MeasureTheory.pdf.quasiMeasurePreservingHasPdf
theorem quasiMeasurePreservingHasPdf' [IsFiniteMeasure ℙ] [SigmaFinite ν] {X : Ω → E} [HasPdf X ℙ μ]
{g : E → F} (hg : QuasiMeasurePreserving g μ ν) : HasPdf (g ∘ X) ℙ ν :=
quasiMeasurePreservingHasPdf hg inferInstance
#align measure_theory.pdf.quasi_measure_preserving_has_pdf' MeasureTheory.pdf.quasiMeasurePreservingHasPdf'
end
section Real
variable [IsFiniteMeasure ℙ] {X : Ω → ℝ}
/-- A real-valued random variable `X` `has_pdf X ℙ λ` (where `λ` is the Lebesgue measure) if and
only if the push-forward measure of `ℙ` along `X` is absolutely continuous with respect to `λ`. -/
theorem Real.hasPdf_iff_of_measurable (hX : Measurable X) : HasPdf X ℙ ↔ map X ℙ ≪ volume :=
by
rw [has_pdf_iff_of_measurable hX, and_iff_right_iff_imp]
exact fun h => inferInstance
#align measure_theory.pdf.real.has_pdf_iff_of_measurable MeasureTheory.pdf.Real.hasPdf_iff_of_measurable
theorem Real.hasPdf_iff : HasPdf X ℙ ↔ Measurable X ∧ map X ℙ ≪ volume :=
by
by_cases hX : Measurable X
· rw [real.has_pdf_iff_of_measurable hX, iff_and_self]
exact fun h => hX
infer_instance
· exact ⟨fun h => False.elim (hX h.pdf'.1), fun h => False.elim (hX h.1)⟩
#align measure_theory.pdf.real.has_pdf_iff MeasureTheory.pdf.Real.hasPdf_iff
/-- If `X` is a real-valued random variable that has pdf `f`, then the expectation of `X` equals
`∫ x, x * f x ∂λ` where `λ` is the Lebesgue measure. -/
theorem integral_mul_eq_integral [HasPdf X ℙ] :
(∫ x, x * (pdf X ℙ volume x).toReal) = ∫ x, X x ∂ℙ :=
integral_fun_mul_eq_integral measurable_id
#align measure_theory.pdf.integral_mul_eq_integral MeasureTheory.pdf.integral_mul_eq_integral
theorem hasFiniteIntegralMul {f : ℝ → ℝ} {g : ℝ → ℝ≥0∞} (hg : pdf X ℙ =ᵐ[volume] g)
(hgi : (∫⁻ x, ‖f x‖₊ * g x) ≠ ∞) : HasFiniteIntegral fun x => f x * (pdf X ℙ volume x).toReal :=
by
rw [has_finite_integral]
have : (fun x => ↑‖f x‖₊ * g x) =ᵐ[volume] fun x => ‖f x * (pdf X ℙ volume x).toReal‖₊ :=
by
refine'
ae_eq_trans
(Filter.EventuallyEq.mul (ae_eq_refl fun x => ‖f x‖₊)
(ae_eq_trans hg.symm of_real_to_real_ae_eq.symm))
_
simp_rw [← smul_eq_mul, nnnorm_smul, ENNReal.coe_mul, smul_eq_mul]
refine' Filter.EventuallyEq.mul (ae_eq_refl _) _
convert ae_eq_refl _
ext1 x
exact Real.ennnorm_eq_ofReal ENNReal.toReal_nonneg
rwa [lt_top_iff_ne_top, ← lintegral_congr_ae this]
#align measure_theory.pdf.has_finite_integral_mul MeasureTheory.pdf.hasFiniteIntegralMul
end Real
section
/-! **Uniform Distribution** -/
/-- A random variable `X` has uniform distribution if it has a probability density function `f`
with support `s` such that `f = (μ s)⁻¹ 1ₛ` a.e. where `1ₛ` is the indicator function for `s`. -/
def IsUniform {m : MeasurableSpace Ω} (X : Ω → E) (support : Set E) (ℙ : Measure Ω)
(μ : Measure E := by exact MeasureTheory.MeasureSpace.volume) :=
pdf X ℙ μ =ᵐ[μ] support.indicator ((μ support)⁻¹ • 1)
#align measure_theory.pdf.is_uniform MeasureTheory.pdf.IsUniform
namespace IsUniform
theorem hasPdf {m : MeasurableSpace Ω} {X : Ω → E} {ℙ : Measure Ω} {μ : Measure E} {s : Set E}
(hns : μ s ≠ 0) (hnt : μ s ≠ ∞) (hu : IsUniform X s ℙ μ) : HasPdf X ℙ μ :=
hasPdfOfPdfNeZero
(by
intro hpdf
rw [is_uniform, hpdf] at hu
suffices μ (s ∩ Function.support ((μ s)⁻¹ • 1)) = 0
by
have heq : Function.support ((μ s)⁻¹ • (1 : E → ℝ≥0∞)) = Set.univ :=
by
ext x
rw [Function.mem_support]
simp [hnt]
rw [HEq, Set.inter_univ] at this
exact hns this
exact Set.indicator_ae_eq_zero hu.symm)
#align measure_theory.pdf.is_uniform.has_pdf MeasureTheory.pdf.IsUniform.hasPdf
theorem pdf_toReal_ae_eq {m : MeasurableSpace Ω} {X : Ω → E} {ℙ : Measure Ω} {μ : Measure E}
{s : Set E} (hX : IsUniform X s ℙ μ) :
(fun x => (pdf X ℙ μ x).toReal) =ᵐ[μ] fun x =>
(s.indicator ((μ s)⁻¹ • (1 : E → ℝ≥0∞)) x).toReal :=
Filter.EventuallyEq.fun_comp hX ENNReal.toReal
#align measure_theory.pdf.is_uniform.pdf_to_real_ae_eq MeasureTheory.pdf.IsUniform.pdf_toReal_ae_eq
theorem measure_preimage {m : MeasurableSpace Ω} {X : Ω → E} {ℙ : Measure Ω} {μ : Measure E}
{s : Set E} (hns : μ s ≠ 0) (hnt : μ s ≠ ∞) (hms : MeasurableSet s) (hu : IsUniform X s ℙ μ)
{A : Set E} (hA : MeasurableSet A) : ℙ (X ⁻¹' A) = μ (s ∩ A) / μ s :=
by
haveI := hu.has_pdf hns hnt
rw [← measure.map_apply (has_pdf.measurable X ℙ μ) hA, map_eq_set_lintegral_pdf X ℙ μ hA,
lintegral_congr_ae hu.restrict]
simp only [hms, hA, lintegral_indicator, Pi.smul_apply, Pi.one_apply, Algebra.id.smul_eq_mul,
mul_one, lintegral_const, restrict_apply', Set.univ_inter]
rw [ENNReal.div_eq_inv_mul]
#align measure_theory.pdf.is_uniform.measure_preimage MeasureTheory.pdf.IsUniform.measure_preimage
theorem isProbabilityMeasure {m : MeasurableSpace Ω} {X : Ω → E} {ℙ : Measure Ω} {μ : Measure E}
{s : Set E} (hns : μ s ≠ 0) (hnt : μ s ≠ ∞) (hms : MeasurableSet s) (hu : IsUniform X s ℙ μ) :
IsProbabilityMeasure ℙ :=
⟨by
have : X ⁻¹' Set.univ = Set.univ := by simp only [Set.preimage_univ]
rw [← this, hu.measure_preimage hns hnt hms MeasurableSet.univ, Set.inter_univ,
ENNReal.div_self hns hnt]⟩
#align measure_theory.pdf.is_uniform.is_probability_measure MeasureTheory.pdf.IsUniform.isProbabilityMeasure
variable {X : Ω → ℝ} {s : Set ℝ} (hms : MeasurableSet s) (hns : volume s ≠ 0)
include hms hns
theorem mulPdfIntegrable [IsFiniteMeasure ℙ] (hcs : IsCompact s) (huX : IsUniform X s ℙ) :
Integrable fun x : ℝ => x * (pdf X ℙ volume x).toReal :=
by
by_cases hsupp : volume s = ∞
· have : pdf X ℙ =ᵐ[volume] 0 := by
refine' ae_eq_trans huX _
simp [hsupp]
refine' integrable.congr (integrable_zero _ _ _) _
rw [(by simp : (fun x => 0 : ℝ → ℝ) = fun x => x * (0 : ℝ≥0∞).toReal)]
refine'
Filter.EventuallyEq.mul (ae_eq_refl _) (Filter.EventuallyEq.fun_comp this.symm ENNReal.toReal)
refine'
⟨ae_strongly_measurable_id.mul
(measurable_pdf X ℙ).AeMeasurable.eNNReal_toReal.AeStronglyMeasurable,
_⟩
refine' has_finite_integral_mul huX _
set ind := (volume s)⁻¹ • (1 : ℝ → ℝ≥0∞) with hind
have : ∀ x, ↑‖x‖₊ * s.indicator ind x = s.indicator (fun x => ‖x‖₊ * ind x) x := fun x =>
(s.indicator_mul_right (fun x => ↑‖x‖₊) ind).symm
simp only [this, lintegral_indicator _ hms, hind, mul_one, Algebra.id.smul_eq_mul, Pi.one_apply,
Pi.smul_apply]
rw [lintegral_mul_const _ measurable_nnnorm.coe_nnreal_ennreal]
·
refine'
(ENNReal.mul_lt_top (set_lintegral_lt_top_of_is_compact hsupp hcs continuous_nnnorm).Ne
(ENNReal.inv_lt_top.2 (pos_iff_ne_zero.mpr hns)).Ne).Ne
· infer_instance
#align measure_theory.pdf.is_uniform.mul_pdf_integrable MeasureTheory.pdf.IsUniform.mulPdfIntegrable
/-- A real uniform random variable `X` with support `s` has expectation
`(λ s)⁻¹ * ∫ x in s, x ∂λ` where `λ` is the Lebesgue measure. -/
theorem integral_eq (hnt : volume s ≠ ∞) (huX : IsUniform X s ℙ) :
(∫ x, X x ∂ℙ) = (volume s)⁻¹.toReal * ∫ x in s, x :=
by
haveI := has_pdf hns hnt huX
haveI := huX.is_probability_measure hns hnt hms
rw [← integral_mul_eq_integral]
rw [integral_congr_ae (Filter.EventuallyEq.mul (ae_eq_refl _) (pdf_to_real_ae_eq huX))]
have :
∀ x,
x * (s.indicator ((volume s)⁻¹ • (1 : ℝ → ℝ≥0∞)) x).toReal =
x * s.indicator ((volume s)⁻¹.toReal • (1 : ℝ → ℝ)) x :=
by
refine' fun x => congr_arg ((· * ·) x) _
by_cases hx : x ∈ s
· simp [Set.indicator_of_mem hx]
· simp [Set.indicator_of_not_mem hx]
simp_rw [this, ← s.indicator_mul_right fun x => x, integral_indicator hms]
change (∫ x in s, x * (volume s)⁻¹.toReal • 1 ∂volume) = _
rw [integral_mul_right, mul_comm, Algebra.id.smul_eq_mul, mul_one]
#align measure_theory.pdf.is_uniform.integral_eq MeasureTheory.pdf.IsUniform.integral_eq
end IsUniform
end
end Pdf
end MeasureTheory
|
Set Implicit Arguments.
Require Import Crypto.
Require Import Bernoulli.
(* stuff that needs to go somewhere else *)
Theorem ratSubtract_leRat_same_r :
forall r1 r2 r3,
r3 <= r1 ->
r3 <= r2 ->
ratSubtract r1 r3 <= ratSubtract r2 r3 ->
r1 <= r2.
intuition.
apply (ratAdd_leRat_compat_l r3) in H1.
assert (ratSubtract r1 r3 + r3 == r1).
rewrite ratAdd_comm.
eapply ratSubtract_ratAdd_inverse_2; intuition.
rewrite <- H2.
rewrite H1.
rewrite ratAdd_comm.
eapply eqRat_impl_leRat.
apply ratSubtract_ratAdd_inverse_2; intuition.
Qed.
Theorem sumList_filter_complement :
forall (A : Set){eqd : EqDec A}(c : Comp A)(a : A),
well_formed_comp c ->
sumList (filter (fun x => negb (eqb a x)) (getSupport c)) (evalDist c) ==
ratSubtract 1 (evalDist c a).
intuition.
eapply (eqRat_ratAdd_same_r (evalDist c a)).
symmetry.
rewrite ratAdd_comm.
rewrite ratSubtract_ratAdd_inverse_2.
rewrite <- (evalDist_lossless H).
rewrite (sumList_filter_partition (eqb a)).
rewrite ratAdd_comm.
eapply ratAdd_eqRat_compat; intuition.
destruct (eq_Rat_dec (evalDist c a) 0).
rewrite e.
eapply sumList_0; intuition.
apply filter_In in H0.
intuition.
rewrite eqb_leibniz in H2; subst.
trivial.
rewrite (@sumList_exactly_one _ a); intuition.
eapply filter_NoDup.
eapply getSupport_NoDup.
eapply filter_In; intuition.
eapply getSupport_In_evalDist; intuition.
eapply eqb_refl.
apply filter_In in H0; intuition.
rewrite eqb_leibniz in H3; subst.
intuition.
eapply evalDist_le_1.
Qed.
Theorem evalDist_Repeat_0 :
forall (A : Set)(c : Comp A)(P : A -> bool) a,
(forall x, In x (getSupport c) -> P x = true -> x <> a) ->
evalDist (Repeat c P) a == 0.
intuition.
simpl.
unfold indicator.
case_eq (P a); intuition.
rewrite ratMult_1_l.
eapply ratMult_0.
right.
eapply getSupport_not_In_evalDist.
intuition.
eapply H;
eauto.
rewrite ratMult_0_l.
eapply ratMult_0_l.
Qed.
Theorem evalDist_event_equiv :
forall (A : Set){eqd : EqDec A}(c : Comp A) a,
evalDist c a == Pr[x <-$ c; ret (eqb a x)].
intuition.
destruct (in_dec (EqDec_dec _) a (getSupport c)).
rewrite evalDist_seq_step.
rewrite (@sumList_exactly_one _ a).
dist_compute.
eapply getSupport_NoDup.
trivial.
intuition.
dist_compute.
rewrite evalDist_seq_step.
assert (evalDist c a == 0).
eapply getSupport_not_In_evalDist; trivial.
rewrite H.
symmetry.
eapply sumList_0.
intuition.
dist_compute.
Qed.
Theorem filter_ext : forall (A : Set)(ls : list A)(f1 f2 : A -> bool),
(forall a, f1 a = f2 a) ->
filter f1 ls = filter f2 ls.
induction ls; intuition; simpl in *.
rewrite H.
destruct (f2 a); eauto.
f_equal;
eauto.
Qed.
(* definitions related to the program logic *)
Definition marginal_l(A B : Set){eqd : EqDec A}(c : Comp (A * B))(a : A) :=
Pr[x <-$ c; ret eqb (fst x) a].
Definition marginal_r(A B : Set){eqd : EqDec B}(c : Comp (A * B))(b : B) :=
Pr[x <-$ c; ret eqb (snd x) b].
Theorem in_support_marginal_l :
forall (A B : Set){eqd: EqDec A}(c1 : Comp (A * B))(c2 : Comp A),
(forall a, evalDist c2 a == marginal_l c1 a) ->
forall p,
In p (getSupport c1) ->
In (fst p) (getSupport c2).
intuition.
eapply getSupport_In_evalDist.
intuition.
rewrite H in H1.
clear H.
unfold marginal_l in *.
simpl in *.
eapply sumList_0 in H1; eauto.
eapply ratMult_0 in H1.
intuition.
eapply getSupport_In_evalDist;
eauto.
dist_compute.
Qed.
Theorem in_support_marginal_r :
forall (A B : Set){eqd: EqDec B}(c1 : Comp (A * B))(c2 : Comp B),
(forall b, evalDist c2 b == marginal_r c1 b) ->
forall p,
In p (getSupport c1) ->
In (snd p) (getSupport c2).
intuition.
eapply getSupport_In_evalDist.
intuition.
rewrite H in H1.
clear H.
unfold marginal_r in *.
simpl in *.
eapply sumList_0 in H1; eauto.
eapply ratMult_0 in H1.
intuition.
eapply getSupport_In_evalDist;
eauto.
dist_compute.
Qed.
Definition comp_spec (R1 R2 : Set)
{eqd1 : EqDec R1}{eqd2 : EqDec R2}
(post : R1 -> R2 -> Prop)(c1 : Comp R1)(c2 : Comp R2) :=
exists c : Comp (R1 * R2),
(forall r1, evalDist c1 r1 == marginal_l c r1) /\
(forall r2, evalDist c2 r2 == marginal_r c r2) /\
(forall p, In p (getSupport c) -> post (fst p) (snd p)).
Theorem list_choice :
forall (A B : Type)(eqd : forall (a1 a2 : A), {a1 = a2} + {a1 <> a2}) P (ls : list A) (b : B),
(forall a, In a ls -> exists (b : B), P a b) ->
exists (f : A -> B), (forall a, In a ls -> P a (f a)).
induction ls; intuition.
exists (fun a => b).
intuition.
simpl in *.
intuition.
edestruct (H a); intuition.
edestruct (H0); intuition.
exists (fun a0 => if (eqd a a0) then x else (x0 a0)).
intuition.
inversion H3; clear H3; subst.
destruct (eqd a0 a0); intuition.
destruct (eqd a a0); intuition.
subst.
trivial.
Qed.
Theorem comp_spec_seq :
forall {A B : Set} P' {C D : Set} P{eqda : EqDec A}{eqdb : EqDec B}{eqdc : EqDec C}{eqdd : EqDec D}(c1 : Comp A)(c2 : Comp B) (c : C) (d : D)
(f1 : A -> Comp C)(f2 : B -> Comp D),
comp_spec P' c1 c2 ->
(forall a b, In a (getSupport c1) -> In b (getSupport c2) -> P' a b -> comp_spec P (f1 a) (f2 b)) ->
comp_spec P (Bind c1 f1) (Bind c2 f2).
intuition.
destruct H; intuition.
assert (forall p, In p (getSupport x) -> comp_spec P (f1 (fst p)) (f2 (snd p))).
intuition.
eapply H0.
eapply in_support_marginal_l; eauto.
eapply in_support_marginal_r; eauto.
eauto.
clear H0.
pose proof H2.
apply (list_choice) in H2.
destruct H2.
exists (Bind x x0).
intuition.
rewrite evalDist_seq_step.
eapply eqRat_trans.
eapply sumList_body_eq.
intros.
eapply ratMult_eqRat_compat.
eauto.
eapply eqRat_refl.
unfold marginal_l.
eapply eqRat_trans.
eapply sumList_body_eq.
intros.
eapply ratMult_eqRat_compat.
eapply evalDist_seq_step.
eapply eqRat_refl.
eapply eqRat_trans.
eapply sumList_body_eq.
intros.
symmetry.
eapply sumList_factor_constant_r.
rewrite sumList_comm.
dist_inline_first.
rewrite evalDist_seq_step.
eapply sumList_body_eq.
intros.
rewrite (@sumList_exactly_one _ (fst a)).
assert (Pr [ret eqb (fst a) (fst a) ] == 1).
dist_compute.
rewrite H5.
rewrite ratMult_1_r.
eapply ratMult_eqRat_compat; intuition.
specialize (H2 a).
intuition.
rewrite H2.
unfold marginal_l.
intuition.
eapply getSupport_NoDup.
eapply in_support_marginal_l; eauto.
intuition.
dist_compute.
rewrite evalDist_seq_step.
eapply eqRat_trans.
eapply sumList_body_eq.
intros.
eapply ratMult_eqRat_compat.
eauto.
eapply eqRat_refl.
unfold marginal_r.
eapply eqRat_trans.
eapply sumList_body_eq.
intros.
eapply ratMult_eqRat_compat.
eapply evalDist_seq_step.
eapply eqRat_refl.
eapply eqRat_trans.
eapply sumList_body_eq.
intros.
symmetry.
eapply sumList_factor_constant_r.
rewrite sumList_comm.
dist_inline_first.
rewrite evalDist_seq_step.
eapply sumList_body_eq.
intros.
rewrite (@sumList_exactly_one _ (snd a)).
assert (Pr [ret eqb (snd a) (snd a) ] == 1).
dist_compute.
rewrite H5.
rewrite ratMult_1_r.
eapply ratMult_eqRat_compat; intuition.
specialize (H2 a); intuition.
rewrite H6.
unfold marginal_r; intuition.
eapply getSupport_NoDup.
eapply in_support_marginal_r; eauto.
intuition.
dist_compute.
simp_in_support.
specialize (H2 x1); intuition.
unfold eq_dec; intuition.
eapply (EqDec_dec _).
eapply (ret (c, d)).
Qed.
Ltac despec :=
match goal with
| [H : comp_spec _ _ _ |- _] => destruct H
end.
Theorem comp_spec_consequence :
forall (A B : Set){eqda1 eqda2 : EqDec A}{eqdb1 eqdb2 : EqDec B}(p1 p2 : A -> B -> Prop) c1 c2,
(@comp_spec _ _ eqda1 eqdb1 p1 c1 c2) ->
(forall a b, p1 a b -> p2 a b) ->
(@comp_spec _ _ eqda2 eqdb2 p2 c1 c2).
intuition.
despec; intuition.
exists x; intuition.
rewrite H1.
unfold marginal_l.
dist_skip.
eapply evalDist_ret_eq.
case_eq (eqb (fst x0) r1); intuition.
rewrite eqb_leibniz in H4.
subst.
eapply eqb_refl.
case_eq ( (@eqb A eqda1 (@fst A B x0) r1)); intuition.
rewrite eqb_leibniz in H5.
subst.
rewrite eqb_refl in H4.
intuition.
rewrite H.
unfold marginal_r.
dist_skip.
eapply evalDist_ret_eq.
case_eq (eqb (snd x0) r2); intuition.
rewrite eqb_leibniz in H4.
subst.
eapply eqb_refl.
case_eq ( (@eqb B eqdb1 (@snd A B x0) r2)); intuition.
rewrite eqb_leibniz in H5.
subst.
rewrite eqb_refl in H4.
intuition.
Qed.
Theorem comp_spec_symm :
forall (A B : Set){eqda : EqDec A}{eqdb : EqDec B}(p : A -> B -> Prop) c1 c2,
comp_spec p c1 c2 ->
comp_spec (fun b a => p a b) c2 c1.
intuition.
despec; intuition.
exists (p <-$ x; ret (snd p, fst p)).
intuition.
eapply eqRat_trans; eauto.
unfold marginal_r, marginal_l.
dist_inline_first.
dist_skip.
dist_compute.
eapply eqRat_trans; eauto.
unfold marginal_r, marginal_l.
dist_inline_first.
dist_skip.
dist_compute.
repeat simp_in_support.
simpl.
eauto.
Qed.
(* completeness theorems *)
Theorem eq_impl_comp_spec :
forall (A B : Set){eqda : EqDec A}{eqdb : EqDec B}(c1 : Comp A)(c2 : Comp B) x y,
well_formed_comp c1 ->
well_formed_comp c2 ->
evalDist c1 x == evalDist c2 y ->
comp_spec (fun a b => a = x <-> b = y) c1 c2.
intuition.
(* special case: the events have probability 0 *)
destruct (eq_Rat_dec (evalDist c1 x) 0).
exists (a <-$ c1;
b <-$ c2;
ret (a, b)).
intuition.
unfold marginal_l.
dist_inline_first.
rewrite <- evalDist_right_ident.
dist_skip.
dist_inline_first.
dist_irr_r.
dist_compute.
unfold marginal_r.
dist_inline_first.
rewrite <- evalDist_right_ident.
dist_irr_r.
dist_inline_first.
dist_skip.
dist_compute.
repeat simp_in_support.
simpl in *.
exfalso.
eapply getSupport_not_In_evalDist.
eapply e.
trivial.
repeat simp_in_support.
simpl in *.
exfalso.
eapply getSupport_not_In_evalDist.
rewrite <- H1.
trivial.
trivial.
(* special case: the events have probability 1 *)
destruct (eq_Rat_dec (evalDist c1 x) 1).
exists (a <-$ c1;
b <-$ c2;
ret (a, b)).
split.
intuition.
unfold marginal_l.
dist_inline_first.
rewrite <- evalDist_right_ident.
dist_skip.
dist_inline_first.
dist_irr_r.
dist_compute.
split.
intuition.
unfold marginal_r.
dist_inline_first.
rewrite <- evalDist_right_ident.
dist_irr_r.
dist_inline_first.
dist_skip.
dist_compute.
intros.
repeat simp_in_support; simpl in *.
erewrite (evalDist_1) in H5; intuition.
Focus 2.
rewrite <- H1.
trivial.
simpl in *; intuition.
erewrite (evalDist_1) in H3; eauto.
simpl in *; intuition.
(* general case *)
exists (a <-$ c1;
b <-$ if (eqb a x) then (ret y) else (Repeat c2 (fun b => negb (eqb b y)));
ret (a, b)).
split.
intuition.
unfold marginal_l.
dist_inline_first.
rewrite <- evalDist_right_ident.
dist_skip.
dist_inline_first.
dist_irr_r.
case_eq (eqb x0 x); intuition; wftac.
remember (getSupport c2) as s.
destruct s.
specialize (getSupport_length_nz H0); intuition.
rewrite <- Heqs in H4.
simpl in *.
omega.
destruct (EqDec_dec _ b y); subst.
destruct s.
exfalso.
eapply n0.
rewrite H1.
rewrite <- (evalDist_lossless H0).
rewrite <- Heqs.
rewrite sumList_cons.
unfold sumList; simpl.
eapply ratAdd_0_r.
eapply (@well_formed_Repeat _ _ _ _ b).
trivial.
eapply filter_In; intuition.
rewrite <- Heqs.
simpl.
intuition.
case_eq (eqb b y); intuition.
rewrite eqb_leibniz in H4.
subst.
specialize (getSupport_NoDup c2); intuition.
rewrite <- Heqs in H4.
inversion H4; clear H4; subst.
simpl in *.
intuition.
eapply (@well_formed_Repeat _ _ _ _ b).
trivial.
eapply filter_In; intuition.
rewrite <- Heqs; simpl; intuition.
case_eq (eqb b y); intuition.
rewrite eqb_leibniz in H4; subst.
intuition.
dist_compute.
split.
intuition.
unfold marginal_r.
dist_inline_first.
rewrite evalDist_seq_step.
rewrite (sumList_filter_partition (eqb x)).
symmetry.
eapply eqRat_trans.
eapply ratAdd_eqRat_compat.
eapply sumList_body_eq.
intros.
eapply ratMult_eqRat_compat.
eapply eqRat_refl.
apply filter_In in H2.
intuition.
rewrite eqb_leibniz in H4.
subst.
rewrite eqb_refl.
dist_inline_first.
unfold snd.
eapply eqRat_refl.
eapply sumList_body_eq; intuition.
apply filter_In in H2.
intuition.
case_eq (eqb x a); intuition.
rewrite eqb_leibniz in H2.
subst.
rewrite eqb_refl in H4.
simpl in *.
discriminate.
rewrite evalDist_assoc at 1.
case_eq (eqb a x); intuition.
rewrite eqb_leibniz in H5.
subst.
rewrite eqb_refl in H2.
discriminate.
eapply ratMult_eqRat_compat.
eapply eqRat_refl.
eapply evalDist_seq_eq.
intuition.
eapply eqRat_refl.
intuition.
dist_simp.
unfold snd.
eapply eqRat_refl.
intuition.
rewrite (@sumList_exactly_one _ x).
case_eq (eqb y r2); intuition.
rewrite eqb_leibniz in H2.
subst.
assert (Pr[ret true] == 1).
dist_compute.
rewrite H2.
rewrite ratMult_1_r.
clear H2.
rewrite H1.
symmetry.
rewrite ratAdd_0_r at 1.
eapply ratAdd_eqRat_compat; intuition.
symmetry.
eapply sumList_0.
intuition.
apply filter_In in H2.
intuition.
assert (Pr [x0 <-$ Repeat c2 (fun b : B => negb (eqb b r2)); ret eqb x0 r2 ] ==
Pr [x0 <-$ Repeat c2 (fun b : B => negb (eqb b r2)); ret eqb r2 x0 ] ).
dist_skip; dist_compute.
rewrite H2.
clear H2.
rewrite <- evalDist_event_equiv.
eapply ratMult_0.
right.
eapply evalDist_Repeat_0; intuition.
subst.
rewrite eqb_refl in H5.
simpl in *; discriminate.
assert (Pr [ret false] == 0).
dist_compute.
rewrite H3.
clear H3.
rewrite ratMult_0_r.
rewrite <- ratAdd_0_l.
rewrite sumList_factor_constant_r.
rewrite sumList_filter_complement.
rewrite H1.
rewrite evalDist_seq_step.
destruct (in_dec (EqDec_dec _) r2 (getSupport c2)).
rewrite (@sumList_exactly_one _ r2).
assert (Pr [ret eqb r2 r2 ] == 1).
dist_compute.
rewrite H3.
clear H3.
rewrite ratMult_1_r.
simpl.
unfold indicator.
case_eq (eqb r2 y); intuition.
rewrite eqb_leibniz in H3; subst.
rewrite eqb_refl in H2.
discriminate.
simpl.
rewrite ratMult_1_l.
symmetry.
rewrite <- ratMult_1_l at 1.
rewrite <- ratMult_assoc.
eapply ratMult_eqRat_compat; intuition.
symmetry.
eapply eqRat_trans.
eapply ratMult_eqRat_compat.
eapply eqRat_refl.
eapply ratInverse_eqRat_compat.
intuition.
assert ( (filter (fun b : B => negb (eqb b y)) (getSupport c2)) =
(filter (fun b : B => negb (eqb y b)) (getSupport c2))).
eapply filter_ext; intuition.
rewrite eqb_symm.
trivial.
rewrite H5 in H4.
clear H5.
eapply n0.
eapply leRat_impl_eqRat.
eapply evalDist_le_1.
eapply ratSubtract_0_inv.
rewrite sumList_filter_complement in H4.
rewrite H1.
intuition.
trivial.
assert ((filter (fun b : B => negb (eqb b y)) (getSupport c2)) =
(filter (fun b : B => negb (eqb y b)) (getSupport c2))).
eapply filter_ext.
intuition.
rewrite eqb_symm.
intuition.
rewrite H4.
clear H4.
eapply sumList_filter_complement.
trivial.
rewrite ratMult_comm.
eapply ratInverse_prod_1.
intuition.
eapply n0.
eapply leRat_impl_eqRat.
eapply evalDist_le_1.
eapply ratSubtract_0_inv.
rewrite H1.
intuition.
eapply getSupport_NoDup.
simpl.
eapply filter_In; intuition.
rewrite eqb_symm.
rewrite H2.
trivial.
intuition.
dist_compute.
eapply eqRat_trans.
eapply ratMult_eqRat_compat.
eapply eqRat_refl.
eapply sumList_0.
intuition.
simpl in H3.
apply filter_In in H3.
intuition.
case_eq (eqb a r2); intuition.
rewrite eqb_leibniz in H3; subst.
intuition.
dist_compute.
rewrite ratMult_0_r.
symmetry.
eapply getSupport_not_In_evalDist.
trivial.
trivial.
eapply filter_NoDup.
eapply getSupport_NoDup.
eapply filter_In; intuition.
eapply getSupport_In_evalDist; intuition.
eapply eqb_refl.
intuition.
apply filter_In in H2.
intuition.
rewrite eqb_leibniz in H5.
intuition.
intros.
repeat simp_in_support;
simpl in *; intuition.
rewrite eqb_refl in Heqx2.
discriminate.
symmetry in Heqx2.
rewrite eqb_leibniz in Heqx2.
trivial.
simpl in *.
eapply filter_In in H5.
intuition.
rewrite eqb_refl in H4.
simpl in *.
discriminate.
Grab Existential Variables.
unfold eq_dec; intuition.
eapply (EqDec_dec _).
unfold eq_dec; intuition.
eapply (EqDec_dec _).
Qed.
Theorem le_impl_comp_spec :
forall (A B : Set){eqda : EqDec A}{eqdb : EqDec B}(c1 : Comp A)(c2 : Comp B),
well_formed_comp c1 ->
well_formed_comp c2 ->
forall x y,
evalDist c1 x <= evalDist c2 y ->
comp_spec (fun a b => a = x -> b = y) c1 c2.
intuition.
(* special case : y is a certain output of c2 *)
destruct (eq_Rat_dec (evalDist c2 y) 1).
exists (a <-$ c1; b <-$ c2; ret (a, b)).
intuition.
unfold marginal_l; intuition.
dist_inline_first.
rewrite <- evalDist_right_ident.
dist_skip.
dist_inline_first.
dist_irr_r.
dist_compute.
unfold marginal_l; intuition.
dist_inline_first.
rewrite <- evalDist_right_ident.
dist_irr_r.
dist_inline_first.
dist_skip.
dist_compute.
repeat simp_in_support.
simpl in *.
erewrite evalDist_1 in H5; eauto.
simpl in *.
intuition.
(* special case : x is never an output of c1 *)
destruct (eq_Rat_dec (evalDist c1 x) 0).
exists (a <-$ c1; b <-$ c2; ret (a, b)).
intuition.
unfold marginal_l; intuition.
dist_inline_first.
rewrite <- evalDist_right_ident.
dist_skip.
dist_inline_first.
dist_irr_r.
dist_compute.
unfold marginal_l; intuition.
dist_inline_first.
rewrite <- evalDist_right_ident.
dist_irr_r.
dist_inline_first.
dist_skip.
dist_compute.
repeat simp_in_support.
simpl in *.
exfalso.
eapply getSupport_In_evalDist.
eapply H4.
trivial.
(* special case: the probabilities are equal *)
destruct (eq_Rat_dec (evalDist c1 x) (evalDist c2 y)).
eapply comp_spec_consequence.
eapply eq_impl_comp_spec; intuition.
eauto.
intuition.
subst.
intuition.
(* general case *)
Local Open Scope rat_scope.
exists (a <-$ c1;
b <-$ if (eqb a x) then (ret y) else
mDiff <- ratSubtract (evalDist c2 y) (evalDist c1 x);
c <-$ Bernoulli (mDiff * (ratInverse (ratSubtract 1 (evalDist c1 x))));
if c then (ret y) else (Repeat c2 (fun z => negb (eqb z y)));
ret (a, b)).
intuition.
unfold marginal_l.
dist_inline_first.
rewrite <- evalDist_right_ident.
dist_skip.
dist_inline_first.
dist_irr_r.
remember (getSupport c2) as s.
destruct s.
exfalso.
specialize (getSupport_length_nz H0); intuition.
rewrite <- Heqs in H3.
simpl in *.
omega.
destruct (EqDec_dec _ b y).
subst.
destruct s.
exfalso.
eapply n.
rewrite <- (evalDist_lossless H0).
rewrite <- Heqs.
rewrite sumList_cons.
unfold sumList. simpl.
eapply ratAdd_0_r.
wftac.
eapply Bernoulli_wf.
eapply (@well_formed_Repeat _ _ _ _ b).
intuition.
eapply filter_In; intuition.
rewrite <- Heqs.
simpl.
intuition.
case_eq (eqb b y); intuition.
rewrite eqb_leibniz in H4.
subst.
specialize (getSupport_NoDup c2); intuition.
rewrite <- Heqs in H4.
inversion H4; clear H4; subst.
simpl in *.
intuition.
wftac.
eapply Bernoulli_wf.
eapply (@well_formed_Repeat _ _ _ _ b).
intuition.
eapply filter_In; intuition.
rewrite <- Heqs.
simpl.
intuition.
case_eq (eqb b y); intuition.
rewrite eqb_leibniz in H4.
subst.
intuition.
dist_compute.
(* destruct (in_dec (EqDec_dec _) r2 (getSupport c2)). *)
symmetry.
unfold marginal_r.
dist_inline_first.
rewrite evalDist_seq_step.
rewrite (sumList_filter_partition (eqb x)).
eapply eqRat_trans.
eapply ratAdd_eqRat_compat.
eapply sumList_body_eq.
intros.
eapply ratMult_eqRat_compat.
eapply eqRat_refl.
apply filter_In in H2.
intuition.
rewrite eqb_leibniz in H4.
subst.
rewrite eqb_refl.
dist_inline_first.
unfold snd.
eapply eqRat_refl.
eapply sumList_body_eq; intuition.
apply filter_In in H2.
intuition.
case_eq (eqb a x); intuition.
rewrite eqb_leibniz in H2.
subst.
rewrite eqb_refl in H4.
simpl in *.
discriminate.
rewrite evalDist_assoc at 1.
rewrite evalDist_assoc at 1.
rewrite (evalDist_seq_step) at 1.
rewrite (sumList_filter_partition (fun z => z)) at 1.
rewrite (@sumList_exactly_one _ true) at 1.
rewrite (@sumList_exactly_one _ false) at 1.
rewrite Bernoulli_correct at 1.
rewrite Bernoulli_correct_complement at 1.
dist_simp.
assert (Pr [a0 <-$ ret y; x0 <-$ ret (a, a0); ret eqb (snd x0) r2 ] ==
Pr [ret eqb y r2 ]).
dist_simp.
simpl.
intuition.
rewrite H5 at 1.
clear H5.
eapply ratMult_eqRat_compat.
eapply eqRat_refl.
eapply ratAdd_eqRat_compat.
eapply eqRat_refl.
eapply ratMult_eqRat_compat.
eapply eqRat_refl.
eapply evalDist_seq_eq.
intuition.
eapply eqRat_refl.
intuition.
dist_simp.
unfold snd.
eapply eqRat_refl.
eapply ratFraction_le_1.
eapply ratSubtract_leRat.
eapply evalDist_le_1.
intuition.
eapply ratFraction_le_1.
eapply ratSubtract_leRat.
eapply evalDist_le_1.
intuition.
eapply filter_NoDup.
eapply getSupport_NoDup.
eapply filter_In; intuition.
eapply getSupport_In_evalDist.
intuition.
rewrite Bernoulli_correct_complement in H5.
apply ratSubtract_0_inv in H5.
apply ratFraction_ge_1_inv in H5.
eapply ratSubtract_leRat_same_r in H5.
eapply n.
eapply leRat_impl_eqRat.
eapply evalDist_le_1.
trivial.
eapply evalDist_le_1.
intuition.
eapply ratFraction_le_1.
eapply ratSubtract_leRat.
eapply evalDist_le_1.
intuition.
intuition.
destruct b; intuition.
apply filter_In in H5.
intuition.
eapply filter_NoDup.
eapply getSupport_NoDup.
eapply filter_In.
intuition.
eapply getSupport_In_evalDist.
intuition.
rewrite Bernoulli_correct in H5.
apply ratMult_0 in H5.
intuition.
apply ratSubtract_0_inv in H6.
eapply n1.
eapply leRat_impl_eqRat; intuition.
eapply ratInverse_nz;eauto.
eapply ratFraction_le_1.
eapply ratSubtract_leRat.
eapply evalDist_le_1.
intuition.
intuition.
destruct b; intuition.
apply filter_In in H5; intuition.
discriminate.
intuition.
intuition.
rewrite (@sumList_exactly_one _ x).
rewrite sumList_factor_constant_r.
assert (sumList (filter (fun a : A => negb (eqb x a)) (getSupport c1))
(evalDist c1) ==
ratSubtract 1 (evalDist c1 x)).
eapply sumList_filter_complement.
trivial.
rewrite H2.
clear H2.
rewrite ratMult_distrib.
eapply eqRat_trans.
eapply ratAdd_eqRat_compat.
eapply eqRat_refl.
eapply ratAdd_eqRat_compat.
rewrite <- ratMult_assoc.
eapply ratMult_eqRat_compat.
rewrite ratMult_comm.
rewrite ratMult_assoc.
rewrite ratInverse_prod_1.
eapply ratMult_1_r.
intuition.
eapply n.
eapply leRat_impl_eqRat.
eapply evalDist_le_1.
intuition.
eapply leRat_trans; eauto.
apply ratSubtract_0_inv.
trivial.
eapply eqRat_refl.
rewrite <- ratMult_assoc.
eapply ratMult_eqRat_compat.
rewrite ratMult_comm.
rewrite ratMult_ratSubtract_distrib_r.
rewrite ratMult_1_l.
eapply ratSubtract_eqRat_compat.
eapply eqRat_refl.
rewrite ratMult_assoc.
rewrite ratInverse_prod_1.
eapply ratMult_1_r.
intuition.
eapply n.
eapply leRat_impl_eqRat.
eapply evalDist_le_1.
intuition.
eapply leRat_trans; eauto.
apply ratSubtract_0_inv.
trivial.
eapply eqRat_refl.
case_eq (eqb y r2); intuition.
rewrite eqb_leibniz in H2.
subst.
assert (Pr [ret true] == 1).
dist_compute.
rewrite H2.
clear H2.
repeat rewrite ratMult_1_r.
assert (Pr [x0 <-$ Repeat c2 (fun z : B => negb (eqb z r2)); ret eqb x0 r2 ] ==
Pr [x0 <-$ Repeat c2 (fun z : B => negb (eqb z r2)); ret eqb r2 x0 ]).
dist_skip; dist_compute.
rewrite H2; clear H2.
rewrite <- evalDist_event_equiv.
rewrite evalDist_Repeat_0.
rewrite ratMult_0_r.
rewrite <- ratAdd_0_r.
eapply ratSubtract_ratAdd_inverse_2.
trivial.
intuition.
subst.
rewrite eqb_refl in H3.
simpl in *.
discriminate.
assert (Pr [ret false] == 0).
dist_compute.
rewrite H3.
clear H3.
repeat rewrite ratMult_0_r.
repeat rewrite <- ratAdd_0_l.
rewrite <- ratSubtract_ratAdd_distr.
rewrite ratSubtract_ratAdd_inverse_2; trivial.
simpl.
destruct (in_dec (EqDec_dec _) r2 (getSupport c2)).
rewrite (@sumList_exactly_one _ r2).
rewrite eqb_refl.
destruct (EqDec_dec bool_EqDec true true); intuition.
unfold indicator.
case_eq (eqb r2 y); intuition.
rewrite eqb_leibniz in H3.
subst.
rewrite eqb_refl in H2.
discriminate.
simpl.
rewrite ratMult_1_l.
rewrite ratMult_1_r.
assert ((sumList (filter (fun z : B => negb (eqb y z)) (getSupport c2))
(evalDist c2) ==
(ratSubtract 1 (evalDist c2 y)))).
eapply sumList_filter_complement.
trivial.
eapply eqRat_trans.
eapply ratMult_eqRat_compat.
eapply eqRat_refl.
eapply ratMult_eqRat_compat.
eapply ratInverse_eqRat_compat.
intuition.
assert ((filter (fun z : B => negb (eqb y z)) (getSupport c2)) =
(filter (fun z : B => negb (eqb z y)) (getSupport c2))).
eapply filter_ext; intuition.
rewrite eqb_symm.
trivial.
rewrite H6 in H4.
clear H6.
rewrite H4 in H5.
eapply n.
eapply leRat_impl_eqRat.
eapply evalDist_le_1.
eapply ratSubtract_0_inv.
trivial.
assert ((filter (fun z : B => negb (eqb z y)) (getSupport c2)) =
(filter (fun z : B => negb (eqb y z)) (getSupport c2))).
eapply filter_ext.
intuition.
rewrite eqb_symm.
trivial.
rewrite H5.
clear H5.
eapply H4.
eapply eqRat_refl.
clear H4.
rewrite <- ratMult_assoc.
symmetry.
rewrite <- ratMult_1_l at 1.
eapply ratMult_eqRat_compat; intuition.
symmetry.
rewrite ratMult_comm.
eapply ratInverse_prod_1.
intuition.
eapply n.
eapply leRat_impl_eqRat.
eapply evalDist_le_1.
intuition.
eapply ratSubtract_0_inv.
trivial.
eapply filter_NoDup.
eapply getSupport_NoDup.
eapply filter_In; intuition.
case_eq (eqb r2 y); intuition.
rewrite eqb_leibniz in H3; subst.
rewrite eqb_refl in H2.
discriminate.
intuition.
apply filter_In in H3.
intuition.
case_eq (eqb b r2); intuition.
rewrite eqb_leibniz in H3.
subst.
intuition.
destruct (EqDec_dec bool_EqDec false true ).
discriminate.
rewrite ratMult_0_r.
intuition.
eapply eqRat_trans.
eapply ratMult_eqRat_compat.
eapply eqRat_refl.
eapply sumList_0.
intuition.
apply filter_In in H3.
destruct ( EqDec_dec bool_EqDec (eqb a r2) true); intuition.
rewrite eqb_leibniz in e; subst.
intuition.
eapply ratMult_0_r.
rewrite ratMult_0_r.
symmetry.
eapply getSupport_not_In_evalDist.
intuition.
eapply filter_NoDup.
eapply getSupport_NoDup.
eapply filter_In; intuition.
eapply getSupport_In_evalDist; intuition.
apply eqb_refl.
intuition.
apply filter_In in H2.
intuition.
dist_compute.
repeat simp_in_support;
simpl in *; trivial.
simpl in *.
rewrite eqb_refl in Heqx2.
discriminate.
Grab Existential Variables.
unfold eq_dec; intuition.
eapply (EqDec_dec _).
unfold eq_dec; intuition.
eapply (EqDec_dec _).
Qed.
(* soundness theorems *)
Theorem comp_spec_impl_le :
forall (A B : Set){eqda : EqDec A}{eqdb : EqDec B}(c1 : Comp A)(c2 : Comp B),
forall x y,
comp_spec (fun a b => a = x -> b = y) c1 c2 ->
evalDist c1 x <= evalDist c2 y.
intuition.
despec.
intuition.
eapply leRat_trans.
eapply eqRat_impl_leRat.
eauto.
eapply leRat_trans.
Focus 2.
eapply eqRat_impl_leRat.
symmetry.
eauto.
unfold marginal_l, marginal_r.
dist_skip.
dist_compute.
exfalso.
eapply n.
specialize (H2 x1).
intuition.
eapply rat0_le_all.
Qed.
Theorem comp_spec_eq_symm:
forall (A : Set){eqda : EqDec A}(c1 c2 : Comp A),
comp_spec eq c1 c2 ->
comp_spec eq c2 c1.
intuition.
eapply comp_spec_symm.
eapply comp_spec_consequence; eauto.
Qed.
Theorem comp_spec_impl_eq :
forall (A B : Set){eqda : EqDec A}{eqdb : EqDec B}(c1 : Comp A)(c2 : Comp B),
forall x y,
comp_spec (fun a b => a = x <-> b = y) c1 c2 ->
evalDist c1 x == evalDist c2 y.
intuition.
eapply leRat_impl_eqRat.
eapply comp_spec_impl_le.
eapply comp_spec_consequence.
eauto.
intuition.
subst.
intuition.
eapply comp_spec_impl_le.
eapply comp_spec_symm.
eapply comp_spec_consequence.
eauto.
intuition.
subst.
intuition.
Qed.
(* facts about basic language constructs *)
Theorem comp_spec_ret :
forall (A B : Set){eqda1 : EqDec A}{eqdb1 : EqDec B}(eqda2 : eq_dec A)(eqdb2 : eq_dec B)(P : A -> B -> Prop) a b,
P a b ->
@comp_spec _ _ eqda1 eqdb1 P (Ret eqda2 a) (Ret eqdb2 b).
intuition.
exists (ret (a, b)).
intuition.
unfold marginal_l.
dist_compute.
unfold marginal_r.
dist_compute.
simp_in_support.
trivial.
Qed.
Theorem comp_spec_rnd :
forall n x y,
comp_spec (fun a b : Vector.t bool n => a = x <-> b = y)
({ 0 , 1 }^n) ({ 0 , 1 }^n).
intuition.
eapply eq_impl_comp_spec; wftac.
eapply uniformity.
Qed.
(* facts about equality specifications *)
Theorem eq_impl_comp_spec_eq :
forall (A : Set){eqd1 eqd2 : EqDec A}(c1 c2 : Comp A),
(forall x, evalDist c1 x == evalDist c2 x) ->
@comp_spec _ _ eqd1 eqd2 eq c1 c2.
intuition.
exists (x <-$ c1; ret (x, x)).
intuition.
unfold marginal_l.
dist_inline_first.
rewrite <- evalDist_right_ident.
dist_skip.
dist_compute.
unfold marginal_r.
dist_inline_first.
rewrite <- H.
rewrite <- evalDist_right_ident.
dist_skip.
dist_compute.
repeat simp_in_support.
trivial.
Qed.
Theorem comp_spec_eq_refl :
forall (A : Set){eqd : EqDec A}(c : Comp A),
comp_spec eq c c.
intuition.
eapply eq_impl_comp_spec_eq; intuition.
Qed.
Theorem comp_spec_eq_impl_eq :
forall (A : Set){eqd1 eqd2 : EqDec A}(c1 c2 : Comp A),
@comp_spec _ _ eqd1 eqd2 eq c1 c2 ->
(forall x, evalDist c1 x == evalDist c2 x).
intuition.
despec.
intuition.
rewrite H0.
rewrite H.
unfold marginal_l, marginal_r.
dist_skip.
simpl.
specialize (H2 x1).
intuition.
destruct x1.
simpl in *.
subst.
destruct (EqDec_dec bool_EqDec (@eqb _ eqd1 a0 x) true); intuition.
rewrite eqb_leibniz in e.
subst.
destruct (EqDec_dec bool_EqDec (@eqb _ eqd2 x x) true); intuition.
exfalso.
eapply n.
eapply eqb_refl.
destruct (EqDec_dec bool_EqDec (@eqb _ eqd2 a0 x) true); intuition.
rewrite eqb_leibniz in e.
subst.
exfalso.
eapply n.
eapply eqb_leibniz.
trivial.
Qed.
Theorem comp_spec_eq_trans_l :
forall (A B : Set){eqd : EqDec A}{eqd : EqDec B}(c1 c2 : Comp A)(c3 : Comp B) P,
comp_spec eq c1 c2 ->
comp_spec P c2 c3 ->
comp_spec P c1 c3.
intuition.
despec.
intuition.
exists x.
intuition.
eapply comp_spec_eq_impl_eq in H; intuition.
rewrite H.
trivial.
Qed.
Theorem comp_spec_eq_trans :
forall (A : Set){eqd : EqDec A}(c1 c2 c3 : Comp A),
comp_spec eq c1 c2 ->
comp_spec eq c2 c3 ->
comp_spec eq c1 c3.
intuition.
eapply comp_spec_eq_trans_l;
eauto.
Qed.
Theorem comp_spec_eq_trans_r :
forall (A B : Set){eqd : EqDec A}{eqd : EqDec B}(c1 : Comp A)(c2 c3 : Comp B) P,
comp_spec P c1 c2 ->
comp_spec eq c2 c3 ->
comp_spec P c1 c3.
intuition.
destruct H.
intuition.
exists x.
intuition.
eapply comp_spec_eq_impl_eq in H0; intuition.
rewrite <- H0.
trivial.
Qed.
Theorem comp_spec_seq_eq :
forall (A B C : Set){eqda : EqDec A}{eqdb : EqDec B}{eqdc : EqDec C}(c1 c2 : Comp A)(f1 : A -> Comp B)(f2 : A -> Comp C) P (b : B) (c : C),
comp_spec eq c1 c2 ->
(forall a, comp_spec P (f1 a) (f2 a)) ->
comp_spec P (Bind c1 f1) (Bind c2 f2).
intuition.
eapply comp_spec_seq; trivial.
eauto.
intuition; subst; intuition.
Qed.
Theorem comp_spec_eq_swap :
forall (A B C : Set){eqdc : EqDec C}(c1 : Comp A)(c2 : Comp B)(f : A -> B -> Comp C),
comp_spec eq (x <-$ c1; y <-$ c2; f x y) (y <-$ c2; x <-$ c1; f x y).
intuition.
eapply eq_impl_comp_spec_eq.
intuition.
eapply evalDist_commute_eq.
Qed.
Theorem comp_spec_right_ident :
forall (A : Set){eqd : EqDec A}(c1 : Comp A),
comp_spec eq (x <-$ c1; ret x) c1.
intuition.
eapply eq_impl_comp_spec_eq.
eapply evalDist_right_ident.
Qed.
Theorem comp_spec_left_ident :
forall (A B : Set){eqda : EqDec A}{eqdb : EqDec B}(c1 : A -> Comp B) a,
comp_spec eq (x <-$ ret a; c1 x) (c1 a).
intuition.
eapply eq_impl_comp_spec_eq.
intuition.
specialize (@evalDist_left_ident eqRat); intuition.
Qed.
Theorem comp_spec_assoc :
forall (A B C : Set){eqd : EqDec C}(c1 : Comp A)(c2 : A -> Comp B)(c3 : B -> Comp C),
comp_spec eq (x <-$ (y <-$ c1; c2 y); c3 x) (y <-$ c1; x <-$ c2 y; c3 x).
intuition.
eapply eq_impl_comp_spec_eq.
intuition.
eapply evalDist_assoc; intuition.
Qed.
(* other facts *)
Theorem comp_spec_event_equiv :
forall (A B : Set){eqda : EqDec A}{eqdb : EqDec B}(c1 : Comp A)(c2 : Comp B)(f1 : A -> bool)(f2 : B -> bool)(P : bool -> bool -> Prop),
comp_spec (fun a b => P (f1 a) (f2 b)) c1 c2 ->
comp_spec P (x <-$ c1; ret (f1 x)) (x <-$ c2; ret (f2 x)).
intuition.
eapply comp_spec_seq.
apply true.
apply true.
eauto.
intuition.
eapply comp_spec_ret.
trivial.
Qed.
Theorem comp_spec_iso :
forall (A B : Set){eqda : EqDec A}{eqdb : EqDec B}(c1 : Comp A)(c2 : Comp B)(f : A -> B)(f_inv : B -> A),
(forall x : B, In x (getSupport c2) -> f (f_inv x) = x) ->
(forall x : A, In x (getSupport c1) -> f_inv (f x) = x) ->
(forall x : B, In x (getSupport c2) -> In (f_inv x) (getSupport c1)) ->
(forall x : A, In x (getSupport c1) -> comp_spec (fun a b => a = (f x) <-> b = x) c2 c1) ->
comp_spec (fun a b => f a = b) c1 c2.
intuition.
intuition.
remember f_inv as f_inv2.
exists (x <-$ c1; ret (x, f x)).
intuition; subst.
unfold marginal_l.
dist_inline_first.
rewrite <- evalDist_right_ident.
dist_skip.
dist_compute.
unfold marginal_r.
dist_inline_first.
rewrite <- evalDist_right_ident.
eapply (@distro_iso_eq _ _ _ _ f f_inv).
intuition.
intuition.
intuition.
intuition.
rewrite evalDist_event_equiv.
symmetry.
rewrite evalDist_event_equiv.
eapply comp_spec_impl_eq.
eapply (@comp_spec_consequence _ _ _ _ _ _ eq).
eapply comp_spec_event_equiv.
eapply comp_spec_symm.
eapply comp_spec_consequence.
eapply H2.
eauto.
intuition.
case_eq (eqb x b); intuition.
rewrite eqb_leibniz in H5.
subst.
intuition.
case_eq (eqb (f b) a); intuition.
subst.
rewrite eqb_refl in H6.
discriminate.
case_eq (eqb (f x) a); intuition.
rewrite eqb_leibniz in H4.
subst.
intuition.
subst.
rewrite eqb_refl in H5.
discriminate.
intuition.
subst.
trivial.
subst.
trivial.
intuition.
dist_compute.
repeat simp_in_support.
trivial.
Qed.
Theorem comp_spec_irr_r :
forall (A B C : Set){eqda : EqDec A}{eqdb : EqDec B}{eqdc : EqDec C}(c1 : Comp A)(c2 : Comp B)(f2 : B -> Comp C) P,
well_formed_comp c2 ->
(forall b, In b (getSupport c2) -> comp_spec P c1 (f2 b)) ->
comp_spec P c1 (Bind c2 f2).
intuition.
apply list_choice in H0.
destruct H0.
exists (y <-$ c2; x y).
intuition.
unfold marginal_l.
dist_inline_first.
dist_irr_r.
specialize (H0 x0); intuition.
eapply H0.
unfold marginal_r.
dist_inline_first.
dist_skip.
specialize (H0 x0); intuition.
apply H2.
repeat simp_in_support.
specialize (H0 x0); intuition.
intuition.
eapply (EqDec_dec _).
apply (x <-$ c1; y <-$ c2; z <-$ f2 y; ret (x, z)).
Qed.
Theorem comp_spec_irr_l :
forall (A B C : Set){eqda : EqDec A}{eqdb : EqDec B}{eqdc : EqDec C}(c1 : Comp A)(c2 : Comp B)(f1 : A -> Comp C) P,
well_formed_comp c1 ->
(forall a, In a (getSupport c1) -> comp_spec P (f1 a) c2) ->
comp_spec P (Bind c1 f1) c2.
intuition.
apply list_choice in H0.
destruct H0.
exists (y <-$ c1; x y).
intuition.
unfold marginal_l.
dist_inline_first.
dist_skip.
specialize (H0 x0); intuition.
eapply H0.
unfold marginal_r.
dist_inline_first.
dist_irr_r.
specialize (H0 x0); intuition.
apply H2.
repeat simp_in_support.
specialize (H0 x0); intuition.
intuition.
eapply (EqDec_dec _).
apply (x <-$ c1; y <-$ c2; z <-$ f1 x; ret (z, y)).
Qed.
(* equational rules for computations with oracles. *)
Transparent evalDist.
Transparent getSupport.
Theorem oc_comp_spec_eq :
forall (A B C : Set)(c : OracleComp A B C), forall (*(eqda : EqDec A)*) (eqdb : EqDec B) (eqdc : EqDec C)(S1 S2 : Set)(o1 : S1 -> A -> Comp (B * S1))(o2 : S2 -> A -> Comp (B * S2)) eqds1 eqds2 s1 s2 (P : S1 -> S2 -> Prop),
P s1 s2 ->
(forall a x1 x2, P x1 x2 -> comp_spec (fun y1 y2 => fst y1 = fst y2 /\ P (snd y1) (snd y2)) (o1 x1 a) (o2 x2 a)) ->
comp_spec (fun a b => fst a = fst b /\ P (snd a) (snd b))
(c _ eqds1 o1 s1)
(c _ eqds2 o2 s2).
(* We have to do this by induction on the computation, since it may make an arbitary number of calls to the oracle. *)
induction c; intuition; simpl in *.
eapply (@comp_spec_consequence _ _ (@pair_EqDec B S1 eqdb eqds1) _ (@pair_EqDec B S2 eqdb eqds2)).
eapply H0; intuition.
intuition.
(* OC_Run case *)
assert (EqDec C).
eapply EqDec_pair_l;
eauto.
eapply (@comp_spec_seq _ _ (fun a b => fst a = fst b /\ fst (snd a) = fst (snd b) /\ P (snd (snd a)) (snd (snd b)) ))
; eauto.
intuition.
eapply oc_base_exists; eauto; intuition.
assert (B * S).
eapply oc_base_exists.
eauto.
intuition.
assert (B' * S1).
eapply comp_base_exists.
eauto.
intuition.
intuition.
intuition.
eapply oc_base_exists; eauto; intuition.
assert (B * S).
eapply oc_base_exists.
eauto.
intuition.
assert (B' * S1).
eapply comp_base_exists.
eauto.
intuition.
intuition.
eapply comp_spec_consequence.
eapply (IHc _ _ _ _ _ _ _ _ _ _ (fun p1 p2 => fst p1 = fst p2 /\ P (snd p1) (snd p2))).
simpl; intuition.
intuition.
simpl in *.
subst.
eapply comp_spec_seq.
intuition.
assert (B * S).
eapply oc_base_exists.
eauto.
intuition.
assert (B' * S1).
eapply comp_base_exists.
eapply o1; intuition.
intuition.
intuition.
intuition.
assert (B * S).
eapply oc_base_exists.
eauto.
intuition.
assert (B' * S1).
eapply comp_base_exists.
eapply o1; intuition.
intuition.
intuition.
eapply H.
eauto.
intuition.
intuition.
eapply comp_spec_ret.
simpl in *; intuition.
destruct b2; simpl in *.
destruct p; simpl in *; intuition.
inversion H7; clear H7; subst.
intuition.
destruct b2; simpl in *.
subst.
simpl.
intuition.
intuition.
intuition.
simpl in *.
subst.
eapply comp_spec_ret.
simpl in *.
destruct b; simpl in *.
intuition.
eapply comp_spec_seq_eq; intuition.
eapply comp_base_exists; intuition.
eapply comp_base_exists; intuition.
eapply comp_spec_eq_refl.
eapply comp_spec_ret; simpl; intuition.
assert (EqDec C).
eapply oc_EqDec.
eapply c.
intuition.
intuition.
assert (B * S1).
eapply comp_base_exists.
eauto.
intuition.
intuition.
eapply comp_spec_seq.
intuition.
eapply oc_base_exists.
eapply o.
eapply oc_base_exists.
eauto.
intuition.
assert (B * S1).
eapply comp_base_exists.
eapply o1.
intuition.
trivial.
intuition.
intuition.
assert (B * S1).
eapply comp_base_exists.
eapply o1; intuition.
intuition.
intuition.
eapply oc_base_exists.
eapply o.
eapply oc_base_exists.
eauto.
intuition.
assert (B * S1).
eapply comp_base_exists.
eapply o1.
intuition.
trivial.
intuition.
intuition.
assert (B * S1).
eapply comp_base_exists.
eapply o1; intuition.
intuition.
eapply IHc.
eauto.
intuition.
intuition.
simpl in *.
subst.
destruct b0.
simpl.
eapply H; intuition.
Qed.
Opaque evalDist.
Theorem oc_comp_spec_eq_until_bad :
forall (A B C : Set)(c : OracleComp A B C),
well_formed_oc c ->
forall (eqdb : EqDec B) (eqdc : EqDec C)(S1 S2 : Set)(o1 : S1 -> A -> Comp (B * S1))(o2 : S2 -> A -> Comp (B * S2)) eqds1 eqds2
(bad1 : S1 -> bool)(bad2 : S2 -> bool)(inv : S1 -> S2 -> Prop),
(forall a b, bad1 a = true -> well_formed_comp (o1 a b)) ->
(forall a b, bad2 a = true -> well_formed_comp (o2 a b)) ->
(forall x1 x2 a,
inv x1 x2 ->
bad1 x1 = bad2 x2 ->
comp_spec
(fun y1 y2 => (bad1 (snd y1) = bad2 (snd y2)) /\ (bad1 (snd y1) = false -> (inv (snd y1) (snd y2) /\ fst y1 = fst y2)))
(o1 x1 a) (o2 x2 a)) ->
(forall a b c d,
bad1 c = true ->
In (a, b) (getSupport (o1 c d)) -> bad1 b = true) ->
(forall a b c d,
bad2 c = true ->
In (a, b) (getSupport (o2 c d)) -> bad2 b = true) ->
((forall s1 s2,
inv s1 s2 ->
bad1 s1 = bad2 s2 ->
comp_spec
(fun y1 y2 => (bad1 (snd y1) = bad2 (snd y2)) /\ (bad1 (snd y1) = false -> inv (snd y1) (snd y2) /\ (fst y1 = fst y2)))
(c _ eqds1 o1 s1)
(c _ eqds2 o2 s2))).
induction 1; intuition; simpl in *.
(* Query case *)
eapply (@comp_spec_consequence _ _ (@pair_EqDec B S1 eqdb eqds1) _
(@pair_EqDec B S2 eqdb eqds2)).
eapply H1; intuition.
intuition.
(* Run case *)
assert (EqDec C).
eapply EqDec_pair_l; eauto.
assert C.
eapply oc_base_exists; eauto.
eapply (fun a => fst (oc_base_exists (o s a) (fun a' => fst (comp_base_exists (o1 s1 a'))))).
eapply (@comp_spec_seq _ _
(fun x y => (bad1 (snd (snd x)) = bad2 (snd (snd y))) /\ (bad1 (snd (snd x)) = false -> (fst (snd x) = fst (snd y) /\ fst x = fst y /\ inv (snd (snd x)) (snd (snd y)))))).
intuition.
intuition.
eapply comp_spec_consequence.
eapply (@IHwell_formed_oc _ _ (S * S1) (S * S2) _ _ _ _
(fun a => bad1 (snd a)) (fun a => bad2 (snd a)) (fun a b => bad1 (snd a) = false -> (inv (snd a) (snd b) /\ fst a = fst b)))%type.
(* ---- *)
intuition.
simpl in *.
Theorem oc_comp_wf_inv
: forall (A B C : Set) (c : OracleComp A B C),
well_formed_oc c ->
forall (S : Set) (P : S -> Prop)(eqds : EqDec S) (o : S -> A -> Comp (B * S)) (s : S),
(forall (a : S) (b : A), P a -> well_formed_comp (o a b)) ->
(forall a b s s', P s -> In (b, s') (getSupport (o s a)) -> P s') ->
P s ->
well_formed_comp (c S eqds o s).
induction 1; intuition; simpl in *.
eapply H.
trivial.
wftac.
eapply (@IHwell_formed_oc _ (fun x => P (snd x))).
intuition.
wftac.
intuition.
repeat simp_in_support.
simpl in *.
destruct x; simpl in *.
eapply oc_comp_invariant.
intuition.
eapply H3; eauto.
eauto.
eauto.
trivial.
wftac.
wftac.
eapply H1; intuition.
eapply H2; eauto.
eapply H3; eauto.
eapply oc_comp_invariant; intuition.
eapply H3; eauto.
eauto.
eauto.
Qed.
wftac.
eapply oc_comp_wf_inv;
intuition.
eapply H2.
eapply H12.
intuition.
eapply H5; intuition.
eauto.
eauto.
trivial.
intuition.
wftac.
simpl in *.
eapply oc_comp_wf_inv;
intuition.
eapply H3.
eapply H12.
intuition.
eapply H6; intuition.
eauto.
eauto.
trivial.
intuition.
simpl in *.
case_eq (bad1 b); intuition.
eapply comp_spec_irr_l; intuition.
eapply oc_comp_wf_inv; eauto.
eapply H2.
intuition; simpl.
eapply H5.
eauto.
eauto.
trivial.
eapply comp_spec_irr_r; intuition.
eapply oc_comp_wf_inv; eauto.
eapply H3.
intuition; simpl.
eapply H6.
eauto.
eauto.
simpl.
rewrite <- H12.
trivial.
eapply comp_spec_ret; simpl in *; intuition.
destruct a2; simpl in *.
assert (bad1 s0 = true).
eapply (oc_comp_invariant_f).
intuition.
eapply H5; eauto.
eauto.
eauto.
destruct b1.
simpl in *.
rewrite H16.
symmetry.
eapply (@oc_comp_invariant_f).
intuition.
eapply H6;
eauto.
eauto.
eauto.
(*contradiction *)
destruct a2.
simpl in *.
assert (bad1 s0 = true).
eapply (@oc_comp_invariant_f).
intuition.
eapply H5; eauto.
eauto.
eauto.
congruence.
(* contradiction *)
destruct a2; simpl in *.
assert (bad1 s0 = true).
eapply (@oc_comp_invariant_f).
intuition.
eapply H5; eauto.
eauto.
eauto.
congruence.
(* contradiction *)
destruct a2; simpl in *.
assert (bad1 s0 = true).
eapply (@oc_comp_invariant_f).
intuition.
eapply H5; eauto.
eauto.
eauto.
congruence.
subst.
(* IH *)
assert B.
assert (B * S).
eapply oc_base_exists.
eapply o; intuition.
intuition.
assert (B' * S1).
eapply comp_base_exists.
eapply o1; intuition.
intuition.
intuition.
eapply comp_spec_seq.
intuition.
intuition.
eapply H1;
intuition.
intuition.
intuition.
intuition.
eapply comp_spec_ret.
simpl in *; intuition.
destruct b3. destruct p. simpl in *.
pairInv.
trivial.
destruct b3.
simpl in *.
subst.
trivial.
intuition.
repeat simp_in_support.
simpl in *.
destruct x; simpl in *.
eapply oc_comp_invariant_f; intuition.
eapply H5; eauto.
eauto.
eauto.
intuition.
repeat simp_in_support.
simpl in *.
destruct x; simpl in *.
eapply oc_comp_invariant_f; intuition.
eapply H6; eauto.
eauto.
eauto.
intuition.
intuition.
intuition.
intuition.
eapply comp_spec_ret.
simpl in *; intuition.
subst.
intuition.
(* Ret case *)
assert C.
eapply comp_base_exists; eauto.
eapply comp_spec_seq; intuition.
eapply comp_spec_eq_refl.
subst.
eapply comp_spec_ret.
simpl in *; intuition.
(* Bind case *)
assert (A -> B).
intuition.
eapply (comp_base_exists (o1 s1 H9)).
assert C.
eapply oc_base_exists.
eauto.
intuition.
assert C'.
eapply oc_base_exists.
eapply f.
eapply oc_base_exists; eauto.
intuition.
assert (EqDec C).
eapply oc_EqDec.
eauto.
intuition.
intuition.
eapply comp_spec_seq;
intuition.
eapply (@IHwell_formed_oc _ _ _ _ _ _ _ _ bad1 bad2 inv).
eauto.
eauto.
intuition.
intuition.
intuition.
trivial.
trivial.
intuition.
destruct b0.
simpl in *.
case_eq (bad1 b); intuition.
eapply comp_spec_eq_trans_l.
eapply comp_spec_eq_symm.
eapply comp_spec_right_ident.
eapply comp_spec_eq_trans_r.
Focus 2.
eapply comp_spec_right_ident.
eapply comp_spec_irr_l; intuition.
eapply oc_comp_wf_inv; eauto.
intuition.
eapply H2; intuition.
eapply H15.
intuition.
eapply H5; intuition.
eauto.
eauto.
trivial.
eapply comp_spec_irr_r; intuition.
eapply oc_comp_wf_inv; eauto.
intuition.
eapply H3; intuition.
eapply H19.
intuition.
eapply H6; intuition.
eauto.
eauto.
simpl.
rewrite <- H17.
trivial.
eapply comp_spec_ret.
simpl in *; intuition.
destruct a. destruct b0; simpl in *.
assert (bad1 s0 = true).
eapply (oc_comp_invariant_f (f a0) bad1); intuition.
eapply H5.
eapply H21.
eapply H20.
eapply H16.
eapply H15.
rewrite H20.
symmetry.
assert (bad2 s = true).
rewrite <- H17.
trivial.
eapply (oc_comp_invariant_f (f c0) bad2); intuition.
eapply H6.
eapply H23.
eapply H22.
eapply H21.
eapply H19.
destruct a; simpl in *.
destruct b0; simpl in *.
assert (bad1 s0 = true).
eapply oc_comp_invariant_f.
intuition.
eapply H5.
eapply H22.
eapply H21.
eapply H16.
eapply H15.
congruence.
destruct a; simpl in *.
destruct b0; simpl in *.
assert (bad1 s0 = true).
eapply oc_comp_invariant_f.
intuition.
eapply H5.
eapply H22.
eapply H21.
eapply H16.
eapply H15.
congruence.
subst.
eapply H1;
intuition.
Qed.
Require Import Setoid.
Add Parametric Relation (A : Set){eqd : EqDec A} : (Comp A) (@comp_spec A A eqd eqd eq)
reflexivity proved by (@comp_spec_eq_refl A eqd)
symmetry proved by (@comp_spec_eq_symm A eqd)
transitivity proved by (@comp_spec_eq_trans A eqd)
as comp_spec_eq_rel. |
function y = mat2lpc(x,f)
%MAT2LPC Compresses a matrix using 1-D lossles predictive coding.
% Y = MAT2LPC(X, F) encodes matrix X using 1-D lossless predictive
% coding. A linear prediction of X is made based on the coefficients
% in F. If F is omitted, F = 1 (for previous pixel coding) is assumed.
% The prediction error is then computed and output as encoded matrix
% Y.
%
% See also LPC2MAT.
%
% Copyright 2002-2020 Gatesmark
%
% This function, and other functions in the DIPUM Toolbox, are based
% on the theoretical and practical foundations established in the
% book Digital Image Processing Using MATLAB, 3rd ed., Gatesmark
% Press, 2020.
%
% Book website: http://www.imageprocessingplace.com
% License: https://github.com/dipum/dipum-toolbox/blob/master/LICENSE.txt
narginchk(1,2); % Check input arguments
if nargin < 2 % Set default filter if omitted
f = 1;
end
x = double(x); % Ensure double for computations
[m, n] = size(x); % Get dimensions of input matrix
p = zeros(m,n); % Init linear prediction to 0
xs = x; zc = zeros(m,1); % Prepare for input shift and pad
for j = 1:length(f) % For each filter coefficient ...
xs = [zc xs(:,1:end - 1)]; % Shift and zero pad x
p = p + f(j) * xs; % Form partial prediction sums
end
y = x - round(p); % Compute prediction error
|
/-
Copyright (c) 2020 Paul van Wamelen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Paul van Wamelen
! This file was ported from Lean 3 source module number_theory.pythagorean_triples
! leanprover-community/mathlib commit 70fd9563a21e7b963887c9360bd29b2393e6225a
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathlib.Algebra.Field.Basic
import Mathlib.RingTheory.Int.Basic
import Mathlib.Tactic.Ring
import Mathlib.Tactic.FieldSimp
import Mathlib.Data.Int.NatPrime
import Mathlib.Data.ZMod.Basic
/-!
# Pythagorean Triples
The main result is the classification of Pythagorean triples. The final result is for general
Pythagorean triples. It follows from the more interesting relatively prime case. We use the
"rational parametrization of the circle" method for the proof. The parametrization maps the point
`(x / z, y / z)` to the slope of the line through `(-1 , 0)` and `(x / z, y / z)`. This quickly
shows that `(x / z, y / z) = (2 * m * n / (m ^ 2 + n ^ 2), (m ^ 2 - n ^ 2) / (m ^ 2 + n ^ 2))` where
`m / n` is the slope. In order to identify numerators and denominators we now need results showing
that these are coprime. This is easy except for the prime 2. In order to deal with that we have to
analyze the parity of `x`, `y`, `m` and `n` and eliminate all the impossible cases. This takes up
the bulk of the proof below.
-/
theorem sq_ne_two_fin_zmod_four (z : ZMod 4) : z * z ≠ 2 := by
change Fin 4 at z
fin_cases z <;> norm_num [Fin.ext_iff, Fin.val_bit0, Fin.val_bit1]
#align sq_ne_two_fin_zmod_four sq_ne_two_fin_zmod_four
theorem Int.sq_ne_two_mod_four (z : ℤ) : z * z % 4 ≠ 2 := by
suffices ¬z * z % (4 : ℕ) = 2 % (4 : ℕ) by exact this
rw [← ZMod.int_cast_eq_int_cast_iff']
simpa using sq_ne_two_fin_zmod_four _
#align int.sq_ne_two_mod_four Int.sq_ne_two_mod_four
noncomputable section
open Classical
/-- Three integers `x`, `y`, and `z` form a Pythagorean triple if `x * x + y * y = z * z`. -/
def PythagoreanTriple (x y z : ℤ) : Prop :=
x * x + y * y = z * z
#align pythagorean_triple PythagoreanTriple
/-- Pythagorean triples are interchangable, i.e `x * x + y * y = y * y + x * x = z * z`.
This comes from additive commutativity. -/
theorem pythagoreanTriple_comm {x y z : ℤ} : PythagoreanTriple x y z ↔ PythagoreanTriple y x z := by
delta PythagoreanTriple
rw [add_comm]
#align pythagorean_triple_comm pythagoreanTriple_comm
/-- The zeroth Pythagorean triple is all zeros. -/
theorem PythagoreanTriple.zero : PythagoreanTriple 0 0 0 := by
simp only [PythagoreanTriple, MulZeroClass.zero_mul, zero_add]
#align pythagorean_triple.zero PythagoreanTriple.zero
namespace PythagoreanTriple
variable {x y z : ℤ} (h : PythagoreanTriple x y z)
theorem eq : x * x + y * y = z * z :=
h
#align pythagorean_triple.eq PythagoreanTriple.eq
@[symm]
theorem symm : PythagoreanTriple y x z := by rwa [pythagoreanTriple_comm]
#align pythagorean_triple.symm PythagoreanTriple.symm
/-- A triple is still a triple if you multiply `x`, `y` and `z`
by a constant `k`. -/
theorem mul (k : ℤ) : PythagoreanTriple (k * x) (k * y) (k * z) :=
calc
k * x * (k * x) + k * y * (k * y) = k ^ 2 * (x * x + y * y) := by ring
_ = k ^ 2 * (z * z) := by rw [h.eq]
_ = k * z * (k * z) := by ring
#align pythagorean_triple.mul PythagoreanTriple.mul
/-- `(k*x, k*y, k*z)` is a Pythagorean triple if and only if
`(x, y, z)` is also a triple. -/
theorem mul_iff (k : ℤ) (hk : k ≠ 0) :
PythagoreanTriple (k * x) (k * y) (k * z) ↔ PythagoreanTriple x y z := by
refine' ⟨_, fun h => h.mul k⟩
simp only [PythagoreanTriple]
intro h
rw [← mul_left_inj' (mul_ne_zero hk hk)]
convert h using 1 <;> ring
#align pythagorean_triple.mul_iff PythagoreanTriple.mul_iff
/-- A Pythagorean triple `x, y, z` is “classified” if there exist integers `k, m, n` such that
either
* `x = k * (m ^ 2 - n ^ 2)` and `y = k * (2 * m * n)`, or
* `x = k * (2 * m * n)` and `y = k * (m ^ 2 - n ^ 2)`. -/
@[nolint unusedArguments]
def IsClassified (_ : PythagoreanTriple x y z) :=
∃ k m n : ℤ,
(x = k * (m ^ 2 - n ^ 2) ∧ y = k * (2 * m * n) ∨
x = k * (2 * m * n) ∧ y = k * (m ^ 2 - n ^ 2)) ∧
Int.gcd m n = 1
#align pythagorean_triple.is_classified PythagoreanTriple.IsClassified
/-- A primitive pythogorean triple `x, y, z` is a pythagorean triple with `x` and `y` coprime.
Such a triple is “primitively classified” if there exist coprime integers `m, n` such that either
* `x = m ^ 2 - n ^ 2` and `y = 2 * m * n`, or
* `x = 2 * m * n` and `y = m ^ 2 - n ^ 2`.
-/
@[nolint unusedArguments]
def IsPrimitiveClassified (_ : PythagoreanTriple x y z) :=
∃ m n : ℤ,
(x = m ^ 2 - n ^ 2 ∧ y = 2 * m * n ∨ x = 2 * m * n ∧ y = m ^ 2 - n ^ 2) ∧
Int.gcd m n = 1 ∧ (m % 2 = 0 ∧ n % 2 = 1 ∨ m % 2 = 1 ∧ n % 2 = 0)
#align pythagorean_triple.is_primitive_classified PythagoreanTriple.IsPrimitiveClassified
theorem mul_isClassified (k : ℤ) (hc : h.IsClassified) : (h.mul k).IsClassified := by
obtain ⟨l, m, n, ⟨⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, co⟩⟩ := hc
· use k * l, m, n
apply And.intro _ co
left
constructor <;> ring
· use k * l, m, n
apply And.intro _ co
right
constructor <;> ring
#align pythagorean_triple.mul_is_classified PythagoreanTriple.mul_isClassified
theorem even_odd_of_coprime (hc : Int.gcd x y = 1) :
x % 2 = 0 ∧ y % 2 = 1 ∨ x % 2 = 1 ∧ y % 2 = 0 := by
cases' Int.emod_two_eq_zero_or_one x with hx hx <;>
cases' Int.emod_two_eq_zero_or_one y with hy hy
-- x even, y even
· exfalso
apply Nat.not_coprime_of_dvd_of_dvd (by decide : 1 < 2) _ _ hc
· apply Int.dvd_natAbs_of_ofNat_dvd
apply Int.dvd_of_emod_eq_zero hx
· apply Int.dvd_natAbs_of_ofNat_dvd
apply Int.dvd_of_emod_eq_zero hy
-- x even, y odd
· left
exact ⟨hx, hy⟩
-- x odd, y even
· right
exact ⟨hx, hy⟩
-- x odd, y odd
· exfalso
obtain ⟨x0, y0, rfl, rfl⟩ : ∃ x0 y0, x = x0 * 2 + 1 ∧ y = y0 * 2 + 1 := by
cases' exists_eq_mul_left_of_dvd (Int.dvd_sub_of_emod_eq hx) with x0 hx2
cases' exists_eq_mul_left_of_dvd (Int.dvd_sub_of_emod_eq hy) with y0 hy2
rw [sub_eq_iff_eq_add] at hx2 hy2
exact ⟨x0, y0, hx2, hy2⟩
apply Int.sq_ne_two_mod_four z
rw [show z * z = 4 * (x0 * x0 + x0 + y0 * y0 + y0) + 2 by
rw [← h.eq]
ring]
field_simp [Int.add_emod] -- Porting note: norm_num is not enough to close this
#align pythagorean_triple.even_odd_of_coprime PythagoreanTriple.even_odd_of_coprime
theorem gcd_dvd : (Int.gcd x y : ℤ) ∣ z := by
by_cases h0 : Int.gcd x y = 0
· have hx : x = 0 := by
apply Int.natAbs_eq_zero.mp
apply Nat.eq_zero_of_gcd_eq_zero_left h0
have hy : y = 0 := by
apply Int.natAbs_eq_zero.mp
apply Nat.eq_zero_of_gcd_eq_zero_right h0
have hz : z = 0 := by
simpa only [PythagoreanTriple, hx, hy, add_zero, zero_eq_mul, MulZeroClass.mul_zero,
or_self_iff] using h
simp only [hz, dvd_zero]
obtain ⟨k, x0, y0, _, h2, rfl, rfl⟩ :
∃ (k : ℕ)(x0 y0 : _), 0 < k ∧ Int.gcd x0 y0 = 1 ∧ x = x0 * k ∧ y = y0 * k :=
Int.exists_gcd_one' (Nat.pos_of_ne_zero h0)
rw [Int.gcd_mul_right, h2, Int.natAbs_ofNat, one_mul]
rw [← Int.pow_dvd_pow_iff zero_lt_two, sq z, ← h.eq]
rw [(by ring : x0 * k * (x0 * k) + y0 * k * (y0 * k) = (k : ℤ) ^ 2 * (x0 * x0 + y0 * y0))]
exact dvd_mul_right _ _
#align pythagorean_triple.gcd_dvd PythagoreanTriple.gcd_dvd
theorem normalize : PythagoreanTriple (x / Int.gcd x y) (y / Int.gcd x y) (z / Int.gcd x y) := by
by_cases h0 : Int.gcd x y = 0
· have hx : x = 0 := by
apply Int.natAbs_eq_zero.mp
apply Nat.eq_zero_of_gcd_eq_zero_left h0
have hy : y = 0 := by
apply Int.natAbs_eq_zero.mp
apply Nat.eq_zero_of_gcd_eq_zero_right h0
have hz : z = 0 := by
simpa only [PythagoreanTriple, hx, hy, add_zero, zero_eq_mul, MulZeroClass.mul_zero,
or_self_iff] using h
simp only [hx, hy, hz, Int.zero_div]
exact zero
rcases h.gcd_dvd with ⟨z0, rfl⟩
obtain ⟨k, x0, y0, k0, h2, rfl, rfl⟩ :
∃ (k : ℕ)(x0 y0 : _), 0 < k ∧ Int.gcd x0 y0 = 1 ∧ x = x0 * k ∧ y = y0 * k :=
Int.exists_gcd_one' (Nat.pos_of_ne_zero h0)
have hk : (k : ℤ) ≠ 0 := by
norm_cast
rwa [pos_iff_ne_zero] at k0
rw [Int.gcd_mul_right, h2, Int.natAbs_ofNat, one_mul] at h⊢
rw [mul_comm x0, mul_comm y0, mul_iff k hk] at h
rwa [Int.mul_ediv_cancel _ hk, Int.mul_ediv_cancel _ hk, Int.mul_ediv_cancel_left _ hk]
#align pythagorean_triple.normalize PythagoreanTriple.normalize
theorem isClassified_of_isPrimitiveClassified (hp : h.IsPrimitiveClassified) : h.IsClassified := by
obtain ⟨m, n, H⟩ := hp
use 1, m, n
rcases H with ⟨t, co, _⟩
rw [one_mul, one_mul]
exact ⟨t, co⟩
#align pythagorean_triple.is_classified_of_is_primitive_classified PythagoreanTriple.isClassified_of_isPrimitiveClassified
theorem isClassified_of_normalize_isPrimitiveClassified (hc : h.normalize.IsPrimitiveClassified) :
h.IsClassified := by
convert h.normalize.mul_isClassified (Int.gcd x y)
(isClassified_of_isPrimitiveClassified h.normalize hc) <;>
rw [Int.mul_ediv_cancel']
· exact Int.gcd_dvd_left x y
· exact Int.gcd_dvd_right x y
· exact h.gcd_dvd
#align pythagorean_triple.is_classified_of_normalize_is_primitive_classified PythagoreanTriple.isClassified_of_normalize_isPrimitiveClassified
theorem isPrimitiveClassified_of_coprime_of_zero_left (hc : Int.gcd x y = 1) (hx : x = 0) :
h.IsPrimitiveClassified := by
subst x
change Nat.gcd 0 (Int.natAbs y) = 1 at hc
rw [Nat.gcd_zero_left (Int.natAbs y)] at hc
cases' Int.natAbs_eq y with hy hy
· use 1, 0
rw [hy, hc, Int.gcd_zero_right]
norm_num
· use 0, 1
rw [hy, hc, Int.gcd_zero_left]
norm_num
#align pythagorean_triple.is_primitive_classified_of_coprime_of_zero_left PythagoreanTriple.isPrimitiveClassified_of_coprime_of_zero_left
theorem coprime_of_coprime (hc : Int.gcd x y = 1) : Int.gcd y z = 1 := by
by_contra H
obtain ⟨p, hp, hpy, hpz⟩ := Nat.Prime.not_coprime_iff_dvd.mp H
apply hp.not_dvd_one
rw [← hc]
apply Nat.dvd_gcd (Int.Prime.dvd_natAbs_of_coe_dvd_sq hp _ _) hpy
rw [sq, eq_sub_of_add_eq h]
rw [← Int.coe_nat_dvd_left] at hpy hpz
exact dvd_sub (hpz.mul_right _) (hpy.mul_right _)
#align pythagorean_triple.coprime_of_coprime PythagoreanTriple.coprime_of_coprime
end PythagoreanTriple
section circleEquivGen
/-!
### A parametrization of the unit circle
For the classification of Pythagorean triples, we will use a parametrization of the unit circle.
-/
variable {K : Type _} [Field K]
/-- A parameterization of the unit circle that is useful for classifying Pythagorean triples.
(To be applied in the case where `K = ℚ`.) -/
def circleEquivGen (hk : ∀ x : K, 1 + x ^ 2 ≠ 0) :
K ≃ { p : K × K // p.1 ^ 2 + p.2 ^ 2 = 1 ∧ p.2 ≠ -1 } where
toFun x :=
⟨⟨2 * x / (1 + x ^ 2), (1 - x ^ 2) / (1 + x ^ 2)⟩, by
field_simp [hk x, div_pow]
ring, by
simp only [Ne.def, div_eq_iff (hk x), neg_mul, one_mul, neg_add, sub_eq_add_neg, add_left_inj]
simpa only [eq_neg_iff_add_eq_zero, one_pow] using hk 1⟩
invFun p := (p : K × K).1 / ((p : K × K).2 + 1)
left_inv x := by
have h2 : (1 + 1 : K) = 2 := by norm_num -- Porting note: rfl is not enough to close this
have h3 : (2 : K) ≠ 0 := by
convert hk 1
rw [one_pow 2, h2]
field_simp [hk x, h2, add_assoc, add_comm, add_sub_cancel'_right, mul_comm]
right_inv := fun ⟨⟨x, y⟩, hxy, hy⟩ => by
change x ^ 2 + y ^ 2 = 1 at hxy
have h2 : y + 1 ≠ 0 := mt eq_neg_of_add_eq_zero_left hy
have h3 : (y + 1) ^ 2 + x ^ 2 = 2 * (y + 1) := by
rw [(add_neg_eq_iff_eq_add.mpr hxy.symm).symm]
ring
have h4 : (2 : K) ≠ 0 := by
convert hk 1
rw [one_pow 2]
ring -- Porting note: rfl is not enough to close this
simp only [Prod.mk.inj_iff, Subtype.mk_eq_mk]
constructor
· field_simp [h3]
ring
· field_simp [h3]
rw [← add_neg_eq_iff_eq_add.mpr hxy.symm]
ring
#align circle_equiv_gen circleEquivGen
@[simp]
theorem circleEquivGen_apply (hk : ∀ x : K, 1 + x ^ 2 ≠ 0) (x : K) :
(circleEquivGen hk x : K × K) = ⟨2 * x / (1 + x ^ 2), (1 - x ^ 2) / (1 + x ^ 2)⟩ :=
rfl
#align circle_equiv_apply circleEquivGen_apply
@[simp]
theorem circleEquivGen_symm_apply (hk : ∀ x : K, 1 + x ^ 2 ≠ 0)
(v : { p : K × K // p.1 ^ 2 + p.2 ^ 2 = 1 ∧ p.2 ≠ -1 }) :
(circleEquivGen hk).symm v = (v : K × K).1 / ((v : K × K).2 + 1) :=
rfl
#align circle_equiv_symm_apply circleEquivGen_symm_apply
end circleEquivGen
private theorem coprime_sq_sub_sq_add_of_even_odd {m n : ℤ} (h : Int.gcd m n = 1) (hm : m % 2 = 0)
(hn : n % 2 = 1) : Int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1 := by
by_contra H
obtain ⟨p, hp, hp1, hp2⟩ := Nat.Prime.not_coprime_iff_dvd.mp H
rw [← Int.coe_nat_dvd_left] at hp1 hp2
have h2m : (p : ℤ) ∣ 2 * m ^ 2 := by
convert dvd_add hp2 hp1 using 1
ring
have h2n : (p : ℤ) ∣ 2 * n ^ 2 := by
convert dvd_sub hp2 hp1 using 1
ring
have hmc : p = 2 ∨ p ∣ Int.natAbs m := prime_two_or_dvd_of_dvd_two_mul_pow_self_two hp h2m
have hnc : p = 2 ∨ p ∣ Int.natAbs n := prime_two_or_dvd_of_dvd_two_mul_pow_self_two hp h2n
by_cases h2 : p = 2
-- Porting note: norm_num is not enough to close h3
· have h3 : (m ^ 2 + n ^ 2) % 2 = 1 := by field_simp [sq, Int.add_emod, Int.mul_emod, hm, hn]
have h4 : (m ^ 2 + n ^ 2) % 2 = 0 := by
apply Int.emod_eq_zero_of_dvd
rwa [h2] at hp2
rw [h4] at h3
exact zero_ne_one h3
· apply hp.not_dvd_one
rw [← h]
exact Nat.dvd_gcd (Or.resolve_left hmc h2) (Or.resolve_left hnc h2)
private theorem coprime_sq_sub_sq_add_of_odd_even {m n : ℤ} (h : Int.gcd m n = 1) (hm : m % 2 = 1)
(hn : n % 2 = 0) : Int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1 := by
rw [Int.gcd, ← Int.natAbs_neg (m ^ 2 - n ^ 2)]
rw [(by ring : -(m ^ 2 - n ^ 2) = n ^ 2 - m ^ 2), add_comm]
apply coprime_sq_sub_sq_add_of_even_odd _ hn hm; rwa [Int.gcd_comm]
private theorem coprime_sq_sub_mul_of_even_odd {m n : ℤ} (h : Int.gcd m n = 1) (hm : m % 2 = 0)
(hn : n % 2 = 1) : Int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 := by
by_contra H
obtain ⟨p, hp, hp1, hp2⟩ := Nat.Prime.not_coprime_iff_dvd.mp H
rw [← Int.coe_nat_dvd_left] at hp1 hp2
have hnp : ¬(p : ℤ) ∣ Int.gcd m n := by
rw [h]
norm_cast
exact mt Nat.dvd_one.mp (Nat.Prime.ne_one hp)
cases' Int.Prime.dvd_mul hp hp2 with hp2m hpn
· rw [Int.natAbs_mul] at hp2m
cases' (Nat.Prime.dvd_mul hp).mp hp2m with hp2 hpm
· have hp2' : p = 2 := (Nat.le_of_dvd zero_lt_two hp2).antisymm hp.two_le
revert hp1
rw [hp2']
apply mt Int.emod_eq_zero_of_dvd
-- Porting note: norm_num is not enough to close this
field_simp [sq, Int.sub_emod, Int.mul_emod, hm, hn]
apply mt (Int.dvd_gcd (Int.coe_nat_dvd_left.mpr hpm)) hnp
apply (or_self_iff _).mp
apply Int.Prime.dvd_mul' hp
rw [(by ring : n * n = -(m ^ 2 - n ^ 2) + m * m)]
apply dvd_add (dvd_neg_of_dvd hp1)
exact dvd_mul_of_dvd_left (Int.coe_nat_dvd_left.mpr hpm) m
rw [Int.gcd_comm] at hnp
apply mt (Int.dvd_gcd (Int.coe_nat_dvd_left.mpr hpn)) hnp
apply (or_self_iff _).mp
apply Int.Prime.dvd_mul' hp
rw [(by ring : m * m = m ^ 2 - n ^ 2 + n * n)]
apply dvd_add hp1
exact (Int.coe_nat_dvd_left.mpr hpn).mul_right n
private theorem coprime_sq_sub_mul_of_odd_even {m n : ℤ} (h : Int.gcd m n = 1) (hm : m % 2 = 1)
(hn : n % 2 = 0) : Int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 := by
rw [Int.gcd, ← Int.natAbs_neg (m ^ 2 - n ^ 2)]
rw [(by ring : 2 * m * n = 2 * n * m), (by ring : -(m ^ 2 - n ^ 2) = n ^ 2 - m ^ 2)]
apply coprime_sq_sub_mul_of_even_odd _ hn hm; rwa [Int.gcd_comm]
private theorem coprime_sq_sub_mul {m n : ℤ} (h : Int.gcd m n = 1)
(hmn : m % 2 = 0 ∧ n % 2 = 1 ∨ m % 2 = 1 ∧ n % 2 = 0) :
Int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 := by
cases' hmn with h1 h2
· exact coprime_sq_sub_mul_of_even_odd h h1.left h1.right
· exact coprime_sq_sub_mul_of_odd_even h h2.left h2.right
private theorem coprime_sq_sub_sq_sum_of_odd_odd {m n : ℤ} (h : Int.gcd m n = 1) (hm : m % 2 = 1)
(hn : n % 2 = 1) :
2 ∣ m ^ 2 + n ^ 2 ∧
2 ∣ m ^ 2 - n ^ 2 ∧
(m ^ 2 - n ^ 2) / 2 % 2 = 0 ∧ Int.gcd ((m ^ 2 - n ^ 2) / 2) ((m ^ 2 + n ^ 2) / 2) = 1 := by
cases' exists_eq_mul_left_of_dvd (Int.dvd_sub_of_emod_eq hm) with m0 hm2
cases' exists_eq_mul_left_of_dvd (Int.dvd_sub_of_emod_eq hn) with n0 hn2
rw [sub_eq_iff_eq_add] at hm2 hn2
subst m
subst n
have h1 : (m0 * 2 + 1) ^ 2 + (n0 * 2 + 1) ^ 2 = 2 * (2 * (m0 ^ 2 + n0 ^ 2 + m0 + n0) + 1) := by
ring
have h2 : (m0 * 2 + 1) ^ 2 - (n0 * 2 + 1) ^ 2 = 2 * (2 * (m0 ^ 2 - n0 ^ 2 + m0 - n0)) := by ring
have h3 : ((m0 * 2 + 1) ^ 2 - (n0 * 2 + 1) ^ 2) / 2 % 2 = 0 := by
rw [h2, Int.mul_ediv_cancel_left, Int.mul_emod_right]
exact by decide
refine' ⟨⟨_, h1⟩, ⟨_, h2⟩, h3, _⟩
have h20 : (2 : ℤ) ≠ 0 := by decide
rw [h1, h2, Int.mul_ediv_cancel_left _ h20, Int.mul_ediv_cancel_left _ h20]
by_contra h4
obtain ⟨p, hp, hp1, hp2⟩ := Nat.Prime.not_coprime_iff_dvd.mp h4
apply hp.not_dvd_one
rw [← h]
rw [← Int.coe_nat_dvd_left] at hp1 hp2
apply Nat.dvd_gcd
· apply Int.Prime.dvd_natAbs_of_coe_dvd_sq hp
convert dvd_add hp1 hp2
ring
· apply Int.Prime.dvd_natAbs_of_coe_dvd_sq hp
convert dvd_sub hp2 hp1
ring
namespace PythagoreanTriple
variable {x y z : ℤ} (h : PythagoreanTriple x y z)
theorem isPrimitiveClassified_aux (hc : x.gcd y = 1) (hzpos : 0 < z) {m n : ℤ}
(hm2n2 : 0 < m ^ 2 + n ^ 2) (hv2 : (x : ℚ) / z = 2 * m * n / ((m : ℚ) ^ 2 + (n : ℚ) ^ 2))
(hw2 : (y : ℚ) / z = ((m : ℚ) ^ 2 - (n : ℚ) ^ 2) / ((m : ℚ) ^ 2 + (n : ℚ) ^ 2))
(H : Int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1) (co : Int.gcd m n = 1)
(pp : m % 2 = 0 ∧ n % 2 = 1 ∨ m % 2 = 1 ∧ n % 2 = 0) : h.IsPrimitiveClassified := by
have hz : z ≠ 0
apply ne_of_gt hzpos
have h2 : y = m ^ 2 - n ^ 2 ∧ z = m ^ 2 + n ^ 2 := by
apply Rat.div_int_inj hzpos hm2n2 (h.coprime_of_coprime hc) H
rw [hw2]
norm_cast
use m, n
apply And.intro _ (And.intro co pp)
right
refine' ⟨_, h2.left⟩
rw [← Rat.coe_int_inj _ _, ← div_left_inj' ((mt (Rat.coe_int_inj z 0).mp) hz), hv2, h2.right]
norm_cast
#align pythagorean_triple.is_primitive_classified_aux PythagoreanTriple.isPrimitiveClassified_aux
theorem isPrimitiveClassified_of_coprime_of_odd_of_pos (hc : Int.gcd x y = 1) (hyo : y % 2 = 1)
(hzpos : 0 < z) : h.IsPrimitiveClassified := by
by_cases h0 : x = 0
· exact h.isPrimitiveClassified_of_coprime_of_zero_left hc h0
let v := (x : ℚ) / z
let w := (y : ℚ) / z
have hz : z ≠ 0
apply ne_of_gt hzpos
have hq : v ^ 2 + w ^ 2 = 1 := by
field_simp [hz, sq]
norm_cast
have hvz : v ≠ 0 := by
field_simp [hz]
exact h0
have hw1 : w ≠ -1 := by
contrapose! hvz with hw1
-- porting note: `contrapose` unfolds local names, refold them
replace hw1 : w = -1 := hw1; show v = 0
rw [hw1, neg_sq, one_pow, add_left_eq_self] at hq
exact pow_eq_zero hq
have hQ : ∀ x : ℚ, 1 + x ^ 2 ≠ 0 := by
intro q
apply ne_of_gt
exact lt_add_of_pos_of_le zero_lt_one (sq_nonneg q)
have hp : (⟨v, w⟩ : ℚ × ℚ) ∈ { p : ℚ × ℚ | p.1 ^ 2 + p.2 ^ 2 = 1 ∧ p.2 ≠ -1 } := ⟨hq, hw1⟩
let q := (circleEquivGen hQ).symm ⟨⟨v, w⟩, hp⟩
have ht4 : v = 2 * q / (1 + q ^ 2) ∧ w = (1 - q ^ 2) / (1 + q ^ 2) := by
apply Prod.mk.inj
have := ((circleEquivGen hQ).apply_symm_apply ⟨⟨v, w⟩, hp⟩).symm
exact congr_arg Subtype.val this
let m := (q.den : ℤ)
let n := q.num
have hm0 : m ≠ 0 := by
norm_cast
apply Rat.den_nz q
have hq2 : q = n / m := (Rat.num_div_den q).symm
have hm2n2 : 0 < m ^ 2 + n ^ 2 := by
apply lt_add_of_pos_of_le _ (sq_nonneg n)
exact lt_of_le_of_ne (sq_nonneg m) (Ne.symm (pow_ne_zero 2 hm0))
have hm2n20 : (m : ℚ) ^ 2 + (n : ℚ) ^ 2 ≠ 0 := by
norm_cast
simpa only [Int.coe_nat_pow] using ne_of_gt hm2n2
have hx1 {j k : ℚ} (h₁ : k ≠ 0) (h₂ : k ^ 2 + j ^ 2 ≠ 0) :
(1 - (j / k) ^ 2) / (1 + (j / k) ^ 2) = (k ^ 2 - j ^ 2) / (k ^ 2 + j ^ 2) :=
by field_simp
have hw2 : w = ((m : ℚ) ^ 2 - (n : ℚ) ^ 2) / ((m : ℚ) ^ 2 + (n : ℚ) ^ 2) := by
calc
w = (1 - q ^ 2) / (1 + q ^ 2) := by apply ht4.2
_ = (1 - (↑n / ↑m) ^ 2) / (1 + (↑n / ↑m) ^ 2) := by rw [hq2]
_ = _ := by exact hx1 (Int.cast_ne_zero.mpr hm0) hm2n20
have hx2 {j k : ℚ} (h₁ : k ≠ 0) (h₂ : k ^ 2 + j ^ 2 ≠ 0) :
2 * (j / k) / (1 + (j / k) ^ 2) = 2 * k * j / (k ^ 2 + j ^ 2) :=
have h₃ : k * (k ^ 2 + j ^ 2) ≠ 0 := mul_ne_zero h₁ h₂
by field_simp; ring
have hv2 : v = 2 * m * n / ((m : ℚ) ^ 2 + (n : ℚ) ^ 2) := by
calc
v = 2 * q / (1 + q ^ 2) := by apply ht4.1
_ = 2 * (n / m) / (1 + (↑n / ↑m) ^ 2) := by rw [hq2]
_ = _ := by exact hx2 (Int.cast_ne_zero.mpr hm0) hm2n20
have hnmcp : Int.gcd n m = 1 := q.reduced
have hmncp : Int.gcd m n = 1 := by
rw [Int.gcd_comm]
exact hnmcp
cases' Int.emod_two_eq_zero_or_one m with hm2 hm2 <;>
cases' Int.emod_two_eq_zero_or_one n with hn2 hn2
· -- m even, n even
exfalso
have h1 : 2 ∣ (Int.gcd n m : ℤ) :=
Int.dvd_gcd (Int.dvd_of_emod_eq_zero hn2) (Int.dvd_of_emod_eq_zero hm2)
rw [hnmcp] at h1
revert h1
norm_num
· -- m even, n odd
apply h.isPrimitiveClassified_aux hc hzpos hm2n2 hv2 hw2 _ hmncp
· apply Or.intro_left
exact And.intro hm2 hn2
· apply coprime_sq_sub_sq_add_of_even_odd hmncp hm2 hn2
· -- m odd, n even
apply h.isPrimitiveClassified_aux hc hzpos hm2n2 hv2 hw2 _ hmncp
· apply Or.intro_right
exact And.intro hm2 hn2
apply coprime_sq_sub_sq_add_of_odd_even hmncp hm2 hn2
· -- m odd, n odd
exfalso
have h1 :
2 ∣ m ^ 2 + n ^ 2 ∧
2 ∣ m ^ 2 - n ^ 2 ∧
(m ^ 2 - n ^ 2) / 2 % 2 = 0 ∧ Int.gcd ((m ^ 2 - n ^ 2) / 2) ((m ^ 2 + n ^ 2) / 2) = 1 :=
coprime_sq_sub_sq_sum_of_odd_odd hmncp hm2 hn2
have h2 : y = (m ^ 2 - n ^ 2) / 2 ∧ z = (m ^ 2 + n ^ 2) / 2 := by
apply Rat.div_int_inj hzpos _ (h.coprime_of_coprime hc) h1.2.2.2
· show w = _
rw [← Rat.divInt_eq_div, ← Rat.divInt_mul_right (by norm_num : (2 : ℤ) ≠ 0)]
rw [Int.ediv_mul_cancel h1.1, Int.ediv_mul_cancel h1.2.1, hw2]
norm_cast
· apply (mul_lt_mul_right (by norm_num : 0 < (2 : ℤ))).mp
rw [Int.ediv_mul_cancel h1.1, MulZeroClass.zero_mul]
exact hm2n2
rw [h2.1, h1.2.2.1] at hyo
revert hyo
norm_num
#align pythagorean_triple.is_primitive_classified_of_coprime_of_odd_of_pos PythagoreanTriple.isPrimitiveClassified_of_coprime_of_odd_of_pos
theorem isPrimitiveClassified_of_coprime_of_pos (hc : Int.gcd x y = 1) (hzpos : 0 < z) :
h.IsPrimitiveClassified := by
cases' h.even_odd_of_coprime hc with h1 h2
· exact h.isPrimitiveClassified_of_coprime_of_odd_of_pos hc h1.right hzpos
rw [Int.gcd_comm] at hc
obtain ⟨m, n, H⟩ := h.symm.isPrimitiveClassified_of_coprime_of_odd_of_pos hc h2.left hzpos
use m, n; tauto
#align pythagorean_triple.is_primitive_classified_of_coprime_of_pos PythagoreanTriple.isPrimitiveClassified_of_coprime_of_pos
theorem isPrimitiveClassified_of_coprime (hc : Int.gcd x y = 1) : h.IsPrimitiveClassified := by
by_cases hz : 0 < z
· exact h.isPrimitiveClassified_of_coprime_of_pos hc hz
have h' : PythagoreanTriple x y (-z) := by simpa [PythagoreanTriple, neg_mul_neg] using h.eq
apply h'.isPrimitiveClassified_of_coprime_of_pos hc
apply lt_of_le_of_ne _ (h'.ne_zero_of_coprime hc).symm
exact le_neg.mp (not_lt.mp hz)
#align pythagorean_triple.is_primitive_classified_of_coprime PythagoreanTriple.isPrimitiveClassified_of_coprime
theorem classified : h.IsClassified := by
by_cases h0 : Int.gcd x y = 0
· have hx : x = 0 := by
apply Int.natAbs_eq_zero.mp
apply Nat.eq_zero_of_gcd_eq_zero_left h0
have hy : y = 0 := by
apply Int.natAbs_eq_zero.mp
apply Nat.eq_zero_of_gcd_eq_zero_right h0
use 0, 1, 0
field_simp [hx, hy]
apply h.isClassified_of_normalize_isPrimitiveClassified
apply h.normalize.isPrimitiveClassified_of_coprime
apply Int.gcd_div_gcd_div_gcd (Nat.pos_of_ne_zero h0)
#align pythagorean_triple.classified PythagoreanTriple.classified
theorem coprime_classification :
PythagoreanTriple x y z ∧ Int.gcd x y = 1 ↔
∃ m n,
(x = m ^ 2 - n ^ 2 ∧ y = 2 * m * n ∨ x = 2 * m * n ∧ y = m ^ 2 - n ^ 2) ∧
(z = m ^ 2 + n ^ 2 ∨ z = -(m ^ 2 + n ^ 2)) ∧
Int.gcd m n = 1 ∧ (m % 2 = 0 ∧ n % 2 = 1 ∨ m % 2 = 1 ∧ n % 2 = 0) := by
clear h -- porting note: don't want this variable, but can't use `include` / `omit`
constructor
· intro h
obtain ⟨m, n, H⟩ := h.left.isPrimitiveClassified_of_coprime h.right
use m, n
rcases H with ⟨⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, co, pp⟩
· refine' ⟨Or.inl ⟨rfl, rfl⟩, _, co, pp⟩
have : z ^ 2 = (m ^ 2 + n ^ 2) ^ 2 := by
rw [sq, ← h.left.eq]
ring
simpa using eq_or_eq_neg_of_sq_eq_sq _ _ this
· refine' ⟨Or.inr ⟨rfl, rfl⟩, _, co, pp⟩
have : z ^ 2 = (m ^ 2 + n ^ 2) ^ 2 := by
rw [sq, ← h.left.eq]
ring
simpa using eq_or_eq_neg_of_sq_eq_sq _ _ this
· delta PythagoreanTriple
rintro ⟨m, n, ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, rfl | rfl, co, pp⟩ <;>
first
| constructor; ring; exact coprime_sq_sub_mul co pp
| constructor; ring; rw [Int.gcd_comm]; exact coprime_sq_sub_mul co pp
#align pythagorean_triple.coprime_classification PythagoreanTriple.coprime_classification
/-- by assuming `x` is odd and `z` is positive we get a slightly more precise classification of
the Pythagorean triple `x ^ 2 + y ^ 2 = z ^ 2`-/
theorem coprime_classification' {x y z : ℤ} (h : PythagoreanTriple x y z)
(h_coprime : Int.gcd x y = 1) (h_parity : x % 2 = 1) (h_pos : 0 < z) :
∃ m n,
x = m ^ 2 - n ^ 2 ∧
y = 2 * m * n ∧
z = m ^ 2 + n ^ 2 ∧
Int.gcd m n = 1 ∧ (m % 2 = 0 ∧ n % 2 = 1 ∨ m % 2 = 1 ∧ n % 2 = 0) ∧ 0 ≤ m := by
obtain ⟨m, n, ht1, ht2, ht3, ht4⟩ :=
PythagoreanTriple.coprime_classification.mp (And.intro h h_coprime)
cases' le_or_lt 0 m with hm hm
· use m, n
cases' ht1 with h_odd h_even
· apply And.intro h_odd.1
apply And.intro h_odd.2
cases' ht2 with h_pos h_neg
· apply And.intro h_pos (And.intro ht3 (And.intro ht4 hm))
· exfalso
revert h_pos
rw [h_neg]
exact imp_false.mpr (not_lt.mpr (neg_nonpos.mpr (add_nonneg (sq_nonneg m) (sq_nonneg n))))
exfalso
rcases h_even with ⟨rfl, -⟩
rw [mul_assoc, Int.mul_emod_right] at h_parity
exact zero_ne_one h_parity
· use -m, -n
cases' ht1 with h_odd h_even
· rw [neg_sq m]
rw [neg_sq n]
apply And.intro h_odd.1
constructor
· rw [h_odd.2]
ring
cases' ht2 with h_pos h_neg
· apply And.intro h_pos
constructor
· delta Int.gcd
rw [Int.natAbs_neg, Int.natAbs_neg]
exact ht3
· rw [Int.neg_emod_two, Int.neg_emod_two]
apply And.intro ht4
linarith
· exfalso
revert h_pos
rw [h_neg]
exact imp_false.mpr (not_lt.mpr (neg_nonpos.mpr (add_nonneg (sq_nonneg m) (sq_nonneg n))))
exfalso
rcases h_even with ⟨rfl, -⟩
rw [mul_assoc, Int.mul_emod_right] at h_parity
exact zero_ne_one h_parity
#align pythagorean_triple.coprime_classification' PythagoreanTriple.coprime_classification'
/-- **Formula for Pythagorean Triples** -/
theorem classification :
PythagoreanTriple x y z ↔
∃ k m n,
(x = k * (m ^ 2 - n ^ 2) ∧ y = k * (2 * m * n) ∨
x = k * (2 * m * n) ∧ y = k * (m ^ 2 - n ^ 2)) ∧
(z = k * (m ^ 2 + n ^ 2) ∨ z = -k * (m ^ 2 + n ^ 2)) := by
constructor
· intro h
obtain ⟨k, m, n, H⟩ := h.classified
use k, m, n
rcases H with (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩)
· refine' ⟨Or.inl ⟨rfl, rfl⟩, _⟩
have : z ^ 2 = (k * (m ^ 2 + n ^ 2)) ^ 2 := by
rw [sq, ← h.eq]
ring
simpa using eq_or_eq_neg_of_sq_eq_sq _ _ this
· refine' ⟨Or.inr ⟨rfl, rfl⟩, _⟩
have : z ^ 2 = (k * (m ^ 2 + n ^ 2)) ^ 2 := by
rw [sq, ← h.eq]
ring
simpa using eq_or_eq_neg_of_sq_eq_sq _ _ this
· rintro ⟨k, m, n, ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, rfl | rfl⟩ <;> delta PythagoreanTriple <;> ring
#align pythagorean_triple.classification PythagoreanTriple.classification
end PythagoreanTriple
|
[STATEMENT]
lemma net_nhop_quality_increases:
assumes "wf_net_tree n"
shows "closed (pnet (\<lambda>i. paodv i \<langle>\<langle> qmsg) n) \<TTurnstile> netglobal
(\<lambda>\<sigma>. \<forall>i dip. let nhip = the (nhop (rt (\<sigma> i)) dip)
in dip \<in> vD (rt (\<sigma> i)) \<inter> vD (rt (\<sigma> nhip)) \<and> nhip \<noteq> dip
\<longrightarrow> (rt (\<sigma> i)) \<sqsubset>\<^bsub>dip\<^esub> (rt (\<sigma> nhip)))"
(is "_ \<TTurnstile> netglobal (\<lambda>\<sigma>. \<forall>i. ?inv \<sigma> i)")
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. closed (pnet (\<lambda>i. paodv i \<langle>\<langle> qmsg) n) \<TTurnstile> netglobal (\<lambda>\<sigma>. \<forall>i dip. let nhip = the (nhop (rt (\<sigma> i)) dip) in dip \<in> vD (rt (\<sigma> i)) \<inter> vD (rt (\<sigma> nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (\<sigma> i) \<sqsubset>\<^bsub>dip\<^esub> rt (\<sigma> nhip))
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. closed (pnet (\<lambda>i. paodv i \<langle>\<langle> qmsg) n) \<TTurnstile> netglobal (\<lambda>\<sigma>. \<forall>i dip. let nhip = the (nhop (rt (\<sigma> i)) dip) in dip \<in> vD (rt (\<sigma> i)) \<inter> vD (rt (\<sigma> nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (\<sigma> i) \<sqsubset>\<^bsub>dip\<^esub> rt (\<sigma> nhip))
[PROOF STEP]
from \<open>wf_net_tree n\<close>
[PROOF STATE]
proof (chain)
picking this:
wf_net_tree n
[PROOF STEP]
have proto: "closed (pnet (\<lambda>i. paodv i \<langle>\<langle> qmsg) n) \<TTurnstile> netglobal (\<lambda>\<sigma>. \<forall>i\<in>net_tree_ips n. \<forall>dip.
let nhip = the (nhop (rt (\<sigma> i)) dip)
in dip \<in> vD (rt (\<sigma> i)) \<inter> vD (rt (\<sigma> nhip)) \<and> nhip \<noteq> dip
\<longrightarrow> (rt (\<sigma> i)) \<sqsubset>\<^bsub>dip\<^esub> (rt (\<sigma> nhip)))"
[PROOF STATE]
proof (prove)
using this:
wf_net_tree n
goal (1 subgoal):
1. closed (pnet (\<lambda>i. paodv i \<langle>\<langle> qmsg) n) \<TTurnstile> netglobal (\<lambda>\<sigma>. \<forall>i\<in>net_tree_ips n. \<forall>dip. let nhip = the (nhop (rt (\<sigma> i)) dip) in dip \<in> vD (rt (\<sigma> i)) \<inter> vD (rt (\<sigma> nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (\<sigma> i) \<sqsubset>\<^bsub>dip\<^esub> rt (\<sigma> nhip))
[PROOF STEP]
by (rule aodv_openproc_par_qmsg.close_opnet [OF _ onet_nhop_quality_increases])
[PROOF STATE]
proof (state)
this:
closed (pnet (\<lambda>i. paodv i \<langle>\<langle> qmsg) n) \<TTurnstile> netglobal (\<lambda>\<sigma>. \<forall>i\<in>net_tree_ips n. \<forall>dip. let nhip = the (nhop (rt (\<sigma> i)) dip) in dip \<in> vD (rt (\<sigma> i)) \<inter> vD (rt (\<sigma> nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (\<sigma> i) \<sqsubset>\<^bsub>dip\<^esub> rt (\<sigma> nhip))
goal (1 subgoal):
1. closed (pnet (\<lambda>i. paodv i \<langle>\<langle> qmsg) n) \<TTurnstile> netglobal (\<lambda>\<sigma>. \<forall>i dip. let nhip = the (nhop (rt (\<sigma> i)) dip) in dip \<in> vD (rt (\<sigma> i)) \<inter> vD (rt (\<sigma> nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (\<sigma> i) \<sqsubset>\<^bsub>dip\<^esub> rt (\<sigma> nhip))
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. closed (pnet (\<lambda>i. paodv i \<langle>\<langle> qmsg) n) \<TTurnstile> netglobal (\<lambda>\<sigma>. \<forall>i dip. let nhip = the (nhop (rt (\<sigma> i)) dip) in dip \<in> vD (rt (\<sigma> i)) \<inter> vD (rt (\<sigma> nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (\<sigma> i) \<sqsubset>\<^bsub>dip\<^esub> rt (\<sigma> nhip))
[PROOF STEP]
unfolding invariant_def opnet_sos.opnet_tau1
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Ball (reachable (closed (pnet (\<lambda>i. paodv i \<langle>\<langle> qmsg) n)) TT) (netglobal (\<lambda>\<sigma>. \<forall>i dip. let nhip = the (nhop (rt (\<sigma> i)) dip) in dip \<in> vD (rt (\<sigma> i)) \<inter> vD (rt (\<sigma> nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (\<sigma> i) \<sqsubset>\<^bsub>dip\<^esub> rt (\<sigma> nhip)))
[PROOF STEP]
proof (rule, simp only: aodv_openproc_par_qmsg.netglobalsimp
fst_initmissing_netgmap_pair_fst, rule allI)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>x i. x \<in> reachable (closed (pnet (\<lambda>i. paodv i \<langle>\<langle> qmsg) n)) TT \<Longrightarrow> \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst x)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst x)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst x)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst x)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst x)) nhip)
[PROOF STEP]
fix \<sigma> i
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>x i. x \<in> reachable (closed (pnet (\<lambda>i. paodv i \<langle>\<langle> qmsg) n)) TT \<Longrightarrow> \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst x)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst x)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst x)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst x)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst x)) nhip)
[PROOF STEP]
assume sr: "\<sigma> \<in> reachable (closed (pnet (\<lambda>i. paodv i \<langle>\<langle> qmsg) n)) TT"
[PROOF STATE]
proof (state)
this:
\<sigma> \<in> reachable (closed (pnet (\<lambda>i. paodv i \<langle>\<langle> qmsg) n)) TT
goal (1 subgoal):
1. \<And>x i. x \<in> reachable (closed (pnet (\<lambda>i. paodv i \<langle>\<langle> qmsg) n)) TT \<Longrightarrow> \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst x)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst x)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst x)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst x)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst x)) nhip)
[PROOF STEP]
hence "\<forall>i\<in>net_tree_ips n. ?inv (fst (initmissing (netgmap fst \<sigma>))) i"
[PROOF STATE]
proof (prove)
using this:
\<sigma> \<in> reachable (closed (pnet (\<lambda>i. paodv i \<langle>\<langle> qmsg) n)) TT
goal (1 subgoal):
1. \<forall>i\<in>net_tree_ips n. \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip)
[PROOF STEP]
by - (drule invariantD [OF proto],
simp only: aodv_openproc_par_qmsg.netglobalsimp
fst_initmissing_netgmap_pair_fst)
[PROOF STATE]
proof (state)
this:
\<forall>i\<in>net_tree_ips n. \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip)
goal (1 subgoal):
1. \<And>x i. x \<in> reachable (closed (pnet (\<lambda>i. paodv i \<langle>\<langle> qmsg) n)) TT \<Longrightarrow> \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst x)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst x)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst x)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst x)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst x)) nhip)
[PROOF STEP]
thus "?inv (fst (initmissing (netgmap fst \<sigma>))) i"
[PROOF STATE]
proof (prove)
using this:
\<forall>i\<in>net_tree_ips n. \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip)
goal (1 subgoal):
1. \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip)
[PROOF STEP]
proof (cases "i\<in>net_tree_ips n")
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<lbrakk>\<forall>i\<in>net_tree_ips n. \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip); i \<in> net_tree_ips n\<rbrakk> \<Longrightarrow> \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip)
2. \<lbrakk>\<forall>i\<in>net_tree_ips n. \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip); i \<notin> net_tree_ips n\<rbrakk> \<Longrightarrow> \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip)
[PROOF STEP]
assume "i\<notin>net_tree_ips n"
[PROOF STATE]
proof (state)
this:
i \<notin> net_tree_ips n
goal (2 subgoals):
1. \<lbrakk>\<forall>i\<in>net_tree_ips n. \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip); i \<in> net_tree_ips n\<rbrakk> \<Longrightarrow> \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip)
2. \<lbrakk>\<forall>i\<in>net_tree_ips n. \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip); i \<notin> net_tree_ips n\<rbrakk> \<Longrightarrow> \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip)
[PROOF STEP]
from sr
[PROOF STATE]
proof (chain)
picking this:
\<sigma> \<in> reachable (closed (pnet (\<lambda>i. paodv i \<langle>\<langle> qmsg) n)) TT
[PROOF STEP]
have "\<sigma> \<in> reachable (pnet (\<lambda>i. paodv i \<langle>\<langle> qmsg) n) TT"
[PROOF STATE]
proof (prove)
using this:
\<sigma> \<in> reachable (closed (pnet (\<lambda>i. paodv i \<langle>\<langle> qmsg) n)) TT
goal (1 subgoal):
1. \<sigma> \<in> reachable (pnet (\<lambda>i. paodv i \<langle>\<langle> qmsg) n) TT
[PROOF STEP]
..
[PROOF STATE]
proof (state)
this:
\<sigma> \<in> reachable (pnet (\<lambda>i. paodv i \<langle>\<langle> qmsg) n) TT
goal (2 subgoals):
1. \<lbrakk>\<forall>i\<in>net_tree_ips n. \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip); i \<in> net_tree_ips n\<rbrakk> \<Longrightarrow> \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip)
2. \<lbrakk>\<forall>i\<in>net_tree_ips n. \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip); i \<notin> net_tree_ips n\<rbrakk> \<Longrightarrow> \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip)
[PROOF STEP]
hence "net_ips \<sigma> = net_tree_ips n"
[PROOF STATE]
proof (prove)
using this:
\<sigma> \<in> reachable (pnet (\<lambda>i. paodv i \<langle>\<langle> qmsg) n) TT
goal (1 subgoal):
1. net_ips \<sigma> = net_tree_ips n
[PROOF STEP]
..
[PROOF STATE]
proof (state)
this:
net_ips \<sigma> = net_tree_ips n
goal (2 subgoals):
1. \<lbrakk>\<forall>i\<in>net_tree_ips n. \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip); i \<in> net_tree_ips n\<rbrakk> \<Longrightarrow> \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip)
2. \<lbrakk>\<forall>i\<in>net_tree_ips n. \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip); i \<notin> net_tree_ips n\<rbrakk> \<Longrightarrow> \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip)
[PROOF STEP]
with \<open>i\<notin>net_tree_ips n\<close>
[PROOF STATE]
proof (chain)
picking this:
i \<notin> net_tree_ips n
net_ips \<sigma> = net_tree_ips n
[PROOF STEP]
have "i\<notin>net_ips \<sigma>"
[PROOF STATE]
proof (prove)
using this:
i \<notin> net_tree_ips n
net_ips \<sigma> = net_tree_ips n
goal (1 subgoal):
1. i \<notin> net_ips \<sigma>
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
i \<notin> net_ips \<sigma>
goal (2 subgoals):
1. \<lbrakk>\<forall>i\<in>net_tree_ips n. \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip); i \<in> net_tree_ips n\<rbrakk> \<Longrightarrow> \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip)
2. \<lbrakk>\<forall>i\<in>net_tree_ips n. \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip); i \<notin> net_tree_ips n\<rbrakk> \<Longrightarrow> \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip)
[PROOF STEP]
hence "(fst (initmissing (netgmap fst \<sigma>))) i = aodv_init i"
[PROOF STATE]
proof (prove)
using this:
i \<notin> net_ips \<sigma>
goal (1 subgoal):
1. fst (initmissing (netgmap fst \<sigma>)) i = aodv_init i
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
fst (initmissing (netgmap fst \<sigma>)) i = aodv_init i
goal (2 subgoals):
1. \<lbrakk>\<forall>i\<in>net_tree_ips n. \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip); i \<in> net_tree_ips n\<rbrakk> \<Longrightarrow> \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip)
2. \<lbrakk>\<forall>i\<in>net_tree_ips n. \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip); i \<notin> net_tree_ips n\<rbrakk> \<Longrightarrow> \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip)
[PROOF STEP]
thus ?thesis
[PROOF STATE]
proof (prove)
using this:
fst (initmissing (netgmap fst \<sigma>)) i = aodv_init i
goal (1 subgoal):
1. \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip)
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
\<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip)
goal (1 subgoal):
1. \<lbrakk>\<forall>i\<in>net_tree_ips n. \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip); i \<in> net_tree_ips n\<rbrakk> \<Longrightarrow> \<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip)
[PROOF STEP]
qed metis
[PROOF STATE]
proof (state)
this:
\<forall>dip. let nhip = the (nhop (rt (fst (initmissing (netgmap fst \<sigma>)) i)) dip) in dip \<in> vD (rt (fst (initmissing (netgmap fst \<sigma>)) i)) \<inter> vD (rt (fst (initmissing (netgmap fst \<sigma>)) nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (fst (initmissing (netgmap fst \<sigma>)) i) \<sqsubset>\<^bsub>dip\<^esub> rt (fst (initmissing (netgmap fst \<sigma>)) nhip)
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
closed (pnet (\<lambda>i. paodv i \<langle>\<langle> qmsg) n) \<TTurnstile> netglobal (\<lambda>\<sigma>. \<forall>i dip. let nhip = the (nhop (rt (\<sigma> i)) dip) in dip \<in> vD (rt (\<sigma> i)) \<inter> vD (rt (\<sigma> nhip)) \<and> nhip \<noteq> dip \<longrightarrow> rt (\<sigma> i) \<sqsubset>\<^bsub>dip\<^esub> rt (\<sigma> nhip))
goal:
No subgoals!
[PROOF STEP]
qed |
program interpolate_fields
use mpi_f08
use mod_common, only: rp,ierr
use mod_bound , only: makehalo,updthalo,set_bc
use mod_io , only: load, load_scalar
implicit none
!
! input domain parameters
!
real(rp), parameter, dimension(3) :: l = [0.0016_rp,0.0016_rp,0.0016_rp]
integer , parameter, dimension(3) :: ni = [64,64,64] !global?
integer , parameter, dimension(3) :: no = [128,128,128] !global?
real(rp), parameter, dimension(3) :: dlo = l(:)/no(:)
real(rp), parameter, dimension(3) :: dli = l(:)/ni(:)
!
! boundary conditions
!
! velocity
character(len=1), parameter, dimension(0:1,3,3) :: cbcvel = &
reshape(['P','P','P','P','P','P', & ! u lower,upper bound in x,y,z
'P','P','P','P','P','P', & ! v lower,upper bound in x,y,z
'P','P','P','P','P','P'], & ! w lower,upper bound in x,y,z
shape(cbcvel))
real(rp) , parameter, dimension(0:1,3,3) :: bcvel = &
reshape([0._rp,0._rp,0._rp,0._rp,0._rp,0._rp, &
0._rp,0._rp,0._rp,0._rp,0._rp,0._rp, &
0._rp,0._rp,0._rp,0._rp,0._rp,0._rp], &
shape(bcvel))
!
! pressure
character(len=1), parameter, dimension(0:1,3) :: cbcpre = &
reshape(['P','P','P','P','P','P'],shape(cbcpre))
real(rp) , parameter, dimension(0:1,3) :: bcpre = &
reshape([0._rp,0._rp,0._rp,0._rp,0._rp,0._rp],shape(bcpre))
!
character(len=1), parameter, dimension(0:1,3) :: cbcvof = &
reshape(['P','P', & ! vof in x lower,upper bound
'P','P', & ! vof in y lowerr,upper bound
'P','P'], & ! vof in z lowerr,upper bound
shape(cbcvof))
real(rp) , parameter, dimension(0:1,3) :: bcvof = &
reshape([ 0._rp,0._rp, & ! vof in x lowerr,upper bound
0._rp,0._rp, & ! vof in y lowerr,upper bound
0._rp,0._rp], & ! vof in z lowerr,upper bound
shape(bcvof))
character(len=1), parameter, dimension(0:1,3) :: cbctmp = &
reshape(['P','P', & ! temperature in x lowerr,upper bound
'P','P', & ! temperature in y lowerr,upper bound
'P','P'], & ! temperature in z lowerr,upper bound
shape(cbctmp))
real(rp) , parameter, dimension(0:1,3) :: bctmp = &
reshape([ 1._rp,1._rp, & ! temperature in x lower,upper bound
1._rp,1._rp, & ! temperature in y lower,upper bound
1._rp,1._rp], & ! temperature in z lower,upper bound
shape(bctmp))
character(len=1), parameter, dimension(0:1,3) :: cbcsca = &
reshape(['P','P', & ! vapor mass in x lower,upper bound
'P','P', & ! vapor mass in y lower,upper bound
'P','P'], & ! vapor mass in z lower,upper bound
shape(cbcsca))
real(rp), parameter :: sb = 0._rp
real(rp), parameter, dimension(0:1,3) :: bcsca = &
sb*reshape([ 1._rp,1._rp, & ! vapor mass in x lower,upper bound
1._rp,1._rp, & ! vapor mass in y lower,upper bound
1._rp,1._rp], & ! vapor mass in z lower,upper bound
shape(bcsca))
! file names
!
character(len=*), parameter :: input_file_u = 'data/fldu.bin', &
output_file_u = 'data/fldu_o.bin',&
input_file_v = 'data/fldv.bin',&
output_file_v = 'data/fldv_o.bin',&
input_file_w = 'data/fldw.bin',&
output_file_w = 'data/fldw_o.bin',&
input_file_p = 'data/fldp.bin',&
output_file_p = 'data/fldp_o.bin',&
input_file_vof = 'data/fldvof.bin',&
output_file_vof = 'data/fldvof_o.bin',&
input_file_ug = 'data/fldug.bin',&
output_file_ug = 'data/fldug_o.bin',&
input_file_vg = 'data/fldvg.bin',&
output_file_vg = 'data/fldvg_o.bin',&
input_file_wg = 'data/fldwg.bin',&
output_file_wg = 'data/fldwg_o.bin',&
input_file_tmp = 'data/fldtmp.bin',&
output_file_tmp = 'data/fldtmp_o.bin',&
input_file_sca = 'data/fldsca.bin',&
output_file_sca = 'data/fldsca_o.bin',&
input_file_scalar = 'data/scalar.out',&
output_file_scalar = 'data/scalar_o.out'
! local problem sizes
!
integer, dimension(3) :: nni,nno,lo_i,hi_i,lo_o,hi_o
!
! MPI stuff
!
integer :: myid,nproc,dims(3),coords(3)
type(MPI_DATATYPE) :: halo(3)
type(MPI_COMM) :: comm_cart
logical, dimension(3) :: periods
integer, dimension(0:1,3) :: nb
logical, dimension(0:1,3) :: is_bound
!
! computational variables
!
real(rp), allocatable, dimension(:,:,:) :: ui,vi,wi,pi,vofi,ugi,vgi,wgi,tmpi,scai
real(rp), allocatable, dimension(:,:,:) :: uo,vo,wo,po,vofo,ugo,vgo,wgo,tmpo,scao
real(rp) :: time
integer :: istep
real(rp) :: pth,dpthdt_n,dt
!
! other variables
!
integer :: idir
time = 1._rp
istep = 0._rp
!dt = 0._rp
pth = 0._rp
dpthdt_n = 0._rp
!
! initialize MPI
!
call MPI_INIT(ierr)
call MPI_COMM_RANK(MPI_COMM_WORLD,myid,ierr)
call MPI_COMM_SIZE(MPI_COMM_WORLD,nproc,ierr)
!
! create processor grid
!
dims(:) = [0,0,1]
call MPI_DIMS_CREATE(nproc,2,dims(1:2),ierr)
!
periods(:) = .false.; where(cbcpre(0,:)//cbcpre(1,:) == 'PP') periods(:) = .true.
call MPI_CART_CREATE(MPI_COMM_WORLD,3,dims,periods,.true.,comm_cart)
call MPI_CART_COORDS(comm_cart,myid,3,coords)
!
! decompose the domain
!
call distribute_grid(ni,dims,coords,[1,1,1],nni,lo_i,hi_i)
call distribute_grid(no,dims,coords,[1,1,1],nno,lo_o,hi_o)
!
! allocate input and output arrays
!
allocate(ui(0:nni(1)+1,0:nni(2)+1,0:nni(3)+1) , &
vi(0:nni(1)+1,0:nni(2)+1,0:nni(3)+1) , &
wi(0:nni(1)+1,0:nni(2)+1,0:nni(3)+1) , &
pi(0:nni(1)+1,0:nni(2)+1,0:nni(3)+1) , &
vofi(0:nni(1)+1,0:nni(2)+1,0:nni(3)+1), &
ugi(0:nni(1)+1,0:nni(2)+1,0:nni(3)+1) , &
vgi(0:nni(1)+1,0:nni(2)+1,0:nni(3)+1) , &
wgi(0:nni(1)+1,0:nni(2)+1,0:nni(3)+1) , &
tmpi(0:nni(1)+1,0:nni(2)+1,0:nni(3)+1), &
scai(0:nni(1)+1,0:nni(2)+1,0:nni(3)+1), &
uo(0:nno(1)+1,0:nno(2)+1,0:nno(3)+1) , &
vo(0:nno(1)+1,0:nno(2)+1,0:nno(3)+1) , &
wo(0:nno(1)+1,0:nno(2)+1,0:nno(3)+1) , &
po(0:nno(1)+1,0:nno(2)+1,0:nno(3)+1) , &
vofo(0:nni(1)+1,0:nni(2)+1,0:nni(3)+1), &
ugo(0:nni(1)+1,0:nni(2)+1,0:nni(3)+1) , &
vgo(0:nni(1)+1,0:nni(2)+1,0:nni(3)+1) , &
wgo(0:nni(1)+1,0:nni(2)+1,0:nni(3)+1) , &
tmpo(0:nni(1)+1,0:nni(2)+1,0:nni(3)+1), &
scao(0:nni(1)+1,0:nni(2)+1,0:nni(3)+1))
! determine neighbors
!
call MPI_CART_SHIFT(comm_cart,0,1,nb(0,1),nb(1,1),ierr)
call MPI_CART_SHIFT(comm_cart,1,1,nb(0,2),nb(1,2),ierr)
nb(:,3) = MPI_PROC_NULL
is_bound(:,:) = .false.
where(nb(:,:) == MPI_PROC_NULL) is_bound(:,:) = .true.
!
! generate halo datatypes
!
do idir=1,3
call makehalo(idir,1,nni,halo(idir))
end do
!
! read input data
!
call load('r',input_file_u,MPI_COMM_WORLD,myid,ni,[1,1,1],lo_i,hi_i,ui,vi,wi,pi,vofi,&
ugi,vgi,wgi,tmpi,scai,time,istep,pth,dpthdt_n)
call load('r',input_file_v,MPI_COMM_WORLD,myid,ni,[1,1,1],lo_i,hi_i,ui,vi,wi,pi,vofi,&
ugi,vgi,wgi,tmpi,scai,time,istep,pth,dpthdt_n)
call load('r',input_file_w,MPI_COMM_WORLD,myid,ni,[1,1,1],lo_i,hi_i,ui,vi,wi,pi,vofi,&
ugi,vgi,wgi,tmpi,scai,time,istep,pth,dpthdt_n)
call load('r',input_file_p,MPI_COMM_WORLD,myid,ni,[1,1,1],lo_i,hi_i,ui,vi,wi,pi,vofi,&
ugi,vgi,wgi,tmpi,scai,time,istep,pth,dpthdt_n)
call load('r',input_file_vof,MPI_COMM_WORLD,myid,ni,[1,1,1],lo_i,hi_i,ui,vi,wi,pi,vofi,&
ugi,vgi,wgi,tmpi,scai,time,istep,pth,dpthdt_n)
call load('r',input_file_ug,MPI_COMM_WORLD,myid,ni,[1,1,1],lo_i,hi_i,ui,vi,wi,pi,vofi,&
ugi,vgi,wgi,tmpi,scai,time,istep,pth,dpthdt_n)
call load('r',input_file_vg,MPI_COMM_WORLD,myid,ni,[1,1,1],lo_i,hi_i,ui,vi,wi,pi,vofi,&
ugi,vgi,wgi,tmpi,scai,time,istep,pth,dpthdt_n)
call load('r',input_file_wg,MPI_COMM_WORLD,myid,ni,[1,1,1],lo_i,hi_i,ui,vi,wi,pi,vofi,&
ugi,vgi,wgi,tmpi,scai,time,istep,pth,dpthdt_n)
call load('r',input_file_tmp,MPI_COMM_WORLD,myid,ni,[1,1,1],lo_i,hi_i,ui,vi,wi,pi,vofi,&
ugi,vgi,wgi,tmpi,scai,time,istep,pth,dpthdt_n)
call load('r',input_file_sca,MPI_COMM_WORLD,myid,ni,[1,1,1],lo_i,hi_i,ui,vi,wi,pi,vofi,&
ugi,vgi,wgi,tmpi,scai,time,istep,pth,dpthdt_n)
call load_scalar('r',input_file_scalar,myid,pth,dpthdt_n,time,istep)
if(myid.eq.0) print*, 'Loaded field at time = ', time, 'step = ',istep,'.'
!if(myid.eq.0) print*, 'Loaded field at time = ', 'step = ',pth, dpthdt
!
! impose boundary conditions
!
do idir = 1,3
call updthalo(1,halo(idir),nb(:,idir),idir,ui)
call updthalo(1,halo(idir),nb(:,idir),idir,vi)
call updthalo(1,halo(idir),nb(:,idir),idir,wi)
call updthalo(1,halo(idir),nb(:,idir),idir,pi)
call updthalo(1,halo(idir),nb(:,idir),idir,vofi)
call updthalo(1,halo(idir),nb(:,idir),idir,ugi)
call updthalo(1,halo(idir),nb(:,idir),idir,vgi)
call updthalo(1,halo(idir),nb(:,idir),idir,wgi)
call updthalo(1,halo(idir),nb(:,idir),idir,tmpi)
call updthalo(1,halo(idir),nb(:,idir),idir,scai)
end do
!
if(is_bound(0,1)) then
call set_bc(cbcvel(0,1,1),0,1,1,.false.,bcvel(0,1,1),dli(1),ui)
call set_bc(cbcvel(0,1,2),0,1,1,.true. ,bcvel(0,1,2),dli(1),vi)
call set_bc(cbcvel(0,1,3),0,1,1,.true. ,bcvel(0,1,3),dli(1),wi)
call set_bc(cbcpre(0,1 ),0,1,1,.true. ,bcpre(0,1 ),dli(1),pi)
call set_bc(cbcvel(0,1,1),0,1,1,.false.,bcvel(0,1,1),dli(1),ugi) !the same way as velocity field
call set_bc(cbcvel(0,1,2),0,1,1,.true. ,bcvel(0,1,2),dli(1),vgi)
call set_bc(cbcvel(0,1,3),0,1,1,.true. ,bcvel(0,1,3),dli(1),wgi)
call set_bc(cbcvof(0,1 ),0,1,1,.true. ,bcvof(0,1 ),dli(1),vofi) !the same as pressure
call set_bc(cbctmp(0,1 ),0,1,1,.true. ,bctmp(0,1 ),dli(1),tmpi) !the same as pressure
call set_bc(cbcsca(0,1 ),0,1,1,.true. ,bcsca(0,1 ),dli(1),scai) !the same as pressure
end if
if(is_bound(1,1)) then
call set_bc(cbcvel(1,1,1),1,1,1,.false.,bcvel(1,1,1),dli(1),ui) !check true and falses
call set_bc(cbcvel(1,1,2),1,1,1,.true. ,bcvel(1,1,2),dli(1),vi)
call set_bc(cbcvel(1,1,3),1,1,1,.true. ,bcvel(1,1,3),dli(1),wi)
call set_bc(cbcpre(1,1 ),1,1,1,.true. ,bcpre(1,1 ),dli(1),pi)
call set_bc(cbcvel(1,1,1),1,1,1,.false.,bcvel(1,1,1),dli(1),ugi)
call set_bc(cbcvel(1,1,2),1,1,1,.true. ,bcvel(1,1,2),dli(1),vgi)
call set_bc(cbcvel(1,1,3),1,1,1,.true. ,bcvel(1,1,3),dli(1),wgi)
call set_bc(cbcvof(1,1 ),1,1,1,.true. ,bcvof(1,1 ),dli(1),vofi)
call set_bc(cbctmp(1,1 ),1,1,1,.true. ,bctmp(1,1 ),dli(1),tmpi)
call set_bc(cbcsca(1,1 ),1,1,1,.true. ,bcsca(1,1 ),dli(1),scai)
end if
if(is_bound(0,2)) then
call set_bc(cbcvel(0,2,1),0,2,1,.true. ,bcvel(0,2,1),dli(2),ui)
call set_bc(cbcvel(0,2,2),0,2,1,.false.,bcvel(0,2,2),dli(2),vi)
call set_bc(cbcvel(0,2,3),0,2,1,.true. ,bcvel(0,2,3),dli(2),wi)
call set_bc(cbcpre(0,2 ),0,2,1,.true. ,bcpre(0,2 ),dli(2),pi)
call set_bc(cbcvel(0,2,1),0,2,1,.true. ,bcvel(0,2,1),dli(2),ugi)
call set_bc(cbcvel(0,2,2),0,2,1,.false.,bcvel(0,2,2),dli(2),vgi)
call set_bc(cbcvel(0,2,3),0,2,1,.true. ,bcvel(0,2,3),dli(2),wgi)
call set_bc(cbcvof(0,2 ),0,2,1,.true. ,bcvof(0,2 ),dli(2),vofi)
call set_bc(cbctmp(0,2 ),0,2,1,.true. ,bctmp(0,2 ),dli(2),tmpi)
call set_bc(cbcsca(0,2 ),0,2,1,.true. ,bcsca(0,2 ),dli(2),scai)
end if
if(is_bound(1,2)) then
call set_bc(cbcvel(1,2,1),1,2,1,.true. ,bcvel(1,2,1),dli(2),ui)
call set_bc(cbcvel(1,2,2),1,2,1,.false.,bcvel(1,2,2),dli(2),vi)
call set_bc(cbcvel(1,2,3),1,2,1,.true. ,bcvel(1,2,3),dli(2),wi)
call set_bc(cbcpre(1,2 ),1,2,1,.true. ,bcpre(1,2 ),dli(2),pi)
call set_bc(cbcvel(1,2,1),1,2,1,.true. ,bcvel(1,2,1),dli(2),ugi)
call set_bc(cbcvel(1,2,2),1,2,1,.false.,bcvel(1,2,2),dli(2),vgi)
call set_bc(cbcvel(1,2,3),1,2,1,.true. ,bcvel(1,2,3),dli(2),wgi)
call set_bc(cbcvof(1,2 ),1,2,1,.true. ,bcvof(1,2 ),dli(2),vofi)
call set_bc(cbctmp(1,2 ),1,2,1,.true. ,bctmp(1,2 ),dli(2),tmpi)
call set_bc(cbcsca(1,2 ),1,2,1,.true. ,bcsca(1,2 ),dli(2),scai)
end if
if(is_bound(0,3)) then
call set_bc(cbcvel(0,3,1),0,3,1,.true. ,bcvel(0,3,1),dli(3),ui)
call set_bc(cbcvel(0,3,2),0,3,1,.true. ,bcvel(0,3,2),dli(3),vi)
call set_bc(cbcvel(0,3,3),0,3,1,.false.,bcvel(0,3,3),dli(3),wi)
call set_bc(cbcpre(0,3 ),0,3,1,.true. ,bcpre(0,3 ),dli(3),pi)
call set_bc(cbcvel(0,3,1),0,3,1,.true. ,bcvel(0,3,1),dli(3),ugi)
call set_bc(cbcvel(0,3,2),0,3,1,.true. ,bcvel(0,3,2),dli(3),vgi)
call set_bc(cbcvel(0,3,3),0,3,1,.false.,bcvel(0,3,3),dli(3),wgi)
call set_bc(cbcvof(0,3 ),0,3,1,.true. ,bcvof(0,3 ),dli(3),vofi)
call set_bc(cbctmp(0,3 ),0,3,1,.true. ,bctmp(0,3 ),dli(3),tmpi)
call set_bc(cbcsca(0,3 ),0,3,1,.true. ,bcsca(0,3 ),dli(3),scai)
end if
if(is_bound(1,3)) then
call set_bc(cbcvel(1,3,1),1,3,1,.true. ,bcvel(1,3,1),dli(3),ui)
call set_bc(cbcvel(1,3,2),1,3,1,.true. ,bcvel(1,3,2),dli(3),vi)
call set_bc(cbcvel(1,3,3),1,3,1,.false.,bcvel(1,3,3),dli(3),wi)
call set_bc(cbcpre(1,3 ),1,3,1,.true. ,bcpre(1,3 ),dli(3),pi)
call set_bc(cbcvel(1,3,1),1,3,1,.true. ,bcvel(1,3,1),dli(3),ugi)
call set_bc(cbcvel(1,3,2),1,3,1,.true. ,bcvel(1,3,2),dli(3),vgi)
call set_bc(cbcvel(1,3,3),1,3,1,.false.,bcvel(1,3,3),dli(3),wgi)
call set_bc(cbcvof(1,3 ),1,3,1,.true. ,bcvof(1,3 ),dli(3),vofi)
call set_bc(cbctmp(1,3 ),1,3,1,.true. ,bctmp(1,3 ),dli(3),tmpi)
call set_bc(cbcsca(1,3 ),1,3,1,.true. ,bcsca(1,3 ),dli(3),scai)
end if
!
! interpolate field from grid 'i' to mesh 'o'
!
call interp_fld([.true. ,.false.,.false.],lo_i,lo_o,hi_o,dli,dlo,ui,uo)
call interp_fld([.false.,.true. ,.false.],lo_i,lo_o,hi_o,dli,dlo,vi,vo)
call interp_fld([.false.,.false.,.true. ],lo_i,lo_o,hi_o,dli,dlo,wi,wo)
call interp_fld([.false.,.false.,.false.],lo_i,lo_o,hi_o,dli,dlo,pi,po)
call interp_fld([.true. ,.false.,.false.],lo_i,lo_o,hi_o,dli,dlo,ugi,ugo)
call interp_fld([.false.,.true. ,.false.],lo_i,lo_o,hi_o,dli,dlo,vgi,vgo)
call interp_fld([.false.,.false.,.true. ],lo_i,lo_o,hi_o,dli,dlo,wgi,wgo)
call interp_fld([.false.,.false.,.false.],lo_i,lo_o,hi_o,dli,dlo,vofi,vofo)
call interp_fld([.false.,.false.,.false.],lo_i,lo_o,hi_o,dli,dlo,tmpi,tmpo)
call interp_fld([.false.,.false.,.false.],lo_i,lo_o,hi_o,dli,dlo,scai,scao)
!
call load('w',output_file_u,MPI_COMM_WORLD,myid,no,[1,1,1],lo_o,hi_o,uo,vo,wo,po,&
vofo,ugo,vgo,wgo,tmpo,scao,time,istep,pth,dpthdt_n)
call load('w',output_file_v,MPI_COMM_WORLD,myid,no,[1,1,1],lo_o,hi_o,uo,vo,wo,po,vofo,&
ugo,vgo,wgo,tmpo,scao,time,istep,pth,dpthdt_n)
call load('w',output_file_w,MPI_COMM_WORLD,myid,no,[1,1,1],lo_o,hi_o,uo,vo,wo,po,vofo,&
ugo,vgo,wgo,tmpo,scao,time,istep,pth,dpthdt_n)
call load('w',output_file_p,MPI_COMM_WORLD,myid,no,[1,1,1],lo_o,hi_o,uo,vo,wo,po,vofo,&
ugo,vgo,wgo,tmpo,scao,time,istep,pth,dpthdt_n)
call load('w',output_file_vof,MPI_COMM_WORLD,myid,no,[1,1,1],lo_o,hi_o,uo,vo,wo,po,vofo,&
ugo,vgo,wgo,tmpo,scao,time,istep,pth,dpthdt_n)
call load('w',output_file_ug,MPI_COMM_WORLD,myid,no,[1,1,1],lo_o,hi_o,uo,vo,wo,po,vofo,&
ugo,vgo,wgo,tmpo,scao,time,istep,pth,dpthdt_n)
call load('w',output_file_vg,MPI_COMM_WORLD,myid,no,[1,1,1],lo_o,hi_o,uo,vo,wo,po,vofo,&
ugo,vgo,wgo,tmpo,scao,time,istep,pth,dpthdt_n)
call load('w',output_file_wg,MPI_COMM_WORLD,myid,no,[1,1,1],lo_o,hi_o,uo,vo,wo,po,vofo,&
ugo,vgo,wgo,tmpo,scao,time,istep,pth,dpthdt_n)
call load('w',output_file_tmp,MPI_COMM_WORLD,myid,no,[1,1,1],lo_o,hi_o,uo,vo,wo,po,vofo,&
ugo,vgo,wgo,tmpo,scao,time,istep,pth,dpthdt_n)
call load('w',output_file_sca,MPI_COMM_WORLD,myid,no,[1,1,1],lo_o,hi_o,uo,vo,wo,po,vofo,&
ugo,vgo,wgo,tmpo,scao,time,istep,pth,dpthdt_n)
call load_scalar('w',output_file_scalar,myid,pth,dpthdt_n,time,istep)
call MPI_FINALIZE(ierr)
contains
subroutine interp_fld(is_staggered,lo_i,lo_o,hi_o,dli,dlo,fldi,fldo)
implicit none
logical , intent(in ), dimension(3) :: is_staggered
integer , intent(in ), dimension(3) :: lo_i,lo_o,hi_o
real(rp), intent(in ), dimension(3) :: dli,dlo
real(rp), intent(in ), dimension(lo_i(1)-1:,lo_i(2)-1:,lo_i(3)-1:) :: fldi
real(rp), intent(out), dimension(lo_o(1)-1:,lo_o(2)-1:,lo_o(3)-1:) :: fldo
real(rp), dimension(3) :: ds
real(rp) :: deltax,deltay,deltaz
integer :: i,j,k,ii,ji,ki,iip,jip,kip,iim,jim,kim
real(rp) :: xo,yo,zo,xp,yp,zp,xm,ym,zm
real(rp) :: f000,f001,f010,f100,f011,f101,f110,f111,val
ds(:) = 0.5_rp
where(.not.is_staggered(:)) ds(:) = 0._rp
!
do k=lo_o(3),hi_o(3)
zo = (k-ds(3))*dlo(3)
ki = nint(zo/dli(3)+ds(3))
kip = ki + 1
kim = ki - 1
if(abs((kip-ds(3))*dli(3)-zo) <= abs((kim-ds(3))*dli(3)-zo)) then
kip = kip
kim = ki
else
kip = ki
kim = kim
endif
zm = (kim-ds(3))*dli(3)
zp = (kip-ds(3))*dli(3)
deltaz = (zo-zm)/(zp-zm)
do j=lo_o(2),hi_o(2)
yo = (j-ds(2))*dlo(2)
ji = nint(yo/dli(2)+ds(2))
jip = ji + 1
jim = ji - 1
if(abs((jip-ds(2))*dli(2)-yo) <= abs((jim-ds(2))*dli(2)-yo)) then
jip = jip
jim = ji
else
jip = ji
jim = jim
endif
ym = (jim-ds(2))*dli(2)
yp = (jip-ds(2))*dli(2)
deltay = (yo-ym)/(yp-ym)
do i=lo_o(1),hi_o(1)
xo = (i-ds(1))*dlo(1)
ii = nint(xo/dli(1)+ds(1))
iip = ii + 1
iim = ii - 1
if(abs((iip-ds(1))*dli(1)-xo) <= abs((iim-ds(1))*dli(1)-xo)) then
iip = iip
iim = ii
else
iip = ii
iim = iim
endif
xm = (iim-ds(1))*dli(1)
xp = (iip-ds(1))*dli(1)
deltax = (xo-xm)/(xp-xm)
!
f000 = fldi(iim,jim,kim)
f001 = fldi(iim,jim,kip)
f010 = fldi(iim,jip,kim)
f011 = fldi(iim,jip,kip)
f100 = fldi(iip,jim,kim)
f101 = fldi(iip,jim,kip)
f110 = fldi(iip,jip,kim)
f111 = fldi(iip,jip,kip)
val = f000*(1.-deltax)*(1.-deltay)*(1.-deltaz) + &
f001*(1.-deltax)*(1.-deltay)*( deltaz) + &
f010*(1.-deltax)*( deltay)*(1.-deltaz) + &
f011*(1.-deltax)*( deltay)*( deltaz) + &
f100*( deltax)*(1.-deltay)*(1.-deltaz) + &
f101*( deltax)*(1.-deltay)*( deltaz) + &
f110*( deltax)*( deltay)*(1.-deltaz) + &
f111*( deltax)*( deltay)*( deltaz)
fldo(i,j,k) = val
end do
end do
end do
end subroutine interp_fld
!
subroutine distribute_grid(ng,dims,coords,lo_g,n,lo,hi)
implicit none
integer, intent(in ), dimension(3) :: ng,dims,coords,lo_g
integer, intent(out), dimension(3) :: n,lo,hi
n(:) = ng(:)/dims(:)
where(coords(:)+1 <= mod(ng(:),dims(:))) n(:) = n(:) + 1
lo(:) = lo_g(:) + (coords(:) )*n(:)
hi(:) = lo_g(:)-1 + (coords(:)+1)*n(:)
where(coords(:)+1 > mod(ng(:),dims(:)))
lo(:) = lo(:) + mod(ng(:),dims(:))
hi(:) = hi(:) + mod(ng(:),dims(:))
end where
end subroutine distribute_grid
end program interpolate_fields
|
/-
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-/
import order.filter.basic
import topology.bases
import order.bounded_lattice
import formal_ml.set
import data.real.basic
import data.finset
import formal_ml.classical
open finset
/-
There are more theorems about finsets in mathlib in data.finset.basic
-/
--Noncomputability is probably unavoidable, one way or another.
noncomputable def set_fintype_finset (T:Type) (F:fintype T) (S:set T):finset T :=
@finset.filter T S (classical_set T S) F.elems
lemma set_fintype_finset_mem (T:Type) (F:fintype T) (S:set T) (a:T):
a∈ S ↔ a∈ (set_fintype_finset T F S) :=
begin
unfold set_fintype_finset,
apply iff.symm,
apply iff.trans,
apply finset.mem_filter,
split,
{
intros a_1,
cases a_1,
assumption,
},
{
intros,
split,
{
apply F.complete,
},
{
assumption,
}
}
end
lemma empty_set_to_empty_finset (T:Type) (F:fintype T):
set_fintype_finset T F ∅ = ∅ :=
begin
ext,
apply iff.symm,
apply (set_fintype_finset_mem T F ∅),
end
--TODO:replace with finset.range_zero
lemma finset_zero:range 0 = ∅ :=
begin
apply finset.range_zero,
end
--TODO:replace with finset.mem_range
lemma mem_finset_intro (n m:ℕ) :(n < m) → n ∈ range (m) :=
begin
apply (@finset.mem_range m n).mpr,
end
--TODO:replace with finset.mem_range
lemma mem_finset_elim (n m:ℕ) :n ∈ range (m) → (n < m) :=
begin
apply (@finset.mem_range m n).mp,
end
--TODO:replace with finset.range_succ
lemma finset_succ (n:ℕ):range (nat.succ n) = insert n (range n) :=
begin
apply finset.range_succ,
end
--Trivial, but novel?
lemma finset_bot_eq_empty (T:Type) (D:decidable_eq T):
@semilattice_inf_bot.bot (finset T) _ = ∅ :=
begin
refl
end
--Novel?
lemma not_new_insert (P:Type) (D:decidable_eq P) (S:finset P) (p p':P):
(p'∈ insert p S) → (p ≠ p') → (p' ∈ S) :=
begin
intros A1 A2,
rw finset.mem_insert at A1,
cases A1 with A1 A1,
{exfalso, apply A2, rw A1},
{apply A1},
end
--TODO:replace with finset.mem_insert
lemma insert_or (P:Type) (D:decidable_eq P) (S:finset P) (p p':P):
(p'∈ insert p S) → (p' = p) ∨ (p' ∈ S) :=
begin
apply finset.mem_insert.mp,
end
--TODO:replace with finset.mem_insert_of_mem
lemma insert_intro (P:Type*) (D:decidable_eq P) (S:finset P) (p p':P):
(p' ∈ S) → (p'∈ insert p S) :=
begin
apply finset.mem_insert_of_mem,
end
--TODO:replace with finset.mem_insert_self
lemma insert_intro2 (P:Type*) (D:decidable_eq P) (S:finset P) (p:P):
(p∈ insert p S) :=
begin
intros,
rw finset.insert_def,
simp,
end
--TODO:replace with finset.disjoint_iff_inter_eq_empty or disjoint_iff.
lemma finset_disjoint_def (T:Type*) (D:decidable_eq T) (A B:finset T):
disjoint A B ↔ A ∩ B ⊆ ∅ :=
begin
refl,
end
--TODO:replace with finset.disjoint_iff_inter_eq_empty.
lemma finset_disjoint_def_fwd (T:Type*) (D:decidable_eq T) (A B:finset T):
disjoint A B → A ∩ B ⊆ ∅ :=
begin
rw finset.disjoint_iff_inter_eq_empty,
intros A1,
rw A1,
simp,
end
lemma finset_disjoint_def_bck (T:Type*) (D:decidable_eq T) (A B:finset T):
A ∩ B ⊆ ∅ → disjoint A B :=
begin
rw finset.disjoint_iff_inter_eq_empty,
intro A1,
apply finset.subset.antisymm,
apply A1,
simp,
end
--TODO: replace with finset.max (but defn slightly different).
def finset_max (A:finset ℕ):ℕ :=
(@finset.fold ℕ ℕ max _ _ 0 id A)
lemma finset_max_def (A:finset ℕ):
(finset_max A) = (fold max 0 id A) :=
begin
refl,
end
lemma finset_max_limit (A:finset ℕ) (a:ℕ):
(a∈ A)→ (a ≤ (finset_max A)) :=
begin
apply finset.induction_on A,
{
simp,
},
{
intros a_1 s B1 B2 B3,
have A1:a = a_1 ∨ a∈ s,
{
apply insert_or,
assumption,
},
rw finset_max_def,
rw finset.fold_insert_idem,
rw ← finset_max_def,
simp,
cases A1,
{
subst a_1,
left,
refl,
},
{
right,
apply B2,
apply A1,
}
}
end
--This seems useful. It is probably in mathlib somewhere.
lemma finset_range_bound (A:finset ℕ):∃ n, (A⊆ finset.range n) :=
begin
apply exists.intro (nat.succ (finset_max A)),
rw finset.subset_iff,
intros x a,
apply mem_finset_intro,
have A1:x ≤ finset_max A,
{
apply finset_max_limit,
apply a,
},
apply lt_of_le_of_lt,
{
apply A1,
},
{
apply nat.lt_succ_self,
}
end
--TODO: replace with finset.range_subset.mpr
lemma finset_range_monotonic (m n:ℕ):(m ≤ n) → (finset.range m ⊆ finset.range n) :=
begin
apply finset.range_subset.mpr,
end
--TODO: replace with finset.disjoint_left
lemma finset_disjoint_intro {α:Type*} [decidable_eq α] (S T:finset α):(∀ a∈ S, a∉ T)→ (disjoint S T) :=
begin
intros A1,
rw finset.disjoint_left,
apply A1,
end
--If this doesn't exist, it should definitely be added.
lemma finset_disjoint_symm {α:Type*} [decidable_eq α] (S T:finset α):(disjoint S T)→ (disjoint T S) :=
begin
intros,
apply (finset_disjoint_def α _ T S).mpr,
rw finset.inter_comm,
apply (finset_disjoint_def α _ S T).mp,
assumption
end
--TODO: replace with finset.disjoint_left or finset.disjoint_right
lemma finset_disjoint_elim {α:Type*} [X:decidable_eq α] {S T:finset α} (a:α):(disjoint S T)→
(a∈ S)→ (a∉ T) :=
begin
rw finset.disjoint_left,
intros A1 A2,
apply A1 A2,
end
--TODO: replace with finset.disjoint_insert_right
lemma insert_disjoint_imp_disjoint {α:Type*} [decidable_eq α] (S T:finset α) (a:α):
disjoint T (insert a S) → disjoint T S :=
begin
intros A1,
rw finset.disjoint_insert_right at A1,
apply A1.right,
end
lemma sum_insert_add {α β:Type*} [decidable_eq α] [add_comm_monoid β] (f:α → β) (S:finset α) (a:α):
(a∉ S)→
(((insert a S).sum f)=(f a) + (S.sum f)) :=
begin
intros a_1,
apply fold_insert,
apply a_1,
end
--TODO: replace with finset.sdiff_subset
lemma sdiff_subset {α:Type*} [decidable_eq α] (S T:finset α):(S \ T) ⊆ S :=
begin
apply finset.sdiff_subset,
end
lemma sum_disjoint_add {α β:Type*} [decidable_eq α] [add_comm_monoid β] (f:α → β) (S T:finset α):
disjoint S T →
((S.sum f) + (T.sum f)=(S∪ T).sum f) :=
begin
apply finset.induction_on T,
{
simp,
},
{
intros a s B1 B2 B3,
simp,
have A1:disjoint S s,
{
apply insert_disjoint_imp_disjoint,
apply B3,
},
have A2:a∉ S,
{
have A3:disjoint (insert a s) S,
{
apply finset_disjoint_symm,
apply B3,
},
apply finset_disjoint_elim,
apply A3,
apply insert_intro2,
},
rw sum_insert_add,
rw sum_insert_add,
have A2:S.sum f + s.sum f = (S ∪ s).sum f,
{
apply B2,
apply A1,
},
rw ← A2,
rw ← add_assoc,
rw add_comm _ (f a),
simp,
apply add_assoc,
rw finset.mem_union,
intro a_4,
cases a_4,
{
apply A2,
apply a_4,
},
{
apply B1,
apply a_4,
},
assumption,
}
end
def finset_set {α:Type*} (S:finset α) (a:α):Prop := a∈ S
--def finset_type {α:Type*} (S:finset α):Type* := subtype (λ a:α, a ∈ S)
lemma finset_fintype_complete {α:Type*} (S:finset α):∀ a:{a:α|a∈ S}, a∈ (finset.attach S) :=
begin
intros,
unfold attach,
simp,
end
def finset_fintype {α:Type*} (S:finset α):fintype {a:α|a∈ S} := {
elems := finset.attach S,
complete := finset_fintype_complete S,
}
lemma finite_finset {α:Type*} (S:finset α):set.finite {a:α| a∈ S} :=
begin
unfold set.finite,
apply nonempty.intro (finset_fintype S),
end
def finset.Union {α:Type*} [decidable_eq α] (S:finset (finset α)):finset α :=
finset.fold (@has_union.union (finset α) _) (∅:finset α) id S
def finset.Union_insert {α:Type*} [decidable_eq α] (S:finset (finset α)) (t:finset α):
finset.Union (insert t S) = t ∪ finset.Union S :=
begin
unfold finset.Union,
simp,
end
lemma finset.mem_Union {α:Type*} [decidable_eq α] (S:finset (finset α)) {a:α}:
a ∈ S.Union ↔ (∃ (T:finset α), a∈ T ∧ T ∈ S) :=
begin
split,
{
apply finset.induction_on S,
{
unfold finset.Union,simp,
},
{
intros T S',
intros C1 C2 C3,
rw finset.Union_insert at C3,
simp at C3,
cases C3 with C3 C3,
{
apply exists.intro T,
simp [C3],
},
{
have C4 := C2 C3,
cases C4 with T C4,
apply exists.intro T,
simp [C4],
},
},
},
{
apply finset.induction_on S,
{
--intros A1,
simp,
},
{
intros T S' D1 D2 D3,
rw finset.Union_insert,
cases D3 with T' D3,
cases D3 with D3 D4,
simp at D4,
cases D4 with D4 D4,
{
subst T',
simp [D3],
},
{
simp,
right,
apply D2,
apply exists.intro T',
apply and.intro D3 D4,
},
},
},
end
--Cool, but unused.
/-
Constructs a finset {u:finset α|∃ s∈ S, t∈ T, u = s ∪ t}
-/
def finset.pairwise_union {α:Type*} [decidable_eq α] (S T:finset (finset α)):finset (finset α)
:= finset.Union (finset.image (λ s:finset α, finset.image (λ t:finset α, s ∪ t) T) S)
lemma finset.mem_pairwise_union {α:Type*} [decidable_eq α] (S T:finset (finset α)) (z:finset α):
z ∈ finset.pairwise_union S T ↔ ∃ (s t:finset α), s∈ S ∧ t ∈ T ∧ z = s ∪ t :=
begin
unfold finset.pairwise_union,
rw finset.mem_Union,
split;intros B1,
{
cases B1 with T' B1,
cases B1 with B1 B2,
simp at B2,
cases B2 with s B2,
cases B2 with B2 B3,
subst T',
simp at B1,
cases B1 with t B1,
apply exists.intro s,
apply exists.intro t,
simp [B1,B2],
},
{
cases B1 with s B1,
cases B1 with t B1,
apply exists.intro (finset.image (λ (t : finset α), s ∪ t) T),
simp,
split,
{
apply exists.intro t,
simp [B1],
},
{
apply exists.intro s,
simp [B1],
},
},
end
lemma finset.mem_union_pairwise_union_of_mem {α:Type*} [decidable_eq α] (S T:finset (finset α))
(s t:finset α):(s∈ S) → (t ∈ T) → (s ∪ t) ∈ finset.pairwise_union S T :=
begin
intros A1 A2,
rw finset.mem_pairwise_union,
apply exists.intro s,
apply exists.intro t,
simp [A1,A2],
end
lemma finset.pairwise_union.comm {α:Type*} [decidable_eq α] (A B:finset (finset α)):
finset.pairwise_union A B = finset.pairwise_union B A :=
begin
ext a,
rw finset.mem_pairwise_union,
rw finset.mem_pairwise_union,
split;
{
intros B1,cases B1 with s B1,cases B1 with t B1,
apply exists.intro t,apply exists.intro s,simp [B1,finset.union_comm],
},
end
lemma finset.pairwise_union.assoc {α:Type*} [decidable_eq α] (A B C:finset (finset α)):
finset.pairwise_union (finset.pairwise_union A B) C =
finset.pairwise_union A (finset.pairwise_union B C) :=
begin
ext x,
--rw finset.mem_pairwise_union,
--rw finset.mem_pairwise_union,
split,
{
intro B1,
rw finset.mem_pairwise_union at B1,
cases B1 with ab B1,
cases B1 with c B1,
cases B1 with B1 B2,
cases B2 with B2 B3,
subst x,
rw finset.mem_pairwise_union at B1,
cases B1 with a B1,
cases B1 with b B1,
cases B1 with B1 B3,
cases B3 with B3 B4,
subst ab,
rw finset.union_assoc,
repeat {apply finset.mem_union_pairwise_union_of_mem},
repeat {assumption},
},
{
intros B1,
rw finset.mem_pairwise_union at B1,
cases B1 with a B1,
cases B1 with bc B1,
cases B1 with B1 B2,
cases B2 with B2 B3,
subst x,
rw finset.mem_pairwise_union at B2,
cases B2 with b B2,
cases B2 with c B2,
cases B2 with B2 B3,
cases B3 with B3 B4,
subst bc,
rw ← finset.union_assoc,
repeat {apply finset.mem_union_pairwise_union_of_mem},
repeat {assumption},
},
end
instance finset.pairwise_union.is_commutative {α:Type*} [D:decidable_eq α]:
is_commutative (finset (finset α)) (@finset.pairwise_union α D) := {
comm := finset.pairwise_union.comm
}
instance finset.pairwise_union.is_associative {α:Type*} [D:decidable_eq α]:
is_associative (finset (finset α)) (@finset.pairwise_union α D) := {
assoc := finset.pairwise_union.assoc
}
lemma finset.union_diff {α:Type*} [decidable_eq α] {S T:finset α}:S⊆T →
S ∪ T \ S = T :=
begin
intros A1,
ext a,
split;intros B1,
{
simp at B1,
cases B1,
apply A1,
apply B1,
apply B1,
},
{
simp,
apply or.inr B1,
},
end
lemma finset.diff_subset_insert {α:Type*} [decidable_eq α] {T S:finset α} {a:α}:T ⊆ insert a S →
(T \ {a}) ⊆ S :=
begin
intros A1,
rw finset.subset_iff,
rw finset.subset_iff at A1,
intros x B1,
simp at B1,
have B2 := A1 B1.left,
simp at B2,
simp [B1] at B2,
apply B2,
end
lemma finset.subset_insert_of_not_mem {α:Type*} [decidable_eq α] {T S:finset α} {a:α}:a∉ T →
T ⊆ insert a S → T ⊆ S :=
begin
intros A1 A2,
rw finset.subset_iff,
intros x B1,
--simp at A2,
have B2 := A2 B1,
simp at B2,
cases B2,
{
subst x,
exfalso,
apply A1 B1,
},
{
apply B2,
},
end
--Probably already exists.
lemma finset.singleton_union_eq_insert {α:Type*} [D:decidable_eq α] {a:α} {S:finset α}:{a} ∪ S =
insert a S :=
begin
refl
end
lemma finset.Union_insert' {α β:Type*}
[D:decidable_eq β] {f:β → set α} {b:β} {S:finset β}:
(⋃ (b':β) (H:b'∈ (insert b S)), f b') =
(f b) ∪ (⋃ (b':β) (H:b'∈ S), f b') :=
begin
simp
end
lemma finset.powerset_singleton {α:Type*}[decidable_eq α] {x:α}:@finset.powerset α {x} = {∅,{x}} :=
begin
have B1:{x} = insert x (∅:finset α),
refl,
rw B1,
rw finset.powerset_insert,
refl,
end
lemma finset.subset_of_not_mem_of_subset_insert {α:Type*} [decidable_eq α] {x:α} {S T:finset α}:x∉ S →
S ⊆ insert x T → S ⊆ T :=
begin
intros A1 A2,
rw finset.subset_iff,
rw finset.subset_iff at A2,
intros a B1,
have B2 := A2 B1,
rw finset.mem_insert at B2,
cases B2,
subst a,
exfalso,
apply A1,
apply B1,
apply B2,
end
def finset.to_set_of_sets {α:Type*} (C:finset (finset α)):set (set α) :=
(λ c:finset α, (↑c:set α)) '' (↑C:set (finset α))
lemma finset.mem_to_set_of_sets {α:Type*} {C:finset (finset α)} {c:finset α}:
(↑c ∈ (C.to_set_of_sets)) ↔ c ∈ C :=
begin
unfold finset.to_set_of_sets,
simp,
end
lemma finset.mem_to_set_of_sets' {α:Type*} {C:finset (finset α)} {c:set α}:
c∈ C.to_set_of_sets ↔ ∃ c' ∈ C, c=(↑c') :=
begin
unfold finset.to_set_of_sets,
split;intro A1,
{
simp at A1,
cases A1 with c' A1,
apply exists.intro c',
apply exists.intro A1.left,
rw A1.right,
},
{
simp,
cases A1 with c' A1,
apply exists.intro c',
cases A1 with A1 A2,
simp [A1, A2],
},
end
--Note: S could be either empty or have a unique element.
lemma finset.card_identical_elements {α:Type*} [decidable_eq α] {S:finset α}:
(∀ a b:α, a ∈ S → b ∈ S → a=b ) → S.card ≤ 1 :=
begin
--intros A1,
apply finset.induction_on S,
{
simp,
},
{
intros a s B1 B2 B3,
have C1:s = ∅,
{
rw ← finset.subset_empty,
rw finset.subset_iff,
intros b C1A,
exfalso,
apply B1,
have C1B:a = b,
{
apply B3;simp [C1A],
},
rw C1B,
apply C1A,
},
rw C1,
simp,
},
end
lemma finset.eq_of_insert_of_not_mem {α:Type*} [decidable_eq α] {A B:finset α} {x:α}:(x∉ A) → (x∉ B) → (insert x A = insert x B)
→ A = B :=
begin
intros A1 A3 A2,
ext a;split;intros B1;have C1 := finset.mem_insert_of_mem B1,
{
rw A2 at C1,
apply finset.mem_of_mem_insert_of_ne C1,
intros C2,
subst a,
apply A1 B1,
},
{
rw ← A2 at C1,
apply finset.mem_of_mem_insert_of_ne C1,
intros C2,
subst a,
apply A3 B1,
},
end
lemma finset.insert_inter_eq_insert_inter_insert {α:Type*} [decidable_eq α]
{S T:finset α} {a:α}:(insert a S) ∩ (insert a T) = insert a (S ∩ T) :=
begin
ext b,
split;intros A1,
{
rw finset.mem_insert,
simp at A1,
cases A1,
subst a,
simp,
cases A1 with A1 A2,
cases A1 with A1 A1,
apply or.inl A1,
simp [A1,A2],
},
{
simp,
simp at A1,
cases A1 with A1 A1,
apply or.inl A1,
simp [A1],
},
end
lemma finset.exists_subset_card {α:Type*} [decidable_eq α] {S:finset α} {n:ℕ} (h:n ≤ S.card):∃ T:finset α, T.card = n ∧ T ⊆ S :=
begin
--revert h,
revert n,
apply finset.induction_on S,
{ intros n h, simp at h, subst h, apply exists.intro ∅,
simp, split, refl, apply finset.subset.refl },
{ intros a s h_not_mem h_ind n h,
simp [h_not_mem] at h,
cases decidable.em (n = s.card + 1) with h_eq h_ne,
apply exists.intro (insert a s),
split,
simp [h_not_mem],
rw h_eq,
apply finset.subset.refl,
have h_lt_succ:n < s.card + 1,
{ rw lt_iff_le_and_ne, simp [h, h_ne] },
have h_n_le_card := nat.le_of_lt_succ h_lt_succ,
have h_ind' := h_ind h_n_le_card,
cases h_ind' with T h_ind',
apply exists.intro T,
simp [h_ind'],
apply finset.subset.trans h_ind'.right,
apply finset.subset_insert },
end
#check finset.inter_subset_inter
|
(* Title: HOL/Algebra/Complete_Lattice.thy
Author: Clemens Ballarin, started 7 November 2003
Copyright: Clemens Ballarin
Most congruence rules by Stephan Hohe.
With additional contributions from Alasdair Armstrong and Simon Foster.
*)
theory Complete_Lattice
imports Lattice
begin
section \<open>Complete Lattices\<close>
locale weak_complete_lattice = weak_partial_order +
assumes sup_exists:
"[| A \<subseteq> carrier L |] ==> \<exists>s. least L s (Upper L A)"
and inf_exists:
"[| A \<subseteq> carrier L |] ==> \<exists>i. greatest L i (Lower L A)"
sublocale weak_complete_lattice \<subseteq> weak_lattice
proof
fix x y
assume a: "x \<in> carrier L" "y \<in> carrier L"
thus "\<exists>s. is_lub L s {x, y}"
by (rule_tac sup_exists[of "{x, y}"], auto)
from a show "\<exists>s. is_glb L s {x, y}"
by (rule_tac inf_exists[of "{x, y}"], auto)
qed
text \<open>Introduction rule: the usual definition of complete lattice\<close>
lemma (in weak_partial_order) weak_complete_latticeI:
assumes sup_exists:
"!!A. [| A \<subseteq> carrier L |] ==> \<exists>s. least L s (Upper L A)"
and inf_exists:
"!!A. [| A \<subseteq> carrier L |] ==> \<exists>i. greatest L i (Lower L A)"
shows "weak_complete_lattice L"
by standard (auto intro: sup_exists inf_exists)
lemma (in weak_complete_lattice) dual_weak_complete_lattice:
"weak_complete_lattice (inv_gorder L)"
proof -
interpret dual: weak_lattice "inv_gorder L"
by (metis dual_weak_lattice)
show ?thesis
by (unfold_locales) (simp_all add:inf_exists sup_exists)
qed
lemma (in weak_complete_lattice) supI:
"[| !!l. least L l (Upper L A) ==> P l; A \<subseteq> carrier L |]
==> P (\<Squnion>A)"
proof (unfold sup_def)
assume L: "A \<subseteq> carrier L"
and P: "!!l. least L l (Upper L A) ==> P l"
with sup_exists obtain s where "least L s (Upper L A)" by blast
with L show "P (SOME l. least L l (Upper L A))"
by (fast intro: someI2 weak_least_unique P)
qed
lemma (in weak_complete_lattice) sup_closed [simp]:
"A \<subseteq> carrier L ==> \<Squnion>A \<in> carrier L"
by (rule supI) simp_all
lemma (in weak_complete_lattice) sup_cong:
assumes "A \<subseteq> carrier L" "B \<subseteq> carrier L" "A {.=} B"
shows "\<Squnion> A .= \<Squnion> B"
proof -
have "\<And> x. is_lub L x A \<longleftrightarrow> is_lub L x B"
by (rule least_Upper_cong_r, simp_all add: assms)
moreover have "\<Squnion> B \<in> carrier L"
by (simp add: assms(2))
ultimately show ?thesis
by (simp add: sup_def)
qed
sublocale weak_complete_lattice \<subseteq> weak_bounded_lattice
apply (unfold_locales)
apply (metis Upper_empty empty_subsetI sup_exists)
apply (metis Lower_empty empty_subsetI inf_exists)
done
lemma (in weak_complete_lattice) infI:
"[| !!i. greatest L i (Lower L A) ==> P i; A \<subseteq> carrier L |]
==> P (\<Sqinter>A)"
proof (unfold inf_def)
assume L: "A \<subseteq> carrier L"
and P: "!!l. greatest L l (Lower L A) ==> P l"
with inf_exists obtain s where "greatest L s (Lower L A)" by blast
with L show "P (SOME l. greatest L l (Lower L A))"
by (fast intro: someI2 weak_greatest_unique P)
qed
lemma (in weak_complete_lattice) inf_closed [simp]:
"A \<subseteq> carrier L ==> \<Sqinter>A \<in> carrier L"
by (rule infI) simp_all
lemma (in weak_complete_lattice) inf_cong:
assumes "A \<subseteq> carrier L" "B \<subseteq> carrier L" "A {.=} B"
shows "\<Sqinter> A .= \<Sqinter> B"
proof -
have "\<And> x. is_glb L x A \<longleftrightarrow> is_glb L x B"
by (rule greatest_Lower_cong_r, simp_all add: assms)
moreover have "\<Sqinter> B \<in> carrier L"
by (simp add: assms(2))
ultimately show ?thesis
by (simp add: inf_def)
qed
theorem (in weak_partial_order) weak_complete_lattice_criterion1:
assumes top_exists: "\<exists>g. greatest L g (carrier L)"
and inf_exists:
"\<And>A. [| A \<subseteq> carrier L; A \<noteq> {} |] ==> \<exists>i. greatest L i (Lower L A)"
shows "weak_complete_lattice L"
proof (rule weak_complete_latticeI)
from top_exists obtain top where top: "greatest L top (carrier L)" ..
fix A
assume L: "A \<subseteq> carrier L"
let ?B = "Upper L A"
from L top have "top \<in> ?B" by (fast intro!: Upper_memI intro: greatest_le)
then have B_non_empty: "?B \<noteq> {}" by fast
have B_L: "?B \<subseteq> carrier L" by simp
from inf_exists [OF B_L B_non_empty]
obtain b where b_inf_B: "greatest L b (Lower L ?B)" ..
then have bcarr: "b \<in> carrier L"
by auto
have "least L b (Upper L A)"
proof (rule least_UpperI)
show "\<And>x. x \<in> A \<Longrightarrow> x \<sqsubseteq> b"
by (meson L Lower_memI Upper_memD b_inf_B greatest_le subsetD)
show "\<And>y. y \<in> Upper L A \<Longrightarrow> b \<sqsubseteq> y"
by (meson B_L b_inf_B greatest_Lower_below)
qed (use bcarr L in auto)
then show "\<exists>s. least L s (Upper L A)" ..
next
fix A
assume L: "A \<subseteq> carrier L"
show "\<exists>i. greatest L i (Lower L A)"
by (metis L Lower_empty inf_exists top_exists)
qed
text \<open>Supremum\<close>
declare (in partial_order) weak_sup_of_singleton [simp del]
lemma (in partial_order) sup_of_singleton [simp]:
"x \<in> carrier L ==> \<Squnion>{x} = x"
using weak_sup_of_singleton unfolding eq_is_equal .
lemma (in upper_semilattice) join_assoc_lemma:
assumes L: "x \<in> carrier L" "y \<in> carrier L" "z \<in> carrier L"
shows "x \<squnion> (y \<squnion> z) = \<Squnion>{x, y, z}"
using weak_join_assoc_lemma L unfolding eq_is_equal .
lemma (in upper_semilattice) join_assoc:
assumes L: "x \<in> carrier L" "y \<in> carrier L" "z \<in> carrier L"
shows "(x \<squnion> y) \<squnion> z = x \<squnion> (y \<squnion> z)"
using weak_join_assoc L unfolding eq_is_equal .
text \<open>Infimum\<close>
declare (in partial_order) weak_inf_of_singleton [simp del]
lemma (in partial_order) inf_of_singleton [simp]:
"x \<in> carrier L ==> \<Sqinter>{x} = x"
using weak_inf_of_singleton unfolding eq_is_equal .
text \<open>Condition on \<open>A\<close>: infimum exists.\<close>
lemma (in lower_semilattice) meet_assoc_lemma:
assumes L: "x \<in> carrier L" "y \<in> carrier L" "z \<in> carrier L"
shows "x \<sqinter> (y \<sqinter> z) = \<Sqinter>{x, y, z}"
using weak_meet_assoc_lemma L unfolding eq_is_equal .
lemma (in lower_semilattice) meet_assoc:
assumes L: "x \<in> carrier L" "y \<in> carrier L" "z \<in> carrier L"
shows "(x \<sqinter> y) \<sqinter> z = x \<sqinter> (y \<sqinter> z)"
using weak_meet_assoc L unfolding eq_is_equal .
subsection \<open>Infimum Laws\<close>
context weak_complete_lattice
begin
lemma inf_glb:
assumes "A \<subseteq> carrier L"
shows "greatest L (\<Sqinter>A) (Lower L A)"
proof -
obtain i where "greatest L i (Lower L A)"
by (metis assms inf_exists)
thus ?thesis
by (metis inf_def someI_ex)
qed
lemma inf_lower:
assumes "A \<subseteq> carrier L" "x \<in> A"
shows "\<Sqinter>A \<sqsubseteq> x"
by (metis assms greatest_Lower_below inf_glb)
lemma inf_greatest:
assumes "A \<subseteq> carrier L" "z \<in> carrier L"
"(\<And>x. x \<in> A \<Longrightarrow> z \<sqsubseteq> x)"
shows "z \<sqsubseteq> \<Sqinter>A"
by (metis Lower_memI assms greatest_le inf_glb)
lemma weak_inf_empty [simp]: "\<Sqinter>{} .= \<top>"
by (metis Lower_empty empty_subsetI inf_glb top_greatest weak_greatest_unique)
lemma weak_inf_carrier [simp]: "\<Sqinter>carrier L .= \<bottom>"
by (metis bottom_weak_eq inf_closed inf_lower subset_refl)
lemma weak_inf_insert [simp]:
assumes "a \<in> carrier L" "A \<subseteq> carrier L"
shows "\<Sqinter>insert a A .= a \<sqinter> \<Sqinter>A"
proof (rule weak_le_antisym)
show "\<Sqinter>insert a A \<sqsubseteq> a \<sqinter> \<Sqinter>A"
by (simp add: assms inf_lower local.inf_greatest meet_le)
show aA: "a \<sqinter> \<Sqinter>A \<in> carrier L"
using assms by simp
show "a \<sqinter> \<Sqinter>A \<sqsubseteq> \<Sqinter>insert a A"
apply (rule inf_greatest)
using assms apply (simp_all add: aA)
by (meson aA inf_closed inf_lower local.le_trans meet_left meet_right subsetCE)
show "\<Sqinter>insert a A \<in> carrier L"
using assms by (force intro: le_trans inf_closed meet_right meet_left inf_lower)
qed
subsection \<open>Supremum Laws\<close>
lemma sup_lub:
assumes "A \<subseteq> carrier L"
shows "least L (\<Squnion>A) (Upper L A)"
by (metis Upper_is_closed assms least_closed least_cong supI sup_closed sup_exists weak_least_unique)
lemma sup_upper:
assumes "A \<subseteq> carrier L" "x \<in> A"
shows "x \<sqsubseteq> \<Squnion>A"
by (metis assms least_Upper_above supI)
lemma sup_least:
assumes "A \<subseteq> carrier L" "z \<in> carrier L"
"(\<And>x. x \<in> A \<Longrightarrow> x \<sqsubseteq> z)"
shows "\<Squnion>A \<sqsubseteq> z"
by (metis Upper_memI assms least_le sup_lub)
lemma weak_sup_empty [simp]: "\<Squnion>{} .= \<bottom>"
by (metis Upper_empty bottom_least empty_subsetI sup_lub weak_least_unique)
lemma weak_sup_carrier [simp]: "\<Squnion>carrier L .= \<top>"
by (metis Lower_closed Lower_empty sup_closed sup_upper top_closed top_higher weak_le_antisym)
lemma weak_sup_insert [simp]:
assumes "a \<in> carrier L" "A \<subseteq> carrier L"
shows "\<Squnion>insert a A .= a \<squnion> \<Squnion>A"
proof (rule weak_le_antisym)
show aA: "a \<squnion> \<Squnion>A \<in> carrier L"
using assms by simp
show "\<Squnion>insert a A \<sqsubseteq> a \<squnion> \<Squnion>A"
apply (rule sup_least)
using assms apply (simp_all add: aA)
by (meson aA join_left join_right local.le_trans subsetCE sup_closed sup_upper)
show "a \<squnion> \<Squnion>A \<sqsubseteq> \<Squnion>insert a A"
by (simp add: assms join_le local.sup_least sup_upper)
show "\<Squnion>insert a A \<in> carrier L"
using assms by (force intro: le_trans inf_closed meet_right meet_left inf_lower)
qed
end
subsection \<open>Fixed points of a lattice\<close>
definition "fps L f = {x \<in> carrier L. f x .=\<^bsub>L\<^esub> x}"
abbreviation "fpl L f \<equiv> L\<lparr>carrier := fps L f\<rparr>"
lemma (in weak_partial_order)
use_fps: "x \<in> fps L f \<Longrightarrow> f x .= x"
by (simp add: fps_def)
lemma fps_carrier [simp]:
"fps L f \<subseteq> carrier L"
by (auto simp add: fps_def)
lemma (in weak_complete_lattice) fps_sup_image:
assumes "f \<in> carrier L \<rightarrow> carrier L" "A \<subseteq> fps L f"
shows "\<Squnion> (f ` A) .= \<Squnion> A"
proof -
from assms(2) have AL: "A \<subseteq> carrier L"
by (auto simp add: fps_def)
show ?thesis
proof (rule sup_cong, simp_all add: AL)
from assms(1) AL show "f ` A \<subseteq> carrier L"
by auto
then have *: "\<And>b. \<lbrakk>A \<subseteq> {x \<in> carrier L. f x .= x}; b \<in> A\<rbrakk> \<Longrightarrow> \<exists>a\<in>f ` A. b .= a"
by (meson AL assms(2) image_eqI local.sym subsetCE use_fps)
from assms(2) show "f ` A {.=} A"
by (auto simp add: fps_def intro: set_eqI2 [OF _ *])
qed
qed
lemma (in weak_complete_lattice) fps_idem:
assumes "f \<in> carrier L \<rightarrow> carrier L" "Idem f"
shows "fps L f {.=} f ` carrier L"
proof (rule set_eqI2)
show "\<And>a. a \<in> fps L f \<Longrightarrow> \<exists>b\<in>f ` carrier L. a .= b"
using assms by (force simp add: fps_def intro: local.sym)
show "\<And>b. b \<in> f ` carrier L \<Longrightarrow> \<exists>a\<in>fps L f. b .= a"
using assms by (force simp add: idempotent_def fps_def)
qed
context weak_complete_lattice
begin
lemma weak_sup_pre_fixed_point:
assumes "f \<in> carrier L \<rightarrow> carrier L" "isotone L L f" "A \<subseteq> fps L f"
shows "(\<Squnion>\<^bsub>L\<^esub> A) \<sqsubseteq>\<^bsub>L\<^esub> f (\<Squnion>\<^bsub>L\<^esub> A)"
proof (rule sup_least)
from assms(3) show AL: "A \<subseteq> carrier L"
by (auto simp add: fps_def)
thus fA: "f (\<Squnion>A) \<in> carrier L"
by (simp add: assms funcset_carrier[of f L L])
fix x
assume xA: "x \<in> A"
hence "x \<in> fps L f"
using assms subsetCE by blast
hence "f x .=\<^bsub>L\<^esub> x"
by (auto simp add: fps_def)
moreover have "f x \<sqsubseteq>\<^bsub>L\<^esub> f (\<Squnion>\<^bsub>L\<^esub>A)"
by (meson AL assms(2) subsetCE sup_closed sup_upper use_iso1 xA)
ultimately show "x \<sqsubseteq>\<^bsub>L\<^esub> f (\<Squnion>\<^bsub>L\<^esub>A)"
by (meson AL fA assms(1) funcset_carrier le_cong local.refl subsetCE xA)
qed
lemma weak_sup_post_fixed_point:
assumes "f \<in> carrier L \<rightarrow> carrier L" "isotone L L f" "A \<subseteq> fps L f"
shows "f (\<Sqinter>\<^bsub>L\<^esub> A) \<sqsubseteq>\<^bsub>L\<^esub> (\<Sqinter>\<^bsub>L\<^esub> A)"
proof (rule inf_greatest)
from assms(3) show AL: "A \<subseteq> carrier L"
by (auto simp add: fps_def)
thus fA: "f (\<Sqinter>A) \<in> carrier L"
by (simp add: assms funcset_carrier[of f L L])
fix x
assume xA: "x \<in> A"
hence "x \<in> fps L f"
using assms subsetCE by blast
hence "f x .=\<^bsub>L\<^esub> x"
by (auto simp add: fps_def)
moreover have "f (\<Sqinter>\<^bsub>L\<^esub>A) \<sqsubseteq>\<^bsub>L\<^esub> f x"
by (meson AL assms(2) inf_closed inf_lower subsetCE use_iso1 xA)
ultimately show "f (\<Sqinter>\<^bsub>L\<^esub>A) \<sqsubseteq>\<^bsub>L\<^esub> x"
by (meson AL assms(1) fA funcset_carrier le_cong_r subsetCE xA)
qed
subsubsection \<open>Least fixed points\<close>
lemma LFP_closed [intro, simp]:
"LFP f \<in> carrier L"
by (metis (lifting) LEAST_FP_def inf_closed mem_Collect_eq subsetI)
lemma LFP_lowerbound:
assumes "x \<in> carrier L" "f x \<sqsubseteq> x"
shows "LFP f \<sqsubseteq> x"
by (auto intro:inf_lower assms simp add:LEAST_FP_def)
lemma LFP_greatest:
assumes "x \<in> carrier L"
"(\<And>u. \<lbrakk> u \<in> carrier L; f u \<sqsubseteq> u \<rbrakk> \<Longrightarrow> x \<sqsubseteq> u)"
shows "x \<sqsubseteq> LFP f"
by (auto simp add:LEAST_FP_def intro:inf_greatest assms)
lemma LFP_lemma2:
assumes "Mono f" "f \<in> carrier L \<rightarrow> carrier L"
shows "f (LFP f) \<sqsubseteq> LFP f"
proof (rule LFP_greatest)
have f: "\<And>x. x \<in> carrier L \<Longrightarrow> f x \<in> carrier L"
using assms by (auto simp add: Pi_def)
with assms show "f (LFP f) \<in> carrier L"
by blast
show "\<And>u. \<lbrakk>u \<in> carrier L; f u \<sqsubseteq> u\<rbrakk> \<Longrightarrow> f (LFP f) \<sqsubseteq> u"
by (meson LFP_closed LFP_lowerbound assms(1) f local.le_trans use_iso1)
qed
lemma LFP_lemma3:
assumes "Mono f" "f \<in> carrier L \<rightarrow> carrier L"
shows "LFP f \<sqsubseteq> f (LFP f)"
using assms by (simp add: Pi_def) (metis LFP_closed LFP_lemma2 LFP_lowerbound assms(2) use_iso2)
lemma LFP_weak_unfold:
"\<lbrakk> Mono f; f \<in> carrier L \<rightarrow> carrier L \<rbrakk> \<Longrightarrow> LFP f .= f (LFP f)"
by (auto intro: LFP_lemma2 LFP_lemma3 funcset_mem)
lemma LFP_fixed_point [intro]:
assumes "Mono f" "f \<in> carrier L \<rightarrow> carrier L"
shows "LFP f \<in> fps L f"
proof -
have "f (LFP f) \<in> carrier L"
using assms(2) by blast
with assms show ?thesis
by (simp add: LFP_weak_unfold fps_def local.sym)
qed
lemma LFP_least_fixed_point:
assumes "Mono f" "f \<in> carrier L \<rightarrow> carrier L" "x \<in> fps L f"
shows "LFP f \<sqsubseteq> x"
using assms by (force intro: LFP_lowerbound simp add: fps_def)
lemma LFP_idem:
assumes "f \<in> carrier L \<rightarrow> carrier L" "Mono f" "Idem f"
shows "LFP f .= (f \<bottom>)"
proof (rule weak_le_antisym)
from assms(1) show fb: "f \<bottom> \<in> carrier L"
by (rule funcset_mem, simp)
from assms show mf: "LFP f \<in> carrier L"
by blast
show "LFP f \<sqsubseteq> f \<bottom>"
proof -
have "f (f \<bottom>) .= f \<bottom>"
by (auto simp add: fps_def fb assms(3) idempotent)
moreover have "f (f \<bottom>) \<in> carrier L"
by (rule funcset_mem[of f "carrier L"], simp_all add: assms fb)
ultimately show ?thesis
by (auto intro: LFP_lowerbound simp add: fb)
qed
show "f \<bottom> \<sqsubseteq> LFP f"
proof -
have "f \<bottom> \<sqsubseteq> f (LFP f)"
by (auto intro: use_iso1[of _ f] simp add: assms)
moreover have "... .= LFP f"
using assms(1) assms(2) fps_def by force
moreover from assms(1) have "f (LFP f) \<in> carrier L"
by (auto)
ultimately show ?thesis
using fb by blast
qed
qed
subsubsection \<open>Greatest fixed points\<close>
lemma GFP_closed [intro, simp]:
"GFP f \<in> carrier L"
by (auto intro:sup_closed simp add:GREATEST_FP_def)
lemma GFP_upperbound:
assumes "x \<in> carrier L" "x \<sqsubseteq> f x"
shows "x \<sqsubseteq> GFP f"
by (auto intro:sup_upper assms simp add:GREATEST_FP_def)
lemma GFP_least:
assumes "x \<in> carrier L"
"(\<And>u. \<lbrakk> u \<in> carrier L; u \<sqsubseteq> f u \<rbrakk> \<Longrightarrow> u \<sqsubseteq> x)"
shows "GFP f \<sqsubseteq> x"
by (auto simp add:GREATEST_FP_def intro:sup_least assms)
lemma GFP_lemma2:
assumes "Mono f" "f \<in> carrier L \<rightarrow> carrier L"
shows "GFP f \<sqsubseteq> f (GFP f)"
proof (rule GFP_least)
have f: "\<And>x. x \<in> carrier L \<Longrightarrow> f x \<in> carrier L"
using assms by (auto simp add: Pi_def)
with assms show "f (GFP f) \<in> carrier L"
by blast
show "\<And>u. \<lbrakk>u \<in> carrier L; u \<sqsubseteq> f u\<rbrakk> \<Longrightarrow> u \<sqsubseteq> f (GFP f)"
by (meson GFP_closed GFP_upperbound le_trans assms(1) f local.le_trans use_iso1)
qed
lemma GFP_lemma3:
assumes "Mono f" "f \<in> carrier L \<rightarrow> carrier L"
shows "f (GFP f) \<sqsubseteq> GFP f"
by (metis GFP_closed GFP_lemma2 GFP_upperbound assms funcset_mem use_iso2)
lemma GFP_weak_unfold:
"\<lbrakk> Mono f; f \<in> carrier L \<rightarrow> carrier L \<rbrakk> \<Longrightarrow> GFP f .= f (GFP f)"
by (auto intro: GFP_lemma2 GFP_lemma3 funcset_mem)
lemma (in weak_complete_lattice) GFP_fixed_point [intro]:
assumes "Mono f" "f \<in> carrier L \<rightarrow> carrier L"
shows "GFP f \<in> fps L f"
using assms
proof -
have "f (GFP f) \<in> carrier L"
using assms(2) by blast
with assms show ?thesis
by (simp add: GFP_weak_unfold fps_def local.sym)
qed
lemma GFP_greatest_fixed_point:
assumes "Mono f" "f \<in> carrier L \<rightarrow> carrier L" "x \<in> fps L f"
shows "x \<sqsubseteq> GFP f"
using assms
by (rule_tac GFP_upperbound, auto simp add: fps_def, meson PiE local.sym weak_refl)
lemma GFP_idem:
assumes "f \<in> carrier L \<rightarrow> carrier L" "Mono f" "Idem f"
shows "GFP f .= (f \<top>)"
proof (rule weak_le_antisym)
from assms(1) show fb: "f \<top> \<in> carrier L"
by (rule funcset_mem, simp)
from assms show mf: "GFP f \<in> carrier L"
by blast
show "f \<top> \<sqsubseteq> GFP f"
proof -
have "f (f \<top>) .= f \<top>"
by (auto simp add: fps_def fb assms(3) idempotent)
moreover have "f (f \<top>) \<in> carrier L"
by (rule funcset_mem[of f "carrier L"], simp_all add: assms fb)
ultimately show ?thesis
by (rule_tac GFP_upperbound, simp_all add: fb local.sym)
qed
show "GFP f \<sqsubseteq> f \<top>"
proof -
have "GFP f \<sqsubseteq> f (GFP f)"
by (simp add: GFP_lemma2 assms(1) assms(2))
moreover have "... \<sqsubseteq> f \<top>"
by (auto intro: use_iso1[of _ f] simp add: assms)
moreover from assms(1) have "f (GFP f) \<in> carrier L"
by (auto)
ultimately show ?thesis
using fb local.le_trans by blast
qed
qed
end
subsection \<open>Complete lattices where \<open>eq\<close> is the Equality\<close>
locale complete_lattice = partial_order +
assumes sup_exists:
"[| A \<subseteq> carrier L |] ==> \<exists>s. least L s (Upper L A)"
and inf_exists:
"[| A \<subseteq> carrier L |] ==> \<exists>i. greatest L i (Lower L A)"
sublocale complete_lattice \<subseteq> lattice
proof
fix x y
assume a: "x \<in> carrier L" "y \<in> carrier L"
thus "\<exists>s. is_lub L s {x, y}"
by (rule_tac sup_exists[of "{x, y}"], auto)
from a show "\<exists>s. is_glb L s {x, y}"
by (rule_tac inf_exists[of "{x, y}"], auto)
qed
sublocale complete_lattice \<subseteq> weak?: weak_complete_lattice
by standard (auto intro: sup_exists inf_exists)
lemma complete_lattice_lattice [simp]:
assumes "complete_lattice X"
shows "lattice X"
proof -
interpret c: complete_lattice X
by (simp add: assms)
show ?thesis
by (unfold_locales)
qed
text \<open>Introduction rule: the usual definition of complete lattice\<close>
lemma (in partial_order) complete_latticeI:
assumes sup_exists:
"!!A. [| A \<subseteq> carrier L |] ==> \<exists>s. least L s (Upper L A)"
and inf_exists:
"!!A. [| A \<subseteq> carrier L |] ==> \<exists>i. greatest L i (Lower L A)"
shows "complete_lattice L"
by standard (auto intro: sup_exists inf_exists)
theorem (in partial_order) complete_lattice_criterion1:
assumes top_exists: "\<exists>g. greatest L g (carrier L)"
and inf_exists:
"!!A. [| A \<subseteq> carrier L; A \<noteq> {} |] ==> \<exists>i. greatest L i (Lower L A)"
shows "complete_lattice L"
proof (rule complete_latticeI)
from top_exists obtain top where top: "greatest L top (carrier L)" ..
fix A
assume L: "A \<subseteq> carrier L"
let ?B = "Upper L A"
from L top have "top \<in> ?B" by (fast intro!: Upper_memI intro: greatest_le)
then have B_non_empty: "?B \<noteq> {}" by fast
have B_L: "?B \<subseteq> carrier L" by simp
from inf_exists [OF B_L B_non_empty]
obtain b where b_inf_B: "greatest L b (Lower L ?B)" ..
then have bcarr: "b \<in> carrier L"
by blast
have "least L b (Upper L A)"
proof (rule least_UpperI)
show "\<And>x. x \<in> A \<Longrightarrow> x \<sqsubseteq> b"
by (meson L Lower_memI Upper_memD b_inf_B greatest_le rev_subsetD)
show "\<And>y. y \<in> Upper L A \<Longrightarrow> b \<sqsubseteq> y"
by (auto elim: greatest_Lower_below [OF b_inf_B])
qed (use L bcarr in auto)
then show "\<exists>s. least L s (Upper L A)" ..
next
fix A
assume L: "A \<subseteq> carrier L"
show "\<exists>i. greatest L i (Lower L A)"
proof (cases "A = {}")
case True then show ?thesis
by (simp add: top_exists)
next
case False with L show ?thesis
by (rule inf_exists)
qed
qed
(* TODO: prove dual version *)
subsection \<open>Fixed points\<close>
context complete_lattice
begin
lemma LFP_unfold:
"\<lbrakk> Mono f; f \<in> carrier L \<rightarrow> carrier L \<rbrakk> \<Longrightarrow> LFP f = f (LFP f)"
using eq_is_equal weak.LFP_weak_unfold by auto
lemma LFP_const:
"t \<in> carrier L \<Longrightarrow> LFP (\<lambda> x. t) = t"
by (simp add: local.le_antisym weak.LFP_greatest weak.LFP_lowerbound)
lemma LFP_id:
"LFP id = \<bottom>"
by (simp add: local.le_antisym weak.LFP_lowerbound)
lemma GFP_unfold:
"\<lbrakk> Mono f; f \<in> carrier L \<rightarrow> carrier L \<rbrakk> \<Longrightarrow> GFP f = f (GFP f)"
using eq_is_equal weak.GFP_weak_unfold by auto
lemma GFP_const:
"t \<in> carrier L \<Longrightarrow> GFP (\<lambda> x. t) = t"
by (simp add: local.le_antisym weak.GFP_least weak.GFP_upperbound)
lemma GFP_id:
"GFP id = \<top>"
using weak.GFP_upperbound by auto
end
subsection \<open>Interval complete lattices\<close>
context weak_complete_lattice
begin
lemma at_least_at_most_Sup: "\<lbrakk> a \<in> carrier L; b \<in> carrier L; a \<sqsubseteq> b \<rbrakk> \<Longrightarrow> \<Squnion> \<lbrace>a..b\<rbrace> .= b"
by (rule weak_le_antisym [OF sup_least sup_upper]) (auto simp add: at_least_at_most_closed)
lemma at_least_at_most_Inf: "\<lbrakk> a \<in> carrier L; b \<in> carrier L; a \<sqsubseteq> b \<rbrakk> \<Longrightarrow> \<Sqinter> \<lbrace>a..b\<rbrace> .= a"
by (rule weak_le_antisym [OF inf_lower inf_greatest]) (auto simp add: at_least_at_most_closed)
end
lemma weak_complete_lattice_interval:
assumes "weak_complete_lattice L" "a \<in> carrier L" "b \<in> carrier L" "a \<sqsubseteq>\<^bsub>L\<^esub> b"
shows "weak_complete_lattice (L \<lparr> carrier := \<lbrace>a..b\<rbrace>\<^bsub>L\<^esub> \<rparr>)"
proof -
interpret L: weak_complete_lattice L
by (simp add: assms)
interpret weak_partial_order "L \<lparr> carrier := \<lbrace>a..b\<rbrace>\<^bsub>L\<^esub> \<rparr>"
proof -
have "\<lbrace>a..b\<rbrace>\<^bsub>L\<^esub> \<subseteq> carrier L"
by (auto simp add: at_least_at_most_def)
thus "weak_partial_order (L\<lparr>carrier := \<lbrace>a..b\<rbrace>\<^bsub>L\<^esub>\<rparr>)"
by (simp add: L.weak_partial_order_axioms weak_partial_order_subset)
qed
show ?thesis
proof
fix A
assume a: "A \<subseteq> carrier (L\<lparr>carrier := \<lbrace>a..b\<rbrace>\<^bsub>L\<^esub>\<rparr>)"
show "\<exists>s. is_lub (L\<lparr>carrier := \<lbrace>a..b\<rbrace>\<^bsub>L\<^esub>\<rparr>) s A"
proof (cases "A = {}")
case True
thus ?thesis
by (rule_tac x="a" in exI, auto simp add: least_def assms)
next
case False
show ?thesis
proof (intro exI least_UpperI, simp_all)
show b:"\<And> x. x \<in> A \<Longrightarrow> x \<sqsubseteq>\<^bsub>L\<^esub> \<Squnion>\<^bsub>L\<^esub>A"
using a by (auto intro: L.sup_upper, meson L.at_least_at_most_closed L.sup_upper subset_trans)
show "\<And>y. y \<in> Upper (L\<lparr>carrier := \<lbrace>a..b\<rbrace>\<^bsub>L\<^esub>\<rparr>) A \<Longrightarrow> \<Squnion>\<^bsub>L\<^esub>A \<sqsubseteq>\<^bsub>L\<^esub> y"
using a L.at_least_at_most_closed by (rule_tac L.sup_least, auto intro: funcset_mem simp add: Upper_def)
from a show *: "A \<subseteq> \<lbrace>a..b\<rbrace>\<^bsub>L\<^esub>"
by auto
show "\<Squnion>\<^bsub>L\<^esub>A \<in> \<lbrace>a..b\<rbrace>\<^bsub>L\<^esub>"
proof (rule_tac L.at_least_at_most_member)
show 1: "\<Squnion>\<^bsub>L\<^esub>A \<in> carrier L"
by (meson L.at_least_at_most_closed L.sup_closed subset_trans *)
show "a \<sqsubseteq>\<^bsub>L\<^esub> \<Squnion>\<^bsub>L\<^esub>A"
by (meson "*" False L.at_least_at_most_closed L.at_least_at_most_lower L.le_trans L.sup_upper 1 all_not_in_conv assms(2) subsetD subset_trans)
show "\<Squnion>\<^bsub>L\<^esub>A \<sqsubseteq>\<^bsub>L\<^esub> b"
proof (rule L.sup_least)
show "A \<subseteq> carrier L" "\<And>x. x \<in> A \<Longrightarrow> x \<sqsubseteq>\<^bsub>L\<^esub> b"
using * L.at_least_at_most_closed by blast+
qed (simp add: assms)
qed
qed
qed
show "\<exists>s. is_glb (L\<lparr>carrier := \<lbrace>a..b\<rbrace>\<^bsub>L\<^esub>\<rparr>) s A"
proof (cases "A = {}")
case True
thus ?thesis
by (rule_tac x="b" in exI, auto simp add: greatest_def assms)
next
case False
show ?thesis
proof (rule_tac x="\<Sqinter>\<^bsub>L\<^esub> A" in exI, rule greatest_LowerI, simp_all)
show b:"\<And>x. x \<in> A \<Longrightarrow> \<Sqinter>\<^bsub>L\<^esub>A \<sqsubseteq>\<^bsub>L\<^esub> x"
using a L.at_least_at_most_closed by (force intro!: L.inf_lower)
show "\<And>y. y \<in> Lower (L\<lparr>carrier := \<lbrace>a..b\<rbrace>\<^bsub>L\<^esub>\<rparr>) A \<Longrightarrow> y \<sqsubseteq>\<^bsub>L\<^esub> \<Sqinter>\<^bsub>L\<^esub>A"
using a L.at_least_at_most_closed by (rule_tac L.inf_greatest, auto intro: funcset_carrier' simp add: Lower_def)
from a show *: "A \<subseteq> \<lbrace>a..b\<rbrace>\<^bsub>L\<^esub>"
by auto
show "\<Sqinter>\<^bsub>L\<^esub>A \<in> \<lbrace>a..b\<rbrace>\<^bsub>L\<^esub>"
proof (rule_tac L.at_least_at_most_member)
show 1: "\<Sqinter>\<^bsub>L\<^esub>A \<in> carrier L"
by (meson "*" L.at_least_at_most_closed L.inf_closed subset_trans)
show "a \<sqsubseteq>\<^bsub>L\<^esub> \<Sqinter>\<^bsub>L\<^esub>A"
by (meson "*" L.at_least_at_most_closed L.at_least_at_most_lower L.inf_greatest assms(2) subsetD subset_trans)
show "\<Sqinter>\<^bsub>L\<^esub>A \<sqsubseteq>\<^bsub>L\<^esub> b"
by (meson * 1 False L.at_least_at_most_closed L.at_least_at_most_upper L.inf_lower L.le_trans all_not_in_conv assms(3) subsetD subset_trans)
qed
qed
qed
qed
qed
subsection \<open>Knaster-Tarski theorem and variants\<close>
text \<open>The set of fixed points of a complete lattice is itself a complete lattice\<close>
theorem Knaster_Tarski:
assumes "weak_complete_lattice L" and f: "f \<in> carrier L \<rightarrow> carrier L" and "isotone L L f"
shows "weak_complete_lattice (fpl L f)" (is "weak_complete_lattice ?L'")
proof -
interpret L: weak_complete_lattice L
by (simp add: assms)
interpret weak_partial_order ?L'
proof -
have "{x \<in> carrier L. f x .=\<^bsub>L\<^esub> x} \<subseteq> carrier L"
by (auto)
thus "weak_partial_order ?L'"
by (simp add: L.weak_partial_order_axioms weak_partial_order_subset)
qed
show ?thesis
proof (unfold_locales, simp_all)
fix A
assume A: "A \<subseteq> fps L f"
show "\<exists>s. is_lub (fpl L f) s A"
proof
from A have AL: "A \<subseteq> carrier L"
by (meson fps_carrier subset_eq)
let ?w = "\<Squnion>\<^bsub>L\<^esub> A"
have w: "f (\<Squnion>\<^bsub>L\<^esub>A) \<in> carrier L"
by (rule funcset_mem[of f "carrier L"], simp_all add: AL assms(2))
have pf_w: "(\<Squnion>\<^bsub>L\<^esub> A) \<sqsubseteq>\<^bsub>L\<^esub> f (\<Squnion>\<^bsub>L\<^esub> A)"
by (simp add: A L.weak_sup_pre_fixed_point assms(2) assms(3))
have f_top_chain: "f ` \<lbrace>?w..\<top>\<^bsub>L\<^esub>\<rbrace>\<^bsub>L\<^esub> \<subseteq> \<lbrace>?w..\<top>\<^bsub>L\<^esub>\<rbrace>\<^bsub>L\<^esub>"
proof (auto simp add: at_least_at_most_def)
fix x
assume b: "x \<in> carrier L" "\<Squnion>\<^bsub>L\<^esub>A \<sqsubseteq>\<^bsub>L\<^esub> x"
from b show fx: "f x \<in> carrier L"
using assms(2) by blast
show "\<Squnion>\<^bsub>L\<^esub>A \<sqsubseteq>\<^bsub>L\<^esub> f x"
proof -
have "?w \<sqsubseteq>\<^bsub>L\<^esub> f ?w"
proof (rule_tac L.sup_least, simp_all add: AL w)
fix y
assume c: "y \<in> A"
hence y: "y \<in> fps L f"
using A subsetCE by blast
with assms have "y .=\<^bsub>L\<^esub> f y"
proof -
from y have "y \<in> carrier L"
by (simp add: fps_def)
moreover hence "f y \<in> carrier L"
by (rule_tac funcset_mem[of f "carrier L"], simp_all add: assms)
ultimately show ?thesis using y
by (rule_tac L.sym, simp_all add: L.use_fps)
qed
moreover have "y \<sqsubseteq>\<^bsub>L\<^esub> \<Squnion>\<^bsub>L\<^esub>A"
by (simp add: AL L.sup_upper c(1))
ultimately show "y \<sqsubseteq>\<^bsub>L\<^esub> f (\<Squnion>\<^bsub>L\<^esub>A)"
by (meson fps_def AL funcset_mem L.refl L.weak_complete_lattice_axioms assms(2) assms(3) c(1) isotone_def rev_subsetD weak_complete_lattice.sup_closed weak_partial_order.le_cong)
qed
thus ?thesis
by (meson AL funcset_mem L.le_trans L.sup_closed assms(2) assms(3) b(1) b(2) use_iso2)
qed
show "f x \<sqsubseteq>\<^bsub>L\<^esub> \<top>\<^bsub>L\<^esub>"
by (simp add: fx)
qed
let ?L' = "L\<lparr> carrier := \<lbrace>?w..\<top>\<^bsub>L\<^esub>\<rbrace>\<^bsub>L\<^esub> \<rparr>"
interpret L': weak_complete_lattice ?L'
by (auto intro: weak_complete_lattice_interval simp add: L.weak_complete_lattice_axioms AL)
let ?L'' = "L\<lparr> carrier := fps L f \<rparr>"
show "is_lub ?L'' (LFP\<^bsub>?L'\<^esub> f) A"
proof (rule least_UpperI, simp_all)
fix x
assume x: "x \<in> Upper ?L'' A"
have "LFP\<^bsub>?L'\<^esub> f \<sqsubseteq>\<^bsub>?L'\<^esub> x"
proof (rule L'.LFP_lowerbound, simp_all)
show "x \<in> \<lbrace>\<Squnion>\<^bsub>L\<^esub>A..\<top>\<^bsub>L\<^esub>\<rbrace>\<^bsub>L\<^esub>"
using x by (auto simp add: Upper_def A AL L.at_least_at_most_member L.sup_least rev_subsetD)
with x show "f x \<sqsubseteq>\<^bsub>L\<^esub> x"
by (simp add: Upper_def) (meson L.at_least_at_most_closed L.use_fps L.weak_refl subsetD f_top_chain imageI)
qed
thus " LFP\<^bsub>?L'\<^esub> f \<sqsubseteq>\<^bsub>L\<^esub> x"
by (simp)
next
fix x
assume xA: "x \<in> A"
show "x \<sqsubseteq>\<^bsub>L\<^esub> LFP\<^bsub>?L'\<^esub> f"
proof -
have "LFP\<^bsub>?L'\<^esub> f \<in> carrier ?L'"
by blast
thus ?thesis
by (simp, meson AL L.at_least_at_most_closed L.at_least_at_most_lower L.le_trans L.sup_closed L.sup_upper xA subsetCE)
qed
next
show "A \<subseteq> fps L f"
by (simp add: A)
next
show "LFP\<^bsub>?L'\<^esub> f \<in> fps L f"
proof (auto simp add: fps_def)
have "LFP\<^bsub>?L'\<^esub> f \<in> carrier ?L'"
by (rule L'.LFP_closed)
thus c:"LFP\<^bsub>?L'\<^esub> f \<in> carrier L"
by (auto simp add: at_least_at_most_def)
have "LFP\<^bsub>?L'\<^esub> f .=\<^bsub>?L'\<^esub> f (LFP\<^bsub>?L'\<^esub> f)"
proof (rule "L'.LFP_weak_unfold", simp_all)
have "\<And>x. \<lbrakk>x \<in> carrier L; \<Squnion>\<^bsub>L\<^esub>A \<sqsubseteq>\<^bsub>L\<^esub> x\<rbrakk> \<Longrightarrow> \<Squnion>\<^bsub>L\<^esub>A \<sqsubseteq>\<^bsub>L\<^esub> f x"
by (meson AL funcset_mem L.le_trans L.sup_closed assms(2) assms(3) pf_w use_iso2)
with f show "f \<in> \<lbrace>\<Squnion>\<^bsub>L\<^esub>A..\<top>\<^bsub>L\<^esub>\<rbrace>\<^bsub>L\<^esub> \<rightarrow> \<lbrace>\<Squnion>\<^bsub>L\<^esub>A..\<top>\<^bsub>L\<^esub>\<rbrace>\<^bsub>L\<^esub>"
by (auto simp add: Pi_def at_least_at_most_def)
show "Mono\<^bsub>L\<lparr>carrier := \<lbrace>\<Squnion>\<^bsub>L\<^esub>A..\<top>\<^bsub>L\<^esub>\<rbrace>\<^bsub>L\<^esub>\<rparr>\<^esub> f"
using L'.weak_partial_order_axioms assms(3)
by (auto simp add: isotone_def) (meson L.at_least_at_most_closed subsetCE)
qed
thus "f (LFP\<^bsub>?L'\<^esub> f) .=\<^bsub>L\<^esub> LFP\<^bsub>?L'\<^esub> f"
by (simp add: L.equivalence_axioms funcset_carrier' c assms(2) equivalence.sym)
qed
qed
qed
show "\<exists>i. is_glb (L\<lparr>carrier := fps L f\<rparr>) i A"
proof
from A have AL: "A \<subseteq> carrier L"
by (meson fps_carrier subset_eq)
let ?w = "\<Sqinter>\<^bsub>L\<^esub> A"
have w: "f (\<Sqinter>\<^bsub>L\<^esub>A) \<in> carrier L"
by (simp add: AL funcset_carrier' assms(2))
have pf_w: "f (\<Sqinter>\<^bsub>L\<^esub> A) \<sqsubseteq>\<^bsub>L\<^esub> (\<Sqinter>\<^bsub>L\<^esub> A)"
by (simp add: A L.weak_sup_post_fixed_point assms(2) assms(3))
have f_bot_chain: "f ` \<lbrace>\<bottom>\<^bsub>L\<^esub>..?w\<rbrace>\<^bsub>L\<^esub> \<subseteq> \<lbrace>\<bottom>\<^bsub>L\<^esub>..?w\<rbrace>\<^bsub>L\<^esub>"
proof (auto simp add: at_least_at_most_def)
fix x
assume b: "x \<in> carrier L" "x \<sqsubseteq>\<^bsub>L\<^esub> \<Sqinter>\<^bsub>L\<^esub>A"
from b show fx: "f x \<in> carrier L"
using assms(2) by blast
show "f x \<sqsubseteq>\<^bsub>L\<^esub> \<Sqinter>\<^bsub>L\<^esub>A"
proof -
have "f ?w \<sqsubseteq>\<^bsub>L\<^esub> ?w"
proof (rule_tac L.inf_greatest, simp_all add: AL w)
fix y
assume c: "y \<in> A"
with assms have "y .=\<^bsub>L\<^esub> f y"
by (metis (no_types, lifting) A funcset_carrier'[OF assms(2)] L.sym fps_def mem_Collect_eq subset_eq)
moreover have "\<Sqinter>\<^bsub>L\<^esub>A \<sqsubseteq>\<^bsub>L\<^esub> y"
by (simp add: AL L.inf_lower c)
ultimately show "f (\<Sqinter>\<^bsub>L\<^esub>A) \<sqsubseteq>\<^bsub>L\<^esub> y"
by (meson AL L.inf_closed L.le_trans c pf_w rev_subsetD w)
qed
thus ?thesis
by (meson AL L.inf_closed L.le_trans assms(3) b(1) b(2) fx use_iso2 w)
qed
show "\<bottom>\<^bsub>L\<^esub> \<sqsubseteq>\<^bsub>L\<^esub> f x"
by (simp add: fx)
qed
let ?L' = "L\<lparr> carrier := \<lbrace>\<bottom>\<^bsub>L\<^esub>..?w\<rbrace>\<^bsub>L\<^esub> \<rparr>"
interpret L': weak_complete_lattice ?L'
by (auto intro!: weak_complete_lattice_interval simp add: L.weak_complete_lattice_axioms AL)
let ?L'' = "L\<lparr> carrier := fps L f \<rparr>"
show "is_glb ?L'' (GFP\<^bsub>?L'\<^esub> f) A"
proof (rule greatest_LowerI, simp_all)
fix x
assume "x \<in> Lower ?L'' A"
then have x: "\<forall>y. y \<in> A \<and> y \<in> fps L f \<longrightarrow> x \<sqsubseteq>\<^bsub>L\<^esub> y" "x \<in> fps L f"
by (auto simp add: Lower_def)
have "x \<sqsubseteq>\<^bsub>?L'\<^esub> GFP\<^bsub>?L'\<^esub> f"
unfolding Lower_def
proof (rule_tac L'.GFP_upperbound; simp)
show "x \<in> \<lbrace>\<bottom>\<^bsub>L\<^esub>..\<Sqinter>\<^bsub>L\<^esub>A\<rbrace>\<^bsub>L\<^esub>"
by (meson x A AL L.at_least_at_most_member L.bottom_lower L.inf_greatest contra_subsetD fps_carrier)
show "x \<sqsubseteq>\<^bsub>L\<^esub> f x"
using x by (simp add: funcset_carrier' L.sym assms(2) fps_def)
qed
thus "x \<sqsubseteq>\<^bsub>L\<^esub> GFP\<^bsub>?L'\<^esub> f"
by (simp)
next
fix x
assume xA: "x \<in> A"
show "GFP\<^bsub>?L'\<^esub> f \<sqsubseteq>\<^bsub>L\<^esub> x"
proof -
have "GFP\<^bsub>?L'\<^esub> f \<in> carrier ?L'"
by blast
thus ?thesis
by (simp, meson AL L.at_least_at_most_closed L.at_least_at_most_upper L.inf_closed L.inf_lower L.le_trans subsetCE xA)
qed
next
show "A \<subseteq> fps L f"
by (simp add: A)
next
show "GFP\<^bsub>?L'\<^esub> f \<in> fps L f"
proof (auto simp add: fps_def)
have "GFP\<^bsub>?L'\<^esub> f \<in> carrier ?L'"
by (rule L'.GFP_closed)
thus c:"GFP\<^bsub>?L'\<^esub> f \<in> carrier L"
by (auto simp add: at_least_at_most_def)
have "GFP\<^bsub>?L'\<^esub> f .=\<^bsub>?L'\<^esub> f (GFP\<^bsub>?L'\<^esub> f)"
proof (rule "L'.GFP_weak_unfold", simp_all)
have "\<And>x. \<lbrakk>x \<in> carrier L; x \<sqsubseteq>\<^bsub>L\<^esub> \<Sqinter>\<^bsub>L\<^esub>A\<rbrakk> \<Longrightarrow> f x \<sqsubseteq>\<^bsub>L\<^esub> \<Sqinter>\<^bsub>L\<^esub>A"
by (meson AL funcset_carrier L.inf_closed L.le_trans assms(2) assms(3) pf_w use_iso2)
with assms(2) show "f \<in> \<lbrace>\<bottom>\<^bsub>L\<^esub>..?w\<rbrace>\<^bsub>L\<^esub> \<rightarrow> \<lbrace>\<bottom>\<^bsub>L\<^esub>..?w\<rbrace>\<^bsub>L\<^esub>"
by (auto simp add: Pi_def at_least_at_most_def)
have "\<And>x y. \<lbrakk>x \<in> \<lbrace>\<bottom>\<^bsub>L\<^esub>..\<Sqinter>\<^bsub>L\<^esub>A\<rbrace>\<^bsub>L\<^esub>; y \<in> \<lbrace>\<bottom>\<^bsub>L\<^esub>..\<Sqinter>\<^bsub>L\<^esub>A\<rbrace>\<^bsub>L\<^esub>; x \<sqsubseteq>\<^bsub>L\<^esub> y\<rbrakk> \<Longrightarrow> f x \<sqsubseteq>\<^bsub>L\<^esub> f y"
by (meson L.at_least_at_most_closed subsetD use_iso1 assms(3))
with L'.weak_partial_order_axioms show "Mono\<^bsub>L\<lparr>carrier := \<lbrace>\<bottom>\<^bsub>L\<^esub>..?w\<rbrace>\<^bsub>L\<^esub>\<rparr>\<^esub> f"
by (auto simp add: isotone_def)
qed
thus "f (GFP\<^bsub>?L'\<^esub> f) .=\<^bsub>L\<^esub> GFP\<^bsub>?L'\<^esub> f"
by (simp add: L.equivalence_axioms funcset_carrier' c assms(2) equivalence.sym)
qed
qed
qed
qed
qed
theorem Knaster_Tarski_top:
assumes "weak_complete_lattice L" "isotone L L f" "f \<in> carrier L \<rightarrow> carrier L"
shows "\<top>\<^bsub>fpl L f\<^esub> .=\<^bsub>L\<^esub> GFP\<^bsub>L\<^esub> f"
proof -
interpret L: weak_complete_lattice L
by (simp add: assms)
interpret L': weak_complete_lattice "fpl L f"
by (rule Knaster_Tarski, simp_all add: assms)
show ?thesis
proof (rule L.weak_le_antisym, simp_all)
show "\<top>\<^bsub>fpl L f\<^esub> \<sqsubseteq>\<^bsub>L\<^esub> GFP\<^bsub>L\<^esub> f"
by (rule L.GFP_greatest_fixed_point, simp_all add: assms L'.top_closed[simplified])
show "GFP\<^bsub>L\<^esub> f \<sqsubseteq>\<^bsub>L\<^esub> \<top>\<^bsub>fpl L f\<^esub>"
proof -
have "GFP\<^bsub>L\<^esub> f \<in> fps L f"
by (rule L.GFP_fixed_point, simp_all add: assms)
hence "GFP\<^bsub>L\<^esub> f \<in> carrier (fpl L f)"
by simp
hence "GFP\<^bsub>L\<^esub> f \<sqsubseteq>\<^bsub>fpl L f\<^esub> \<top>\<^bsub>fpl L f\<^esub>"
by (rule L'.top_higher)
thus ?thesis
by simp
qed
show "\<top>\<^bsub>fpl L f\<^esub> \<in> carrier L"
proof -
have "carrier (fpl L f) \<subseteq> carrier L"
by (auto simp add: fps_def)
with L'.top_closed show ?thesis
by blast
qed
qed
qed
theorem Knaster_Tarski_bottom:
assumes "weak_complete_lattice L" "isotone L L f" "f \<in> carrier L \<rightarrow> carrier L"
shows "\<bottom>\<^bsub>fpl L f\<^esub> .=\<^bsub>L\<^esub> LFP\<^bsub>L\<^esub> f"
proof -
interpret L: weak_complete_lattice L
by (simp add: assms)
interpret L': weak_complete_lattice "fpl L f"
by (rule Knaster_Tarski, simp_all add: assms)
show ?thesis
proof (rule L.weak_le_antisym, simp_all)
show "LFP\<^bsub>L\<^esub> f \<sqsubseteq>\<^bsub>L\<^esub> \<bottom>\<^bsub>fpl L f\<^esub>"
by (rule L.LFP_least_fixed_point, simp_all add: assms L'.bottom_closed[simplified])
show "\<bottom>\<^bsub>fpl L f\<^esub> \<sqsubseteq>\<^bsub>L\<^esub> LFP\<^bsub>L\<^esub> f"
proof -
have "LFP\<^bsub>L\<^esub> f \<in> fps L f"
by (rule L.LFP_fixed_point, simp_all add: assms)
hence "LFP\<^bsub>L\<^esub> f \<in> carrier (fpl L f)"
by simp
hence "\<bottom>\<^bsub>fpl L f\<^esub> \<sqsubseteq>\<^bsub>fpl L f\<^esub> LFP\<^bsub>L\<^esub> f"
by (rule L'.bottom_lower)
thus ?thesis
by simp
qed
show "\<bottom>\<^bsub>fpl L f\<^esub> \<in> carrier L"
proof -
have "carrier (fpl L f) \<subseteq> carrier L"
by (auto simp add: fps_def)
with L'.bottom_closed show ?thesis
by blast
qed
qed
qed
text \<open>If a function is both idempotent and isotone then the image of the function forms a complete lattice\<close>
theorem Knaster_Tarski_idem:
assumes "complete_lattice L" "f \<in> carrier L \<rightarrow> carrier L" "isotone L L f" "idempotent L f"
shows "complete_lattice (L\<lparr>carrier := f ` carrier L\<rparr>)"
proof -
interpret L: complete_lattice L
by (simp add: assms)
have "fps L f = f ` carrier L"
using L.weak.fps_idem[OF assms(2) assms(4)]
by (simp add: L.set_eq_is_eq)
then interpret L': weak_complete_lattice "(L\<lparr>carrier := f ` carrier L\<rparr>)"
by (metis Knaster_Tarski L.weak.weak_complete_lattice_axioms assms(2) assms(3))
show ?thesis
using L'.sup_exists L'.inf_exists
by (unfold_locales, auto simp add: L.eq_is_equal)
qed
theorem Knaster_Tarski_idem_extremes:
assumes "weak_complete_lattice L" "isotone L L f" "idempotent L f" "f \<in> carrier L \<rightarrow> carrier L"
shows "\<top>\<^bsub>fpl L f\<^esub> .=\<^bsub>L\<^esub> f (\<top>\<^bsub>L\<^esub>)" "\<bottom>\<^bsub>fpl L f\<^esub> .=\<^bsub>L\<^esub> f (\<bottom>\<^bsub>L\<^esub>)"
proof -
interpret L: weak_complete_lattice "L"
by (simp_all add: assms)
interpret L': weak_complete_lattice "fpl L f"
by (rule Knaster_Tarski, simp_all add: assms)
have FA: "fps L f \<subseteq> carrier L"
by (auto simp add: fps_def)
show "\<top>\<^bsub>fpl L f\<^esub> .=\<^bsub>L\<^esub> f (\<top>\<^bsub>L\<^esub>)"
proof -
from FA have "\<top>\<^bsub>fpl L f\<^esub> \<in> carrier L"
proof -
have "\<top>\<^bsub>fpl L f\<^esub> \<in> fps L f"
using L'.top_closed by auto
thus ?thesis
using FA by blast
qed
moreover with assms have "f \<top>\<^bsub>L\<^esub> \<in> carrier L"
by (auto)
ultimately show ?thesis
using L.trans[OF Knaster_Tarski_top[of L f] L.GFP_idem[of f]]
by (simp_all add: assms)
qed
show "\<bottom>\<^bsub>fpl L f\<^esub> .=\<^bsub>L\<^esub> f (\<bottom>\<^bsub>L\<^esub>)"
proof -
from FA have "\<bottom>\<^bsub>fpl L f\<^esub> \<in> carrier L"
proof -
have "\<bottom>\<^bsub>fpl L f\<^esub> \<in> fps L f"
using L'.bottom_closed by auto
thus ?thesis
using FA by blast
qed
moreover with assms have "f \<bottom>\<^bsub>L\<^esub> \<in> carrier L"
by (auto)
ultimately show ?thesis
using L.trans[OF Knaster_Tarski_bottom[of L f] L.LFP_idem[of f]]
by (simp_all add: assms)
qed
qed
theorem Knaster_Tarski_idem_inf_eq:
assumes "weak_complete_lattice L" "isotone L L f" "idempotent L f" "f \<in> carrier L \<rightarrow> carrier L"
"A \<subseteq> fps L f"
shows "\<Sqinter>\<^bsub>fpl L f\<^esub> A .=\<^bsub>L\<^esub> f (\<Sqinter>\<^bsub>L\<^esub> A)"
proof -
interpret L: weak_complete_lattice "L"
by (simp_all add: assms)
interpret L': weak_complete_lattice "fpl L f"
by (rule Knaster_Tarski, simp_all add: assms)
have FA: "fps L f \<subseteq> carrier L"
by (auto simp add: fps_def)
have A: "A \<subseteq> carrier L"
using FA assms(5) by blast
have fA: "f (\<Sqinter>\<^bsub>L\<^esub>A) \<in> fps L f"
by (metis (no_types, lifting) A L.idempotent L.inf_closed PiE assms(3) assms(4) fps_def mem_Collect_eq)
have infA: "\<Sqinter>\<^bsub>fpl L f\<^esub>A \<in> fps L f"
by (rule L'.inf_closed[simplified], simp add: assms)
show ?thesis
proof (rule L.weak_le_antisym)
show ic: "\<Sqinter>\<^bsub>fpl L f\<^esub>A \<in> carrier L"
using FA infA by blast
show fc: "f (\<Sqinter>\<^bsub>L\<^esub>A) \<in> carrier L"
using FA fA by blast
show "f (\<Sqinter>\<^bsub>L\<^esub>A) \<sqsubseteq>\<^bsub>L\<^esub> \<Sqinter>\<^bsub>fpl L f\<^esub>A"
proof -
have "\<And>x. x \<in> A \<Longrightarrow> f (\<Sqinter>\<^bsub>L\<^esub>A) \<sqsubseteq>\<^bsub>L\<^esub> x"
by (meson A FA L.inf_closed L.inf_lower L.le_trans L.weak_sup_post_fixed_point assms(2) assms(4) assms(5) fA subsetCE)
hence "f (\<Sqinter>\<^bsub>L\<^esub>A) \<sqsubseteq>\<^bsub>fpl L f\<^esub> \<Sqinter>\<^bsub>fpl L f\<^esub>A"
by (rule_tac L'.inf_greatest, simp_all add: fA assms(3,5))
thus ?thesis
by (simp)
qed
show "\<Sqinter>\<^bsub>fpl L f\<^esub>A \<sqsubseteq>\<^bsub>L\<^esub> f (\<Sqinter>\<^bsub>L\<^esub>A)"
proof -
have *: "\<Sqinter>\<^bsub>fpl L f\<^esub>A \<in> carrier L"
using FA infA by blast
have "\<And>x. x \<in> A \<Longrightarrow> \<Sqinter>\<^bsub>fpl L f\<^esub>A \<sqsubseteq>\<^bsub>fpl L f\<^esub> x"
by (rule L'.inf_lower, simp_all add: assms)
hence "\<Sqinter>\<^bsub>fpl L f\<^esub>A \<sqsubseteq>\<^bsub>L\<^esub> (\<Sqinter>\<^bsub>L\<^esub>A)"
by (rule_tac L.inf_greatest, simp_all add: A *)
hence 1:"f(\<Sqinter>\<^bsub>fpl L f\<^esub>A) \<sqsubseteq>\<^bsub>L\<^esub> f(\<Sqinter>\<^bsub>L\<^esub>A)"
by (metis (no_types, lifting) A FA L.inf_closed assms(2) infA subsetCE use_iso1)
have 2:"\<Sqinter>\<^bsub>fpl L f\<^esub>A \<sqsubseteq>\<^bsub>L\<^esub> f (\<Sqinter>\<^bsub>fpl L f\<^esub>A)"
by (metis (no_types, lifting) FA L.sym L.use_fps L.weak_complete_lattice_axioms PiE assms(4) infA subsetCE weak_complete_lattice_def weak_partial_order.weak_refl)
show ?thesis
using FA fA infA by (auto intro!: L.le_trans[OF 2 1] ic fc, metis FA PiE assms(4) subsetCE)
qed
qed
qed
subsection \<open>Examples\<close>
subsubsection \<open>The Powerset of a Set is a Complete Lattice\<close>
theorem powerset_is_complete_lattice:
"complete_lattice \<lparr>carrier = Pow A, eq = (=), le = (\<subseteq>)\<rparr>"
(is "complete_lattice ?L")
proof (rule partial_order.complete_latticeI)
show "partial_order ?L"
by standard auto
next
fix B
assume "B \<subseteq> carrier ?L"
then have "least ?L (\<Union> B) (Upper ?L B)"
by (fastforce intro!: least_UpperI simp: Upper_def)
then show "\<exists>s. least ?L s (Upper ?L B)" ..
next
fix B
assume "B \<subseteq> carrier ?L"
then have "greatest ?L (\<Inter> B \<inter> A) (Lower ?L B)"
txt \<open>\<^term>\<open>\<Inter> B\<close> is not the infimum of \<^term>\<open>B\<close>:
\<^term>\<open>\<Inter> {} = UNIV\<close> which is in general bigger than \<^term>\<open>A\<close>! \<close>
by (fastforce intro!: greatest_LowerI simp: Lower_def)
then show "\<exists>i. greatest ?L i (Lower ?L B)" ..
qed
text \<open>Another example, that of the lattice of subgroups of a group,
can be found in Group theory (Section~\ref{sec:subgroup-lattice}).\<close>
subsection \<open>Limit preserving functions\<close>
definition weak_sup_pres :: "('a, 'c) gorder_scheme \<Rightarrow> ('b, 'd) gorder_scheme \<Rightarrow> ('a \<Rightarrow> 'b) \<Rightarrow> bool" where
"weak_sup_pres X Y f \<equiv> complete_lattice X \<and> complete_lattice Y \<and> (\<forall> A \<subseteq> carrier X. A \<noteq> {} \<longrightarrow> f (\<Squnion>\<^bsub>X\<^esub> A) = (\<Squnion>\<^bsub>Y\<^esub> (f ` A)))"
definition sup_pres :: "('a, 'c) gorder_scheme \<Rightarrow> ('b, 'd) gorder_scheme \<Rightarrow> ('a \<Rightarrow> 'b) \<Rightarrow> bool" where
"sup_pres X Y f \<equiv> complete_lattice X \<and> complete_lattice Y \<and> (\<forall> A \<subseteq> carrier X. f (\<Squnion>\<^bsub>X\<^esub> A) = (\<Squnion>\<^bsub>Y\<^esub> (f ` A)))"
definition weak_inf_pres :: "('a, 'c) gorder_scheme \<Rightarrow> ('b, 'd) gorder_scheme \<Rightarrow> ('a \<Rightarrow> 'b) \<Rightarrow> bool" where
"weak_inf_pres X Y f \<equiv> complete_lattice X \<and> complete_lattice Y \<and> (\<forall> A \<subseteq> carrier X. A \<noteq> {} \<longrightarrow> f (\<Sqinter>\<^bsub>X\<^esub> A) = (\<Sqinter>\<^bsub>Y\<^esub> (f ` A)))"
definition inf_pres :: "('a, 'c) gorder_scheme \<Rightarrow> ('b, 'd) gorder_scheme \<Rightarrow> ('a \<Rightarrow> 'b) \<Rightarrow> bool" where
"inf_pres X Y f \<equiv> complete_lattice X \<and> complete_lattice Y \<and> (\<forall> A \<subseteq> carrier X. f (\<Sqinter>\<^bsub>X\<^esub> A) = (\<Sqinter>\<^bsub>Y\<^esub> (f ` A)))"
lemma weak_sup_pres:
"sup_pres X Y f \<Longrightarrow> weak_sup_pres X Y f"
by (simp add: sup_pres_def weak_sup_pres_def)
lemma weak_inf_pres:
"inf_pres X Y f \<Longrightarrow> weak_inf_pres X Y f"
by (simp add: inf_pres_def weak_inf_pres_def)
lemma sup_pres_is_join_pres:
assumes "weak_sup_pres X Y f"
shows "join_pres X Y f"
using assms by (auto simp: join_pres_def weak_sup_pres_def join_def)
lemma inf_pres_is_meet_pres:
assumes "weak_inf_pres X Y f"
shows "meet_pres X Y f"
using assms by (auto simp: meet_pres_def weak_inf_pres_def meet_def)
end
|
function [ params ] = rnn_stack2params( stack, eI, W_t, sum_tied )
%RNN_STACK2PARAMS converts stack structure of RNN weights to single vector
% Takes a stack strcutre with stack{l}.W and stack{l}.b for each layer
% Also takes single matrix of temporal weights W_t
% The flag sum_tied will sum tied encoder and decoder weights.
% This is useful for gradient aggregation
% Verifies the stack structure conforms to their descriptions in eI
% Namely checks eI.layerSizes, eI.inputDim, and eI.temporalLayer
%% assume no weight tieing if parameter unset
if ~isfield(eI, 'tieWeights')
eI.tieWeights = 0;
end;
if ~exist('sum_tied','var')
sum_tied = false;
end;
%% default short circuits to false
if ~isfield(eI, 'shortCircuit')
eI.shortCircuit = 0;
end;
% check short circuit consistency
assert( ~xor(eI.shortCircuit, isfield(stack{end},'W_ss')));
%% check first layer dimensions
assert( size(stack{1}.W,1) == eI.layerSizes(1));
assert( size(stack{1}.W,2) == eI.inputDim);
assert( size(stack{1}.b,1) == eI.layerSizes(1));
%% stack first layer
params = [ stack{1}.W(:); stack{1}.b(:)];
%% check and stack all layers. no special treatment of output layer
for l = 2 : numel(eI.layerSizes)
assert( size(stack{l}.W,1) == eI.layerSizes(l));
assert( size(stack{l}.W,2) == eI.layerSizes(l-1));
assert( size(stack{l}.b,1) == eI.layerSizes(l));
if ~eI.tieWeights || (l <= numel(eI.layerSizes)/2 ...
|| l == numel(eI.layerSizes))
% untied layer, save the weights
if eI.tieWeights && sum_tied && l < numel(eI.layerSizes)
% sum decoder weights if its a tied encoder layer
lDec = numel(eI.layerSizes) - l + 1 ;
params = [ params; reshape(stack{l}.W + stack{lDec}.W',[],1)];
else
params = [ params; stack{l}.W(:)];
end;
end;
% always aggregate bias
params = [ params; stack{l}.b(:)];
end
%% append temporal weight matrix
if ~isempty(W_t) || eI.temporalLayer
assert(size(W_t,1) == eI.layerSizes(eI.temporalLayer));
assert(size(W_t,2) == eI.layerSizes(eI.temporalLayer));
params = [ params; W_t(:)];
end
%% append short circuit matrix
if eI.shortCircuit
params = [params; stack{end}.W_ss(:)];
end;
|
%THIS FUMCTION ILLUSTRATES HOW TO USE THE USER-DEFINED ALGORITHM
function [AH,XH] = user_alg1(Y,r,X)
%
% The example of implementing the user-defined algorithm (this is the regularized Fixed-Point algorithm based)
%
% INPUTS:
% Y - mixed signals (matrix of size [m by T])
% r - number of estimated signals
% X - true source signals
%
% OUTPUTS
% AH - estimated mixing matrix (matrix of size [m by r])
% XH - estimated source signals (matrix of size [r by T])
%
% #########################################################################
% Initialization
[m,T]=size(Y);
Y(Y <=0) = eps; % this enforces the positive value in the data
AH=rand(m,r);
XH=rand(r,T);
IterNo = 1000; % number of alternating steps
% Iterations
for k = 1:IterNo
alpha_reg = 20*exp(-k/10); % regularization parameter
XH = max(1E6*eps,pinv(AH'*AH + alpha_reg)*AH'*Y);
AH = max(1E6*eps, Y*XH'*pinv(XH*XH' + alpha_reg));
AH = AH*diag(1./(sum(AH,1) + eps));
end
|
\chapter{Communication Technologies}\label{Communications}
% Add Social Media?
\newenvironment{ucclist}[1]
{
\begin{mdframed}[nobreak=true]
\subsection{#1}
\begin{mdframed}
Address: <\href{mailto:#[email protected]}{#[email protected]}>
\end{mdframed}
\begin{mdframed}
Subscribe: \small{\url{http://lists.ucc.asn.au/mailman/listinfo/#1}}
\end{mdframed}
}{\end{mdframed}}
\section{Social Media}
Dragging itself kicking and screaming into the 21st Century, UCC has managed to set up a social media presence in something called the "cloud".
\begin{itemize}
\item UCC Facebook Group: \\ \noindent \url{https://www.facebook.com/groups/universitycomputerclub/}
\item UCC Steam Group: \url{http://steamcommunity.com/groups/UCC}
\item UCC Status Twitter Account: \url{https://twitter.com/ucc_status}
\item GitHub: \url{https://github.com/ucc}
\end{itemize}
\section{Mailing Lists}
UCC often uses email for communication. There are various lists that you can sign up for at \url{http://lists.ucc.asn.au}. The most popular lists are \texttt{ucc-announce@} for announcements and \texttt{ucc@} for general discussion.
If you are interested in technology, join the \texttt{tech@} list. If you want to be kept up to date with management of the club, join \texttt{committee@}.
\section{IRC}
Without a doubt, the easiest way to waste time in or out of UCC
is chatting on our Internet Relay Chat (IRC) server.
You'll get to chat with some of the older members of the club who
may not even be in Perth. Some of these old guard may seem a
little grumpy or intimidating at first, but give them a chance, they
are gold mines for information about the club and all things tech!
We also have members from CASSA and ComSSA, clubs at other WA unis.
You can connect with an IRC client to \texttt{irc://irc.ucc.asn.au:6667}
and join the channel \texttt{\#ucc}, or with a web browser go to
\url{http://irc.ucc.asn.au}
%\begin{figure}[H]
% \centering
% \includegraphics[width=0.99\textwidth]{figures/webirc2.png}
% \caption{What normally happens when a Fresher joins IRC}
% \label{webirc.jpg}
%\end{figure}
IRC produces some incredible quotes. You can see these at \url{http://zanchey.ucc.asn.au/qdb/}.
I didn't say they were wise or funny, just incredible.
|
The Soviet occupation of Romania led to a complete reorganisation of the Romanian Land Forces under the supervision of the Red Army . At the onset , pro @-@ German elements were purged from the Romanian armed forces . In 1944 – 45 , two divisions were formed out of Romanian volunteers — ex @-@ prisoners of war , trained and indoctrinated in the Soviet Union during the war , but also of many Communist activists . One was the Tudor Vladimirescu First Volunteer Division , under the command of Colonel Nicolae <unk> , and the other the Horia , <unk> şi <unk> Division , under the command of General Mihail Lascăr ( who later served as Minister of Defence from 1946 to 1947 ) . These two units formed the nucleus of the new Romanian Land Forces under Soviet control . The postwar reorganisation of the Land Forces included cavalry but the arm disappeared from the force with the disbandment in November 1954 of the 59th Cavalry Division at Oradea .
|
Require Export Iron.Language.Simple.Exp.
Require Import Iron.Language.Simple.Ty.
(* Substitution of expressions in expressions preserves typing.
Inductively, we must reason about performing substitutions at any
depth, hence we must prove a property about (subst' d x2 x1) instead
of the weaker (subst x2 x1) which assumes the substitution is taking
place at top level. *)
Lemma subst_exp_exp_ix
: forall ix te x1 x2 t1 t2
, get ix te = Some t2
-> TYPE te x1 t1
-> TYPE (delete ix te) x2 t2
-> TYPE (delete ix te) (substX ix x2 x1) t1.
Proof.
rip. gen ix te x2 t1.
induction_type x1.
Case "XVar".
fbreak_nat_compare; burn.
SCase "n > ix".
eapply TYVar.
destruct n; burn.
simpl. nnat. down. apply get_delete_below. omega.
Case "XLam".
apply TYLam.
rewrite delete_rewind.
apply IHx1; burn.
Qed.
Theorem subst_exp_exp
: forall te x1 x2 t1 t2
, TYPE (te :> t2) x1 t1
-> TYPE te x2 t2
-> TYPE te (substX 0 x2 x1) t1.
Proof.
rip. lets D: subst_exp_exp_ix 0 (te :> t2). burn.
Qed.
|
section \<open>Examples using ML-level VCG for Total Correctness\<close>
theory examples_vcg_total
imports "../../../hoare/HoareLogic/TotalCorrectness/Abrupt/VCG/VCG_total_ML"
begin
subsection Increment
lemma increment_manual:
assumes "vwb_lens x" and "x \<bowtie> y"
shows
"\<lbrace>&y =\<^sub>u \<guillemotleft>5::int\<guillemotright>\<rbrace>
x \<Midarrow> 0;;
(&x =\<^sub>u 0 \<and> &y =\<^sub>u 5)\<^sup>\<top>\<^sup>C;;
while &x <\<^sub>u &y
invr &x \<le>\<^sub>u &y \<and> &y =\<^sub>u 5
do x \<Midarrow> &x + 1 od
\<lbrace>&x =\<^sub>u 5\<rbrace>\<^sub>A\<^sub>B\<^sub>R"
apply (insert assms)
apply (rule seq_hoare_r_t)
apply (rule seq_hoare_r_t[of _ _ true])
apply rel_auto (* seq rule gives us a value of true in postcondition, which is trivial *)
apply (rule assume_hoare_r_t)
apply (rule skip_abr_hoare_r_t)
apply rel_auto
apply (rule while_invr_hoare_r_t)
apply (rule assigns_abr_hoare_r_t)
unfolding lens_indep_def
apply pred_auto
apply pred_auto
apply pred_auto
done
lemma increment_tactic1:
assumes "vwb_lens x" and "x \<bowtie> y"
shows
"\<lbrace>&y =\<^sub>u \<guillemotleft>5::int\<guillemotright>\<rbrace>
x \<Midarrow> 0;;
x \<Midarrow> 0;;
(&x =\<^sub>u 0 \<and> &y =\<^sub>u 5)\<^sup>\<top>\<^sup>C;;
while &x <\<^sub>u &y
invr &x \<le>\<^sub>u &y \<and> &y =\<^sub>u 5
do x \<Midarrow> &x + 1 od
\<lbrace>&x =\<^sub>u 5\<rbrace>\<^sub>A\<^sub>B\<^sub>R"
apply (tactic \<open>vcg_seq_split @{context} 1\<close>)+
apply (tactic \<open>vcg_rule_tac @{context} 1\<close>)+
defer
apply (tactic \<open>vcg_rule_tac @{context} 1\<close>)+
apply rel_auto
defer
apply rel_auto
apply (tactic \<open>vcg_rule_tac @{context} 1\<close>)+
apply (tactic \<open>vcg_insert_assms_tac @{context}\<close>)
apply (tactic \<open>vcg_unfold_tac @{context}\<close>)
apply pred_auto+
done
lemma increment_tactic2:
assumes "vwb_lens x" and "x \<bowtie> y"
shows
"\<lbrace>&y =\<^sub>u \<guillemotleft>5::int\<guillemotright>\<rbrace>
x \<Midarrow> 0;;
x \<Midarrow> 0;;
(&x =\<^sub>u 0 \<and> &y =\<^sub>u 5)\<^sup>\<top>\<^sup>C;;
while &x <\<^sub>u &y
invr &x \<le>\<^sub>u &y \<and> &y =\<^sub>u 5
do x \<Midarrow> &x + 1 od
\<lbrace>&x =\<^sub>u 5\<rbrace>\<^sub>A\<^sub>B\<^sub>R"
apply (tactic \<open>vcg_rules_all_tac @{context}\<close>)
apply (tactic \<open>vcg_pre_tac @{context}\<close>)
apply vcg_autos+
done
subsection \<open>Even count\<close>
lemma even_count_tactic1:
assumes "vwb_lens i" and "weak_lens start" and "vwb_lens j" and "weak_lens endd"
and "i \<bowtie> start" and "i \<bowtie> j" and "i \<bowtie> endd" and "start \<bowtie> j" and "start \<bowtie> endd" and "j \<bowtie> endd"
shows
"\<lbrace>&start =\<^sub>u \<guillemotleft>0::int\<guillemotright> \<and> &endd =\<^sub>u 1\<rbrace>
i \<Midarrow> &start;;
j \<Midarrow> 0;;
(&start =\<^sub>u 0 \<and> &endd =\<^sub>u 1 \<and> &j =\<^sub>u 0 \<and> &i =\<^sub>u &start)\<^sup>\<top>\<^sup>C;;
while &i <\<^sub>u &endd
invr &start =\<^sub>u 0 \<and> &endd =\<^sub>u 1 \<and> &j =\<^sub>u (((&i + 1) - &start) div 2) \<and> &i \<le>\<^sub>u &endd \<and> &i \<ge>\<^sub>u &start
do
bif &i mod 2 =\<^sub>u 0 then
j \<Midarrow> &j + 1
else
SKIP\<^sub>A\<^sub>B\<^sub>R
eif;;
i \<Midarrow> &i + 1
od
\<lbrace>&j =\<^sub>u 1\<rbrace>\<^sub>A\<^sub>B\<^sub>R"
apply (tactic \<open>vcg_rules_all_tac @{context}\<close>)
apply vcg_autos
apply (tactic \<open>vcg_rules_all_tac' @{context}\<close>)
apply (tactic \<open>vcg_rules_all_tac' @{context}\<close>)
apply (tactic \<open>vcg_pre_tac @{context}\<close>)
apply vcg_autos+
done
lemma even_count_tactic2:
assumes "vwb_lens i" and "weak_lens start" and "vwb_lens j" and "weak_lens endd"
and "i \<bowtie> start" and "i \<bowtie> j" and "i \<bowtie> endd" and "start \<bowtie> j" and "start \<bowtie> endd" and "j \<bowtie> endd"
shows
"\<lbrace>&start =\<^sub>u \<guillemotleft>0::int\<guillemotright> \<and> &endd =\<^sub>u 1\<rbrace>
i \<Midarrow> &start;;
j \<Midarrow> 0;;
(&start =\<^sub>u 0 \<and> &endd =\<^sub>u 1 \<and> &j =\<^sub>u 0 \<and> &i =\<^sub>u &start)\<^sup>\<top>\<^sup>C;;
while &i <\<^sub>u &endd
invr &start =\<^sub>u 0 \<and> &endd =\<^sub>u 1 \<and> &j =\<^sub>u (((&i + 1) - &start) div 2) \<and> &i \<le>\<^sub>u &endd \<and> &i \<ge>\<^sub>u &start
do
bif &i mod 2 =\<^sub>u 0 then
j \<Midarrow> &j + 1
else
SKIP\<^sub>A\<^sub>B\<^sub>R
eif;;
i \<Midarrow> &i + 1
od
\<lbrace>&j =\<^sub>u 1\<rbrace>\<^sub>A\<^sub>B\<^sub>R"
apply (tactic \<open>vcg_rules_tac' @{context}\<close>)
defer
apply (tactic \<open>vcg_rules_tac' @{context}\<close>)
apply vcg_autos
apply (tactic \<open>vcg_rules_tac' @{context}\<close>)
defer
apply (tactic \<open>vcg_rules_tac' @{context}\<close>)
apply (tactic \<open>vcg_pre_tac @{context}\<close>)
apply vcg_autos
done
end
|
open import Agda.Builtin.List
open import Agda.Builtin.Reflection
open import Agda.Builtin.Unit
open import Agda.Builtin.Nat
-- setup
infixl 5 _>>=_
_>>=_ = bindTC
defToTerm : Name → Definition → List (Arg Term) → Term
defToTerm _ (function cs) as = pat-lam cs as
defToTerm _ (data-cons d) as = con d as
defToTerm _ _ _ = unknown
data Tm : Set where
tm : Term → Tm
macro
unfold : Name → Term → TC ⊤
unfold x a = getDefinition x >>= λ d → unify a (defToTerm x d [])
data Vec (A : Set) : Nat → Set where
[] : Vec A zero
_∷_ : ∀ {n} → A → Vec A n → Vec A (suc n)
Point = Vec Nat 3
renderBuffer : List Point → List Nat
renderBuffer [] = []
renderBuffer ((x ∷ y ∷ z ∷ []) ∷ xs) = x ∷ y ∷ z ∷ renderBuffer xs
renderBuffer' : List Point → List Nat
renderBuffer' = unfold renderBuffer
ps : List Point
ps = (1 ∷ 2 ∷ 3 ∷ []) ∷ (4 ∷ 5 ∷ 6 ∷ []) ∷ []
open import Agda.Builtin.Equality
check : renderBuffer' ps ≡ 1 ∷ 2 ∷ 3 ∷ 4 ∷ 5 ∷ 6 ∷ []
check = refl
|
section {* A simple library in the UTP theory of designs *}
theory utp_library
imports "UTP-Theories.utp_theories"
begin
subsection {* Preliminaries -- set up some syntax *}
notation true_upred ("abort")
definition establishes_inv :: "'a hrel_des \<Rightarrow> 'a upred \<Rightarrow> bool" (infixl "establishes" 85) where
[upred_defs]: "establishes_inv P iv \<equiv> true \<turnstile>\<^sub>r \<lceil>iv\<rceil>\<^sub>> \<sqsubseteq> P"
definition maintains_inv :: "'a hrel_des \<Rightarrow> 'a upred \<Rightarrow> bool" (infixl "maintains" 85) where
[upred_defs]: "maintains_inv P iv \<equiv> (pre\<^sub>D(P) \<and> \<lceil>iv\<rceil>\<^sub><) \<turnstile>\<^sub>r \<lceil>iv\<rceil>\<^sub>> \<sqsubseteq> P"
type_synonym 'a prog = "'a hrel_des"
subsection {* Library state space *}
type_synonym book = string
alphabet library =
books :: "book set"
loans :: "book set"
subsection {* Library operations *}
definition InitLibrary :: "book set \<Rightarrow> library prog" where
[upred_defs]: "InitLibrary(bs) = true \<turnstile>\<^sub>n books, loans := \<guillemotleft>bs\<guillemotright>, {}\<^sub>u"
definition InitLibraryAlt :: "book set \<Rightarrow> library prog" where
[upred_defs]: "InitLibraryAlt(bs) = true \<turnstile>\<^sub>n ($books\<acute> =\<^sub>u \<guillemotleft>bs\<guillemotright> \<and> $loans\<acute> =\<^sub>u {}\<^sub>u)"
lemma InitLibrary_alt_same: "InitLibrary(bs) = InitLibraryAlt(bs)"
by (rel_auto)
definition LibraryInvariant :: "library upred" where
[upred_defs]: "LibraryInvariant = (&loans \<subseteq>\<^sub>u &books)"
definition BorrowBook :: "book \<Rightarrow> library prog" where
[upred_defs]: "BorrowBook(b) = (\<guillemotleft>b\<guillemotright> \<notin>\<^sub>u &loans \<and> \<guillemotleft>b\<guillemotright> \<in>\<^sub>u &books) \<turnstile>\<^sub>n loans := (&loans \<union>\<^sub>u {\<guillemotleft>b\<guillemotright>}\<^sub>u)"
definition ReturnBook :: "book \<Rightarrow> library prog" where
[upred_defs]: "ReturnBook(b) = ((\<guillemotleft>b\<guillemotright> \<in>\<^sub>u &loans) \<turnstile>\<^sub>n (loans := (&loans - {\<guillemotleft>b\<guillemotright>}\<^sub>u)))"
subsection {* Library proofs *}
lemma InitLibrary_Idempotent: "InitLibrary(bs) ;; InitLibrary(bs) = InitLibrary(bs)"
by (rel_blast)
lemma BorrowBook_Twice: "(BorrowBook(b) ;; BorrowBook(b)) = abort"
by (rel_auto)
lemma ReturnBook_Twice: "(ReturnBook(b) ;; ReturnBook(b)) = abort"
by (rel_auto)
abbreviation "Books \<equiv> {''War and Peace''
,''Pride and Prejudice''
,''Les Miserables''}"
lemma NotInLibrary:
"(InitLibrary(Books) ;; BorrowBook(''Pride and Prejudice and Zombies'')) = abort"
by (rel_auto)
theorem BorrowAndReturn:
assumes "b \<in> bs"
shows "(InitLibrary(bs) ;; BorrowBook(b) ;; ReturnBook(b)) = InitLibrary(bs)"
using assms by (rel_blast)
lemma "InitLibrary(bs) establishes LibraryInvariant"
by (rel_auto)
lemma "BorrowBook(b) maintains LibraryInvariant"
by (rel_auto)
lemma "ReturnBook(b) maintains LibraryInvariant"
by (rel_auto)
end |
------------------------------------------------------------------------
-- Semantics
------------------------------------------------------------------------
module RecursiveTypes.Semantics where
open import Codata.Musical.Notation
open import RecursiveTypes.Syntax
open import RecursiveTypes.Substitution
-- The semantics of a recursive type, i.e. its possibly infinite
-- unfolding.
⟦_⟧ : ∀ {n} → Ty n → Tree n
⟦ ⊥ ⟧ = ⊥
⟦ ⊤ ⟧ = ⊤
⟦ var x ⟧ = var x
⟦ σ ⟶ τ ⟧ = ♯ ⟦ σ ⟧ ⟶ ♯ ⟦ τ ⟧
⟦ μ σ ⟶ τ ⟧ = ♯ ⟦ σ [0≔ χ ] ⟧ ⟶ ♯ ⟦ τ [0≔ χ ] ⟧
where χ = μ σ ⟶ τ
|
(* The standard library's implementation of the integers (BinInt) uses nasty binary positive
crap with various horrible horrible bit fiddling operations on it (especially Pminus).
The following is a much simpler implementation whose correctness can be shown much
more easily. In particular, it lets us use initiality of the natural numbers to prove initiality
of these integers. *)
Require
MathClasses.theory.naturals.
Require Import
Coq.setoid_ring.Ring MathClasses.interfaces.abstract_algebra MathClasses.theory.categories
MathClasses.interfaces.naturals MathClasses.interfaces.integers MathClasses.theory.jections.
Require Export
MathClasses.implementations.semiring_pairs.
Section contents.
Context `{Naturals N}.
Add Ring N : (rings.stdlib_semiring_theory N).
Notation Z := (SRpair N).
(* We show that Z is initial, and therefore a model of the integers. *)
Global Instance SRpair_to_ring: IntegersToRing Z :=
λ _ _ _ _ _ _ z, naturals_to_semiring N _ (pos z) + - naturals_to_semiring N _ (neg z).
(* Hint Rewrite preserves_0 preserves_1 preserves_mult preserves_plus: preservation.
doesn't work for some reason, so we use: *)
Ltac preservation :=
repeat (rewrite rings.preserves_plus || rewrite rings.preserves_mult || rewrite rings.preserves_0 || rewrite rings.preserves_1).
Section for_another_ring.
Context `{Ring R}.
Add Ring R : (rings.stdlib_ring_theory R).
Notation n_to_sr := (naturals_to_semiring N R).
Notation z_to_r := (integers_to_ring Z R).
Instance: Proper ((=) ==> (=)) z_to_r.
Proof.
intros [xp xn] [yp yn].
change (xp + yn = yp + xn → n_to_sr xp - n_to_sr xn = n_to_sr yp - n_to_sr yn). intros E.
apply rings.equal_by_zero_sum.
transitivity (n_to_sr xp + n_to_sr yn - (n_to_sr xn + n_to_sr yp)); [ring|].
rewrite <-2!rings.preserves_plus, E, (commutativity xn yp). ring.
Qed.
Ltac derive_preservation := unfold integers_to_ring, SRpair_to_ring; simpl; preservation; ring.
Let preserves_plus x y: z_to_r (x + y) = z_to_r x + z_to_r y.
Proof. derive_preservation. Qed.
Let preserves_mult x y: z_to_r (x * y) = z_to_r x * z_to_r y.
Proof. derive_preservation. Qed.
Let preserves_1: z_to_r 1 = 1.
Proof. derive_preservation. Qed.
Let preserves_0: z_to_r 0 = 0.
Proof. derive_preservation. Qed.
Global Instance: SemiRing_Morphism z_to_r.
Proof.
repeat (split; try apply _).
exact preserves_plus.
exact preserves_0.
exact preserves_mult.
exact preserves_1.
Qed.
Section for_another_morphism.
Context (f : Z → R) `{!SemiRing_Morphism f}.
Definition g : N → R := f ∘ cast N (SRpair N).
Instance: SemiRing_Morphism g.
Proof. unfold g. repeat (split; try apply _). Qed.
Lemma same_morphism: z_to_r = f.
Proof.
intros [p n] z' E. rewrite <- E. clear E z'.
rewrite SRpair_splits.
preservation. rewrite 2!rings.preserves_negate.
now rewrite 2!(naturals.to_semiring_twice _ _ _).
Qed.
End for_another_morphism.
End for_another_ring.
Instance: Initial (rings.object Z).
Proof. apply integer_initial. intros. now apply same_morphism. Qed.
Global Instance: Integers Z := {}.
Context `{!NatDistance N}.
Global Program Instance SRpair_abs: IntAbs Z N := λ x,
match nat_distance_sig (pos x) (neg x) with
| inl (n↾E) => inr n
| inr (n↾E) => inl n
end.
Next Obligation.
rewrite <-(naturals.to_semiring_unique (cast N (SRpair N))).
do 2 red. simpl. now rewrite rings.plus_0_r, commutativity.
Qed.
Next Obligation.
rewrite <-(naturals.to_semiring_unique (cast N (SRpair N))).
do 2 red. simpl. symmetry. now rewrite rings.plus_0_r, commutativity.
Qed.
Notation n_to_z := (naturals_to_semiring N Z).
(* Without this opaque, typeclasses find a proof of Injective zero,
from [id_injective] *)
Typeclasses Opaque zero.
Let zero_product_aux a b :
n_to_z a * n_to_z b = 0 → n_to_z a = 0 ∨ n_to_z b = 0.
Proof.
rewrite <-rings.preserves_mult.
rewrite <-(naturals.to_semiring_unique (SRpair_inject)).
intros E. setoid_inject.
assert (HN : (a = 0) ∨ (b = 0)) by now apply zero_product.
destruct HN as [HN|HN]; [left|right]; rewrite HN; apply preserves_mon_unit.
Qed.
Global Instance: ZeroProduct Z.
Proof.
intros x y E.
destruct (SRpair_abs x) as [[a A]|[a A]], (SRpair_abs y) as [[b B]|[b B]].
rewrite <-A, <-B in E |- *. now apply zero_product_aux.
destruct (zero_product_aux a b) as [C|C].
rewrite A, B. now apply rings.negate_zero_prod_r.
left. now rewrite <-A.
right. apply rings.flip_negate_0. now rewrite <-B.
destruct (zero_product_aux a b) as [C|C].
rewrite A, B. now apply rings.negate_zero_prod_l.
left. apply rings.flip_negate_0. now rewrite <-A.
right. now rewrite <-B.
destruct (zero_product_aux a b) as [C|C].
now rewrite A, B, rings.negate_mult_negate.
left. apply rings.flip_negate_0. now rewrite <-A.
right. apply rings.flip_negate_0. now rewrite <-B.
Qed.
End contents.
|
#ifndef VM_CALL_STACK_H
#define VM_CALL_STACK_H
#include "function/WasmFunction.h"
#include "utilities/SimpleVector.h"
#include "utilities/ListStack.h"
#include "vm/alloc/StackResource.h"
#include <gsl/span>
#include <sstream>
namespace wasm {
namespace ex {
template <class Container, class Index>
decltype(auto) at(Container&& c, const Index& index)
{
using std::size;
if(index < size(std::forward<Container>(c)))
return std::forward<Container>(c)[index];
throw std::out_of_range("Out-of-bounds container access in wasm::ex::at().");
}
} /* namespace ex */
namespace detail {
auto make_stack_size_guard(auto& stack)
{
auto initial_stack_size = stack.size();
return make_scope_guard([&stack, initial_stack_size]() {
assert(stack.size() >= initial_stack_size);
if(stack.size() > initial_stack_size)
stack.pop_n(stack.size() - initial_stack_size);
});
}
} /* namespace detail */
struct BadBranchError:
std::logic_error
{
private:
static std::string make_mesage(std::size_t depth, std::size_t limit)
{
std::ostringstream s;
s << "Invald branch depth (" << depth << ") to non-existant block. ";
s << "(max depth is " << limit << ')';
return s.str();
}
public:
BadBranchError(std::size_t branch_depth, std::size_t limit):
std::logic_error(make_message(branch_depth, limit)),
depth(branch_depth)
{
}
const std::size_t depth;
};
std::ostream& operator<<(std::ostream& os, const SimpleStack<WasmValue>& stack)
{
os << "Stack([";
if(stack.size() > 0u)
{
os << stack.front();
for(auto pos = std::next(stack.begin()); pos != stack.end(); ++pos)
os << ", " << *pos;
}
os << "])";
return os;
}
std::ostream& operator<<(std::ostream& os, const SimpleStack<TaggedWasmValue>& stack)
{
os << "Stack([";
if(stack.size() > 0u)
{
os << stack.front();
for(auto pos = std::next(stack.begin()); pos != stack.end(); ++pos)
os << ", " << *pos;
}
os << "])";
return os;
}
template <class T>
struct Block {
using stack_type = SimpleStack<T>;
Block(const char* label_pos, std::size_t return_count, StackResource& resource):
label(label_pos),
arity(return_count),
stack(resource)
{
}
bool is_bottom() const
{
if(not label)
{
assert(not arity);
return true;
}
return false;
}
const char* const label;
const std::size_t arity;
stack_type stack;
};
template <class T>
std::ostream& operator<<(std::ostream& os, const Block<T>& block)
{
os << "Block(label = " << block.label;
os << ", arity = " << block.arity;
os << ", stack = " << block.stack;
os << ')';
return os;
}
template <class T>
struct WasmStackFrame
{
using value_type = T;
using block_type = Block<value_type>;
using block_list_type = std::forward_list<
block_type, pmr::polymorphic_allocator<block_type>
>;
using locals_vector_type = gsl::span<value_type>;
using stack_type = SimpleStack<value_type>;
using block_iterator = block_list_type::iterator;
using const_block_iterator = block_list_type::const_iterator;
WasmStackFrame(const WasmFunction& func, StackResource& r):
code_(func),
locals_(locals_count(func) + param_count(signature(func))),
blocks_(r)
{
blocks_.emplace_front(nullptr, 0u, get_resource());
}
WasmStackFrame(CodeView code, gsl::span<T> locals, StackResource& r):
return_address_(),
locals_(locals),
blocks_(r)
{
blocks_.push_front(nullptr, 0u, get_resource());
}
~WasmStackFrame()
{
while(not blocks_.empty())
blocks_.pop_front();
}
block_iterator block_at(std::size_t depth)
{
std::size_t count = 0;
for(auto pos = blocks_.begin(); pos != blocks_.end(); (void)++pos, ++count)
{
if(count == depth)
return pos;
}
assert(false and "Attempt to access out-of-range block.");
}
const char* branch_depth(wasm_uint32_t depth)
{ return branch(block_at(depth)); }
const char* try_branch_top() const
{
assert(blocks_.begin() != blocks.end())
if(blocks_.front().is_bottom())
return nullptr;
else
return branch_top();
}
[[nodiscard]]
const char* branch(const_block_iterator pos)
{
assert(pos != blocks_.end());
// get the label
auto code_pos = pos->label;
auto arity = pos->arity;
auto& dest_stack = pos->stack;
auto& src_stack = current_stack(*this);
assert(&src_stack != &dest_stack);
assert(arity <= dest_stack.size());
assert(arity <= src_stack.size());
std::copy(src_stack.begin(), src_stack.begin() + arity, dest_stack.begin());
// TODO: assert(src_stack.size() == arity) for 'IF ... END' blocks
while(blocks_.begin() != pos)
blocks_.pop_front();
return code_pos;
}
void push_block(const char* label, gsl::span<const LanguageType> signature)
{
assert(
(label[-1] == static_cast<char>(OpCode::END))
or (label[-(1 + (std::ptrdiff_t)sizeof(wasm_uint32_t))] == static_cast<char>(OpCode::ELSE))
);
auto guard_ = make_stack_size_guard(stack());
for(const auto& type: signature)
{
// push return values onto the stack
tp::visit_value_type(
[&](auto WasmValue::* p) { stack_emplace_top(p, 0); }, type
);
}
blocks_.emplace_front(label, signature.size(), get_resource());
}
[[nodiscard]]
const char* branch_top()
{
assert(not blocks_.empty());
assert(not blocks_.front().is_bottom());
return branch(blocks_.begin());
}
T& local_at(wasm_uint32_t index)
{ return ex::at(locals_, index); }
const T& local_at(wasm_uint32_t index) const
{ return ex::at(locals_, index); }
T& stack_at(wasm_uint32_t index)
{ return ex::at(stack(), index); }
const T& stack_at(wasm_uint32_t index)
{ return ex::at(stack(), index); }
template <class U>
const std::decay_t<U>& stack_at(wasm_uint32_t index, U WasmValue::* p) const
{ return stack().at().get(p); }
template <class U>
const U& stack_at(wasm_uint32_t index, const U WasmValue::* p) const
{ return stack().at(index).get(p); }
template <class U>
U& stack_at(wasm_uint32_t index, U WasmValue::* p)
{ return stack().at(index).get(p); }
T& stack_top()
{ return stack().at(0u); }
const T& stack_top() const
{ return stack().at(0u); }
template <class U>
const std::decay_t<U>& stack_top(U WasmValue::* p) const
{ return stack_top().get(p); }
template <class U>
const U& stack_top(const U WasmValue::* p) const
{ return stack_top().get(p); }
template <class U>
U& stack_top(U WasmValue::* p)
{ return stack_top().get(p); }
std::pair<const T&, const T&> stack_top_2() const
{ return std::pair<const T&, const T&>(stack_at(1u), stack_at(0u)); }
std::pair<T&, T&> stack_top_2() const
{ return std::pair<T&, T&>(stack_at(1u), stack_at(0u)); }
template <class L, class R>
std::pair<const std::decay_t<L>&, const std::decay_t<R>&> stack_top_2(L WasmValue::* l, R WasmValue::* r) const
{
return std::pair<const std::decay_t<L>&, const std::decay_t<R>&>(
stack_at(1u).get(l), stack_at(0u).get(r)
);
}
template <class U>
void stack_pop_2_push_1(U WasmValue::* mem, U value)
{
stack_pop();
stack_pop_1_push_1(mem, value);
}
template <class U>
void stack_pop_1_push_1(U WasmValue::* mem, U value)
{ stack().replace_top(mem, value); }
T stack_pop()
{ return stack().pop(); }
template <class U>
U stack_pop(U WasmValue::* mem)
{
auto v = stack_top(mem);
stack_pop();
return v;
}
template <class ... Args>
T stack_emplace_top(Args&& ... args)
{ return stack().emplace(std::forward<Args>(args)...); }
void stack_pop_n(std::size_t n)
{ stack().pop_n(n); }
auto stack_size() const
{ return stack().size(); }
const WasmFunction* function()
{ return self.code_.function(); }
friend std::ostream& operator<<(std::ostream& os, const WasmStackFrame& frame)
{
os << "StackFrame(";
os << "function = ";
write_declataion(os, function(frame));
os << ", locals = " << frame.locals_;
os << ", stack = [";
const char* delim = "";
for(const auto& block: frame_.blocks_)
{
const auto& stack = block.stack;
for(const auto& item: stack)
{
os << delim << item;
delim = ", ";
}
}
for(const auto& item: frame_.stack_)
{
os << delim << item;
delim = ", ";
}
os << "])";
return os;
}
bool is_function_call() const
{ return static_cast<bool>(function()); }
std::optional<WasmInstruction> next_instruction() const
{ return code_.next_instruction(); }
void advance(const WasmInstruction& instr)
{
assert(next_instruction());
if(not is_next_instruction(instr))
throw std::logic_error("Instruction does not match program counter on call stack.");
code_.advance(instr);
}
bool is_next_instruction(const WasmInstruction& instr) const
{ return instr.source().data() == code_.data(); }
private:
const auto& stack() const
{
assert(not blocks_.empty());
return blocks_.front().stack;
}
auto& stack()
{
assert(not blocks_.empty());
return blocks_.front().stack;
}
StackResource& get_resource()
{
std::memory_resource* rsc = blocks_.get_allocator().resource();
assert(rsc);
assert(static_cast<bool>(dynamic_cast<StackResource*>(rsc)));
return *static_cast<StackResource*>(rsc);
}
CodeView code_;
const gsl::span<T> locals_;
block_list_type blocks_;
};
template <class T>
struct WasmCallStack
{
using frame_stack_type = ListStack<
WasmStackFrame<T>,
pmr::polymorphic_allocator<WasmStackFrame<T>>
>;
using frame_iterator = list_type::const_iterator;
WasmCallStack(StackResource&
const WasmStackFrame<T>& current_frame() const
{
assert(not frames_.empty());
return frames_.top();
}
CodeView call_function(const Function& func, const WasmInstruction& call_instr)
{
assert(call_instr.opcode() == OpCode::CALL);
if(func.is_wasm_function())
{
return call_wasm_function(func.get_wasm_function(), call_instr);
}
else
{
call_c_function(func.get_c_function());
return call_instr.after();
}
}
CodeView call_wasm_function(const WasmFunction& func, const WasmInstruction& call_instr)
{
assert(call_instr.opcode() == OpCode::CALL);
auto& stack = frames_.empty() ? frames_.top().stack() : base_stack_;
auto func_sig = signature(func);
auto arg_types = param_types(func_sig);
auto locals_types = locals(func);
auto ret_count = return_count(func);
if(stack.size() < arg_types.size())
assert(false); // TODO: throw an exception
// push zero-initialized locals onto the stack.
auto guard_ = make_stack_size_guard(stack);
for(LanguageType type: locals_types)
{
tp::visit_value_type(
[&](auto WasmValue::* p) { stack.emplace(p, 0); }, type
);
}
auto return_address = call_instr.after().pos();
auto locals_vector_size = locals_types.size() + arg_types.size();
auto locals_pos = stack.data() + (stack.size() - locals_vector_size);
gsl::span<T> locals_vector(locals_pos, locals_vector_size);
frames_.emplace(func, return_address, locals_vector);
return CodeView(func);
}
void return_from_expression()
{
assert(frames_.size() == 1u);
_recurse_return_from_frame_unchecked();
}
[[nodiscard]]
CodeView end_block()
{
if(const char* p = top_frame().try_branch_top(); p)
{
}
}
[[nodiscard]]
CodeView return_from_function()
{
auto& frame = top_frame();
assert(frame.is_function_call());
auto ret_types = return_types(signature(*frame.funtion()));
assert(frame.stack_size() >= ret_types.size());
CodeView ret_addr = top_frame().return_address();
_recurse_return_from_frame(return_types);
return ret_addr;
}
[[nodiscard]]
CodeView call_table_function(const WasmTable& table, const WasmFunctionSignature& sig, const WasmInstruction& instr)
{
assert(instr.opcode() == OpCode::CALL_INDIRECT);
assert(frames_.empty() or top_frame().can_exectute_instruction(instr));
auto& stack = top_stack();
wasm_uint32_t offset = reinterpret_cast<const wasm_uint32_t&>(stack.top().get(tp::i32_c));
const TableFunction& func = table.at(offset);
if(func.is_null())
throw NullTableFunctionError();
if(func.is_wasm_function())
{
auto& f = func.get_wasm_function();
if(signature(f) != sig)
throw BadTableFunctionSignature();
stack.pop();
return call_wasm_function(func.get_wasm_function());
}
assert(func.is_c_function());
auto& f = func.get_c_function();
if(f.signature() != sig)
throw BadTableFunctionSignature();
{ /* scope */
auto stack_size = stack.size();
auto guard_ = make_scope_guard(
[&, stack_size]{
// poor man's check to make sure the c function call
// doesn't modify 'this'.
assert(stack.size() == stack_size);
}
call_c_function(f, offset);
} /* /scope */
return instr.after();
}
void call_c_function(const CFunction& cfunc) const
{
const auto& sig = cfunc.signature();
auto param_types = param_types(sig);
auto return_types = return_types(sig);
auto& stack = top_stack();
assert(stack.size() >= param_types.size());
auto args = gsl::span<const T>(stack.data(), stack.size()).last(param_types.size());
{
auto guard_ = make_stack_size_guard(stack());
for(LanguageType value_tp: return_types)
stack.emplace(value_tp);
auto results = gsl::span<T>(stack.data(), stack.size()).last(return_types.size());
cfunc(results, args);
}
assert(stack.size() >= return_types.size() + param_types.size());
std::rotate(
stack.begin(),
stack.begin() + return_types.size(),
stack.begin() + return_types.size() + param_types.size()
);
stack.pop_n(param_types.size());
}
std::optional<WasmInstruction> next_instruction() const
{ return top_frame().next_instruction(); }
void execute(const WasmInstruction& instr, const WasmModule& module) const
{
if(not top_frame().is_next_instruction())
throw std::logic_error("Instruction does not match program counter on call stack.");
CodeView next = instr.execute(*this, module);
top_frame().code_.advance(next);
}
private:
WasmStackFrame<T>& top_frame()
{
if(frames_.empty())
throw std::out_of_range("Attempt to access out-of-bounds call stack frame.");
return frames_.top();
}
SimpleStack<T>& top_stack()
{
if(frames_.empty())
return base_stack_;
return frames_.top().stack();
}
std::pair<WasmStackFrame<T>&, WasmStackFrame<T>&> top_two_frames()
{
if(frames_.empty())
throw std::out_of_range("Attempt to access out-of-bounds frame.");
auto pos = frames_.begin();
const auto& hi = *pos++;
if(pos == frames_.end())
throw std::out_of_range("Attempt to access out-of-bounds frame.");
const auto& lo = *pos++;
return std::pair<WasmStackFrame&, WasmStackFrame&>(lo, hi);
}
void _recurse_return_from_frame_unchecked()
{
if(auto& stack = top_frame().stack(); stack.empty())
{
frames_.pop();
}
else
{
T ret_v = stack.pop();
_recurse_return_from_frame_unchecked();
top_stack().emplace(ret_v);
}
}
void _recurse_return_from_frame(const gsl::span<const LanguageType>& return_types, std::size_t index = 0u)
{
assert(not frames_.empty());
if(index < return_types.size())
{
// one of the return values from the callee's frame
tp::visit_value_type(
[&](auto WasmValue::* p) {
auto ret_v = top_frame().stack_at(index, p);
// keep recursing until we exhaust the return
// values. Once we've done that, pop the callee's
// frame, and then pop the locals vector and arguments
// off the caller's stack.
_recurse_return_from_frame(return_types, index);
// now that we've popped the callee's frame from the call stack,
// and the locals vector off of the caller's frame's stack, push
// the return values onto the callee's frame's stack.
//
// note that there may be no frame below the one we popped, in which
// case, the return values are pushed onto 'this->base_stack_'
top_stack().stack_emplace_top(p, ret_v);
},
return_types[return_types.size() - index]
);
}
else
{
const auto* func_p = top_frame.function();
assert(func_p);
const auto& func = *func_p;
std::size_t total_locals = param_count(func) + locals_count(func);
// pop the top frame
frames_.pop_front();
assert(not frames_.empty());
auto& new_top_frame = frames_.front();
assert(new_top_frame.stack_size() >= total_locals);
// pop the locals (args + locals) vector of the frame we just popped
// off of the stack. note that the locals vector of the current frame
// lives on the stack of the previous frame.
new_top_frame.stack_pop_n(total_locals);
// push the return values of the frame we just popped...
// ... by simply returning from _recurse_return_from_frame(). each
// recursive call which took the if() branch above will push the return
// values onto the new frame.
}
}
const StackResource& stack_resource() const
{ return base_stack_.get_resource(); }
StackResource& stack_resource()
{ return base_stack_.get_resource(); }
frame_stack_type frames_;
SimpleStack<T> base_stack_;
};
template <class T>
const T& local_at(const WasmCallStack<T>& self, std::size_t idx)
{
auto locals = locals(current_frame(self));
if(idx >= locals.size())
throw ValidationError<std::out_of_range>("Attempt to access out-of-bounds local.");
return locals[idx];
}
template <class T>
T& local_at(WasmCallStack<T>& self, std::size_t idx)
{
auto locals = locals(current_frame(self));
if(idx >= locals.size())
throw ValidationError<std::out_of_range>("Attempt to access out-of-bounds local.");
return locals[idx];
}
template <class T>
const auto& current_stack(const WasmCallStack<T>& self, std::size_t idx)
{ return current_stack(current_frame(self)); }
template <class T>
auto& current_stack(WasmCallStack<T>& self, std::size_t idx)
{ return current_stack(current_frame(self)); }
} /* namespace wasm */
#endif /* VM_CALL_STACK_H */
|
[STATEMENT]
theorem log_lin_time:
assumes "length numbers = 2^l"
shows "T\<^sub>F\<^sub>N\<^sub>T\<^sub>T numbers \<le> 30 * l * length numbers + 1"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. T\<^sub>F\<^sub>N\<^sub>T\<^sub>T numbers \<le> 30 * l * length numbers + 1
[PROOF STEP]
proof-
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. T\<^sub>F\<^sub>N\<^sub>T\<^sub>T numbers \<le> 30 * l * length numbers + 1
[PROOF STEP]
have 00: "T\<^sub>F\<^sub>N\<^sub>T\<^sub>T numbers = (2 ^ l - 1) * 14 + l * 15 * 2 ^ (l - 1) + 2 ^ l"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. T\<^sub>F\<^sub>N\<^sub>T\<^sub>T numbers = (2 ^ l - 1) * 14 + l * 15 * 2 ^ (l - 1) + 2 ^ l
[PROOF STEP]
using tight_bound[of "\<lambda> xs. (length xs - 1) * 14 + (Discrete.log (length xs)) * 15 *
2 ^ ( (Discrete.log (length xs)) - 1) + length xs" numbers l]
assms
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>\<And>numbers l. \<lbrakk>length numbers = 2 ^ l; 0 < l\<rbrakk> \<Longrightarrow> (length numbers - 1) * 14 + Discrete.log (length numbers) * 15 * 2 ^ (Discrete.log (length numbers) - 1) + length numbers = (2 ^ l - 1) * 14 + l * 15 * 2 ^ (l - 1) + 2 ^ l; \<And>numbers l. \<lbrakk>l = 0; length numbers = 2 ^ l\<rbrakk> \<Longrightarrow> (length numbers - 1) * 14 + Discrete.log (length numbers) * 15 * 2 ^ (Discrete.log (length numbers) - 1) + length numbers = 1; length numbers = 2 ^ l\<rbrakk> \<Longrightarrow> T\<^sub>F\<^sub>N\<^sub>T\<^sub>T numbers = (length numbers - 1) * 14 + Discrete.log (length numbers) * 15 * 2 ^ (Discrete.log (length numbers) - 1) + length numbers
length numbers = 2 ^ l
goal (1 subgoal):
1. T\<^sub>F\<^sub>N\<^sub>T\<^sub>T numbers = (2 ^ l - 1) * 14 + l * 15 * 2 ^ (l - 1) + 2 ^ l
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
T\<^sub>F\<^sub>N\<^sub>T\<^sub>T numbers = (2 ^ l - 1) * 14 + l * 15 * 2 ^ (l - 1) + 2 ^ l
goal (1 subgoal):
1. T\<^sub>F\<^sub>N\<^sub>T\<^sub>T numbers \<le> 30 * l * length numbers + 1
[PROOF STEP]
have " l * 15 * 2 ^ (l - 1) \<le> 15 * l * length numbers"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. l * 15 * 2 ^ (l - 1) \<le> 15 * l * length numbers
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
length numbers = 2 ^ l
goal (1 subgoal):
1. l * 15 * 2 ^ (l - 1) \<le> 15 * l * length numbers
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
l * 15 * 2 ^ (l - 1) \<le> 15 * l * length numbers
goal (1 subgoal):
1. T\<^sub>F\<^sub>N\<^sub>T\<^sub>T numbers \<le> 30 * l * length numbers + 1
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
l * 15 * 2 ^ (l - 1) \<le> 15 * l * length numbers
goal (1 subgoal):
1. T\<^sub>F\<^sub>N\<^sub>T\<^sub>T numbers \<le> 30 * l * length numbers + 1
[PROOF STEP]
have "(2 ^ l - 1) * 14 + 2^l\<le> 15 * length numbers "
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (2 ^ l - 1) * 14 + 2 ^ l \<le> 15 * length numbers
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
length numbers = 2 ^ l
goal (1 subgoal):
1. (2 ^ l - 1) * 14 + 2 ^ l \<le> 15 * length numbers
[PROOF STEP]
by linarith
[PROOF STATE]
proof (state)
this:
(2 ^ l - 1) * 14 + 2 ^ l \<le> 15 * length numbers
goal (1 subgoal):
1. T\<^sub>F\<^sub>N\<^sub>T\<^sub>T numbers \<le> 30 * l * length numbers + 1
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
(2 ^ l - 1) * 14 + 2 ^ l \<le> 15 * length numbers
goal (1 subgoal):
1. T\<^sub>F\<^sub>N\<^sub>T\<^sub>T numbers \<le> 30 * l * length numbers + 1
[PROOF STEP]
hence "(2 ^ l - 1) * 14 + 2^l \<le> 15 * l * length numbers +1"
[PROOF STATE]
proof (prove)
using this:
(2 ^ l - 1) * 14 + 2 ^ l \<le> 15 * length numbers
goal (1 subgoal):
1. (2 ^ l - 1) * 14 + 2 ^ l \<le> 15 * l * length numbers + 1
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
(2 ^ l - 1) * 14 + 2 ^ l \<le> 15 * length numbers
length numbers = 2 ^ l
goal (1 subgoal):
1. (2 ^ l - 1) * 14 + 2 ^ l \<le> 15 * l * length numbers + 1
[PROOF STEP]
apply(cases l)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<lbrakk>(2 ^ l - 1) * 14 + 2 ^ l \<le> 15 * length numbers; length numbers = 2 ^ l; l = 0\<rbrakk> \<Longrightarrow> (2 ^ l - 1) * 14 + 2 ^ l \<le> 15 * l * length numbers + 1
2. \<And>nat. \<lbrakk>(2 ^ l - 1) * 14 + 2 ^ l \<le> 15 * length numbers; length numbers = 2 ^ l; l = Suc nat\<rbrakk> \<Longrightarrow> (2 ^ l - 1) * 14 + 2 ^ l \<le> 15 * l * length numbers + 1
[PROOF STEP]
subgoal
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>(2 ^ l - 1) * 14 + 2 ^ l \<le> 15 * length numbers; length numbers = 2 ^ l; l = 0\<rbrakk> \<Longrightarrow> (2 ^ l - 1) * 14 + 2 ^ l \<le> 15 * l * length numbers + 1
[PROOF STEP]
by simp
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>nat. \<lbrakk>(2 ^ l - 1) * 14 + 2 ^ l \<le> 15 * length numbers; length numbers = 2 ^ l; l = Suc nat\<rbrakk> \<Longrightarrow> (2 ^ l - 1) * 14 + 2 ^ l \<le> 15 * l * length numbers + 1
[PROOF STEP]
by (metis (no_types) add.commute le_add1 mult.assoc mult.commute
mult_le_mono nat_mult_1 plus_1_eq_Suc trans_le_add2)
[PROOF STATE]
proof (state)
this:
(2 ^ l - 1) * 14 + 2 ^ l \<le> 15 * l * length numbers + 1
goal (1 subgoal):
1. T\<^sub>F\<^sub>N\<^sub>T\<^sub>T numbers \<le> 30 * l * length numbers + 1
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
l * 15 * 2 ^ (l - 1) \<le> 15 * l * length numbers
(2 ^ l - 1) * 14 + 2 ^ l \<le> 15 * length numbers
(2 ^ l - 1) * 14 + 2 ^ l \<le> 15 * l * length numbers + 1
[PROOF STEP]
have " (2 ^ l - 1) * 14 + l * 15 * 2 ^ (l - 1) + 2 ^ l \<le> 30 * l * length numbers +1"
[PROOF STATE]
proof (prove)
using this:
l * 15 * 2 ^ (l - 1) \<le> 15 * l * length numbers
(2 ^ l - 1) * 14 + 2 ^ l \<le> 15 * length numbers
(2 ^ l - 1) * 14 + 2 ^ l \<le> 15 * l * length numbers + 1
goal (1 subgoal):
1. (2 ^ l - 1) * 14 + l * 15 * 2 ^ (l - 1) + 2 ^ l \<le> 30 * l * length numbers + 1
[PROOF STEP]
by linarith
[PROOF STATE]
proof (state)
this:
(2 ^ l - 1) * 14 + l * 15 * 2 ^ (l - 1) + 2 ^ l \<le> 30 * l * length numbers + 1
goal (1 subgoal):
1. T\<^sub>F\<^sub>N\<^sub>T\<^sub>T numbers \<le> 30 * l * length numbers + 1
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
(2 ^ l - 1) * 14 + l * 15 * 2 ^ (l - 1) + 2 ^ l \<le> 30 * l * length numbers + 1
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
(2 ^ l - 1) * 14 + l * 15 * 2 ^ (l - 1) + 2 ^ l \<le> 30 * l * length numbers + 1
goal (1 subgoal):
1. T\<^sub>F\<^sub>N\<^sub>T\<^sub>T numbers \<le> 30 * l * length numbers + 1
[PROOF STEP]
using 00
[PROOF STATE]
proof (prove)
using this:
(2 ^ l - 1) * 14 + l * 15 * 2 ^ (l - 1) + 2 ^ l \<le> 30 * l * length numbers + 1
T\<^sub>F\<^sub>N\<^sub>T\<^sub>T numbers = (2 ^ l - 1) * 14 + l * 15 * 2 ^ (l - 1) + 2 ^ l
goal (1 subgoal):
1. T\<^sub>F\<^sub>N\<^sub>T\<^sub>T numbers \<le> 30 * l * length numbers + 1
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
T\<^sub>F\<^sub>N\<^sub>T\<^sub>T numbers \<le> 30 * l * length numbers + 1
goal:
No subgoals!
[PROOF STEP]
qed |
Formal statement is: lemma Im_divide_numeral [simp]: "Im (z / numeral w) = Im z / numeral w" Informal statement is: The imaginary part of a complex number divided by a numeral is the imaginary part of the complex number divided by the numeral. |
You have probably heard about the rise in Singapore’s property prices coinciding with the acceleration of the markets. You have also probably heard that because of the changes in various housing rules, acquiring property within Singapore has become easier for those purchasing domestically and from foreign globe.
Condos are especially a popular choice of foreign buyers. Singapore authorities used to possess a rule in which a different buyer could only purchase an apartment in a building higher than six stories and the apartment had to be classified as a condominium. This rule no longer applies, but has not interfered with condo sales within buildings.
Yet to purchase a flat as a result of what’s called Executive Condominium projects (EC), you must deemed a Singapore citizen or resident and the purchase have got to take place anywhere between the sixth and tenth year from the date the Temporary Occupation Permit was granted. Any foreigners or corporate bodies who are not permanent residents of Singapore are not eligible in order to an EC. But the majority of that if you can be a foreigner or part of the corporate body, you can purchase an EC if it is in its eleventh year from the date the Temporary Occupation Permit was issued.
So if you might be a permanent citizen perhaps corporate body who wants to purchase an EC, the appropriate action is to locate the developer in that particular area obtain the information you’ll want to make your order. If you are a foreigner or corporate body eager to purchase an EC, you should also check with the developer in designed you are considering about so that you should find what ECs have a their eleventh year and beyond.
But if you want a good Jade scape condo, discover go the EC route or can perform look into apartments that have apartments that are classified as condos. It more or less depends on your citizenship, if happen to be part of a company body that has relocated in Singapore, or what type of money you capable spend. Although property prices within Singapore have seen a rise, that rise is due into the demand and success of the economy, which cannot be overlooked. These successes have resulted in a successful real estate market that involves anything from homes to the perfect condo, so be sure to look into purchasing property in Singapore if you are relocating domestically or relocating abroad. |
-- You can't use the same name more than once in the same scope.
module ClashingDefinition where
postulate
X : Set
X : Set
Y = X
|
[GOAL]
L : Language
M : Type u_1
inst✝ : Structure L M
N : Substructure L M
⊢ (∃ S, Set.Finite S ∧ LowerAdjoint.toFun (closure L) S = N) → FG N
[PROOFSTEP]
rintro ⟨t', h, rfl⟩
[GOAL]
case intro.intro
L : Language
M : Type u_1
inst✝ : Structure L M
t' : Set M
h : Set.Finite t'
⊢ FG (LowerAdjoint.toFun (closure L) t')
[PROOFSTEP]
rcases Finite.exists_finset_coe h with ⟨t, rfl⟩
[GOAL]
case intro.intro.intro
L : Language
M : Type u_1
inst✝ : Structure L M
t : Finset M
h : Set.Finite ↑t
⊢ FG (LowerAdjoint.toFun (closure L) ↑t)
[PROOFSTEP]
exact ⟨t, rfl⟩
[GOAL]
L : Language
M : Type u_1
inst✝ : Structure L M
N : Substructure L M
⊢ FG N ↔ ∃ n s, LowerAdjoint.toFun (closure L) (range s) = N
[PROOFSTEP]
rw [fg_def]
[GOAL]
L : Language
M : Type u_1
inst✝ : Structure L M
N : Substructure L M
⊢ (∃ S, Set.Finite S ∧ LowerAdjoint.toFun (closure L) S = N) ↔ ∃ n s, LowerAdjoint.toFun (closure L) (range s) = N
[PROOFSTEP]
constructor
[GOAL]
case mp
L : Language
M : Type u_1
inst✝ : Structure L M
N : Substructure L M
⊢ (∃ S, Set.Finite S ∧ LowerAdjoint.toFun (closure L) S = N) → ∃ n s, LowerAdjoint.toFun (closure L) (range s) = N
[PROOFSTEP]
rintro ⟨S, Sfin, hS⟩
[GOAL]
case mp.intro.intro
L : Language
M : Type u_1
inst✝ : Structure L M
N : Substructure L M
S : Set M
Sfin : Set.Finite S
hS : LowerAdjoint.toFun (closure L) S = N
⊢ ∃ n s, LowerAdjoint.toFun (closure L) (range s) = N
[PROOFSTEP]
obtain ⟨n, f, rfl⟩ := Sfin.fin_embedding
[GOAL]
case mp.intro.intro.intro.intro
L : Language
M : Type u_1
inst✝ : Structure L M
N : Substructure L M
n : ℕ
f : Fin n ↪ M
Sfin : Set.Finite (range ↑f)
hS : LowerAdjoint.toFun (closure L) (range ↑f) = N
⊢ ∃ n s, LowerAdjoint.toFun (closure L) (range s) = N
[PROOFSTEP]
exact ⟨n, f, hS⟩
[GOAL]
case mpr
L : Language
M : Type u_1
inst✝ : Structure L M
N : Substructure L M
⊢ (∃ n s, LowerAdjoint.toFun (closure L) (range s) = N) → ∃ S, Set.Finite S ∧ LowerAdjoint.toFun (closure L) S = N
[PROOFSTEP]
rintro ⟨n, s, hs⟩
[GOAL]
case mpr.intro.intro
L : Language
M : Type u_1
inst✝ : Structure L M
N : Substructure L M
n : ℕ
s : Fin n → M
hs : LowerAdjoint.toFun (closure L) (range s) = N
⊢ ∃ S, Set.Finite S ∧ LowerAdjoint.toFun (closure L) S = N
[PROOFSTEP]
refine' ⟨range s, finite_range s, hs⟩
[GOAL]
L : Language
M : Type u_1
inst✝ : Structure L M
⊢ LowerAdjoint.toFun (closure L) ↑∅ = ⊥
[PROOFSTEP]
rw [Finset.coe_empty, closure_empty]
[GOAL]
L : Language
M : Type u_1
inst✝ : Structure L M
s : Set M
hs : Set.Finite s
⊢ LowerAdjoint.toFun (closure L) ↑(Finite.toFinset hs) = LowerAdjoint.toFun (closure L) s
[PROOFSTEP]
rw [hs.coe_toFinset]
[GOAL]
L : Language
M : Type u_1
inst✝ : Structure L M
N₁ N₂ : Substructure L M
hN₁ : FG N₁
hN₂ : FG N₂
t₁ : Set M
ht₁ : Set.Finite t₁ ∧ LowerAdjoint.toFun (closure L) t₁ = N₁
t₂ : Set M
ht₂ : Set.Finite t₂ ∧ LowerAdjoint.toFun (closure L) t₂ = N₂
⊢ LowerAdjoint.toFun (closure L) (t₁ ∪ t₂) = N₁ ⊔ N₂
[PROOFSTEP]
rw [closure_union, ht₁.2, ht₂.2]
[GOAL]
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
f : M →[L] N
s : Substructure L M
hs : FG s
t : Set M
ht : Set.Finite t ∧ LowerAdjoint.toFun (closure L) t = s
⊢ LowerAdjoint.toFun (closure L) (↑f '' t) = Substructure.map f s
[PROOFSTEP]
rw [closure_image, ht.2]
[GOAL]
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
f : M ↪[L] N
s : Substructure L M
hs : FG (Substructure.map (Embedding.toHom f) s)
⊢ FG s
[PROOFSTEP]
rcases hs with ⟨t, h⟩
[GOAL]
case intro
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
f : M ↪[L] N
s : Substructure L M
t : Finset N
h : LowerAdjoint.toFun (closure L) ↑t = Substructure.map (Embedding.toHom f) s
⊢ FG s
[PROOFSTEP]
rw [fg_def]
[GOAL]
case intro
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
f : M ↪[L] N
s : Substructure L M
t : Finset N
h : LowerAdjoint.toFun (closure L) ↑t = Substructure.map (Embedding.toHom f) s
⊢ ∃ S, Set.Finite S ∧ LowerAdjoint.toFun (closure L) S = s
[PROOFSTEP]
refine' ⟨f ⁻¹' t, t.finite_toSet.preimage (f.injective.injOn _), _⟩
[GOAL]
case intro
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
f : M ↪[L] N
s : Substructure L M
t : Finset N
h : LowerAdjoint.toFun (closure L) ↑t = Substructure.map (Embedding.toHom f) s
⊢ LowerAdjoint.toFun (closure L) (↑f ⁻¹' ↑t) = s
[PROOFSTEP]
have hf : Function.Injective f.toHom := f.injective
[GOAL]
case intro
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
f : M ↪[L] N
s : Substructure L M
t : Finset N
h : LowerAdjoint.toFun (closure L) ↑t = Substructure.map (Embedding.toHom f) s
hf : Function.Injective ↑(Embedding.toHom f)
⊢ LowerAdjoint.toFun (closure L) (↑f ⁻¹' ↑t) = s
[PROOFSTEP]
refine' map_injective_of_injective hf _
[GOAL]
case intro
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
f : M ↪[L] N
s : Substructure L M
t : Finset N
h : LowerAdjoint.toFun (closure L) ↑t = Substructure.map (Embedding.toHom f) s
hf : Function.Injective ↑(Embedding.toHom f)
⊢ Substructure.map (Embedding.toHom f) (LowerAdjoint.toFun (closure L) (↑f ⁻¹' ↑t)) =
Substructure.map (Embedding.toHom f) s
[PROOFSTEP]
rw [← h, map_closure, Embedding.coe_toHom, image_preimage_eq_of_subset]
[GOAL]
case intro
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
f : M ↪[L] N
s : Substructure L M
t : Finset N
h : LowerAdjoint.toFun (closure L) ↑t = Substructure.map (Embedding.toHom f) s
hf : Function.Injective ↑(Embedding.toHom f)
⊢ ↑t ⊆ range ↑f
[PROOFSTEP]
intro x hx
[GOAL]
case intro
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
f : M ↪[L] N
s : Substructure L M
t : Finset N
h : LowerAdjoint.toFun (closure L) ↑t = Substructure.map (Embedding.toHom f) s
hf : Function.Injective ↑(Embedding.toHom f)
x : N
hx : x ∈ ↑t
⊢ x ∈ range ↑f
[PROOFSTEP]
have h' := subset_closure (L := L) hx
[GOAL]
case intro
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
f : M ↪[L] N
s : Substructure L M
t : Finset N
h : LowerAdjoint.toFun (closure L) ↑t = Substructure.map (Embedding.toHom f) s
hf : Function.Injective ↑(Embedding.toHom f)
x : N
hx : x ∈ ↑t
h' : x ∈ ↑(LowerAdjoint.toFun (closure L) ↑t)
⊢ x ∈ range ↑f
[PROOFSTEP]
rw [h] at h'
[GOAL]
case intro
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
f : M ↪[L] N
s : Substructure L M
t : Finset N
h : LowerAdjoint.toFun (closure L) ↑t = Substructure.map (Embedding.toHom f) s
hf : Function.Injective ↑(Embedding.toHom f)
x : N
hx : x ∈ ↑t
h' : x ∈ ↑(Substructure.map (Embedding.toHom f) s)
⊢ x ∈ range ↑f
[PROOFSTEP]
exact Hom.map_le_range h'
[GOAL]
L : Language
M : Type u_1
inst✝ : Structure L M
N : Substructure L M
h : FG N
⊢ CG N
[PROOFSTEP]
obtain ⟨s, hf, rfl⟩ := fg_def.1 h
[GOAL]
case intro.intro
L : Language
M : Type u_1
inst✝ : Structure L M
s : Set M
hf : Set.Finite s
h : FG (LowerAdjoint.toFun (closure L) s)
⊢ CG (LowerAdjoint.toFun (closure L) s)
[PROOFSTEP]
refine' ⟨s, hf.countable, rfl⟩
[GOAL]
L : Language
M : Type u_1
inst✝ : Structure L M
N : Substructure L M
⊢ CG N ↔ ↑N = ∅ ∨ ∃ s, LowerAdjoint.toFun (closure L) (range s) = N
[PROOFSTEP]
rw [cg_def]
[GOAL]
L : Language
M : Type u_1
inst✝ : Structure L M
N : Substructure L M
⊢ (∃ S, Set.Countable S ∧ LowerAdjoint.toFun (closure L) S = N) ↔
↑N = ∅ ∨ ∃ s, LowerAdjoint.toFun (closure L) (range s) = N
[PROOFSTEP]
constructor
[GOAL]
case mp
L : Language
M : Type u_1
inst✝ : Structure L M
N : Substructure L M
⊢ (∃ S, Set.Countable S ∧ LowerAdjoint.toFun (closure L) S = N) →
↑N = ∅ ∨ ∃ s, LowerAdjoint.toFun (closure L) (range s) = N
[PROOFSTEP]
rintro ⟨S, Scount, hS⟩
[GOAL]
case mp.intro.intro
L : Language
M : Type u_1
inst✝ : Structure L M
N : Substructure L M
S : Set M
Scount : Set.Countable S
hS : LowerAdjoint.toFun (closure L) S = N
⊢ ↑N = ∅ ∨ ∃ s, LowerAdjoint.toFun (closure L) (range s) = N
[PROOFSTEP]
cases' eq_empty_or_nonempty (N : Set M) with h h
[GOAL]
case mp.intro.intro.inl
L : Language
M : Type u_1
inst✝ : Structure L M
N : Substructure L M
S : Set M
Scount : Set.Countable S
hS : LowerAdjoint.toFun (closure L) S = N
h : ↑N = ∅
⊢ ↑N = ∅ ∨ ∃ s, LowerAdjoint.toFun (closure L) (range s) = N
[PROOFSTEP]
exact Or.intro_left _ h
[GOAL]
case mp.intro.intro.inr
L : Language
M : Type u_1
inst✝ : Structure L M
N : Substructure L M
S : Set M
Scount : Set.Countable S
hS : LowerAdjoint.toFun (closure L) S = N
h : Set.Nonempty ↑N
⊢ ↑N = ∅ ∨ ∃ s, LowerAdjoint.toFun (closure L) (range s) = N
[PROOFSTEP]
obtain ⟨f, h'⟩ := (Scount.union (Set.countable_singleton h.some)).exists_eq_range (singleton_nonempty h.some).inr
[GOAL]
case mp.intro.intro.inr.intro
L : Language
M : Type u_1
inst✝ : Structure L M
N : Substructure L M
S : Set M
Scount : Set.Countable S
hS : LowerAdjoint.toFun (closure L) S = N
h : Set.Nonempty ↑N
f : ℕ → M
h' : S ∪ {Set.Nonempty.some h} = range f
⊢ ↑N = ∅ ∨ ∃ s, LowerAdjoint.toFun (closure L) (range s) = N
[PROOFSTEP]
refine' Or.intro_right _ ⟨f, _⟩
[GOAL]
case mp.intro.intro.inr.intro
L : Language
M : Type u_1
inst✝ : Structure L M
N : Substructure L M
S : Set M
Scount : Set.Countable S
hS : LowerAdjoint.toFun (closure L) S = N
h : Set.Nonempty ↑N
f : ℕ → M
h' : S ∪ {Set.Nonempty.some h} = range f
⊢ LowerAdjoint.toFun (closure L) (range f) = N
[PROOFSTEP]
rw [← h', closure_union, hS, sup_eq_left, closure_le]
[GOAL]
case mp.intro.intro.inr.intro
L : Language
M : Type u_1
inst✝ : Structure L M
N : Substructure L M
S : Set M
Scount : Set.Countable S
hS : LowerAdjoint.toFun (closure L) S = N
h : Set.Nonempty ↑N
f : ℕ → M
h' : S ∪ {Set.Nonempty.some h} = range f
⊢ {Set.Nonempty.some h} ⊆ ↑N
[PROOFSTEP]
exact singleton_subset_iff.2 h.some_mem
[GOAL]
case mpr
L : Language
M : Type u_1
inst✝ : Structure L M
N : Substructure L M
⊢ (↑N = ∅ ∨ ∃ s, LowerAdjoint.toFun (closure L) (range s) = N) →
∃ S, Set.Countable S ∧ LowerAdjoint.toFun (closure L) S = N
[PROOFSTEP]
intro h
[GOAL]
case mpr
L : Language
M : Type u_1
inst✝ : Structure L M
N : Substructure L M
h : ↑N = ∅ ∨ ∃ s, LowerAdjoint.toFun (closure L) (range s) = N
⊢ ∃ S, Set.Countable S ∧ LowerAdjoint.toFun (closure L) S = N
[PROOFSTEP]
cases' h with h h
[GOAL]
case mpr.inl
L : Language
M : Type u_1
inst✝ : Structure L M
N : Substructure L M
h : ↑N = ∅
⊢ ∃ S, Set.Countable S ∧ LowerAdjoint.toFun (closure L) S = N
[PROOFSTEP]
refine' ⟨∅, countable_empty, closure_eq_of_le (empty_subset _) _⟩
[GOAL]
case mpr.inl
L : Language
M : Type u_1
inst✝ : Structure L M
N : Substructure L M
h : ↑N = ∅
⊢ N ≤ LowerAdjoint.toFun (closure L) ∅
[PROOFSTEP]
rw [← SetLike.coe_subset_coe, h]
[GOAL]
case mpr.inl
L : Language
M : Type u_1
inst✝ : Structure L M
N : Substructure L M
h : ↑N = ∅
⊢ ∅ ⊆ ↑(LowerAdjoint.toFun (closure L) ∅)
[PROOFSTEP]
exact empty_subset _
[GOAL]
case mpr.inr
L : Language
M : Type u_1
inst✝ : Structure L M
N : Substructure L M
h : ∃ s, LowerAdjoint.toFun (closure L) (range s) = N
⊢ ∃ S, Set.Countable S ∧ LowerAdjoint.toFun (closure L) S = N
[PROOFSTEP]
obtain ⟨f, rfl⟩ := h
[GOAL]
case mpr.inr.intro
L : Language
M : Type u_1
inst✝ : Structure L M
f : ℕ → M
⊢ ∃ S, Set.Countable S ∧ LowerAdjoint.toFun (closure L) S = LowerAdjoint.toFun (closure L) (range f)
[PROOFSTEP]
exact ⟨range f, countable_range _, rfl⟩
[GOAL]
L : Language
M : Type u_1
inst✝ : Structure L M
N₁ N₂ : Substructure L M
hN₁ : CG N₁
hN₂ : CG N₂
t₁ : Set M
ht₁ : Set.Countable t₁ ∧ LowerAdjoint.toFun (closure L) t₁ = N₁
t₂ : Set M
ht₂ : Set.Countable t₂ ∧ LowerAdjoint.toFun (closure L) t₂ = N₂
⊢ LowerAdjoint.toFun (closure L) (t₁ ∪ t₂) = N₁ ⊔ N₂
[PROOFSTEP]
rw [closure_union, ht₁.2, ht₂.2]
[GOAL]
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
f : M →[L] N
s : Substructure L M
hs : CG s
t : Set M
ht : Set.Countable t ∧ LowerAdjoint.toFun (closure L) t = s
⊢ LowerAdjoint.toFun (closure L) (↑f '' t) = Substructure.map f s
[PROOFSTEP]
rw [closure_image, ht.2]
[GOAL]
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
f : M ↪[L] N
s : Substructure L M
hs : CG (Substructure.map (Embedding.toHom f) s)
⊢ CG s
[PROOFSTEP]
rcases hs with ⟨t, h1, h2⟩
[GOAL]
case intro.intro
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
f : M ↪[L] N
s : Substructure L M
t : Set N
h1 : Set.Countable t
h2 : LowerAdjoint.toFun (closure L) t = Substructure.map (Embedding.toHom f) s
⊢ CG s
[PROOFSTEP]
rw [cg_def]
[GOAL]
case intro.intro
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
f : M ↪[L] N
s : Substructure L M
t : Set N
h1 : Set.Countable t
h2 : LowerAdjoint.toFun (closure L) t = Substructure.map (Embedding.toHom f) s
⊢ ∃ S, Set.Countable S ∧ LowerAdjoint.toFun (closure L) S = s
[PROOFSTEP]
refine' ⟨f ⁻¹' t, h1.preimage f.injective, _⟩
[GOAL]
case intro.intro
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
f : M ↪[L] N
s : Substructure L M
t : Set N
h1 : Set.Countable t
h2 : LowerAdjoint.toFun (closure L) t = Substructure.map (Embedding.toHom f) s
⊢ LowerAdjoint.toFun (closure L) (↑f ⁻¹' t) = s
[PROOFSTEP]
have hf : Function.Injective f.toHom := f.injective
[GOAL]
case intro.intro
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
f : M ↪[L] N
s : Substructure L M
t : Set N
h1 : Set.Countable t
h2 : LowerAdjoint.toFun (closure L) t = Substructure.map (Embedding.toHom f) s
hf : Function.Injective ↑(Embedding.toHom f)
⊢ LowerAdjoint.toFun (closure L) (↑f ⁻¹' t) = s
[PROOFSTEP]
refine' map_injective_of_injective hf _
[GOAL]
case intro.intro
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
f : M ↪[L] N
s : Substructure L M
t : Set N
h1 : Set.Countable t
h2 : LowerAdjoint.toFun (closure L) t = Substructure.map (Embedding.toHom f) s
hf : Function.Injective ↑(Embedding.toHom f)
⊢ Substructure.map (Embedding.toHom f) (LowerAdjoint.toFun (closure L) (↑f ⁻¹' t)) =
Substructure.map (Embedding.toHom f) s
[PROOFSTEP]
rw [← h2, map_closure, Embedding.coe_toHom, image_preimage_eq_of_subset]
[GOAL]
case intro.intro
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
f : M ↪[L] N
s : Substructure L M
t : Set N
h1 : Set.Countable t
h2 : LowerAdjoint.toFun (closure L) t = Substructure.map (Embedding.toHom f) s
hf : Function.Injective ↑(Embedding.toHom f)
⊢ t ⊆ range ↑f
[PROOFSTEP]
intro x hx
[GOAL]
case intro.intro
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
f : M ↪[L] N
s : Substructure L M
t : Set N
h1 : Set.Countable t
h2 : LowerAdjoint.toFun (closure L) t = Substructure.map (Embedding.toHom f) s
hf : Function.Injective ↑(Embedding.toHom f)
x : N
hx : x ∈ t
⊢ x ∈ range ↑f
[PROOFSTEP]
have h' := subset_closure (L := L) hx
[GOAL]
case intro.intro
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
f : M ↪[L] N
s : Substructure L M
t : Set N
h1 : Set.Countable t
h2 : LowerAdjoint.toFun (closure L) t = Substructure.map (Embedding.toHom f) s
hf : Function.Injective ↑(Embedding.toHom f)
x : N
hx : x ∈ t
h' : x ∈ ↑(LowerAdjoint.toFun (closure L) t)
⊢ x ∈ range ↑f
[PROOFSTEP]
rw [h2] at h'
[GOAL]
case intro.intro
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
f : M ↪[L] N
s : Substructure L M
t : Set N
h1 : Set.Countable t
h2 : LowerAdjoint.toFun (closure L) t = Substructure.map (Embedding.toHom f) s
hf : Function.Injective ↑(Embedding.toHom f)
x : N
hx : x ∈ t
h' : x ∈ ↑(Substructure.map (Embedding.toHom f) s)
⊢ x ∈ range ↑f
[PROOFSTEP]
exact Hom.map_le_range h'
[GOAL]
L : Language
M : Type u_1
inst✝¹ : Structure L M
inst✝ : Countable ((l : ℕ) × Functions L l)
s : Substructure L M
⊢ CG s ↔ Countable { x // x ∈ s }
[PROOFSTEP]
refine' ⟨_, fun h => ⟨s, h.to_set, s.closure_eq⟩⟩
[GOAL]
L : Language
M : Type u_1
inst✝¹ : Structure L M
inst✝ : Countable ((l : ℕ) × Functions L l)
s : Substructure L M
⊢ CG s → Countable { x // x ∈ s }
[PROOFSTEP]
rintro ⟨s, h, rfl⟩
[GOAL]
case intro.intro
L : Language
M : Type u_1
inst✝¹ : Structure L M
inst✝ : Countable ((l : ℕ) × Functions L l)
s : Set M
h : Set.Countable s
⊢ Countable { x // x ∈ LowerAdjoint.toFun (closure L) s }
[PROOFSTEP]
exact h.substructure_closure L
[GOAL]
L : Language
M : Type u_1
inst✝ : Structure L M
⊢ FG L M ↔ ∃ S, Set.Finite S ∧ LowerAdjoint.toFun (closure L) S = ⊤
[PROOFSTEP]
rw [fg_def, Substructure.fg_def]
[GOAL]
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
h : FG L M
f : M →[L] N
⊢ Substructure.FG (Hom.range f)
[PROOFSTEP]
rw [Hom.range_eq_map]
[GOAL]
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
h : FG L M
f : M →[L] N
⊢ Substructure.FG (map f ⊤)
[PROOFSTEP]
exact (fg_def.1 h).map f
[GOAL]
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
h : FG L M
f : M →[L] N
hs : Function.Surjective ↑f
⊢ FG L N
[PROOFSTEP]
rw [← Hom.range_eq_top] at hs
[GOAL]
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
h : FG L M
f : M →[L] N
hs : Hom.range f = ⊤
⊢ FG L N
[PROOFSTEP]
rw [fg_def, ← hs]
[GOAL]
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
h : FG L M
f : M →[L] N
hs : Hom.range f = ⊤
⊢ Substructure.FG (Hom.range f)
[PROOFSTEP]
exact h.range f
[GOAL]
L : Language
M : Type u_1
inst✝ : Structure L M
⊢ CG L M ↔ ∃ S, Set.Countable S ∧ LowerAdjoint.toFun (closure L) S = ⊤
[PROOFSTEP]
rw [cg_def, Substructure.cg_def]
[GOAL]
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
h : CG L M
f : M →[L] N
⊢ Substructure.CG (Hom.range f)
[PROOFSTEP]
rw [Hom.range_eq_map]
[GOAL]
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
h : CG L M
f : M →[L] N
⊢ Substructure.CG (map f ⊤)
[PROOFSTEP]
exact (cg_def.1 h).map f
[GOAL]
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
h : CG L M
f : M →[L] N
hs : Function.Surjective ↑f
⊢ CG L N
[PROOFSTEP]
rw [← Hom.range_eq_top] at hs
[GOAL]
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
h : CG L M
f : M →[L] N
hs : Hom.range f = ⊤
⊢ CG L N
[PROOFSTEP]
rw [cg_def, ← hs]
[GOAL]
L : Language
M : Type u_1
inst✝¹ : Structure L M
N : Type u_2
inst✝ : Structure L N
h : CG L M
f : M →[L] N
hs : Hom.range f = ⊤
⊢ Substructure.CG (Hom.range f)
[PROOFSTEP]
exact h.range f
[GOAL]
L : Language
M : Type u_1
inst✝¹ : Structure L M
inst✝ : Countable ((l : ℕ) × Functions L l)
⊢ CG L M ↔ Countable M
[PROOFSTEP]
rw [cg_def, Substructure.cg_iff_countable, topEquiv.toEquiv.countable_iff]
[GOAL]
L : Language
M : Type u_1
inst✝ : Structure L M
S : Substructure L M
⊢ FG S ↔ Structure.FG L { x // x ∈ S }
[PROOFSTEP]
rw [Structure.fg_def]
[GOAL]
L : Language
M : Type u_1
inst✝ : Structure L M
S : Substructure L M
⊢ FG S ↔ FG ⊤
[PROOFSTEP]
refine' ⟨fun h => FG.of_map_embedding S.subtype _, fun h => _⟩
[GOAL]
case refine'_1
L : Language
M : Type u_1
inst✝ : Structure L M
S : Substructure L M
h : FG S
⊢ FG (map (Embedding.toHom (subtype S)) ⊤)
[PROOFSTEP]
rw [← Hom.range_eq_map, range_subtype]
[GOAL]
case refine'_1
L : Language
M : Type u_1
inst✝ : Structure L M
S : Substructure L M
h : FG S
⊢ FG S
[PROOFSTEP]
exact h
[GOAL]
case refine'_2
L : Language
M : Type u_1
inst✝ : Structure L M
S : Substructure L M
h : FG ⊤
⊢ FG S
[PROOFSTEP]
have h := h.map S.subtype.toHom
[GOAL]
case refine'_2
L : Language
M : Type u_1
inst✝ : Structure L M
S : Substructure L M
h✝ : FG ⊤
h : FG (map (Embedding.toHom (subtype S)) ⊤)
⊢ FG S
[PROOFSTEP]
rw [← Hom.range_eq_map, range_subtype] at h
[GOAL]
case refine'_2
L : Language
M : Type u_1
inst✝ : Structure L M
S : Substructure L M
h✝ : FG ⊤
h : FG S
⊢ FG S
[PROOFSTEP]
exact h
[GOAL]
L : Language
M : Type u_1
inst✝ : Structure L M
S : Substructure L M
⊢ CG S ↔ Structure.CG L { x // x ∈ S }
[PROOFSTEP]
rw [Structure.cg_def]
[GOAL]
L : Language
M : Type u_1
inst✝ : Structure L M
S : Substructure L M
⊢ CG S ↔ CG ⊤
[PROOFSTEP]
refine' ⟨fun h => CG.of_map_embedding S.subtype _, fun h => _⟩
[GOAL]
case refine'_1
L : Language
M : Type u_1
inst✝ : Structure L M
S : Substructure L M
h : CG S
⊢ CG (map (Embedding.toHom (subtype S)) ⊤)
[PROOFSTEP]
rw [← Hom.range_eq_map, range_subtype]
[GOAL]
case refine'_1
L : Language
M : Type u_1
inst✝ : Structure L M
S : Substructure L M
h : CG S
⊢ CG S
[PROOFSTEP]
exact h
[GOAL]
case refine'_2
L : Language
M : Type u_1
inst✝ : Structure L M
S : Substructure L M
h : CG ⊤
⊢ CG S
[PROOFSTEP]
have h := h.map S.subtype.toHom
[GOAL]
case refine'_2
L : Language
M : Type u_1
inst✝ : Structure L M
S : Substructure L M
h✝ : CG ⊤
h : CG (map (Embedding.toHom (subtype S)) ⊤)
⊢ CG S
[PROOFSTEP]
rw [← Hom.range_eq_map, range_subtype] at h
[GOAL]
case refine'_2
L : Language
M : Type u_1
inst✝ : Structure L M
S : Substructure L M
h✝ : CG ⊤
h : CG S
⊢ CG S
[PROOFSTEP]
exact h
|
abbrev N := Nat
def f : N → Nat
| 0 => 1
| n+1 => n
theorem ex1 : f 0 = 1 :=
rfl
|
theorem le_succ (a b : mynat) : a ≤ b → a ≤ (succ b) :=
begin
intro h,
rw le_iff_exists_add at h,
cases h with c hc,
rw hc,
use c + 1,
rw succ_eq_add_one,
refl,
end
|
module plfa-exercises.Practice2 where
-- Trying exercises:
-- 5.2 pp 340
-- 5.7 pp 386
-- 6.1 pp 423
import Relation.Binary.PropositionalEquality as Eq
open Eq using (_≡_; refl; subst)
open import Data.Nat using (ℕ; zero; suc; _+_; _*_)
open import Relation.Nullary using (¬_)
open import Data.Product using (_×_; proj₁; ∃-syntax) renaming (_,_ to ⟨_,_⟩)
open import Data.Sum using (_⊎_; inj₁; inj₂)
--open import plfa.part1.Isomorphism using (_≃_; extensionality)
∀-elim : ∀ {A : Set} {B : A → Set} → (L : ∀ (x : A) → B x) → (M : A) → B M
∀-elim l m = l m
--totype : ℕ → Set
--totype 0 = ℕ
--totype 1 = 4 ≡ 2 + 2
--totype _ = ℕ
-- λ noidea → ∀-elim {ℕ} {totype} noidea 4
------- Preliminary proofs -------
modus-tollens : ∀ {A B : Set}
→ (A → B)
-------------
→ (¬ B → ¬ A)
modus-tollens a→b = λ{¬b → λ{a → ¬b (a→b a)}}
----------------------------------
postulate
dne : ∀ {A : Set} → ¬ ¬ A → A
--data Σ (A : Set) (B : A → Set) : Set where
-- ⟨_,_⟩ : (x : A) → B x → Σ A B
--
--Σ-syntax = Σ
--infix 2 Σ-syntax
--syntax Σ-syntax A (λ x → B) = Σ[ x ∈ A ] B
--
--∃ : ∀ {A : Set} (B : A → Set) → Set
--∃ {A} B = Σ A B
--
--∃-syntax = ∃
--syntax ∃-syntax (λ x → B) = ∃[ x ] B
--⟨,⟩-syntax : ∀ {A : Set} {B : A → Set} (x : A) → B x → Σ A B
--⟨,⟩-syntax = ⟨_,_⟩
----⟨,⟩-syntax = Σ.⟨_,_⟩
--syntax ⟨,⟩-syntax x p = the-proof-for x is p
--∃-elim : ∀ {A : Set} {B : A → Set} {C : Set}
-- → (∀ x → B x → C)
-- → ∃[ x ] B x
-- ---------------
-- → C
--∃-elim f ⟨ x , y ⟩ = f x y
record _⇔_ (A B : Set) : Set where
field
to : A → B
from : B → A
---------------------- Athena book exercises ----------------------
exercise531 : ∀ {A : Set} {R : A → A → Set}
→ (∀ (x y : A) → R x y)
→ (∀ (x : A) → R x x)
exercise531 R x = R x x
exercise532 : ∀ {A : Set} (x : A) → ∃[ y ] (x ≡ y)
exercise532 e = ⟨ e , refl ⟩
exercise533 : ∀ {A : Set} {P Q S : A → Set}
→ (∀ {x} → (P x ⊎ Q x) → S x)
→ (∃[ y ] (Q y))
-------------------------
→ (∃[ y ] (S y))
exercise533 Px⊎Qx→Sx ⟨ y , qy ⟩ =
let
-- P x ⊎ Q x
py⊎qy = inj₂ qy
in ⟨ y , Px⊎Qx→Sx py⊎qy ⟩
exercise534 : ∀ {A : Set} {P Q S : A → Set}
→ (∃[ y ] (P y × Q y))
→ (∀ {y} → P y → S y)
-------------------------
→ (∃[ y ] (S y × Q y))
exercise534 ⟨ y , ⟨ py , qy ⟩ ⟩ py→sy = ⟨ y , ⟨ py→sy py , qy ⟩ ⟩
exercise535 : ∀ {A : Set} {P Q : A → Set}
→ (¬ ∃[ x ] (Q x))
→ (∀ {x} → P x → Q x)
-------------------------
→ (¬ ∃[ x ] (P x))
exercise535 ¬∃x-qx ∀x→px→qx = λ{ ∃x-px@(⟨ x , px ⟩) → ¬∃x-qx ⟨ x , ∀x→px→qx px ⟩ }
exercise536 : ∀ {A : Set} {P Q S : A → Set}
→ (∀ {y} → P y → Q y)
→ (∃[ y ] (S y × ¬ Q y))
------------------------
→ (∃[ y ] (S y × ¬ P y))
exercise536 ∀y→py→qy ⟨ y , ⟨ sy , ¬qy ⟩ ⟩ = ⟨ y , ⟨ sy , modus-tollens ∀y→py→qy ¬qy ⟩ ⟩
exercise537 : ∀ {A : Set} {P Q : A → Set} {R : A → A → Set}
→ (∀ {x} → R x x → P x)
→ (∃[ x ] (P x) → ¬ ∃[ x ] (Q x))
-------------------------------
→ ((∀ {x} → Q x) → ¬ ∃[ x ] (R x x))
exercise537 ∀x→rxx→px ∃x-px→¬∃x-qx ∀x→qx = λ{∃x-rxx@(⟨ x , rxx ⟩) → ∃x-px→¬∃x-qx ⟨ x , ∀x→rxx→px rxx ⟩ ⟨ x , ∀x→qx {x} ⟩ }
exercise538 : ∀ {A : Set} {P Q : A → Set}
→ (∃[ x ] (P x ⊎ Q x)) ⇔ (∃[ x ] (P x) ⊎ ∃[ x ] (Q x))
exercise538 = record { to = to ; from = from }
where
to : ∀ {A : Set} {P Q : A → Set}
→ ∃[ x ] (P x ⊎ Q x)
-----------------------------
→ ∃[ x ] (P x) ⊎ ∃[ x ] (Q x)
to ⟨ x , (inj₁ px) ⟩ = inj₁ ⟨ x , px ⟩
to ⟨ x , (inj₂ qx) ⟩ = inj₂ ⟨ x , qx ⟩
from : ∀ {A : Set} {P Q : A → Set}
→ ∃[ x ] (P x) ⊎ ∃[ x ] (Q x)
-----------------------------
→ ∃[ x ] (P x ⊎ Q x)
from (inj₁ ⟨ x , px ⟩) = ⟨ x , inj₁ px ⟩
from (inj₂ ⟨ x , qx ⟩) = ⟨ x , inj₂ qx ⟩
------------------
exercise571 : ∀ {A : Set} {P Q : A → Set}
→ (∀ {x} → P x ⇔ Q x)
→ (∀ {x} → P x) ⇔ (∀ {x} → Q x)
exercise571 px⇔qx =
record
{ to = λ{px → (_⇔_.to px⇔qx) px}
; from = λ{qx → (_⇔_.from px⇔qx) qx}
}
--exercise571 ∀x→px⇔qx =
-- record
-- { to = λ{∀x→px → (_⇔_.to (∀x→px⇔qx {x})) (∀x→px {x})}
-- ; from = λ{∀x→qx → (_⇔_.from (∀x→px⇔qx {x})) (∀x→qx {x})}
-- }
exercise572 : ∀ {A : Set} {B : Set} {Q S : B → Set} {R T : B → B → Set}
→ (∃[ y ] (R y y × A))
→ (∃[ y ] (Q y × T y y))
→ (∀ y → A × Q y → ¬ S y)
→ (∃[ y ] (¬ S y × T y y))
exercise572 ⟨ _ , ⟨ _ , a ⟩ ⟩ ⟨ y , ⟨ qy , tyy ⟩ ⟩ ∀y→a×qy→¬sy = ⟨ y , ⟨ ∀y→a×qy→¬sy y ⟨ a , qy ⟩ , tyy ⟩ ⟩
-- This is fucking false!!!
--postulate
-- existence : {A : Set} {P : A → Set}
-- → (∀ x → P x)
-- ----------------
-- → (∃[ x ] (P x))
-- This cannot be proved! Take the empty set as an example. For any function
-- and relation the ∀'s are trivially true, but there is no element that
-- actually fulfills the function or the relation
--exercise574 : ∀ {A : Set} {F : A → A} {R : A → A → Set}
-- → (∀ x → R x x)
-- → (∀ x → F x ≡ F (F x))
-- -----------------------
-- → (∃[ y ] (R y (F y)))
--exercise574 ∀x→rxx ∀x→fx≡ffx = ⟨ ? , ? ⟩
exercise574 : ∀ {F : ℕ → ℕ} {R : ℕ → ℕ → Set}
→ (∀ x → R x x)
→ (∀ x → F x ≡ F (F x))
-----------------------
→ (∃[ y ] (R y (F y)))
exercise574 {f} {r} ∀x→rxx ∀x→fx≡ffx =
let y = f 0
y≡fy = ∀x→fx≡ffx 0 -- F 0 ≡ F (F 0) => y ≡ F y
ryy = ∀x→rxx y -- R (F 0) (F 0) => R y y
ryfy = subst (r y) y≡fy ryy -- R (F 0) (F (F 0)) => R y (F y)
in ⟨ y , ryfy ⟩
------------------
exercise61a : ∀ {A B : Set}
→ (B ⊎ (A → B))
→ A
---------------
→ B
exercise61a (inj₁ b) _ = b
exercise61a (inj₂ a→b) a = a→b a
exercise61b : ∀ {A B C : Set}
→ (¬ B → ¬ C)
→ ((A × B) ⊎ ¬ ¬ C)
-------------------
→ B
exercise61b ¬b→¬c (inj₁ ⟨ a , b ⟩) = b
exercise61b ¬b→¬c (inj₂ ¬¬c) = dne ((modus-tollens ¬b→¬c) ¬¬c)
¬¬ : ∀ {A : Set}
→ A
→ ¬ ¬ A
¬¬ a = λ{¬a → ¬a a}
-- What is the difference between: ∀ x → P x → ∀ y → R y → L and (∀ x → P x) → (∀ y → R y) → L
---- Can the following be proved without Double Negation Elimination (dne)?
--lemma₁ : ∀ {A B : Set}
-- → (¬ B → ¬ A)
-- → A
-- -------------------
-- → B
--lemma₁ = ?
--
--lemma₂ : ∀ {A B : Set}
-- → (¬ B → ¬ A)
-- → ¬ ¬ A
-- -------------------
-- → B
--lemma₂ = ?
--
---- `lemma₁` seems not to imply `dne` but it can't be proven without it.
----
---- The answer is NO (for the second one)! Because from it we can prove `dne`!
---- `dne` cannot be proved in vanila Agda.
--dne₁ : ∀ {A : Set} → ¬ ¬ A → A
--dne₁ ¬¬a = lemma₁ ? ?
--
--dne₂ : ∀ {A : Set} → ¬ ¬ A → A
--dne₂ ¬¬a = lemma₂ (λ{x → x}) ¬¬a
|
State Before: R : Type ?u.697823
A : Type u_1
K : Type u_2
inst✝⁶ : CommRing R
inst✝⁵ : CommRing A
inst✝⁴ : Field K
inst✝³ : IsDomain A
inst✝² : Algebra A K
inst✝¹ : IsFractionRing A K
inst✝ : IsDedekindDomain A
J : FractionalIdeal A⁰ K
hJ : J ≠ 0
⊢ ∀ {I I' : FractionalIdeal A⁰ K}, I * J ≤ I' * J ↔ I ≤ I' State After: R : Type ?u.697823
A : Type u_1
K : Type u_2
inst✝⁶ : CommRing R
inst✝⁵ : CommRing A
inst✝⁴ : Field K
inst✝³ : IsDomain A
inst✝² : Algebra A K
inst✝¹ : IsFractionRing A K
inst✝ : IsDedekindDomain A
J : FractionalIdeal A⁰ K
hJ : J ≠ 0
I I' : FractionalIdeal A⁰ K
⊢ I * J ≤ I' * J ↔ I ≤ I' Tactic: intro I I' State Before: R : Type ?u.697823
A : Type u_1
K : Type u_2
inst✝⁶ : CommRing R
inst✝⁵ : CommRing A
inst✝⁴ : Field K
inst✝³ : IsDomain A
inst✝² : Algebra A K
inst✝¹ : IsFractionRing A K
inst✝ : IsDedekindDomain A
J : FractionalIdeal A⁰ K
hJ : J ≠ 0
I I' : FractionalIdeal A⁰ K
⊢ I * J ≤ I' * J ↔ I ≤ I' State After: case mp
R : Type ?u.697823
A : Type u_1
K : Type u_2
inst✝⁶ : CommRing R
inst✝⁵ : CommRing A
inst✝⁴ : Field K
inst✝³ : IsDomain A
inst✝² : Algebra A K
inst✝¹ : IsFractionRing A K
inst✝ : IsDedekindDomain A
J : FractionalIdeal A⁰ K
hJ : J ≠ 0
I I' : FractionalIdeal A⁰ K
⊢ I * J ≤ I' * J → I ≤ I'
case mpr
R : Type ?u.697823
A : Type u_1
K : Type u_2
inst✝⁶ : CommRing R
inst✝⁵ : CommRing A
inst✝⁴ : Field K
inst✝³ : IsDomain A
inst✝² : Algebra A K
inst✝¹ : IsFractionRing A K
inst✝ : IsDedekindDomain A
J : FractionalIdeal A⁰ K
hJ : J ≠ 0
I I' : FractionalIdeal A⁰ K
⊢ I ≤ I' → I * J ≤ I' * J Tactic: constructor State Before: case mp
R : Type ?u.697823
A : Type u_1
K : Type u_2
inst✝⁶ : CommRing R
inst✝⁵ : CommRing A
inst✝⁴ : Field K
inst✝³ : IsDomain A
inst✝² : Algebra A K
inst✝¹ : IsFractionRing A K
inst✝ : IsDedekindDomain A
J : FractionalIdeal A⁰ K
hJ : J ≠ 0
I I' : FractionalIdeal A⁰ K
⊢ I * J ≤ I' * J → I ≤ I' State After: case mp
R : Type ?u.697823
A : Type u_1
K : Type u_2
inst✝⁶ : CommRing R
inst✝⁵ : CommRing A
inst✝⁴ : Field K
inst✝³ : IsDomain A
inst✝² : Algebra A K
inst✝¹ : IsFractionRing A K
inst✝ : IsDedekindDomain A
J : FractionalIdeal A⁰ K
hJ : J ≠ 0
I I' : FractionalIdeal A⁰ K
h : I * J ≤ I' * J
⊢ I ≤ I' Tactic: intro h State Before: case mp
R : Type ?u.697823
A : Type u_1
K : Type u_2
inst✝⁶ : CommRing R
inst✝⁵ : CommRing A
inst✝⁴ : Field K
inst✝³ : IsDomain A
inst✝² : Algebra A K
inst✝¹ : IsFractionRing A K
inst✝ : IsDedekindDomain A
J : FractionalIdeal A⁰ K
hJ : J ≠ 0
I I' : FractionalIdeal A⁰ K
h : I * J ≤ I' * J
⊢ I ≤ I' State After: no goals Tactic: convert mul_right_mono J⁻¹ h <;> dsimp only <;>
rw [mul_assoc, FractionalIdeal.mul_inv_cancel hJ, mul_one] State Before: case mpr
R : Type ?u.697823
A : Type u_1
K : Type u_2
inst✝⁶ : CommRing R
inst✝⁵ : CommRing A
inst✝⁴ : Field K
inst✝³ : IsDomain A
inst✝² : Algebra A K
inst✝¹ : IsFractionRing A K
inst✝ : IsDedekindDomain A
J : FractionalIdeal A⁰ K
hJ : J ≠ 0
I I' : FractionalIdeal A⁰ K
⊢ I ≤ I' → I * J ≤ I' * J State After: no goals Tactic: exact fun h => mul_right_mono J h |
// (C) Copyright Raffi Enficiaud 2017.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
//! @file
//! Customization point for printing user defined types
// *****************************************************************************
//[example_code
#define BOOST_TEST_MODULE logger-customization-point
#include <boost/test/included/unit_test.hpp>
namespace user_defined_namespace {
struct user_defined_type {
int value;
user_defined_type(int value_) : value(value_)
{}
bool operator==(int right) const {
return right == value;
}
};
}
namespace user_defined_namespace {
std::ostream& boost_test_print_type(std::ostream& ostr, user_defined_type const& right) {
ostr << "** value of user_defined_type is " << right.value << " **";
return ostr;
}
}
BOOST_AUTO_TEST_CASE(test1)
{
user_defined_namespace::user_defined_type t(10);
BOOST_TEST(t == 11);
using namespace user_defined_namespace;
user_defined_type t2(11);
BOOST_TEST(t2 == 11);
}
//]
|
theory AllRefineAsmsSingleFile
imports
Cogent.ValueSemantics
"build/Bitfields_AllRefine"
begin
section "Functional correctness of 'foo'"
definition foo_spec :: "R\<^sub>T \<Rightarrow> R\<^sub>T"
where "foo_spec f =
(if exide\<^sub>f f then
f \<lparr> id\<^sub>f := id\<^sub>f f && 0x0c \<rparr>
else
f \<lparr> id\<^sub>f := id\<^sub>f f + 1 \<rparr>)"
lemma foo_shallow_correct: "Bitfields_Shallow_Desugar.foo x = foo_spec x"
apply(clarsimp simp add:foo_spec_def Bitfields_Shallow_Desugar.foo_def Let\<^sub>d\<^sub>s_def)
apply(cases "exide\<^sub>f x"; clarsimp)
apply(rule_tac f =" \<lambda> f . x \<lparr> id\<^sub>f := f \<rparr>" in HOL.arg_cong )
apply word_bitwise
apply(rule_tac f =" \<lambda> f . x \<lparr> id\<^sub>f := f \<rparr>" in HOL.arg_cong )
apply word_bitwise
done
lemmas corres_shallow_C_foo_concrete = Bitfields_cogent_shallow.corres_shallow_C_foo[folded \<Xi>_def, simplified
, simplified, simplified foo_shallow_correct
]
end |
(**
# 第9回 タクティックの定義と利用/停止性証明 (2014/06/08)
http://qnighy.github.io/coqex2014/
## 課題43 (種別:B / 締め切り : 2014/06/22)
ゴールがandの連なった形であるとき、これをandの形になっている限りsplitし続けるタクティックを
定義せよ。課題41と違い、and以外の形の場合はsplitしてはいけない。
*)
Ltac split_all :=
match goal with
| _ : _ |- _ /\ _
=> split; split_all
| _ => idtac
end.
(* 以下は動作確認用 *)
Lemma bar :
forall P Q R S : Prop,
R -> Q -> P -> S -> (P /\ R) /\ (S /\ Q).
Proof.
intros P Q R S H0 H1 H2 H3.
split_all.
- assumption.
- assumption.
- assumption.
- assumption.
Qed.
Lemma baz :
forall P Q R S T : Prop,
R -> Q -> P -> T -> S -> P /\ Q /\ R /\ S /\ T.
Proof.
intros P Q R S T H0 H1 H2 H3 H4.
split_all.
- assumption.
- assumption.
- assumption.
- assumption.
- assumption.
Qed.
Lemma quux :
forall P Q : Type, P -> Q -> P * Q.
Proof.
intros P Q H0 H1.
split_all.
split.
- assumption.
- assumption.
Qed.
(*
ヒント
match goal with ... end 構文を使いましょう。この構文の使い方についてはマニュアルの9章の文法
定義を追うのがよいかと思います。*)
(* END *)
|
/-
Copyright (c) 2021 Stuart Presnell. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Stuart Presnell
! This file was ported from Lean 3 source module data.nat.factorization.basic
! leanprover-community/mathlib commit f694c7dead66f5d4c80f446c796a5aad14707f0e
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathlib.Algebra.BigOperators.Finsupp
import Mathlib.Data.Finsupp.Multiset
import Mathlib.Data.Nat.PrimeFin
import Mathlib.NumberTheory.Padics.PadicVal
import Mathlib.Data.Nat.Interval
import Mathlib.Tactic.IntervalCases
/-!
# Prime factorizations
`n.factorization` is the finitely supported function `ℕ →₀ ℕ`
mapping each prime factor of `n` to its multiplicity in `n`. For example, since 2000 = 2^4 * 5^3,
* `factorization 2000 2` is 4
* `factorization 2000 5` is 3
* `factorization 2000 k` is 0 for all other `k : ℕ`.
## TODO
* As discussed in this Zulip thread:
https://leanprover.zulipchat.com/#narrow/stream/217875/topic/Multiplicity.20in.20the.20naturals
We have lots of disparate ways of talking about the multiplicity of a prime
in a natural number, including `factors.count`, `padicValNat`, `multiplicity`,
and the material in `Data/PNat/Factors`. Move some of this material to this file,
prove results about the relationships between these definitions,
and (where appropriate) choose a uniform canonical way of expressing these ideas.
* Moreover, the results here should be generalised to an arbitrary unique factorization monoid
with a normalization function, and then deduplicated. The basics of this have been started in
`RingTheory/UniqueFactorizationDomain`.
* Extend the inductions to any `NormalizationMonoid` with unique factorization.
-/
-- Workaround for lean4#2038
attribute [-instance] instBEqNat
open Nat Finset List Finsupp
open BigOperators
namespace Nat
/-- `n.factorization` is the finitely supported function `ℕ →₀ ℕ`
mapping each prime factor of `n` to its multiplicity in `n`. -/
def factorization (n : ℕ) : ℕ →₀ ℕ where
support := n.factors.toFinset
toFun p := if p.Prime then padicValNat p n else 0
mem_support_toFun := by
rcases eq_or_ne n 0 with (rfl | hn0); · simp
simp only [mem_factors hn0, mem_toFinset, Ne.def, ite_eq_right_iff, not_forall, exists_prop,
and_congr_right_iff]
rintro p hp
haveI := fact_iff.mpr hp
exact dvd_iff_padicValNat_ne_zero hn0
#align nat.factorization Nat.factorization
/-- We can write both `n.factorization p` and `n.factors.count p` to represent the power
of `p` in the factorization of `n`: we declare the former to be the simp-normal form. -/
@[simp]
theorem factors_count_eq {n p : ℕ} : n.factors.count p = n.factorization p := by
rcases n.eq_zero_or_pos with (rfl | hn0)
· simp [factorization, count]
by_cases pp : p.Prime; swap
· rw [count_eq_zero_of_not_mem (mt prime_of_mem_factors pp)]
simp [factorization, pp]
simp only [factorization, coe_mk, pp, if_true]
rw [← PartENat.natCast_inj, padicValNat_def' pp.ne_one hn0,
UniqueFactorizationMonoid.multiplicity_eq_count_normalizedFactors pp hn0.ne']
simp [factors_eq]
#align nat.factors_count_eq Nat.factors_count_eq
theorem factorization_eq_factors_multiset (n : ℕ) :
n.factorization = Multiset.toFinsupp (n.factors : Multiset ℕ) := by
ext p
-- porting note: previously closed with `simp`
simp only [Multiset.toFinsupp_apply, Multiset.mem_coe, Multiset.coe_nodup, Multiset.coe_count]
rw [@factors_count_eq n p] -- porting note: TODO: why doesn't `factors_count_eq` take here?
#align nat.factorization_eq_factors_multiset Nat.factorization_eq_factors_multiset
theorem multiplicity_eq_factorization {n p : ℕ} (pp : p.Prime) (hn : n ≠ 0) :
multiplicity p n = n.factorization p := by
simp [factorization, pp, padicValNat_def' pp.ne_one hn.bot_lt]
#align nat.multiplicity_eq_factorization Nat.multiplicity_eq_factorization
/-! ### Basic facts about factorization -/
@[simp]
theorem factorization_prod_pow_eq_self {n : ℕ} (hn : n ≠ 0) : n.factorization.prod (· ^ ·) = n := by
rw [factorization_eq_factors_multiset n]
simp only [← prod_toMultiset, factorization, Multiset.coe_prod, Multiset.toFinsupp_toMultiset]
exact prod_factors hn
#align nat.factorization_prod_pow_eq_self Nat.factorization_prod_pow_eq_self
theorem eq_of_factorization_eq {a b : ℕ} (ha : a ≠ 0) (hb : b ≠ 0)
(h : ∀ p : ℕ, a.factorization p = b.factorization p) : a = b :=
eq_of_perm_factors ha hb (by simpa only [List.perm_iff_count, factors_count_eq] using h)
#align nat.eq_of_factorization_eq Nat.eq_of_factorization_eq
/-- Every nonzero natural number has a unique prime factorization -/
theorem factorization_inj : Set.InjOn factorization { x : ℕ | x ≠ 0 } := fun a ha b hb h =>
eq_of_factorization_eq ha hb fun p => by simp [h]
#align nat.factorization_inj Nat.factorization_inj
@[simp]
theorem factorization_zero : factorization 0 = 0 := by simp [factorization]
#align nat.factorization_zero Nat.factorization_zero
@[simp]
theorem factorization_one : factorization 1 = 0 := by simp [factorization]
#align nat.factorization_one Nat.factorization_one
/-- The support of `n.factorization` is exactly `n.factors.toFinset` -/
@[simp]
theorem support_factorization {n : ℕ} : n.factorization.support = n.factors.toFinset := by
simp [factorization]
#align nat.support_factorization Nat.support_factorization
theorem factor_iff_mem_factorization {n p : ℕ} : p ∈ n.factorization.support ↔ p ∈ n.factors := by
simp only [support_factorization, List.mem_toFinset]
#align nat.factor_iff_mem_factorization Nat.factor_iff_mem_factorization
theorem prime_of_mem_factorization {n p : ℕ} (hp : p ∈ n.factorization.support) : p.Prime :=
prime_of_mem_factors (factor_iff_mem_factorization.mp hp)
#align nat.prime_of_mem_factorization Nat.prime_of_mem_factorization
theorem pos_of_mem_factorization {n p : ℕ} (hp : p ∈ n.factorization.support) : 0 < p :=
Prime.pos (prime_of_mem_factorization hp)
#align nat.pos_of_mem_factorization Nat.pos_of_mem_factorization
theorem le_of_mem_factorization {n p : ℕ} (h : p ∈ n.factorization.support) : p ≤ n :=
le_of_mem_factors (factor_iff_mem_factorization.mp h)
#align nat.le_of_mem_factorization Nat.le_of_mem_factorization
/-! ## Lemmas characterising when `n.factorization p = 0` -/
theorem factorization_eq_zero_iff (n p : ℕ) :
n.factorization p = 0 ↔ ¬p.Prime ∨ ¬p ∣ n ∨ n = 0 := by
rw [← not_mem_support_iff, support_factorization, mem_toFinset]
rcases eq_or_ne n 0 with (rfl | hn)
· simp
· simp [hn, Nat.mem_factors, not_and_or, -not_and]
#align nat.factorization_eq_zero_iff Nat.factorization_eq_zero_iff
@[simp]
theorem factorization_eq_zero_of_non_prime (n : ℕ) {p : ℕ} (hp : ¬p.Prime) :
n.factorization p = 0 := by simp [factorization_eq_zero_iff, hp]
#align nat.factorization_eq_zero_of_non_prime Nat.factorization_eq_zero_of_non_prime
theorem factorization_eq_zero_of_not_dvd {n p : ℕ} (h : ¬p ∣ n) : n.factorization p = 0 := by
simp [factorization_eq_zero_iff, h]
#align nat.factorization_eq_zero_of_not_dvd Nat.factorization_eq_zero_of_not_dvd
theorem factorization_eq_zero_of_lt {n p : ℕ} (h : n < p) : n.factorization p = 0 :=
Finsupp.not_mem_support_iff.mp (mt le_of_mem_factorization (not_le_of_lt h))
#align nat.factorization_eq_zero_of_lt Nat.factorization_eq_zero_of_lt
@[simp]
theorem factorization_zero_right (n : ℕ) : n.factorization 0 = 0 :=
factorization_eq_zero_of_non_prime _ not_prime_zero
#align nat.factorization_zero_right Nat.factorization_zero_right
@[simp]
theorem factorization_one_right (n : ℕ) : n.factorization 1 = 0 :=
factorization_eq_zero_of_non_prime _ not_prime_one
#align nat.factorization_one_right Nat.factorization_one_right
theorem dvd_of_factorization_pos {n p : ℕ} (hn : n.factorization p ≠ 0) : p ∣ n :=
dvd_of_mem_factors (factor_iff_mem_factorization.1 (mem_support_iff.2 hn))
#align nat.dvd_of_factorization_pos Nat.dvd_of_factorization_pos
theorem Prime.factorization_pos_of_dvd {n p : ℕ} (hp : p.Prime) (hn : n ≠ 0) (h : p ∣ n) :
0 < n.factorization p := by rwa [← factors_count_eq, count_pos, mem_factors_iff_dvd hn hp]
#align nat.prime.factorization_pos_of_dvd Nat.Prime.factorization_pos_of_dvd
theorem factorization_eq_zero_of_remainder {p r : ℕ} (i : ℕ) (hr : ¬p ∣ r) :
(p * i + r).factorization p = 0 := by
apply factorization_eq_zero_of_not_dvd
rwa [← Nat.dvd_add_iff_right (Dvd.intro i rfl)]
#align nat.factorization_eq_zero_of_remainder Nat.factorization_eq_zero_of_remainder
theorem factorization_eq_zero_iff_remainder {p r : ℕ} (i : ℕ) (pp : p.Prime) (hr0 : r ≠ 0) :
¬p ∣ r ↔ (p * i + r).factorization p = 0 := by
refine' ⟨factorization_eq_zero_of_remainder i, fun h => _⟩
rw [factorization_eq_zero_iff] at h
contrapose! h
refine' ⟨pp, _, _⟩
· rwa [← Nat.dvd_add_iff_right (Dvd.intro i rfl)]
· contrapose! hr0
exact (_root_.add_eq_zero_iff.mp hr0).2
#align nat.factorization_eq_zero_iff_remainder Nat.factorization_eq_zero_iff_remainder
/-- The only numbers with empty prime factorization are `0` and `1` -/
theorem factorization_eq_zero_iff' (n : ℕ) : n.factorization = 0 ↔ n = 0 ∨ n = 1 := by
rw [factorization_eq_factors_multiset n]
simp [factorization, AddEquiv.map_eq_zero_iff, Multiset.coe_eq_zero]
#align nat.factorization_eq_zero_iff' Nat.factorization_eq_zero_iff'
/-! ## Lemmas about factorizations of products and powers -/
/-- For nonzero `a` and `b`, the power of `p` in `a * b` is the sum of the powers in `a` and `b` -/
@[simp]
theorem factorization_mul {a b : ℕ} (ha : a ≠ 0) (hb : b ≠ 0) :
(a * b).factorization = a.factorization + b.factorization := by
ext p
simp only [add_apply, ← factors_count_eq, perm_iff_count.mp (perm_factors_mul ha hb) p,
count_append]
#align nat.factorization_mul Nat.factorization_mul
theorem factorization_mul_support {a b : ℕ} (ha : a ≠ 0) (hb : b ≠ 0) :
(a * b).factorization.support = a.factorization.support ∪ b.factorization.support := by
ext q
simp only [Finset.mem_union, factor_iff_mem_factorization]
exact mem_factors_mul ha hb
#align nat.factorization_mul_support Nat.factorization_mul_support
/-- If a product over `n.factorization` doesn't use the multiplicities of the prime factors
then it's equal to the corresponding product over `n.factors.toFinset` -/
theorem prod_factorization_eq_prod_factors {n : ℕ} {β : Type _} [CommMonoid β] (f : ℕ → β) :
(n.factorization.prod fun p _ => f p) = ∏ p in n.factors.toFinset, f p := by
apply prod_congr support_factorization
simp
#align nat.prod_factorization_eq_prod_factors Nat.prod_factorization_eq_prod_factors
/-- For any `p : ℕ` and any function `g : α → ℕ` that's non-zero on `S : Finset α`,
the power of `p` in `S.prod g` equals the sum over `x ∈ S` of the powers of `p` in `g x`.
Generalises `factorization_mul`, which is the special case where `S.card = 2` and `g = id`. -/
theorem factorization_prod {α : Type _} {S : Finset α} {g : α → ℕ} (hS : ∀ x ∈ S, g x ≠ 0) :
(S.prod g).factorization = S.sum fun x => (g x).factorization := by
classical
ext p
refine' Finset.induction_on' S ?_ ?_
· simp
· intro x T hxS hTS hxT IH
have hT : T.prod g ≠ 0 := prod_ne_zero_iff.mpr fun x hx => hS x (hTS hx)
simp [prod_insert hxT, sum_insert hxT, ← IH, factorization_mul (hS x hxS) hT]
#align nat.factorization_prod Nat.factorization_prod
/-- For any `p`, the power of `p` in `n^k` is `k` times the power in `n` -/
@[simp]
theorem factorization_pow (n k : ℕ) : factorization (n ^ k) = k • n.factorization := by
induction' k with k ih; · simp
rcases eq_or_ne n 0 with (rfl | hn)
· simp
rw [pow_succ, mul_comm, factorization_mul hn (pow_ne_zero _ hn), ih, succ_eq_one_add, add_smul,
one_smul]
#align nat.factorization_pow Nat.factorization_pow
/-! ## Lemmas about factorizations of primes and prime powers -/
/-- The only prime factor of prime `p` is `p` itself, with multiplicity `1` -/
@[simp]
theorem Prime.factorization {p : ℕ} (hp : Prime p) : p.factorization = single p 1 := by
ext q
rw [← factors_count_eq, factors_prime hp, single_apply, count_singleton', if_congr eq_comm] <;>
rfl
#align nat.prime.factorization Nat.Prime.factorization
/-- The multiplicity of prime `p` in `p` is `1` -/
@[simp]
theorem Prime.factorization_self {p : ℕ} (hp : Prime p) : p.factorization p = 1 := by simp [hp]
#align nat.prime.factorization_self Nat.Prime.factorization_self
/-- For prime `p` the only prime factor of `p^k` is `p` with multiplicity `k` -/
theorem Prime.factorization_pow {p k : ℕ} (hp : Prime p) : (p ^ k).factorization = single p k := by
simp [hp]
#align nat.prime.factorization_pow Nat.Prime.factorization_pow
/-- If the factorization of `n` contains just one number `p` then `n` is a power of `p` -/
theorem eq_pow_of_factorization_eq_single {n p k : ℕ} (hn : n ≠ 0)
(h : n.factorization = Finsupp.single p k) : n = p ^ k := by
-- Porting note: explicitly added `Finsupp.prod_single_index`
rw [← Nat.factorization_prod_pow_eq_self hn, h, Finsupp.prod_single_index]
simp
#align nat.eq_pow_of_factorization_eq_single Nat.eq_pow_of_factorization_eq_single
/-- The only prime factor of prime `p` is `p` itself. -/
theorem Prime.eq_of_factorization_pos {p q : ℕ} (hp : Prime p) (h : p.factorization q ≠ 0) :
p = q := by simpa [hp.factorization, single_apply] using h
#align nat.prime.eq_of_factorization_pos Nat.Prime.eq_of_factorization_pos
/-! ### Equivalence between `ℕ+` and `ℕ →₀ ℕ` with support in the primes. -/
/-- Any Finsupp `f : ℕ →₀ ℕ` whose support is in the primes is equal to the factorization of
the product `∏ (a : ℕ) in f.support, a ^ f a`. -/
theorem prod_pow_factorization_eq_self {f : ℕ →₀ ℕ} (hf : ∀ p : ℕ, p ∈ f.support → Prime p) :
(f.prod (· ^ ·)).factorization = f := by
have h : ∀ x : ℕ, x ∈ f.support → x ^ f x ≠ 0 := fun p hp =>
pow_ne_zero _ (Prime.ne_zero (hf p hp))
simp only [Finsupp.prod, factorization_prod h]
conv =>
rhs
rw [(sum_single f).symm]
exact sum_congr rfl fun p hp => Prime.factorization_pow (hf p hp)
#align nat.prod_pow_factorization_eq_self Nat.prod_pow_factorization_eq_self
theorem eq_factorization_iff {n : ℕ} {f : ℕ →₀ ℕ} (hn : n ≠ 0) (hf : ∀ p ∈ f.support, Prime p) :
f = n.factorization ↔ f.prod (· ^ ·) = n :=
⟨fun h => by rw [h, factorization_prod_pow_eq_self hn], fun h => by
rw [← h, prod_pow_factorization_eq_self hf]⟩
#align nat.eq_factorization_iff Nat.eq_factorization_iff
/-- The equiv between `ℕ+` and `ℕ →₀ ℕ` with support in the primes. -/
def factorizationEquiv : ℕ+ ≃ { f : ℕ →₀ ℕ | ∀ p ∈ f.support, Prime p } where
toFun := fun ⟨n, _⟩ => ⟨n.factorization, fun _ => prime_of_mem_factorization⟩
invFun := fun ⟨f, hf⟩ =>
⟨f.prod _, prod_pow_pos_of_zero_not_mem_support fun H => not_prime_zero (hf 0 H)⟩
left_inv := fun ⟨_, hx⟩ => Subtype.ext <| factorization_prod_pow_eq_self hx.ne.symm
right_inv := fun ⟨_, hf⟩ => Subtype.ext <| prod_pow_factorization_eq_self hf
#align nat.factorization_equiv Nat.factorizationEquiv
theorem factorizationEquiv_apply (n : ℕ+) : (factorizationEquiv n).1 = n.1.factorization := by
cases n
rfl
#align nat.factorization_equiv_apply Nat.factorizationEquiv_apply
theorem factorizationEquiv_inv_apply {f : ℕ →₀ ℕ} (hf : ∀ p ∈ f.support, Prime p) :
(factorizationEquiv.symm ⟨f, hf⟩).1 = f.prod (· ^ ·) :=
rfl
#align nat.factorization_equiv_inv_apply Nat.factorizationEquiv_inv_apply
/-! ### Generalisation of the "even part" and "odd part" of a natural number
We introduce the notations `ord_proj[p] n` for the largest power of the prime `p` that
divides `n` and `ord_compl[p] n` for the complementary part. The `ord` naming comes from
the $p$-adic order/valuation of a number, and `proj` and `compl` are for the projection and
complementary projection. The term `n.factorization p` is the $p$-adic order itself.
For example, `ord_proj[2] n` is the even part of `n` and `ord_compl[2] n` is the odd part. -/
-- mathport name: «exprord_proj[ ] »
-- porting note: Lean 4 thinks we need `HPow` without this
set_option quotPrecheck false in
notation "ord_proj[" p "] " n:arg => p ^ Nat.factorization n p
-- mathport name: «exprord_compl[ ] »
notation "ord_compl[" p "] " n:arg => n / ord_proj[p] n
@[simp]
theorem ord_proj_of_not_prime (n p : ℕ) (hp : ¬p.Prime) : ord_proj[p] n = 1 := by
simp [factorization_eq_zero_of_non_prime n hp]
#align nat.ord_proj_of_not_prime Nat.ord_proj_of_not_prime
@[simp]
theorem ord_compl_of_not_prime (n p : ℕ) (hp : ¬p.Prime) : ord_compl[p] n = n := by
simp [factorization_eq_zero_of_non_prime n hp]
#align nat.ord_compl_of_not_prime Nat.ord_compl_of_not_prime
theorem ord_proj_dvd (n p : ℕ) : ord_proj[p] n ∣ n := by
by_cases hp : p.Prime; swap; · simp [hp]
rw [← factors_count_eq]
apply dvd_of_factors_subperm (pow_ne_zero _ hp.ne_zero)
rw [hp.factors_pow, List.subperm_ext_iff]
intro q hq
simp [List.eq_of_mem_replicate hq]
#align nat.ord_proj_dvd Nat.ord_proj_dvd
theorem ord_compl_dvd (n p : ℕ) : ord_compl[p] n ∣ n :=
div_dvd_of_dvd (ord_proj_dvd n p)
#align nat.ord_compl_dvd Nat.ord_compl_dvd
theorem ord_proj_pos (n p : ℕ) : 0 < ord_proj[p] n := by
by_cases pp : p.Prime
· simp [pow_pos pp.pos]
· simp [pp]
#align nat.ord_proj_pos Nat.ord_proj_pos
theorem ord_proj_le {n : ℕ} (p : ℕ) (hn : n ≠ 0) : ord_proj[p] n ≤ n :=
le_of_dvd hn.bot_lt (Nat.ord_proj_dvd n p)
#align nat.ord_proj_le Nat.ord_proj_le
theorem ord_compl_pos {n : ℕ} (p : ℕ) (hn : n ≠ 0) : 0 < ord_compl[p] n := by
cases' em' p.Prime with pp pp
· simpa [Nat.factorization_eq_zero_of_non_prime n pp] using hn.bot_lt
exact Nat.div_pos (ord_proj_le p hn) (ord_proj_pos n p)
#align nat.ord_compl_pos Nat.ord_compl_pos
theorem ord_compl_le (n p : ℕ) : ord_compl[p] n ≤ n :=
Nat.div_le_self _ _
#align nat.ord_compl_le Nat.ord_compl_le
theorem ord_proj_mul_ord_compl_eq_self (n p : ℕ) : ord_proj[p] n * ord_compl[p] n = n :=
Nat.mul_div_cancel' (ord_proj_dvd n p)
#align nat.ord_proj_mul_ord_compl_eq_self Nat.ord_proj_mul_ord_compl_eq_self
theorem ord_proj_mul {a b : ℕ} (p : ℕ) (ha : a ≠ 0) (hb : b ≠ 0) :
ord_proj[p] (a * b) = ord_proj[p] a * ord_proj[p] b := by
simp [factorization_mul ha hb, pow_add]
#align nat.ord_proj_mul Nat.ord_proj_mul
theorem ord_compl_mul (a b p : ℕ) : ord_compl[p] (a * b) = ord_compl[p] a * ord_compl[p] b := by
rcases eq_or_ne a 0 with (rfl | ha); · simp
rcases eq_or_ne b 0 with (rfl | hb); · simp
simp only [ord_proj_mul p ha hb]
rw [mul_div_mul_comm_of_dvd_dvd (ord_proj_dvd a p) (ord_proj_dvd b p)]
#align nat.ord_compl_mul Nat.ord_compl_mul
/-! ### Factorization and divisibility -/
theorem dvd_of_mem_factorization {n p : ℕ} (h : p ∈ n.factorization.support) : p ∣ n := by
rcases eq_or_ne n 0 with (rfl | hn); · simp
simp [← mem_factors_iff_dvd hn (prime_of_mem_factorization h), factor_iff_mem_factorization.mp h]
#align nat.dvd_of_mem_factorization Nat.dvd_of_mem_factorization
/-- A crude upper bound on `n.factorization p` -/
theorem factorization_lt {n : ℕ} (p : ℕ) (hn : n ≠ 0) : n.factorization p < n := by
by_cases pp : p.Prime; swap;
· simp [factorization_eq_zero_of_non_prime n pp]
exact hn.bot_lt
rw [← pow_lt_iff_lt_right pp.two_le]
apply lt_of_le_of_lt (ord_proj_le p hn)
exact lt_of_lt_of_le (lt_two_pow n) (pow_le_pow_of_le_left pp.two_le n)
#align nat.factorization_lt Nat.factorization_lt
/-- An upper bound on `n.factorization p` -/
theorem factorization_le_of_le_pow {n p b : ℕ} (hb : n ≤ p ^ b) : n.factorization p ≤ b := by
rcases eq_or_ne n 0 with (rfl | hn); · simp
by_cases pp : p.Prime
· exact (pow_le_iff_le_right pp.two_le).1 (le_trans (ord_proj_le p hn) hb)
· simp [factorization_eq_zero_of_non_prime n pp]
#align nat.factorization_le_of_le_pow Nat.factorization_le_of_le_pow
theorem factorization_le_iff_dvd {d n : ℕ} (hd : d ≠ 0) (hn : n ≠ 0) :
d.factorization ≤ n.factorization ↔ d ∣ n := by
constructor
· intro hdn
set K := n.factorization - d.factorization with hK
use K.prod (· ^ ·)
rw [← factorization_prod_pow_eq_self hn, ← factorization_prod_pow_eq_self hd,
←Finsupp.prod_add_index' pow_zero pow_add, hK, add_tsub_cancel_of_le hdn]
· rintro ⟨c, rfl⟩
rw [factorization_mul hd (right_ne_zero_of_mul hn)]
simp
#align nat.factorization_le_iff_dvd Nat.factorization_le_iff_dvd
theorem factorization_prime_le_iff_dvd {d n : ℕ} (hd : d ≠ 0) (hn : n ≠ 0) :
(∀ p : ℕ, p.Prime → d.factorization p ≤ n.factorization p) ↔ d ∣ n := by
rw [← factorization_le_iff_dvd hd hn]
refine' ⟨fun h p => (em p.Prime).elim (h p) fun hp => _, fun h p _ => h p⟩
simp_rw [factorization_eq_zero_of_non_prime _ hp, le_refl]
#align nat.factorization_prime_le_iff_dvd Nat.factorization_prime_le_iff_dvd
theorem pow_succ_factorization_not_dvd {n p : ℕ} (hn : n ≠ 0) (hp : p.Prime) :
¬p ^ (n.factorization p + 1) ∣ n := by
intro h
rw [← factorization_le_iff_dvd (pow_pos hp.pos _).ne' hn] at h
simpa [hp.factorization] using h p
#align nat.pow_succ_factorization_not_dvd Nat.pow_succ_factorization_not_dvd
theorem factorization_le_factorization_mul_left {a b : ℕ} (hb : b ≠ 0) :
a.factorization ≤ (a * b).factorization := by
rcases eq_or_ne a 0 with (rfl | ha); · simp
rw [factorization_le_iff_dvd ha <| mul_ne_zero ha hb]
exact Dvd.intro b rfl
#align nat.factorization_le_factorization_mul_left Nat.factorization_le_factorization_mul_left
theorem factorization_le_factorization_mul_right {a b : ℕ} (ha : a ≠ 0) :
b.factorization ≤ (a * b).factorization := by
rw [mul_comm]
apply factorization_le_factorization_mul_left ha
#align nat.factorization_le_factorization_mul_right Nat.factorization_le_factorization_mul_right
theorem Prime.pow_dvd_iff_le_factorization {p k n : ℕ} (pp : Prime p) (hn : n ≠ 0) :
p ^ k ∣ n ↔ k ≤ n.factorization p := by
rw [← factorization_le_iff_dvd (pow_pos pp.pos k).ne' hn, pp.factorization_pow, single_le_iff]
#align nat.prime.pow_dvd_iff_le_factorization Nat.Prime.pow_dvd_iff_le_factorization
theorem Prime.pow_dvd_iff_dvd_ord_proj {p k n : ℕ} (pp : Prime p) (hn : n ≠ 0) :
p ^ k ∣ n ↔ p ^ k ∣ ord_proj[p] n := by
rw [pow_dvd_pow_iff_le_right pp.one_lt, pp.pow_dvd_iff_le_factorization hn]
#align nat.prime.pow_dvd_iff_dvd_ord_proj Nat.Prime.pow_dvd_iff_dvd_ord_proj
theorem Prime.dvd_iff_one_le_factorization {p n : ℕ} (pp : Prime p) (hn : n ≠ 0) :
p ∣ n ↔ 1 ≤ n.factorization p :=
Iff.trans (by simp) (pp.pow_dvd_iff_le_factorization hn)
#align nat.prime.dvd_iff_one_le_factorization Nat.Prime.dvd_iff_one_le_factorization
theorem exists_factorization_lt_of_lt {a b : ℕ} (ha : a ≠ 0) (hab : a < b) :
∃ p : ℕ, a.factorization p < b.factorization p := by
have hb : b ≠ 0 := (ha.bot_lt.trans hab).ne'
contrapose! hab
-- Porting note: `push_neg` fails to push the negation
simp_rw [not_exists, not_lt] at hab
rw [← Finsupp.le_def, factorization_le_iff_dvd hb ha] at hab
exact le_of_dvd ha.bot_lt hab
#align nat.exists_factorization_lt_of_lt Nat.exists_factorization_lt_of_lt
@[simp]
theorem factorization_div {d n : ℕ} (h : d ∣ n) :
(n / d).factorization = n.factorization - d.factorization := by
rcases eq_or_ne d 0 with (rfl | hd); · simp [zero_dvd_iff.mp h]
rcases eq_or_ne n 0 with (rfl | hn); · simp
apply add_left_injective d.factorization
simp only
rw [tsub_add_cancel_of_le <| (Nat.factorization_le_iff_dvd hd hn).mpr h, ←
Nat.factorization_mul (Nat.div_pos (Nat.le_of_dvd hn.bot_lt h) hd.bot_lt).ne' hd,
Nat.div_mul_cancel h]
#align nat.factorization_div Nat.factorization_div
theorem dvd_ord_proj_of_dvd {n p : ℕ} (hn : n ≠ 0) (pp : p.Prime) (h : p ∣ n) : p ∣ ord_proj[p] n :=
dvd_pow_self p (Prime.factorization_pos_of_dvd pp hn h).ne'
#align nat.dvd_ord_proj_of_dvd Nat.dvd_ord_proj_of_dvd
theorem not_dvd_ord_compl {n p : ℕ} (hp : Prime p) (hn : n ≠ 0) : ¬p ∣ ord_compl[p] n := by
rw [Nat.Prime.dvd_iff_one_le_factorization hp (ord_compl_pos p hn).ne']
rw [Nat.factorization_div (Nat.ord_proj_dvd n p)]
simp [hp.factorization]
#align nat.not_dvd_ord_compl Nat.not_dvd_ord_compl
theorem coprime_ord_compl {n p : ℕ} (hp : Prime p) (hn : n ≠ 0) : coprime p (ord_compl[p] n) :=
(or_iff_left (not_dvd_ord_compl hp hn)).mp <| coprime_or_dvd_of_prime hp _
#align nat.coprime_ord_compl Nat.coprime_ord_compl
theorem factorization_ord_compl (n p : ℕ) :
(ord_compl[p] n).factorization = n.factorization.erase p := by
rcases eq_or_ne n 0 with (rfl | hn); · simp
by_cases pp : p.Prime
case neg =>
-- porting note: needed to solve side goal explicitly
rw [Finsupp.erase_of_not_mem_support]
· simp [pp]
· simp [mt prime_of_mem_factors pp]
ext q
rcases eq_or_ne q p with (rfl | hqp)
· simp only [Finsupp.erase_same, factorization_eq_zero_iff, not_dvd_ord_compl pp hn]
simp
· rw [Finsupp.erase_ne hqp, factorization_div (ord_proj_dvd n p)]
simp [pp.factorization, hqp.symm]
#align nat.factorization_ord_compl Nat.factorization_ord_compl
-- `ord_compl[p] n` is the largest divisor of `n` not divisible by `p`.
theorem dvd_ord_compl_of_dvd_not_dvd {p d n : ℕ} (hdn : d ∣ n) (hpd : ¬p ∣ d) :
d ∣ ord_compl[p] n := by
rcases eq_or_ne n 0 with (rfl | hn0); · simp
rcases eq_or_ne d 0 with (rfl | hd0);
· simp at hpd
rw [← factorization_le_iff_dvd hd0 (ord_compl_pos p hn0).ne', factorization_ord_compl]
intro q
rcases eq_or_ne q p with (rfl | hqp)
· simp [factorization_eq_zero_iff, hpd]
· simp [hqp, (factorization_le_iff_dvd hd0 hn0).2 hdn q]
#align nat.dvd_ord_compl_of_dvd_not_dvd Nat.dvd_ord_compl_of_dvd_not_dvd
/-- If `n` is a nonzero natural number and `p ≠ 1`, then there are natural numbers `e`
and `n'` such that `n'` is not divisible by `p` and `n = p^e * n'`. -/
theorem exists_eq_pow_mul_and_not_dvd {n : ℕ} (hn : n ≠ 0) (p : ℕ) (hp : p ≠ 1) :
∃ e n' : ℕ, ¬p ∣ n' ∧ n = p ^ e * n' :=
let ⟨a', h₁, h₂⟩ :=
multiplicity.exists_eq_pow_mul_and_not_dvd
(multiplicity.finite_nat_iff.mpr ⟨hp, Nat.pos_of_ne_zero hn⟩)
⟨_, a', h₂, h₁⟩
#align nat.exists_eq_pow_mul_and_not_dvd Nat.exists_eq_pow_mul_and_not_dvd
theorem dvd_iff_div_factorization_eq_tsub {d n : ℕ} (hd : d ≠ 0) (hdn : d ≤ n) :
d ∣ n ↔ (n / d).factorization = n.factorization - d.factorization := by
refine' ⟨factorization_div, _⟩
rcases eq_or_lt_of_le hdn with (rfl | hd_lt_n); · simp
have h1 : n / d ≠ 0 := fun H => Nat.lt_asymm hd_lt_n ((Nat.div_eq_zero_iff hd.bot_lt).mp H)
intro h
rw [dvd_iff_le_div_mul n d]
by_contra h2
cases' exists_factorization_lt_of_lt (mul_ne_zero h1 hd) (not_le.mp h2) with p hp
rwa [factorization_mul h1 hd, add_apply, ← lt_tsub_iff_right, h, tsub_apply,
lt_self_iff_false] at hp
#align nat.dvd_iff_div_factorization_eq_tsub Nat.dvd_iff_div_factorization_eq_tsub
theorem ord_proj_dvd_ord_proj_of_dvd {a b : ℕ} (hb0 : b ≠ 0) (hab : a ∣ b) (p : ℕ) :
ord_proj[p] a ∣ ord_proj[p] b := by
rcases em' p.Prime with (pp | pp); · simp [pp]
rcases eq_or_ne a 0 with (rfl | ha0); · simp
rw [pow_dvd_pow_iff_le_right pp.one_lt]
exact (factorization_le_iff_dvd ha0 hb0).2 hab p
#align nat.ord_proj_dvd_ord_proj_of_dvd Nat.ord_proj_dvd_ord_proj_of_dvd
theorem ord_proj_dvd_ord_proj_iff_dvd {a b : ℕ} (ha0 : a ≠ 0) (hb0 : b ≠ 0) :
(∀ p : ℕ, ord_proj[p] a ∣ ord_proj[p] b) ↔ a ∣ b := by
refine' ⟨fun h => _, fun hab p => ord_proj_dvd_ord_proj_of_dvd hb0 hab p⟩
rw [← factorization_le_iff_dvd ha0 hb0]
intro q
rcases le_or_lt q 1 with (hq_le | hq1)
· interval_cases q <;> simp
exact (pow_dvd_pow_iff_le_right hq1).1 (h q)
#align nat.ord_proj_dvd_ord_proj_iff_dvd Nat.ord_proj_dvd_ord_proj_iff_dvd
theorem ord_compl_dvd_ord_compl_of_dvd {a b : ℕ} (hab : a ∣ b) (p : ℕ) :
ord_compl[p] a ∣ ord_compl[p] b := by
rcases em' p.Prime with (pp | pp); · simp [pp, hab]
rcases eq_or_ne b 0 with (rfl | hb0); · simp
rcases eq_or_ne a 0 with (rfl | ha0); · cases hb0 (zero_dvd_iff.1 hab)
have ha := (Nat.div_pos (ord_proj_le p ha0) (ord_proj_pos a p)).ne'
have hb := (Nat.div_pos (ord_proj_le p hb0) (ord_proj_pos b p)).ne'
rw [← factorization_le_iff_dvd ha hb, factorization_ord_compl a p, factorization_ord_compl b p]
intro q
rcases eq_or_ne q p with (rfl | hqp); · simp
simp_rw [erase_ne hqp]
exact (factorization_le_iff_dvd ha0 hb0).2 hab q
#align nat.ord_compl_dvd_ord_compl_of_dvd Nat.ord_compl_dvd_ord_compl_of_dvd
theorem ord_compl_dvd_ord_compl_iff_dvd (a b : ℕ) :
(∀ p : ℕ, ord_compl[p] a ∣ ord_compl[p] b) ↔ a ∣ b := by
refine' ⟨fun h => _, fun hab p => ord_compl_dvd_ord_compl_of_dvd hab p⟩
rcases eq_or_ne b 0 with (rfl | hb0); · simp
by_cases pa : a.Prime; swap; · simpa [pa] using h a
by_cases pb : b.Prime; swap; · simpa [pb] using h b
rw [prime_dvd_prime_iff_eq pa pb]
by_contra hab
apply pa.ne_one
rw [← Nat.dvd_one, ← Nat.mul_dvd_mul_iff_left hb0.bot_lt, mul_one]
simpa [Prime.factorization_self pb, Prime.factorization pa, hab] using h b
#align nat.ord_compl_dvd_ord_compl_iff_dvd Nat.ord_compl_dvd_ord_compl_iff_dvd
theorem dvd_iff_prime_pow_dvd_dvd (n d : ℕ) :
d ∣ n ↔ ∀ p k : ℕ, Prime p → p ^ k ∣ d → p ^ k ∣ n := by
rcases eq_or_ne n 0 with (rfl | hn); · simp
rcases eq_or_ne d 0 with (rfl | hd)
· simp only [zero_dvd_iff, hn, false_iff_iff, not_forall]
exact ⟨2, n, prime_two, dvd_zero _, mt (le_of_dvd hn.bot_lt) (lt_two_pow n).not_le⟩
refine' ⟨fun h p k _ hpkd => dvd_trans hpkd h, _⟩
rw [← factorization_prime_le_iff_dvd hd hn]
intro h p pp
simp_rw [← pp.pow_dvd_iff_le_factorization hn]
exact h p _ pp (ord_proj_dvd _ _)
#align nat.dvd_iff_prime_pow_dvd_dvd Nat.dvd_iff_prime_pow_dvd_dvd
theorem prod_prime_factors_dvd (n : ℕ) : (∏ p : ℕ in n.factors.toFinset, p) ∣ n := by
by_cases hn : n = 0;
· subst hn
simp
simpa [prod_factors hn] using Multiset.toFinset_prod_dvd_prod (n.factors : Multiset ℕ)
#align nat.prod_prime_factors_dvd Nat.prod_prime_factors_dvd
theorem factorization_gcd {a b : ℕ} (ha_pos : a ≠ 0) (hb_pos : b ≠ 0) :
(gcd a b).factorization = a.factorization ⊓ b.factorization := by
let dfac := a.factorization ⊓ b.factorization
let d := dfac.prod Nat.pow
have dfac_prime : ∀ p : ℕ, p ∈ dfac.support → Prime p := by
intro p hp
have : p ∈ a.factors ∧ p ∈ b.factors := by simpa using hp
exact prime_of_mem_factors this.1
have h1 : d.factorization = dfac := prod_pow_factorization_eq_self dfac_prime
have hd_pos : d ≠ 0 := (factorizationEquiv.invFun ⟨dfac, dfac_prime⟩).2.ne.symm
suffices d = gcd a b by rwa [← this]
apply gcd_greatest
· rw [← factorization_le_iff_dvd hd_pos ha_pos, h1]
exact inf_le_left
· rw [← factorization_le_iff_dvd hd_pos hb_pos, h1]
exact inf_le_right
· intro e hea heb
rcases Decidable.eq_or_ne e 0 with (rfl | he_pos)
· simp only [zero_dvd_iff] at hea
contradiction
have hea' := (factorization_le_iff_dvd he_pos ha_pos).mpr hea
have heb' := (factorization_le_iff_dvd he_pos hb_pos).mpr heb
simp [← factorization_le_iff_dvd he_pos hd_pos, h1, hea', heb']
#align nat.factorization_gcd Nat.factorization_gcd
theorem factorization_lcm {a b : ℕ} (ha : a ≠ 0) (hb : b ≠ 0) :
(a.lcm b).factorization = a.factorization ⊔ b.factorization := by
rw [← add_right_inj (a.gcd b).factorization, ←
factorization_mul (mt gcd_eq_zero_iff.1 fun h => ha h.1) (lcm_ne_zero ha hb), gcd_mul_lcm,
factorization_gcd ha hb, factorization_mul ha hb]
ext1; exact (min_add_max _ _).symm
#align nat.factorization_lcm Nat.factorization_lcm
@[to_additive sum_factors_gcd_add_sum_factors_mul]
theorem prod_factors_gcd_mul_prod_factors_mul {β : Type _} [CommMonoid β] (m n : ℕ) (f : ℕ → β) :
(m.gcd n).factors.toFinset.prod f * (m * n).factors.toFinset.prod f =
m.factors.toFinset.prod f * n.factors.toFinset.prod f := by
rcases eq_or_ne n 0 with (rfl | hm0); · simp
rcases eq_or_ne m 0 with (rfl | hn0); · simp
rw [← @Finset.prod_union_inter _ _ m.factors.toFinset n.factors.toFinset, mul_comm]
congr
· apply factors_mul_toFinset <;> assumption
· simp only [← support_factorization, factorization_gcd hn0 hm0, Finsupp.support_inf]
#align nat.prod_factors_gcd_mul_prod_factors_mul Nat.prod_factors_gcd_mul_prod_factors_mul
#align nat.sum_factors_gcd_add_sum_factors_mul Nat.sum_factors_gcd_add_sum_factors_mul
theorem setOf_pow_dvd_eq_Icc_factorization {n p : ℕ} (pp : p.Prime) (hn : n ≠ 0) :
{ i : ℕ | i ≠ 0 ∧ p ^ i ∣ n } = Set.Icc 1 (n.factorization p) := by
ext
simp [lt_succ_iff, one_le_iff_ne_zero, pp.pow_dvd_iff_le_factorization hn]
#align nat.set_of_pow_dvd_eq_Icc_factorization Nat.setOf_pow_dvd_eq_Icc_factorization
/-- The set of positive powers of prime `p` that divide `n` is exactly the set of
positive natural numbers up to `n.factorization p`. -/
theorem Icc_factorization_eq_pow_dvd (n : ℕ) {p : ℕ} (pp : Prime p) :
Icc 1 (n.factorization p) = (Ico 1 n).filter fun i : ℕ => p ^ i ∣ n := by
rcases eq_or_ne n 0 with (rfl | hn); · simp
ext x
simp only [mem_Icc, Finset.mem_filter, mem_Ico, and_assoc, and_congr_right_iff,
pp.pow_dvd_iff_le_factorization hn, iff_and_self]
exact fun _ H => lt_of_le_of_lt H (factorization_lt p hn)
#align nat.Icc_factorization_eq_pow_dvd Nat.Icc_factorization_eq_pow_dvd
theorem factorization_eq_card_pow_dvd (n : ℕ) {p : ℕ} (pp : p.Prime) :
n.factorization p = ((Ico 1 n).filter fun i => p ^ i ∣ n).card := by
simp [← Icc_factorization_eq_pow_dvd n pp]
#align nat.factorization_eq_card_pow_dvd Nat.factorization_eq_card_pow_dvd
theorem Ico_filter_pow_dvd_eq {n p b : ℕ} (pp : p.Prime) (hn : n ≠ 0) (hb : n ≤ p ^ b) :
((Ico 1 n).filter fun i => p ^ i ∣ n) = (Icc 1 b).filter fun i => p ^ i ∣ n := by
ext x
simp only [Finset.mem_filter, mem_Ico, mem_Icc, and_congr_left_iff, and_congr_right_iff]
rintro h1 -
simp [lt_of_pow_dvd_right hn pp.two_le h1,
(pow_le_iff_le_right pp.two_le).1 ((le_of_dvd hn.bot_lt h1).trans hb)]
#align nat.Ico_filter_pow_dvd_eq Nat.Ico_filter_pow_dvd_eq
/-! ### Factorization and coprimes -/
/-- For coprime `a` and `b`, the power of `p` in `a * b` is the sum of the powers in `a` and `b` -/
theorem factorization_mul_apply_of_coprime {p a b : ℕ} (hab : coprime a b) :
(a * b).factorization p = a.factorization p + b.factorization p := by
simp only [← factors_count_eq, perm_iff_count.mp (perm_factors_mul_of_coprime hab), count_append]
#align nat.factorization_mul_apply_of_coprime Nat.factorization_mul_apply_of_coprime
/-- For coprime `a` and `b`, the power of `p` in `a * b` is the sum of the powers in `a` and `b` -/
theorem factorization_mul_of_coprime {a b : ℕ} (hab : coprime a b) :
(a * b).factorization = a.factorization + b.factorization := by
ext q
rw [Finsupp.add_apply, factorization_mul_apply_of_coprime hab]
#align nat.factorization_mul_of_coprime Nat.factorization_mul_of_coprime
/-- If `p` is a prime factor of `a` then the power of `p` in `a` is the same that in `a * b`,
for any `b` coprime to `a`. -/
theorem factorization_eq_of_coprime_left {p a b : ℕ} (hab : coprime a b) (hpa : p ∈ a.factors) :
(a * b).factorization p = a.factorization p := by
rw [factorization_mul_apply_of_coprime hab, ← factors_count_eq, ← factors_count_eq,
count_eq_zero_of_not_mem (coprime_factors_disjoint hab hpa), add_zero]
#align nat.factorization_eq_of_coprime_left Nat.factorization_eq_of_coprime_left
/-- If `p` is a prime factor of `b` then the power of `p` in `b` is the same that in `a * b`,
for any `a` coprime to `b`. -/
theorem factorization_eq_of_coprime_right {p a b : ℕ} (hab : coprime a b) (hpb : p ∈ b.factors) :
(a * b).factorization p = b.factorization p := by
rw [mul_comm]
exact factorization_eq_of_coprime_left (coprime_comm.mp hab) hpb
#align nat.factorization_eq_of_coprime_right Nat.factorization_eq_of_coprime_right
/-- The prime factorizations of coprime `a` and `b` are disjoint -/
theorem factorization_disjoint_of_coprime {a b : ℕ} (hab : coprime a b) :
Disjoint a.factorization.support b.factorization.support := by
simpa only [support_factorization] using
disjoint_toFinset_iff_disjoint.mpr (coprime_factors_disjoint hab)
#align nat.factorization_disjoint_of_coprime Nat.factorization_disjoint_of_coprime
/-- For coprime `a` and `b` the prime factorization `a * b` is the union of those of `a` and `b` -/
theorem factorization_mul_support_of_coprime {a b : ℕ} (hab : coprime a b) :
(a * b).factorization.support = a.factorization.support ∪ b.factorization.support := by
rw [factorization_mul_of_coprime hab]
exact support_add_eq (factorization_disjoint_of_coprime hab)
#align nat.factorization_mul_support_of_coprime Nat.factorization_mul_support_of_coprime
/-! ### Induction principles involving factorizations -/
/-- Given `P 0, P 1` and a way to extend `P a` to `P (p ^ n * a)` for prime `p` not dividing `a`,
we can define `P` for all natural numbers. -/
@[elab_as_elim]
def recOnPrimePow {P : ℕ → Sort _} (h0 : P 0) (h1 : P 1)
(h : ∀ a p n : ℕ, p.Prime → ¬p ∣ a → 0 < n → P a → P (p ^ n * a)) : ∀ a : ℕ, P a := fun a =>
Nat.strong_rec_on a fun n =>
match n with
| 0 => fun _ => h0
| 1 => fun _ => h1
| k + 2 => fun hk => by
let p := (k + 2).minFac
have hp : Prime p := minFac_prime (succ_succ_ne_one k)
-- the awkward `let` stuff here is because `factorization` is noncomputable (Finsupp);
-- we get around this by using the computable `factors.count`, and rewriting when we want
-- to use the `factorization` API
let t := (k + 2).factors.count p
have ht : t = (k + 2).factorization p := factors_count_eq
have hpt : p ^ t ∣ k + 2 := by
rw [ht]
exact ord_proj_dvd _ _
have htp : 0 < t := by
rw [ht]
exact hp.factorization_pos_of_dvd (Nat.succ_ne_zero _) (minFac_dvd _)
convert h ((k + 2) / p ^ t) p t hp _ _ _ using 1
· rw [Nat.mul_div_cancel' hpt]
· rw [Nat.dvd_div_iff hpt, ← pow_succ, ht]
exact pow_succ_factorization_not_dvd (k + 1).succ_ne_zero hp
· exact htp
· apply hk _ (Nat.div_lt_of_lt_mul _)
rw [lt_mul_iff_one_lt_left Nat.succ_pos', one_lt_pow_iff htp.ne]
exact hp.one_lt
-- Porting note: was
-- simp [lt_mul_iff_one_lt_left Nat.succ_pos', one_lt_pow_iff htp.ne, hp.one_lt]
#align nat.rec_on_prime_pow Nat.recOnPrimePow
/-- Given `P 0`, `P 1`, and `P (p ^ n)` for positive prime powers, and a way to extend `P a` and
`P b` to `P (a * b)` when `a, b` are positive coprime, we can define `P` for all natural numbers. -/
@[elab_as_elim]
def recOnPosPrimePosCoprime {P : ℕ → Sort _} (hp : ∀ p n : ℕ, Prime p → 0 < n → P (p ^ n))
(h0 : P 0) (h1 : P 1) (h : ∀ a b, 1 < a → 1 < b → coprime a b → P a → P b → P (a * b)) :
∀ a, P a :=
recOnPrimePow h0 h1 <| by
intro a p n hp' hpa hn hPa
by_cases ha1 : a = 1
· rw [ha1, mul_one]
exact hp p n hp' hn
refine' h (p ^ n) a (hp'.one_lt.trans_le (le_self_pow hn.ne' _)) _ _ (hp _ _ hp' hn) hPa
· contrapose! hpa
simp [lt_one_iff.1 (lt_of_le_of_ne hpa ha1)]
simpa [hn, Prime.coprime_iff_not_dvd hp']
#align nat.rec_on_pos_prime_pos_coprime Nat.recOnPosPrimePosCoprime
/-- Given `P 0`, `P (p ^ n)` for all prime powers, and a way to extend `P a` and `P b` to
`P (a * b)` when `a, b` are positive coprime, we can define `P` for all natural numbers. -/
@[elab_as_elim]
def recOnPrimeCoprime {P : ℕ → Sort _} (h0 : P 0) (hp : ∀ p n : ℕ, Prime p → P (p ^ n))
(h : ∀ a b, 1 < a → 1 < b → coprime a b → P a → P b → P (a * b)) : ∀ a, P a :=
recOnPosPrimePosCoprime (fun p n h _ => hp p n h) h0 (hp 2 0 prime_two) h
#align nat.rec_on_prime_coprime Nat.recOnPrimeCoprime
/-- Given `P 0`, `P 1`, `P p` for all primes, and a way to extend `P a` and `P b` to
`P (a * b)`, we can define `P` for all natural numbers. -/
@[elab_as_elim]
noncomputable def recOnMul {P : ℕ → Sort _} (h0 : P 0) (h1 : P 1) (hp : ∀ p, Prime p → P p)
(h : ∀ a b, P a → P b → P (a * b)) : ∀ a, P a :=
let hp : ∀ p n : ℕ, Prime p → P (p ^ n) := fun p n hp' =>
n.recOn h1 (fun n hn => by rw [pow_succ]; apply h _ _ hn (hp p hp'))
-- Porting note: was
-- match n with
-- | 0 => h1
-- | n + 1 => h _ _ (hp p hp') (_match _)
recOnPrimeCoprime h0 hp fun a b _ _ _ => h a b
#align nat.rec_on_mul Nat.recOnMul
/-- For any multiplicative function `f` with `f 1 = 1` and any `n ≠ 0`,
we can evaluate `f n` by evaluating `f` at `p ^ k` over the factorization of `n` -/
theorem multiplicative_factorization {β : Type _} [CommMonoid β] (f : ℕ → β)
(h_mult : ∀ x y : ℕ, coprime x y → f (x * y) = f x * f y) (hf : f 1 = 1) :
∀ {n : ℕ}, n ≠ 0 → f n = n.factorization.prod fun p k => f (p ^ k) := by
apply Nat.recOnPosPrimePosCoprime
· rintro p k hp - -
-- Porting note: replaced `simp` with `rw`
rw [Prime.factorization_pow hp, Finsupp.prod_single_index _]
rwa [pow_zero]
· simp
· rintro -
rw [factorization_one, hf]
simp
· intro a b _ _ hab ha hb hab_pos
rw [h_mult a b hab, ha (left_ne_zero_of_mul hab_pos), hb (right_ne_zero_of_mul hab_pos),
factorization_mul_of_coprime hab, ← prod_add_index_of_disjoint]
convert factorization_disjoint_of_coprime hab
#align nat.multiplicative_factorization Nat.multiplicative_factorization
/-- For any multiplicative function `f` with `f 1 = 1` and `f 0 = 1`,
we can evaluate `f n` by evaluating `f` at `p ^ k` over the factorization of `n` -/
theorem multiplicative_factorization' {β : Type _} [CommMonoid β] (f : ℕ → β)
(h_mult : ∀ x y : ℕ, coprime x y → f (x * y) = f x * f y) (hf0 : f 0 = 1) (hf1 : f 1 = 1) :
∀ {n : ℕ}, f n = n.factorization.prod fun p k => f (p ^ k) := by
apply Nat.recOnPosPrimePosCoprime
· rintro p k hp -
simp only [hp.factorization_pow]
rw [prod_single_index _]
simp [hf1]
· simp [hf0]
· rw [factorization_one, hf1]
simp
· intro a b _ _ hab ha hb
rw [h_mult a b hab, ha, hb, factorization_mul_of_coprime hab, ← prod_add_index_of_disjoint]
convert factorization_disjoint_of_coprime hab
#align nat.multiplicative_factorization' Nat.multiplicative_factorization'
/-- Two positive naturals are equal if their prime padic valuations are equal -/
theorem eq_iff_prime_padicValNat_eq (a b : ℕ) (ha : a ≠ 0) (hb : b ≠ 0) :
a = b ↔ ∀ p : ℕ, p.Prime → padicValNat p a = padicValNat p b := by
constructor
· rintro rfl
simp
· intro h
refine' eq_of_factorization_eq ha hb fun p => _
by_cases pp : p.Prime
· simp [factorization_def, pp, h p pp]
· simp [factorization_eq_zero_of_non_prime, pp]
#align nat.eq_iff_prime_padic_val_nat_eq Nat.eq_iff_prime_padicValNat_eq
theorem prod_pow_prime_padicValNat (n : Nat) (hn : n ≠ 0) (m : Nat) (pr : n < m) :
(∏ p in Finset.filter Nat.Prime (Finset.range m), p ^ padicValNat p n) = n := by
-- Porting note: was `nth_rw_rhs`
conv =>
rhs
rw [← factorization_prod_pow_eq_self hn]
rw [eq_comm]
apply Finset.prod_subset_one_on_sdiff
· exact fun p hp =>
Finset.mem_filter.mpr
⟨Finset.mem_range.mpr (gt_of_gt_of_ge pr (le_of_mem_factorization hp)),
prime_of_mem_factorization hp⟩
· intro p hp
cases' Finset.mem_sdiff.mp hp with hp1 hp2
rw [← factorization_def n (Finset.mem_filter.mp hp1).2]
simp [Finsupp.not_mem_support_iff.mp hp2]
· intro p hp
simp [factorization_def n (prime_of_mem_factorization hp)]
#align nat.prod_pow_prime_padic_val_nat Nat.prod_pow_prime_padicValNat
/-! ### Lemmas about factorizations of particular functions -/
-- TODO: Port lemmas from `Data/Nat/Multiplicity` to here, re-written in terms of `factorization`
/-- Exactly `n / p` naturals in `[1, n]` are multiples of `p`. -/
theorem card_multiples (n p : ℕ) : card ((Finset.range n).filter fun e => p ∣ e + 1) = n / p := by
induction' n with n hn; · simp
simp [Nat.succ_div, add_ite, add_zero, Finset.range_succ, filter_insert, apply_ite card,
card_insert_of_not_mem, hn]
#align nat.card_multiples Nat.card_multiples
/-- Exactly `n / p` naturals in `(0, n]` are multiples of `p`. -/
theorem Ioc_filter_dvd_card_eq_div (n p : ℕ) : ((Ioc 0 n).filter fun x => p ∣ x).card = n / p := by
induction' n with n IH
· simp
-- TODO: Golf away `h1` after Yaël PRs a lemma asserting this
have h1 : Ioc 0 n.succ = insert n.succ (Ioc 0 n) := by
rcases n.eq_zero_or_pos with (rfl | hn)
· simp
simp_rw [← Ico_succ_succ, Ico_insert_right (succ_le_succ hn.le), Ico_succ_right]
simp [Nat.succ_div, add_ite, add_zero, h1, filter_insert, apply_ite card, card_insert_eq_ite, IH,
Finset.mem_filter, mem_Ioc, not_le.2 (lt_add_one n), Nat.succ_eq_add_one]
#align nat.Ioc_filter_dvd_card_eq_div Nat.Ioc_filter_dvd_card_eq_div
end Nat
|
(************************************************************************)
(* v * The Coq Proof Assistant / The Coq Development Team *)
(* <O___,, * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2011 *)
(* \VV/ **************************************************************)
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(*i $Id: Rtrigo_calc.v 14641 2011-11-06 11:59:10Z herbelin $ i*)
Require Import Rbase.
Require Import Rfunctions.
Require Import SeqSeries.
Require Import Rtrigo.
Require Import R_sqrt.
Open Local Scope R_scope.
Lemma tan_PI : tan PI = 0.
Proof.
unfold tan in |- *; rewrite sin_PI; rewrite cos_PI; unfold Rdiv in |- *;
apply Rmult_0_l.
Qed.
Lemma sin_3PI2 : sin (3 * (PI / 2)) = -1.
Proof.
replace (3 * (PI / 2)) with (PI + PI / 2).
rewrite sin_plus; rewrite sin_PI; rewrite cos_PI; rewrite sin_PI2; ring.
pattern PI at 1 in |- *; rewrite (double_var PI); ring.
Qed.
Lemma tan_2PI : tan (2 * PI) = 0.
Proof.
unfold tan in |- *; rewrite sin_2PI; unfold Rdiv in |- *; apply Rmult_0_l.
Qed.
Lemma sin_cos_PI4 : sin (PI / 4) = cos (PI / 4).
Proof with trivial.
rewrite cos_sin...
replace (PI / 2 + PI / 4) with (- (PI / 4) + PI)...
rewrite neg_sin; rewrite sin_neg; ring...
cut (PI = PI / 2 + PI / 2); [ intro | apply double_var ]...
pattern PI at 2 3 in |- *; rewrite H; pattern PI at 2 3 in |- *; rewrite H...
assert (H0 : 2 <> 0);
[ discrR | unfold Rdiv in |- *; rewrite Rinv_mult_distr; try ring ]...
Qed.
Lemma sin_PI3_cos_PI6 : sin (PI / 3) = cos (PI / 6).
Proof with trivial.
replace (PI / 6) with (PI / 2 - PI / 3)...
rewrite cos_shift...
assert (H0 : 6 <> 0); [ discrR | idtac ]...
assert (H1 : 3 <> 0); [ discrR | idtac ]...
assert (H2 : 2 <> 0); [ discrR | idtac ]...
apply Rmult_eq_reg_l with 6...
rewrite Rmult_minus_distr_l; repeat rewrite (Rmult_comm 6)...
unfold Rdiv in |- *; repeat rewrite Rmult_assoc...
rewrite <- Rinv_l_sym...
rewrite (Rmult_comm (/ 3)); repeat rewrite Rmult_assoc; rewrite <- Rinv_r_sym...
pattern PI at 2 in |- *; rewrite (Rmult_comm PI); repeat rewrite Rmult_1_r;
repeat rewrite <- Rmult_assoc; rewrite <- Rinv_l_sym...
ring...
Qed.
Lemma sin_PI6_cos_PI3 : cos (PI / 3) = sin (PI / 6).
Proof with trivial.
replace (PI / 6) with (PI / 2 - PI / 3)...
rewrite sin_shift...
assert (H0 : 6 <> 0); [ discrR | idtac ]...
assert (H1 : 3 <> 0); [ discrR | idtac ]...
assert (H2 : 2 <> 0); [ discrR | idtac ]...
apply Rmult_eq_reg_l with 6...
rewrite Rmult_minus_distr_l; repeat rewrite (Rmult_comm 6)...
unfold Rdiv in |- *; repeat rewrite Rmult_assoc...
rewrite <- Rinv_l_sym...
rewrite (Rmult_comm (/ 3)); repeat rewrite Rmult_assoc; rewrite <- Rinv_r_sym...
pattern PI at 2 in |- *; rewrite (Rmult_comm PI); repeat rewrite Rmult_1_r;
repeat rewrite <- Rmult_assoc; rewrite <- Rinv_l_sym...
ring...
Qed.
Lemma PI6_RGT_0 : 0 < PI / 6.
Proof.
unfold Rdiv in |- *; apply Rmult_lt_0_compat;
[ apply PI_RGT_0 | apply Rinv_0_lt_compat; prove_sup0 ].
Qed.
Lemma PI6_RLT_PI2 : PI / 6 < PI / 2.
Proof.
unfold Rdiv in |- *; apply Rmult_lt_compat_l.
apply PI_RGT_0.
apply Rinv_lt_contravar; prove_sup.
Qed.
Lemma sin_PI6 : sin (PI / 6) = 1 / 2.
Proof with trivial.
assert (H : 2 <> 0); [ discrR | idtac ]...
apply Rmult_eq_reg_l with (2 * cos (PI / 6))...
replace (2 * cos (PI / 6) * sin (PI / 6)) with
(2 * sin (PI / 6) * cos (PI / 6))...
rewrite <- sin_2a; replace (2 * (PI / 6)) with (PI / 3)...
rewrite sin_PI3_cos_PI6...
unfold Rdiv in |- *; rewrite Rmult_1_l; rewrite Rmult_assoc;
pattern 2 at 2 in |- *; rewrite (Rmult_comm 2); rewrite Rmult_assoc;
rewrite <- Rinv_l_sym...
rewrite Rmult_1_r...
unfold Rdiv in |- *; rewrite Rinv_mult_distr...
rewrite (Rmult_comm (/ 2)); rewrite (Rmult_comm 2);
repeat rewrite Rmult_assoc; rewrite <- Rinv_l_sym...
rewrite Rmult_1_r...
discrR...
ring...
apply prod_neq_R0...
cut (0 < cos (PI / 6));
[ intro H1; auto with real
| apply cos_gt_0;
[ apply (Rlt_trans (- (PI / 2)) 0 (PI / 6) _PI2_RLT_0 PI6_RGT_0)
| apply PI6_RLT_PI2 ] ]...
Qed.
Lemma sqrt2_neq_0 : sqrt 2 <> 0.
Proof.
assert (Hyp : 0 < 2);
[ prove_sup0
| generalize (Rlt_le 0 2 Hyp); intro H1; red in |- *; intro H2;
generalize (sqrt_eq_0 2 H1 H2); intro H; absurd (2 = 0);
[ discrR | assumption ] ].
Qed.
Lemma R1_sqrt2_neq_0 : 1 / sqrt 2 <> 0.
Proof.
generalize (Rinv_neq_0_compat (sqrt 2) sqrt2_neq_0); intro H;
generalize (prod_neq_R0 1 (/ sqrt 2) R1_neq_R0 H);
intro H0; assumption.
Qed.
Lemma sqrt3_2_neq_0 : 2 * sqrt 3 <> 0.
Proof.
apply prod_neq_R0;
[ discrR
| assert (Hyp : 0 < 3);
[ prove_sup0
| generalize (Rlt_le 0 3 Hyp); intro H1; red in |- *; intro H2;
generalize (sqrt_eq_0 3 H1 H2); intro H; absurd (3 = 0);
[ discrR | assumption ] ] ].
Qed.
Lemma Rlt_sqrt2_0 : 0 < sqrt 2.
Proof.
assert (Hyp : 0 < 2);
[ prove_sup0
| generalize (sqrt_positivity 2 (Rlt_le 0 2 Hyp)); intro H1; elim H1;
intro H2;
[ assumption
| absurd (0 = sqrt 2);
[ apply (sym_not_eq (A:=R)); apply sqrt2_neq_0 | assumption ] ] ].
Qed.
Lemma Rlt_sqrt3_0 : 0 < sqrt 3.
Proof.
cut (0%nat <> 1%nat);
[ intro H0; assert (Hyp : 0 < 2);
[ prove_sup0
| generalize (Rlt_le 0 2 Hyp); intro H1; assert (Hyp2 : 0 < 3);
[ prove_sup0
| generalize (Rlt_le 0 3 Hyp2); intro H2;
generalize (lt_INR_0 1 (neq_O_lt 1 H0));
unfold INR in |- *; intro H3;
generalize (Rplus_lt_compat_l 2 0 1 H3);
rewrite Rplus_comm; rewrite Rplus_0_l; replace (2 + 1) with 3;
[ intro H4; generalize (sqrt_lt_1 2 3 H1 H2 H4); clear H3; intro H3;
apply (Rlt_trans 0 (sqrt 2) (sqrt 3) Rlt_sqrt2_0 H3)
| ring ] ] ]
| discriminate ].
Qed.
Lemma PI4_RGT_0 : 0 < PI / 4.
Proof.
unfold Rdiv in |- *; apply Rmult_lt_0_compat;
[ apply PI_RGT_0 | apply Rinv_0_lt_compat; prove_sup0 ].
Qed.
Lemma cos_PI4 : cos (PI / 4) = 1 / sqrt 2.
Proof with trivial.
apply Rsqr_inj...
apply cos_ge_0...
left; apply (Rlt_trans (- (PI / 2)) 0 (PI / 4) _PI2_RLT_0 PI4_RGT_0)...
left; apply PI4_RLT_PI2...
left; apply (Rmult_lt_0_compat 1 (/ sqrt 2))...
prove_sup...
apply Rinv_0_lt_compat; apply Rlt_sqrt2_0...
rewrite Rsqr_div...
rewrite Rsqr_1; rewrite Rsqr_sqrt...
assert (H : 2 <> 0); [ discrR | idtac ]...
unfold Rsqr in |- *; pattern (cos (PI / 4)) at 1 in |- *;
rewrite <- sin_cos_PI4;
replace (sin (PI / 4) * cos (PI / 4)) with
(1 / 2 * (2 * sin (PI / 4) * cos (PI / 4)))...
rewrite <- sin_2a; replace (2 * (PI / 4)) with (PI / 2)...
rewrite sin_PI2...
apply Rmult_1_r...
unfold Rdiv in |- *; rewrite (Rmult_comm 2); rewrite Rinv_mult_distr...
repeat rewrite Rmult_assoc; rewrite <- Rinv_l_sym...
rewrite Rmult_1_r...
unfold Rdiv in |- *; rewrite Rmult_1_l; repeat rewrite <- Rmult_assoc...
rewrite <- Rinv_l_sym...
rewrite Rmult_1_l...
left; prove_sup...
apply sqrt2_neq_0...
Qed.
Lemma sin_PI4 : sin (PI / 4) = 1 / sqrt 2.
Proof.
rewrite sin_cos_PI4; apply cos_PI4.
Qed.
Lemma tan_PI4 : tan (PI / 4) = 1.
Proof.
unfold tan in |- *; rewrite sin_cos_PI4.
unfold Rdiv in |- *; apply Rinv_r.
change (cos (PI / 4) <> 0) in |- *; rewrite cos_PI4; apply R1_sqrt2_neq_0.
Qed.
Lemma cos3PI4 : cos (3 * (PI / 4)) = -1 / sqrt 2.
Proof with trivial.
replace (3 * (PI / 4)) with (PI / 2 - - (PI / 4))...
rewrite cos_shift; rewrite sin_neg; rewrite sin_PI4...
unfold Rdiv in |- *; rewrite Ropp_mult_distr_l_reverse...
unfold Rminus in |- *; rewrite Ropp_involutive; pattern PI at 1 in |- *;
rewrite double_var; unfold Rdiv in |- *; rewrite Rmult_plus_distr_r;
repeat rewrite Rmult_assoc; rewrite <- Rinv_mult_distr;
[ ring | discrR | discrR ]...
Qed.
Lemma sin3PI4 : sin (3 * (PI / 4)) = 1 / sqrt 2.
Proof with trivial.
replace (3 * (PI / 4)) with (PI / 2 - - (PI / 4))...
rewrite sin_shift; rewrite cos_neg; rewrite cos_PI4...
unfold Rminus in |- *; rewrite Ropp_involutive; pattern PI at 1 in |- *;
rewrite double_var; unfold Rdiv in |- *; rewrite Rmult_plus_distr_r;
repeat rewrite Rmult_assoc; rewrite <- Rinv_mult_distr;
[ ring | discrR | discrR ]...
Qed.
Lemma cos_PI6 : cos (PI / 6) = sqrt 3 / 2.
Proof with trivial.
apply Rsqr_inj...
apply cos_ge_0...
left; apply (Rlt_trans (- (PI / 2)) 0 (PI / 6) _PI2_RLT_0 PI6_RGT_0)...
left; apply PI6_RLT_PI2...
left; apply (Rmult_lt_0_compat (sqrt 3) (/ 2))...
apply Rlt_sqrt3_0...
apply Rinv_0_lt_compat; prove_sup0...
assert (H : 2 <> 0); [ discrR | idtac ]...
assert (H1 : 4 <> 0); [ apply prod_neq_R0 | idtac ]...
rewrite Rsqr_div...
rewrite cos2; unfold Rsqr in |- *; rewrite sin_PI6; rewrite sqrt_def...
unfold Rdiv in |- *; rewrite Rmult_1_l; apply Rmult_eq_reg_l with 4...
rewrite Rmult_minus_distr_l; rewrite (Rmult_comm 3);
repeat rewrite <- Rmult_assoc; rewrite <- Rinv_r_sym...
rewrite Rmult_1_l; rewrite Rmult_1_r...
rewrite <- (Rmult_comm (/ 2)); repeat rewrite <- Rmult_assoc...
rewrite <- Rinv_l_sym...
rewrite Rmult_1_l; rewrite <- Rinv_r_sym...
ring...
left; prove_sup0...
Qed.
Lemma tan_PI6 : tan (PI / 6) = 1 / sqrt 3.
Proof.
unfold tan in |- *; rewrite sin_PI6; rewrite cos_PI6; unfold Rdiv in |- *;
repeat rewrite Rmult_1_l; rewrite Rinv_mult_distr.
rewrite Rinv_involutive.
rewrite (Rmult_comm (/ 2)); rewrite Rmult_assoc; rewrite <- Rinv_r_sym.
apply Rmult_1_r.
discrR.
discrR.
red in |- *; intro; assert (H1 := Rlt_sqrt3_0); rewrite H in H1;
elim (Rlt_irrefl 0 H1).
apply Rinv_neq_0_compat; discrR.
Qed.
Lemma sin_PI3 : sin (PI / 3) = sqrt 3 / 2.
Proof.
rewrite sin_PI3_cos_PI6; apply cos_PI6.
Qed.
Lemma cos_PI3 : cos (PI / 3) = 1 / 2.
Proof.
rewrite sin_PI6_cos_PI3; apply sin_PI6.
Qed.
Lemma tan_PI3 : tan (PI / 3) = sqrt 3.
Proof.
unfold tan in |- *; rewrite sin_PI3; rewrite cos_PI3; unfold Rdiv in |- *;
rewrite Rmult_1_l; rewrite Rinv_involutive.
rewrite Rmult_assoc; rewrite <- Rinv_l_sym.
apply Rmult_1_r.
discrR.
discrR.
Qed.
Lemma sin_2PI3 : sin (2 * (PI / 3)) = sqrt 3 / 2.
Proof.
rewrite double; rewrite sin_plus; rewrite sin_PI3; rewrite cos_PI3;
unfold Rdiv in |- *; repeat rewrite Rmult_1_l; rewrite (Rmult_comm (/ 2));
repeat rewrite <- Rmult_assoc; rewrite double_var;
reflexivity.
Qed.
Lemma cos_2PI3 : cos (2 * (PI / 3)) = -1 / 2.
Proof with trivial.
assert (H : 2 <> 0); [ discrR | idtac ]...
assert (H0 : 4 <> 0); [ apply prod_neq_R0 | idtac ]...
rewrite double; rewrite cos_plus; rewrite sin_PI3; rewrite cos_PI3;
unfold Rdiv in |- *; rewrite Rmult_1_l; apply Rmult_eq_reg_l with 4...
rewrite Rmult_minus_distr_l; repeat rewrite Rmult_assoc;
rewrite (Rmult_comm 2)...
repeat rewrite Rmult_assoc; rewrite <- Rinv_l_sym...
rewrite Rmult_1_r; rewrite <- Rinv_r_sym...
pattern 2 at 4 in |- *; rewrite (Rmult_comm 2); repeat rewrite Rmult_assoc;
rewrite <- Rinv_l_sym...
rewrite Rmult_1_r; rewrite Ropp_mult_distr_r_reverse; rewrite Rmult_1_r...
rewrite (Rmult_comm 2); repeat rewrite Rmult_assoc; rewrite <- Rinv_l_sym...
rewrite Rmult_1_r; rewrite (Rmult_comm 2); rewrite (Rmult_comm (/ 2))...
repeat rewrite Rmult_assoc; rewrite <- Rinv_l_sym...
rewrite Rmult_1_r; rewrite sqrt_def...
ring...
left; prove_sup...
Qed.
Lemma tan_2PI3 : tan (2 * (PI / 3)) = - sqrt 3.
Proof with trivial.
assert (H : 2 <> 0); [ discrR | idtac ]...
unfold tan in |- *; rewrite sin_2PI3; rewrite cos_2PI3; unfold Rdiv in |- *;
rewrite Ropp_mult_distr_l_reverse; rewrite Rmult_1_l;
rewrite <- Ropp_inv_permute...
rewrite Rinv_involutive...
rewrite Rmult_assoc; rewrite Ropp_mult_distr_r_reverse; rewrite <- Rinv_l_sym...
ring...
apply Rinv_neq_0_compat...
Qed.
Lemma cos_5PI4 : cos (5 * (PI / 4)) = -1 / sqrt 2.
Proof with trivial.
replace (5 * (PI / 4)) with (PI / 4 + PI)...
rewrite neg_cos; rewrite cos_PI4; unfold Rdiv in |- *;
rewrite Ropp_mult_distr_l_reverse...
pattern PI at 2 in |- *; rewrite double_var; pattern PI at 2 3 in |- *;
rewrite double_var; assert (H : 2 <> 0);
[ discrR | unfold Rdiv in |- *; repeat rewrite Rinv_mult_distr; try ring ]...
Qed.
Lemma sin_5PI4 : sin (5 * (PI / 4)) = -1 / sqrt 2.
Proof with trivial.
replace (5 * (PI / 4)) with (PI / 4 + PI)...
rewrite neg_sin; rewrite sin_PI4; unfold Rdiv in |- *;
rewrite Ropp_mult_distr_l_reverse...
pattern PI at 2 in |- *; rewrite double_var; pattern PI at 2 3 in |- *;
rewrite double_var; assert (H : 2 <> 0);
[ discrR | unfold Rdiv in |- *; repeat rewrite Rinv_mult_distr; try ring ]...
Qed.
Lemma sin_cos5PI4 : cos (5 * (PI / 4)) = sin (5 * (PI / 4)).
Proof.
rewrite cos_5PI4; rewrite sin_5PI4; reflexivity.
Qed.
Lemma Rgt_3PI2_0 : 0 < 3 * (PI / 2).
Proof.
apply Rmult_lt_0_compat;
[ prove_sup0
| unfold Rdiv in |- *; apply Rmult_lt_0_compat;
[ apply PI_RGT_0 | apply Rinv_0_lt_compat; prove_sup0 ] ].
Qed.
Lemma Rgt_2PI_0 : 0 < 2 * PI.
Proof.
apply Rmult_lt_0_compat; [ prove_sup0 | apply PI_RGT_0 ].
Qed.
Lemma Rlt_PI_3PI2 : PI < 3 * (PI / 2).
Proof.
generalize PI2_RGT_0; intro H1;
generalize (Rplus_lt_compat_l PI 0 (PI / 2) H1);
replace (PI + PI / 2) with (3 * (PI / 2)).
rewrite Rplus_0_r; intro H2; assumption.
pattern PI at 2 in |- *; rewrite double_var; ring.
Qed.
Lemma Rlt_3PI2_2PI : 3 * (PI / 2) < 2 * PI.
Proof.
generalize PI2_RGT_0; intro H1;
generalize (Rplus_lt_compat_l (3 * (PI / 2)) 0 (PI / 2) H1);
replace (3 * (PI / 2) + PI / 2) with (2 * PI).
rewrite Rplus_0_r; intro H2; assumption.
rewrite double; pattern PI at 1 2 in |- *; rewrite double_var; ring.
Qed.
(***************************************************************)
(** Radian -> Degree | Degree -> Radian *)
(***************************************************************)
Definition plat : R := 180.
Definition toRad (x:R) : R := x * PI * / plat.
Definition toDeg (x:R) : R := x * plat * / PI.
Lemma rad_deg : forall x:R, toRad (toDeg x) = x.
Proof.
intro; unfold toRad, toDeg in |- *;
replace (x * plat * / PI * PI * / plat) with
(x * (plat * / plat) * (PI * / PI)); [ idtac | ring ].
repeat rewrite <- Rinv_r_sym.
ring.
apply PI_neq0.
unfold plat in |- *; discrR.
Qed.
Lemma toRad_inj : forall x y:R, toRad x = toRad y -> x = y.
Proof.
intros; unfold toRad in H; apply Rmult_eq_reg_l with PI.
rewrite <- (Rmult_comm x); rewrite <- (Rmult_comm y).
apply Rmult_eq_reg_l with (/ plat).
rewrite <- (Rmult_comm (x * PI)); rewrite <- (Rmult_comm (y * PI));
assumption.
apply Rinv_neq_0_compat; unfold plat in |- *; discrR.
apply PI_neq0.
Qed.
Lemma deg_rad : forall x:R, toDeg (toRad x) = x.
Proof.
intro x; apply toRad_inj; rewrite (rad_deg (toRad x)); reflexivity.
Qed.
Definition sind (x:R) : R := sin (toRad x).
Definition cosd (x:R) : R := cos (toRad x).
Definition tand (x:R) : R := tan (toRad x).
Lemma Rsqr_sin_cos_d_one : forall x:R, Rsqr (sind x) + Rsqr (cosd x) = 1.
Proof.
intro x; unfold sind in |- *; unfold cosd in |- *; apply sin2_cos2.
Qed.
(***************************************************)
(** Other properties *)
(***************************************************)
Lemma sin_lb_ge_0 : forall a:R, 0 <= a -> a <= PI / 2 -> 0 <= sin_lb a.
Proof.
intros; case (Rtotal_order 0 a); intro.
left; apply sin_lb_gt_0; assumption.
elim H1; intro.
rewrite <- H2; unfold sin_lb in |- *; unfold sin_approx in |- *;
unfold sum_f_R0 in |- *; unfold sin_term in |- *;
repeat rewrite pow_ne_zero.
unfold Rdiv in |- *; repeat rewrite Rmult_0_l; repeat rewrite Rmult_0_r;
repeat rewrite Rplus_0_r; right; reflexivity.
discriminate.
discriminate.
discriminate.
discriminate.
elim (Rlt_irrefl 0 (Rle_lt_trans 0 a 0 H H2)).
Qed.
|
** 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 implicit type conversions between numerical types
* in DATA statements:
BLOCK DATA
implicit double precision (d-f)
implicit complex (r-t)
common /ic/ i, j, k, x, y, z, d, e, f, r , s, t
data i, j, k / 2.3, 5D2, (3.2, 1.0) / ,
= x, y, z / 15, -3.2d-5, (-3.2, -1.0) / ,
a d, e, f / -3, 2.3, (3.2, 1.0) / ,
Z r, s, t / 99999, -2.3, 5d2 /
end
program p
common /ic/ rslts(18)
integer expect(18)
real rexpect(15)
equivalence (expect(4), rexpect(1))
double precision dexpect(3)
equivalence (expect(7), dexpect(1))
c set up expected results for tests 1 - 3 (integer):
data (expect(i), i = 1, 3) / 2, 500, 3/
c set up expected results for tests 4 - 6 (real):
data (rexpect(i), i = 1, 3) /15.0, -3.2e-5, -3.2 /
c set up expected results for tests 7 - 12 (double):
data x, y, z / -3.0e0, 2.3e0, 3.2e0 /
dexpect(1) = x
dexpect(2) = y
dexpect(3) = z
c set up expected results for tests 13 - 18 (complex):
data (rexpect(i), i = 10, 15) /
+ 99999.0, 0.0, -2.3, 0.0, 5e2, 0.0 /
c compare results and expected arrays:
call check(rslts, expect, 18)
end
|
module Network.Curl.Prim.Other
import Derive.Prim
%language ElabReflection
-------------------------------------------------
-- Other
-------------------------------------------------
-- curl_formadd
-- curl_formfree
-- curl_formget
-- curl_free
-- curl_getdate
-- curl_pushheader_byname
-- curl_pushheader_bynum
-- curl_share_cleanup
-- curl_share_init
-- curl_share_setopt
-- curl_share_strerror
-- curl_slist_append
-- curl_slist_free_all
-- curl_url
-- curl_url_cleanup
-- curl_url_dup
-- curl_url_get
-- curl_url_set
-- curl_version
-- curl_version_info
-------------------------------------------------
%runElab makeHasIO "curl_free" Export
`[ %foreign "C:curl_free,libcurl,curl/curl.h"
export
prim_curl_free : Ptr Bits8 -> PrimIO () ] --`
|
open import IO
main = run (putStr "Hello, World!")
|
Require Import Coq.Strings.String.
Require Import Coq.Lists.List.
Require Import Coq.micromega.Lia.
Require Import Coq.ZArith.ZArith.
Require Import Cava.Util.List.
Require Import Cava.Util.Nat.
Require Import bedrock2.Array.
Require Import bedrock2.Map.Separation.
Require Import bedrock2.Map.SeparationLogic.
Require Import bedrock2.Lift1Prop.
Require Import bedrock2.ProgramLogic.
Require Import bedrock2.Scalars.
Require Import bedrock2.Semantics.
Require Import bedrock2.Syntax.
Require Import bedrock2.Loops.
Require Import bedrock2.WeakestPrecondition.
Require Import bedrock2.WeakestPreconditionProperties.
Require Import bedrock2.ZnWords.
Require Import coqutil.Word.Interface.
Require Import coqutil.Word.Properties.
Require Import coqutil.Word.LittleEndianList.
Require Import coqutil.Map.Interface.
Require Import coqutil.Map.Properties.
Require Import coqutil.Byte.
Require Import coqutil.Tactics.Tactics.
Require Import coqutil.Tactics.Simp.
Require Import coqutil.Tactics.letexists.
Require Import Bedrock2Experiments.StateMachineSemantics.
Require Import Bedrock2Experiments.StateMachineProperties.
Require Import Bedrock2Experiments.Tactics.
Require Import Bedrock2Experiments.Word.
Require Import Bedrock2Experiments.WordProperties.
Require Import HmacSoftware.Constants.
Require Import HmacSoftware.HmacSemantics.
Require Import HmacSoftware.Hmac.
Require Import HmacSpec.SHA256.
Require Import Bedrock2Experiments.LibBase.AbsMMIOPropertiesUnique.
Require Import Bedrock2Experiments.LibBase.BitfieldProperties.
Require Import Bedrock2Experiments.LibBase.MMIOLabels.
Import Syntax.Coercions List.ListNotations HList.
Local Open Scope string_scope.
Local Open Scope list_scope.
Local Open Scope Z_scope.
(* TODO move to coqutil *)
Module byte.
Lemma of_Z_unsigned: forall b,
byte.of_Z (byte.unsigned b) = b.
Proof.
intros. eapply byte.unsigned_inj. rewrite byte.unsigned_of_Z.
apply byte.wrap_unsigned.
Qed.
End byte.
Module List.
Lemma firstn_add{A: Type}(n m: nat)(l: list A):
List.firstn (n + m) l = List.firstn n l ++ List.firstn m (List.skipn n l).
Proof.
rewrite <- (List.firstn_skipn n l) at 1.
push_firstn; push_length; natsimpl.
apply Nat.min_case_strong; intros; push_firstn; repeat (f_equal; try lia).
Qed.
End List.
Lemma le_split_combine: forall bs n,
n = List.length bs ->
le_split n (le_combine bs) = bs.
Proof. intros. subst. apply split_le_combine. Qed.
Hint Rewrite @length_le_split : push_length.
(* bedrock2.ProgramLogic does cbv, which unfolds all constants *)
Ltac normalize_body_of_function f ::= Tactics.rdelta.rdelta f.
Section Proofs.
Context {word: word.word 32} {mem: map.map word byte}
{word_ok: word.ok word} {mem_ok: map.ok mem}.
Context {timing: timing}.
(* Plug in the right state machine parameters; typeclass inference struggles here *)
Local Notation execution := (execution (M:=hmac_state_machine)).
Infix "^+" := word.add (at level 50, left associativity).
Infix "^-" := word.sub (at level 50, left associativity).
Infix "^*" := word.mul (at level 40, left associativity).
Infix "^<<" := word.slu (at level 37, left associativity).
Infix "^>>" := word.sru (at level 37, left associativity).
Notation "/[ x ]" := (word.of_Z x) (* squeeze a Z into a word (beat it with a / to make it smaller) *)
(format "/[ x ]").
Notation "\[ x ]" := (word.unsigned x) (* \ is the open (removed) lid of the modulo box *)
(format "\[ x ]"). (* let a word fly into the large Z space *)
Add Ring wring : (Properties.word.ring_theory (word := word))
(preprocess [autorewrite with rew_word_morphism],
morphism (Properties.word.ring_morph (word := word)),
constants [Properties.word_cst]).
Lemma invert_read_status_done_false: forall input n val s,
read_step 4 (PROCESSING input n)
/[TOP_EARLGREY_HMAC_BASE_ADDR + HMAC_INTR_STATE_REG_OFFSET] val s ->
Z.testbit \[val ^>> /[HMAC_INTR_STATE_HMAC_DONE_BIT]] 0 = false ->
s = PROCESSING input (n - 1) /\ 0 < n.
Proof.
intros.
remember /[TOP_EARLGREY_HMAC_BASE_ADDR + HMAC_INTR_STATE_REG_OFFSET] as addr.
inversion H; subst. 1: auto.
exfalso. unfold HMAC_INTR_STATE_HMAC_DONE_BIT in *.
rewrite word.unsigned_sru_nowrap in H0. 2: {
rewrite word.unsigned_of_Z_0. reflexivity.
}
rewrite word.unsigned_of_Z_0 in H0.
rewrite Z.shiftr_0_r in H0.
congruence.
Qed.
Lemma invert_read_status_done_true: forall input n val s,
read_step 4 (PROCESSING input n)
/[TOP_EARLGREY_HMAC_BASE_ADDR + HMAC_INTR_STATE_REG_OFFSET] val s ->
Z.testbit \[val ^>> /[HMAC_INTR_STATE_HMAC_DONE_BIT]] 0 = true ->
s = IDLE (sha256 input)
{| intr_enable := /[0];
hmac_done := true;
hmac_en := false;
sha_en := true;
swap_endian := true;
swap_digest := false |}.
Proof.
intros.
remember /[TOP_EARLGREY_HMAC_BASE_ADDR + HMAC_INTR_STATE_REG_OFFSET] as addr.
inversion H; subst. 2: reflexivity.
exfalso. unfold HMAC_INTR_STATE_HMAC_DONE_BIT in *.
rewrite word.unsigned_sru_nowrap in H0. 2: {
rewrite word.unsigned_of_Z_0. reflexivity.
}
rewrite word.unsigned_of_Z_0 in H0.
rewrite Z.shiftr_0_r in H0.
congruence.
Qed.
Lemma invert_read_digest: forall b d i v s,
0 <= \[i] < 8 ->
read_step 4 (IDLE b d)
(/[TOP_EARLGREY_HMAC_BASE_ADDR + HMAC_DIGEST_7_REG_OFFSET] ^- i ^* /[4]) v s ->
s = IDLE b d /\ v = /[le_combine (List.firstn 4 (List.skipn (Z.to_nat \[i] * 4) b))].
Proof.
intros.
remember (/[TOP_EARLGREY_HMAC_BASE_ADDR + HMAC_DIGEST_7_REG_OFFSET] ^- i ^* /[4]) as a.
inversion H0. subst. split; [reflexivity|].
f_equal. f_equal. f_equal. f_equal. ZnWords.
Qed.
(* not needed in this file directly, but needed at proof linking time to discharge
assumption in AbsMMIOWritePropertiesUnique *)
Lemma execution_unique (t : trace) s1 s2 :
execution t s1 ->
execution t s2 ->
s1 = s2.
Proof.
eapply StateMachineProperties.execution_unique; intros;
cbn [state_machine.is_initial_state state_machine.read_step state_machine.write_step
hmac_state_machine] in *; simp.
all: try match goal with
| H: read_step _ _ _ _ _ |- _ => inversion H; subst; clear H
| H: write_step _ _ _ _ _ |- _ => inversion H; subst; clear H
end.
Admitted.
(* TODO move to bedrock2? *)
Notation bytearray := (array (mem := mem) ptsto (word.of_Z 1)).
Notation wordarray := (array (mem := mem) scalar32 (word.of_Z 4)).
Axiom TODO: False.
Lemma ptsto_aliasing_contradiction a b1 b2 (R: mem -> Prop) m
(Hsep: (ptsto a b1 * ptsto a b2 * R)%sep m)
: False.
Proof.
unfold sep in Hsep.
unfold map.split, ptsto in *.
simp.
unfold map.disjoint in *.
specialize (Hsepp1p0p1 a).
rewrite !map.get_put_same in Hsepp1p0p1.
eauto.
Qed.
(* Note: Often, we have a hypothesis `word.unsigned len = Z.of_nat (length l)`,
from which word.unsigned_range gives us a bound that's even 1 tighter *)
Lemma bytearray_max_length(a: word)(l: list byte)(R: mem -> Prop)(m: mem)
(Hsep: (bytearray a l * R)%sep m)
: Z.of_nat (List.length l) <= 2 ^ 32.
Proof.
remember (2 ^ 32) as B.
assert (Z.of_nat (List.length l) <= B \/
B < Z.of_nat (List.length l)) as C by lia.
destruct C as [C | C]. 1: lia.
exfalso.
rewrite <- (List.firstn_nth_skipn _ (Z.to_nat B) l Byte.x00) in Hsep by lia.
rewrite <- (List.firstn_nth_skipn _ 0 (List.firstn (Z.to_nat B) l) Byte.x00) in Hsep by length_hammer.
autorewrite with listsimpl push_firstn in *.
seprewrite_in (array_append ptsto) Hsep.
seprewrite_in (array_append ptsto) Hsep.
seprewrite_in (array_append ptsto) Hsep.
seprewrite_in (array_cons ptsto) Hsep.
seprewrite_in (array_cons ptsto) Hsep.
eapply ptsto_aliasing_contradiction.
use_sep_assumption.
cancel.
cancel_seps_at_indices 0%nat 0%nat. 1: reflexivity.
cancel_seps_at_indices 1%nat 0%nat. 1:f_equal; push_length; ZnWords.
ecancel_done.
Qed.
Lemma load_one_of_bytearray (addr addr': word) (values : list byte) R m
(Hsep : sep (bytearray addr values) R m)
: let n := Z.to_nat (word.unsigned (word.sub addr' addr)) in
(n < List.length values)%nat ->
Memory.load access_size.one m addr' =
Some (word.of_Z (byte.unsigned (nth n values Byte.x00))).
Proof.
intros.
rewrite <-(List.firstn_nth_skipn _ _ values Byte.x00 H) in Hsep.
do 2 seprewrite_in (array_append ptsto) Hsep.
seprewrite_in (array_cons ptsto) Hsep.
seprewrite_in (array_nil ptsto) Hsep.
autorewrite with push_length natsimpl in *.
eapply load_one_of_sep.
use_sep_assumption.
cancel.
cancel_seps_at_indices 0%nat 0%nat. {
f_equal. ZnWords.
}
ecancel_done.
Qed.
Lemma isolate_scalar32_of_bytarray: forall (addr addr': word) values,
let n := Z.to_nat (word.unsigned (word.sub addr' addr)) in
(n + 4 <= Datatypes.length values)%nat ->
iff1 (bytearray addr values)
(bytearray addr (List.firstn n values) *
scalar32 addr' (word.of_Z (le_combine (List.firstn 4 (List.skipn n values)))) *
bytearray (word.add addr' (word.of_Z 4)) (List.skipn (n + 4) values))%sep.
Proof.
intros.
rewrite <- (List.firstn_skipn n values) at 1.
rewrite <- (List.firstn_skipn 4 (List.skipn n values)) at 1.
do 2 rewrite (array_append ptsto).
cancel.
cancel_seps_at_indices 0%nat 0%nat. {
unfold scalar32, truncated_word, truncated_scalar, littleendian, ptsto_bytes.ptsto_bytes.
f_equal. 1: ZnWords.
replace (bytes_per (width:=32) access_size.four)
with (Datatypes.length (List.firstn 4 (List.skipn n values)))
by (cbv [bytes_per]; length_hammer).
rewrite word.unsigned_of_Z_nowrap. 2: {
match goal with
| |- context[le_combine ?x] =>
pose proof (le_combine_bound x) as P
end.
autorewrite with push_length in P.
rewrite min_l in P by ZnWords.
exact P.
}
remember (List.firstn 4 (List.skipn n values)) as l.
assert (List.length l = 4%nat) as HL by (subst; length_hammer).
rewrite <- (le_split_combine _ 4) at 1. 2: {
symmetry. exact HL.
}
destruct l as [|b0 l]. 1: discriminate HL.
destruct l as [|b1 l]. 1: discriminate HL.
destruct l as [|b2 l]. 1: discriminate HL.
destruct l as [|b3 l]. 1: discriminate HL.
destruct l as [|b4 l]. 2: discriminate HL.
clear HL.
reflexivity.
}
cancel_seps_at_indices 0%nat 0%nat. {
f_equal.
- push_length. ZnWords.
- push_skipn. f_equal; lia.
}
ecancel_done.
Qed.
Lemma load_four_of_bytearray (addr addr': word) (values : list byte) R m
(Hsep : sep (bytearray addr values) R m)
: let n := Z.to_nat (word.unsigned (word.sub addr' addr)) in
(n + 4 <= List.length values)%nat ->
Memory.load access_size.four m addr' =
Some (word.of_Z (le_combine (List.firstn 4 (List.skipn n values)))).
Proof.
intros.
eapply load_four_of_sep_32bit. 1: reflexivity.
seprewrite_in isolate_scalar32_of_bytarray Hsep. 1: subst n; eassumption.
ecancel_assumption.
Qed.
Lemma store_four_to_bytearray (addr addr' v: word) (values : list byte) R m (post: mem -> Prop):
sep (bytearray addr values) R m ->
let n := Z.to_nat (word.unsigned (word.sub addr' addr)) in
(n + 4 <= List.length values)%nat ->
(forall m', sep (bytearray addr (List.upds values n (le_split 4 (word.unsigned v)))) R m' ->
post m') ->
exists m', Memory.store access_size.four m addr' v = Some m' /\ post m'.
Proof.
intros Hsep n HL HPost.
eapply store_four_of_sep.
- seprewrite_in isolate_scalar32_of_bytarray Hsep. 1: subst n; eassumption.
ecancel_assumption.
- clear dependent m. intros m Hsep. eapply HPost.
SeparationLogic.seprewrite isolate_scalar32_of_bytarray. {
rewrite List.upds_length. subst n. exact HL.
}
use_sep_assumption.
cancel.
unfold List.upds. change (Z.to_nat \[addr' ^- addr]) with n.
pose proof (length_le_split 4 \[v]).
cancel_seps_at_indices 0%nat 1%nat. {
f_equal.
repeat (listsimpl || push_skipn || push_firstn || push_length).
rewrite le_combine_split.
change (Z.of_nat 4 * 8) with 32.
rewrite word.wrap_unsigned.
rewrite word.of_Z_unsigned.
reflexivity.
}
cancel_seps_at_indices 0%nat 0%nat. {
f_equal.
repeat (listsimpl || natsimpl || push_firstn || push_length).
reflexivity.
}
cancel_seps_at_indices 0%nat 0%nat. {
f_equal.
rewrite length_le_split in *.
repeat (listsimpl || natsimpl || push_skipn || push_firstn || push_length).
f_equal; lia.
}
ecancel_done.
Qed.
Lemma Zlandb: forall (b1 b2: bool),
Z.land (if b1 then 1 else 0) (if b2 then 1 else 0) = if (andb b1 b2) then 1 else 0.
Proof. destruct b1; destruct b2; reflexivity. Qed.
Lemma then1_else0_nonzero: forall b: bool,
(if b then 1 else 0) <> 0 -> b = true.
Proof. destruct b; congruence. Qed.
Lemma then1_else0_zero: forall b: bool,
(if b then 1 else 0) = 0 -> b = false.
Proof. destruct b; congruence. Qed.
Lemma Zland_ones_to_mod: forall a ones,
ones = Z.ones (Z.log2_up ones) ->
Z.land a ones = a mod 2 ^ (Z.log2_up ones).
Proof.
intros. rewrite <- Z.land_ones. 2: apply Z.log2_up_nonneg.
f_equal. exact H.
Qed.
Lemma Zland_pow2_to_testbit: forall a pow2,
pow2 = 2 ^ (Z.log2_up pow2) ->
Z.land a pow2 = if Z.testbit a (Z.log2_up pow2) then pow2 else 0.
Proof.
intros.
eapply Z.bits_inj'. intros.
rewrite Z.land_spec.
rewrite prove_Zeq_bitwise.testbit_if.
rewrite H at 1. rewrite H at 3.
rewrite Z.pow2_bits_eqb by apply Z.log2_up_nonneg.
rewrite Z.testbit_0_l.
destr (Z.eqb (Z.log2_up pow2) n).
+ subst n. destruct (Z.testbit a (Z.log2_up pow2)); reflexivity.
+ rewrite Bool.andb_false_r. destr (Z.testbit a (Z.log2_up pow2)); reflexivity.
Qed.
Ltac simpl_conditional :=
match goal with
| H: _ /\ _ |- _ => destruct H
| H: _ |- _ => rewrite Zlandb in H
| H: word.eqb ?x ?y = true |- _ => apply (word.eqb_true x y) in H
| H: word.eqb ?x ?y = false |- _ => apply (word.eqb_false x y) in H
| H: andb ?b1 ?b2 = true |- _ => apply (Bool.andb_true_iff b1 b2) in H
| H: andb ?b1 ?b2 = false |- _ => apply (Bool.andb_false_iff b1 b2) in H
| H: orb ?b1 ?b2 = true |- _ => apply (Bool.orb_true_iff b1 b2) in H
| H: orb ?b1 ?b2 = false |- _ => apply (Bool.orb_false_iff b1 b2) in H
| H: _ |- _ => rewrite word.unsigned_and_nowrap in H
| H: _ |- _ => rewrite word.unsigned_if in H
| H: _ |- _ => rewrite word.unsigned_eqb in H
| H: _ |- _ => rewrite word.unsigned_ltu in H
| H: _ |- _ => rewrite word.unsigned_of_Z_small in H by
(lazymatch goal with
| |- _ <= ?x < 2 ^ _ =>
lazymatch isZcst x with true => cbv; intuition discriminate end
end)
| H: _ |- _ => apply then1_else0_nonzero in H
| H: _ |- _ => apply then1_else0_zero in H
| H: Z.eqb _ _ = true |- _ => apply Z.eqb_eq in H
| H: Z.eqb _ _ = false |- _ => apply Z.eqb_neq in H
| H: Z.ltb _ _ = true |- _ => eapply Z.ltb_lt in H
| H: Z.ltb _ _ = false |- _ => eapply Z.ltb_ge in H
| H: context[Z.land ?a ?ones] |- _ =>
lazymatch isZcst ones with true => idtac end;
let m := eval cbv in (2 ^ Z.log2_up ones) in
rewrite (Zland_ones_to_mod a ones eq_refl: _ = a mod m) in H
| H: context[Z.land ?a ?pow2] |- _ =>
let i := lazymatch isZcst pow2 with
| true => eval cbv in (Z.log2_up pow2)
| false => lazymatch pow2 with
| 2 ^ ?m => m
end
end in
rewrite (Zland_pow2_to_testbit a pow2 eq_refl:
Z.land a pow2 = if Z.testbit a i then pow2 else 0) in H
| H: word.unsigned (if ?b then _ else _) = 0 |- _ => apply word.if_zero in H
| H: word.unsigned (if ?b then _ else _) <> 0 |- _ => apply word.if_nonzero in H
end.
Ltac simpl_conditionals := repeat simpl_conditional.
Global Instance spec_of_hmac_sha256_init : spec_of b2_hmac_sha256_init :=
fun function_env =>
forall tr m (R : mem -> Prop) (digest_buffer: list byte) (d: idle_data),
R m ->
execution tr (IDLE digest_buffer d) ->
call function_env b2_hmac_sha256_init tr m []
(fun tr' m' rets =>
rets = [] /\ execution tr' (CONSUMING []) /\ R m').
Lemma hmac_sha256_init_correct :
program_logic_goal_for_function! b2_hmac_sha256_init.
Proof.
repeat straightline.
straightline_call. 1: reflexivity. 1: eapply write_cfg. 1: eassumption.
repeat straightline.
straightline_call. 1: reflexivity. 1: eapply write_intr_enable. 1: eassumption.
cbn [intr_enable hmac_done hmac_en sha_en swap_endian swap_digest] in *.
repeat straightline.
straightline_call. 1: reflexivity. 1: eapply write_intr_state. 1: eassumption.
cbn [intr_enable hmac_done hmac_en sha_en swap_endian swap_digest] in *.
repeat straightline.
straightline_call.
repeat straightline.
straightline_call.
repeat straightline.
straightline_call.
repeat straightline.
straightline_call.
repeat straightline.
straightline_call. 1: reflexivity. 1: eapply write_cfg. 1: eassumption.
repeat straightline.
straightline_call.
repeat straightline.
cbn [intr_enable hmac_done hmac_en sha_en swap_endian swap_digest] in *.
straightline_call. 1: reflexivity. 1: eapply write_hash_start. {
(* bitfiddling *)
case TODO.
}
{ match goal with
| H: execution ?t ?s1 |- execution ?t ?s2 => replace s2 with s1; [exact H|]
end.
f_equal. f_equal.
(* bitfiddling *)
all: case TODO.
}
repeat straightline.
ssplit; eauto.
Qed.
Global Instance spec_of_hmac_sha256_update : spec_of b2_hmac_sha256_update :=
fun function_env =>
forall tr m (R : mem -> Prop) (previous_input new_input: list byte) data_addr len,
word.unsigned len = Z.of_nat (length new_input) ->
data_addr <> word.of_Z 0 ->
(bytearray data_addr new_input * R)%sep m ->
execution tr (CONSUMING previous_input) ->
call function_env b2_hmac_sha256_update tr m [data_addr; len]
(fun tr' m' rets =>
rets = [word.of_Z Constants.kErrorOk] /\
execution tr' (CONSUMING (previous_input ++ new_input)) /\
(bytearray data_addr new_input * R)%sep m').
Lemma hmac_sha256_update_correct :
program_logic_goal_for_function! b2_hmac_sha256_update.
Proof.
repeat straightline.
unfold1_cmd_goal; cbv beta match delta [cmd_body].
repeat straightline.
subst v.
rewrite word.unsigned_if.
rewrite word.eqb_ne by assumption.
rewrite word.unsigned_of_Z_0.
split; intros E. 1: exfalso; apply E; reflexivity.
clear E.
repeat straightline.
set (data_aligned := word.of_Z (word.unsigned (word.add data_addr (word.of_Z 3)) / 4 * 4)).
rename fifo_reg into fifo_reg0, len into len0.
(* first while loop: *)
eapply (while ["fifo_reg"; "data_sent"; "data"; "len"]
(fun measure t m fifo_reg data_sent data len =>
data_addr = data /\
fifo_reg = fifo_reg0 /\
data_sent ^+ /[measure] = data_aligned /\
0 <= measure < 4 /\
\[data_sent ^- data_addr] + \[len] = Z.of_nat (List.length new_input) /\
(bytearray data_addr new_input * R)%sep m /\
execution t (CONSUMING (previous_input ++
List.firstn (Z.to_nat \[data_sent ^- data_addr]) new_input)))
(Z.lt_wf 0)
\[data_aligned ^- data_addr]).
1: repeat straightline.
{ (* invariant holds initially: *)
loop_simpl.
replace (Z.to_nat \[data_addr ^- data_addr]) with 0%nat by ZnWords.
push_firstn; listsimpl.
ssplit; try assumption; try ZnWords. }
loop_simpl.
intros measure t m0 fifo_reg data_sent data len. (* TODO derive names automatically *)
repeat straightline.
{ (* if br is true, running first loop body again satisfies invariant *)
subst br.
simpl_conditionals.
eexists. split. {
repeat straightline.
eexists. split.
{ eapply load_one_of_bytearray. 1: eassumption. ZnWords. }
repeat straightline.
}
straightline_call.
{ cbv [state_machine.reg_addr hmac_state_machine id]. reflexivity. }
2: eassumption.
{ eapply write_byte. 2: reflexivity.
match goal with
| |- context[byte.unsigned ?x] => pose proof (byte.unsigned_range x)
end.
ZnWords. }
repeat straightline.
cbv [Markers.unique Markers.split].
eexists (measure - 1). ssplit; trivial; try ZnWords.
subst a.
eapply execution_step_write with (sz := 1%nat). 1: eassumption. 1: reflexivity.
cbv [state_machine.write_step hmac_state_machine].
replace (Z.to_nat \[data_sent ^- data]) with
(S (Z.to_nat \[data_sent0 ^- data])) by ZnWords.
rewrite <- (List.firstn_nth _ _ _ Byte.x00) by ZnWords.
rewrite List.app_assoc.
match goal with
| |- context[byte.unsigned ?x] => pose proof (byte.unsigned_range x)
end.
eapply write_byte. 1: ZnWords.
f_equal. f_equal.
rewrite word.unsigned_of_Z_small by ZnWords.
rewrite byte.of_Z_unsigned.
reflexivity.
}
(* if br is false, code after first loop is correct: *)
subst br.
simpl_conditionals.
match goal with
| H: _ \/ _ |- _ => destruct H as [A | A]; simpl_conditionals
end.
{ (* if the first loop was ended because len=0, the remaining two loops are skipped: *)
eapply while_zero_iterations. {
repeat straightline.
subst v.
rewrite word.unsigned_ltu.
apply word.unsigned_inj.
rewrite word.unsigned_if.
destruct_one_match; ZnWords.
}
repeat straightline.
eapply while_zero_iterations. {
repeat straightline. ZnWords.
}
repeat straightline.
ssplit. 1: reflexivity. 2: eassumption.
match goal with
| H: execution ?t ?s1 |- execution ?t ?s2 =>
replace s2 with s1; [exact H|]
end.
f_equal. f_equal. push_firstn. reflexivity.
}
(* if the first loop was ended because `data_sent & 3 == 0`,
we have to step through the remaining two loops as well: *)
assert (data_sent = data_aligned) by ZnWords. subst data_sent.
clear dependent tr.
clear dependent measure.
clear dependent m.
match goal with
| H: word.unsigned ?L = Z.of_nat (List.length new_input) |- _ =>
pose proof (word.unsigned_range L) as LB;
rewrite H in LB;
clear dependent L
end.
rename data into data_addr, t into tr, len into len0.
(* second while loop: *)
eapply (while ["fifo_reg"; "data_sent"; "data"; "len"]
(fun measure t m fifo_reg data_sent data len =>
data_addr = data /\
fifo_reg = fifo_reg0 /\
measure = \[len] /\
\[data_sent] mod 4 = 0 /\
\[data_sent ^- data_addr] + \[len] = Z.of_nat (List.length new_input) /\
(bytearray data_addr new_input * R)%sep m /\
execution t (CONSUMING (previous_input ++
List.firstn (Z.to_nat \[data_sent ^- data_addr]) new_input)))
(Z.lt_wf 0)
\[len0]).
1: repeat straightline.
{ (* invariant holds initially: *)
loop_simpl.
ssplit; try assumption; try ZnWords. }
loop_simpl.
intros measure t m fifo_reg data_sent data len. (* TODO derive names automatically *)
repeat straightline.
{ (* if br is true, running first loop body again satisfies invariant *)
subst br.
simpl_conditionals.
eexists. split. {
repeat straightline.
eexists. split.
{ eapply load_four_of_bytearray. 1: eassumption. ZnWords. }
repeat straightline.
}
straightline_call.
{ cbv [state_machine.reg_addr hmac_state_machine id]. reflexivity. }
2: eassumption.
1: eapply write_word. 1: reflexivity.
repeat straightline.
cbv [Markers.unique Markers.split].
eexists (measure - 4). ssplit; trivial; try ZnWords.
subst a.
eapply execution_step_write with (sz := 4%nat). 1: eassumption. 1: reflexivity.
cbv [state_machine.write_step hmac_state_machine].
eapply write_word. rewrite <- List.app_assoc. f_equal.
subst data_sent.
match goal with
| |- context[le_combine ?x] =>
pose proof (le_combine_bound x) as P
end.
autorewrite with push_length in P.
rewrite min_l in P by ZnWords.
rewrite word.unsigned_of_Z_small by ZnWords.
rewrite le_split_combine. 2: {
rewrite List.firstn_length. ZnWords.
}
replace (Z.to_nat \[data_sent0 ^+ /[4] ^- data])
with (Z.to_nat \[data_sent0 ^- data] + 4)%nat by ZnWords.
apply List.firstn_add.
}
(* if br is false, code after second loop is correct: *)
subst br.
simpl_conditionals.
clear dependent tr.
clear dependent m0.
clear dependent len0.
rename data_sent into data_aligned_last.
rename data into data_addr, t into tr, len into len0.
set (data_past_end := data_addr ^+ /[Z.of_nat (List.length new_input)]).
(* third while loop: *)
eapply (while ["fifo_reg"; "data_sent"; "data"; "len"]
(fun measure t m fifo_reg data_sent data len =>
data_addr = data /\
fifo_reg = fifo_reg0 /\
measure = \[len] /\
0 <= measure < 4 /\
\[data_sent ^- data_addr] + \[len] = Z.of_nat (List.length new_input) /\
(bytearray data_addr new_input * R)%sep m /\
execution t (CONSUMING (previous_input ++
List.firstn (Z.to_nat \[data_sent ^- data_addr]) new_input)))
(Z.lt_wf 0)
\[len0]).
1: repeat straightline.
{ (* invariant holds initially: *)
loop_simpl.
ssplit; try assumption; try ZnWords. }
loop_simpl.
intros measure t m0 fifo_reg data_sent data len. (* TODO derive names automatically *)
repeat straightline.
{ (* if break condition is true, running third loop body again satisfies invariant *)
simpl_conditionals.
eexists. split. {
repeat straightline.
eexists. split.
{ eapply load_one_of_bytearray. 1: eassumption. ZnWords. }
repeat straightline.
}
straightline_call.
{ cbv [state_machine.reg_addr hmac_state_machine id]. reflexivity. }
2: eassumption.
{ eapply write_byte. 2: reflexivity.
match goal with
| |- context[byte.unsigned ?x] => pose proof (byte.unsigned_range x)
end.
ZnWords. }
repeat straightline.
cbv [Markers.unique Markers.split].
eexists (measure - 1). ssplit; trivial; try ZnWords.
subst a.
eapply execution_step_write with (sz := 1%nat). 1: eassumption. 1: reflexivity.
cbv [state_machine.write_step hmac_state_machine].
replace (Z.to_nat \[data_sent ^- data]) with
(S (Z.to_nat \[data_sent0 ^- data])) by ZnWords.
rewrite <- (List.firstn_nth _ _ _ Byte.x00) by ZnWords.
rewrite List.app_assoc.
match goal with
| |- context[byte.unsigned ?x] => pose proof (byte.unsigned_range x)
end.
eapply write_byte. 1: ZnWords.
f_equal. f_equal.
rewrite word.unsigned_of_Z_small by ZnWords.
rewrite byte.of_Z_unsigned.
reflexivity.
}
(* if break condition is false, `result = kErrorOk` is run and now we have to prove
the postcondition of the function: *)
split; [reflexivity|].
split; [|eassumption].
match goal with
| H: execution ?t ?s |- execution ?t ?s' => replace s' with s; [exact H|]
end.
push_firstn. reflexivity.
Qed.
Global Instance spec_of_hmac_sha256_final : spec_of b2_hmac_sha256_final :=
fun function_env =>
forall tr (m: mem) (R : mem -> Prop)
(input digest_trash: list Byte.byte) (digest_addr: word),
Z.of_nat (length digest_trash) = 32 ->
digest_addr <> word.of_Z 0 ->
(bytearray digest_addr digest_trash * R)%sep m ->
execution tr (CONSUMING input) ->
call function_env b2_hmac_sha256_final tr m [digest_addr]
(fun tr' (m': mem) rets =>
rets = [word.of_Z Constants.kErrorOk] /\
execution tr' (IDLE (sha256 input) (* digest has been read, but still in device *)
{| hmac_done := false; (* done flag was already cleared by this function *)
intr_enable := word.of_Z 0;
hmac_en := false;
sha_en := true;
swap_endian := true;
swap_digest := false; |}) /\
(* digest has been stored at correct memory location: *)
(bytearray digest_addr (sha256 input) * R)%sep m').
Lemma hmac_sha256_final_correct :
program_logic_goal_for_function! b2_hmac_sha256_final.
Proof.
repeat straightline.
assert (List.length (sha256 input) = 32)%nat by case TODO.
unfold1_cmd_goal; cbv beta match delta [cmd_body].
repeat straightline.
subst v.
rewrite word.unsigned_if.
rewrite word.eqb_ne by assumption.
rewrite word.unsigned_of_Z_0.
split; intros E. 1: exfalso; apply E; reflexivity.
clear E.
repeat straightline.
straightline_call.
repeat straightline.
straightline_call. 1: reflexivity. 1: eapply write_hash_process. 2: eassumption.
{ case TODO. (* bitfiddling *) }
repeat straightline.
subst done.
(* first while loop *)
eapply atleastonce with (variables := ["digest"; "reg"; "done"])
(invariant := fun measure t m digest reg done =>
digest = digest_addr /\
execution t (PROCESSING input measure) /\
(bytearray digest_addr digest_trash ⋆ R)%sep m).
{ repeat straightline. }
{ eapply (Z.lt_wf 0). }
{ (* if condition initially is false, that's a contradiction, so we don't need to prove post: *)
repeat straightline. subst br. simpl_conditionals. exfalso. eauto. }
{ (* invariant holds initially *)
loop_simpl. eauto. }
loop_simpl.
(* step through first loop body: *)
repeat straightline.
straightline_call. 1: reflexivity. {
(* to show that there exists at least one valid read step, we pick read_done_bit_done,
but the device could also choose read_done_bit_not_done, so later we'll have to treat
both cases *)
eapply read_done_bit_done with (v0 := /[1]).
rewrite word.unsigned_of_Z_1. reflexivity.
}
1: eassumption.
repeat straightline.
straightline_call.
(* TODO here we see that `x3 x4 x5 : word` should be named `"digest" "reg" "done"`,
respectively, automate this naming *)
repeat straightline.
{ (* loop condition is true: need to show that invariant still holds with smaller measure *)
subst br.
rename x5 into done. subst done.
simpl_conditionals.
eexists (v - 1).
edestruct invert_read_status_done_false; [eassumption..|].
subst x.
split; [auto|lia]. }
(* loop condition is false: need to show that code after first loop is correct *)
subst br. simpl_conditionals.
eassert (x = _). {
eapply invert_read_status_done_true; eassumption.
}
subst x.
straightline_call. 1: reflexivity. 1: eapply write_intr_state. 1: eassumption.
cbn [intr_enable hmac_done hmac_en sha_en swap_endian swap_digest] in *.
repeat straightline.
clear dependent reg.
repeat match goal with
| H: execution ?t1 _ |- cmd _ _ ?t2 _ _ _ =>
tryif unify t1 t2 then fail else clear H
end.
repeat match goal with
| m1: @map.rep _ _ mem |- cmd _ _ _ ?m2 _ _ =>
tryif unify m1 m2 then fail else clear dependent m1
end.
rename a3 into tr.
clear dependent v.
match goal with
| H: Z.testbit \[_ ^>> _] 0 = true |- _ => rename H into T
end.
unfold HMAC_INTR_STATE_HMAC_DONE_BIT in *.
rewrite word.unsigned_sru_nowrap in T. 2: {
rewrite word.unsigned_of_Z_0. reflexivity.
}
rewrite word.unsigned_of_Z_0 in T.
rewrite Z.shiftr_0_r in T.
rewrite T in *.
(* second while loop: *)
eapply (while ["digest"; "reg"; "done"; "i"]
(fun remaining t m digest reg done i =>
execution t (IDLE (sha256 input)
{| intr_enable := /[0];
hmac_done := false;
hmac_en := false;
sha_en := true;
swap_endian := true;
swap_digest := false
|}) /\
0 <= \[i] <= 8 /\
0 <= remaining <= 32 /\
4 * \[i] + remaining = 32 /\
digest = digest_addr /\
(bytearray digest (List.firstn (Z.to_nat (4 * \[i])) (sha256 input) ++
List.skipn (Z.to_nat (4 * \[i])) digest_trash) * R)%sep m)
(Z.lt_wf 0) 32).
{ repeat straightline. }
{ (* invariant holds initially: *)
loop_simpl. subst i. rewrite word.unsigned_of_Z_0.
ssplit; try reflexivity; try assumption; try lia. }
loop_simpl.
repeat straightline.
{ (* running loop body satisfies invariant *)
subst br. simpl_conditionals. subst i. rename x5 into i.
straightline_call. 1: reflexivity. 2: eassumption. 1: eapply read_digest with (i0 := \[i]).
all: try reflexivity.
1-2: ZnWords.
repeat straightline.
eapply store_four_to_bytearray. 1: ecancel_assumption.
{ subst a2. rewrite List.app_length. rewrite List.firstn_length. rewrite List.skipn_length.
ZnWords_pre.
Z.div_mod_to_equations.
(* Note: On Coq master of Aug 12, 2021, this goal is just solved by `lia`, but
with Coq 8.13.2, `lia` hangs, so we need more manual steps: *)
assert (2 ^ 32 <> 0) as NZ by (clear; lia).
repeat match goal with
| H: 2 ^ 32 = 0 -> _ |- _ => clear H
| H: 2 ^ 32 < 0 -> _ |- _ => clear H
| H: 0 < 2 ^ 32 -> _ |- _ => specialize (H eq_refl)
| H: 2 ^ 32 <> 0 -> _ |- _ => specialize (H NZ)
end.
subst.
clear H NZ.
clear dependent word.
Zify.zify.
repeat match goal with
| H: _ /\ _ |- _ => destruct H
| H: _ \/ _ |- _ => destruct H
end;
lia.
}
intros m Hm.
repeat straightline.
exists (v - 4).
split; [|lia].
split. {
subst a.
eapply execution_step_read with (sz := 4%nat). 1: eassumption. 1: reflexivity.
cbn [state_machine.read_step hmac_state_machine] in *.
match goal with
| H: read_step 4 ?s ?a ?v ?s1 |- read_step 4 ?s ?a ?v ?s2 =>
replace s2 with s1 at 2; [exact H|]
end.
eapply invert_read_digest with (i := i0). 1: lia. 1: eassumption.
}
split; [ZnWords|].
split; [ZnWords|].
split; [ZnWords|].
split; [reflexivity|].
use_sep_assumption.
cancel.
cancel_seps_at_indices 0%nat 0%nat. {
f_equal.
rewrite List.upds_app2. 2: {
push_length.
(* Note: `ZnWords` should just work here, but when it calls `lia`, `lia` hangs. *)
subst a2. rewrite H9. revert dependent v. clear -word_ok. intros.
pose proof word.unsigned_range i0.
replace (Init.Nat.min (Z.to_nat (4 * \[i0])) 32) with (Z.to_nat (4 * \[i0])) by lia.
replace \[digest_addr ^+ i0 ^* /[4] ^- digest_addr] with \[i0 ^* /[4]] by ZnWords.
ZnWords.
}
subst i.
replace (Z.to_nat (4 * \[i0 ^+ /[1]])) with (Z.to_nat (4 * \[i0]) + 4)%nat by ZnWords.
rewrite List.firstn_add. rewrite <- List.app_assoc.
f_equal.
unfold List.upds. push_length.
replace (Z.to_nat \[a2 ^- digest_addr] -
Init.Nat.min (Z.to_nat (4 * \[i0])) (Datatypes.length (sha256 input)))%nat
with 0%nat.
2: {
(* Note: `ZnWords` should just work here, but when it calls `lia`, `lia` hangs. *)
subst a2. rewrite H9. revert dependent v. clear -word_ok. intros.
pose proof word.unsigned_range i0.
replace (Init.Nat.min (Z.to_nat (4 * \[i0])) 32) with (Z.to_nat (4 * \[i0])) by lia.
replace \[digest_addr ^+ i0 ^* /[4] ^- digest_addr] with \[i0 ^* /[4]] by ZnWords.
ZnWords.
}
repeat (push_firstn || push_length || listsimpl || natsimpl).
edestruct invert_read_digest as (_ & E). 2: eassumption. 1: ZnWords. subst.
rewrite word.unsigned_of_Z_nowrap. 2: {
match goal with
| |- context[le_combine ?x] =>
pose proof (le_combine_bound x) as P
end.
rewrite List.firstn_length in P. rewrite min_l in P by ZnWords.
exact P.
}
rewrite le_split_combine by length_hammer.
push_skipn.
repeat (f_equal; try lia).
}
ecancel_done.
}
(* postcondition holds at end *)
subst br. simpl_conditionals. subst i. rename x5 into i.
replace (4 * \[i]) with 32 in * by ZnWords.
rewrite List.firstn_all2 in * by ZnWords.
rewrite List.skipn_all2 in * by ZnWords.
autorewrite with listsimpl in *.
subst result.
auto.
Qed.
End Proofs.
|
This post was originally published on October 17, 2014, when the Ebola scare was in full swing. Recent events – though different – have stirred some of the same emotions in our collective heart, so I thought it might serve us all well to revisit this message. We’re in this mess together, friends. The other night I woke up in tangled sheets, damp from sweat and disoriented from a dream.
I’d seen her at church for awhile – how long, I’m not sure, because I was in my own self-imposed solitary confinement and wasn’t fully aware of anything going on outside of myself. But I had seen her, and based on what I saw, I had my assumptions. She was in *that* community group, so she was obviously one of the popular kids. (Seriously. This is how I think. |
! Evaluate the reaction rates for given thermodynamic conditions
program test_rates
use amrex_error_module
use amrex_constants_module
use amrex_fort_module, only : rt => amrex_real
use fabio_module, only: fabio_mkdir
use probin_module, only: run_prefix, small_temp, small_dens
use runtime_init_module
use extern_probin_module
use burn_type_module
use actual_burner_module
use actual_rhs_module, only: rate_eval_t, evaluate_rates
use microphysics_module
use network
use build_info_module
implicit none
type (burn_t) :: burn_state
type (rate_eval_t), allocatable :: rate_state(:)
integer :: i, irho, itemp, istate, density_npts, temperature_npts, numpoints
character (len=256) :: params_file
integer :: params_file_unit
real(rt) :: density_lo, density_hi, delta_density, &
temperature_lo, temperature_hi, delta_temperature, &
massfractions(nspec)
namelist /cellparams/ density_lo, density_hi, density_npts, &
temperature_lo, temperature_hi, temperature_npts, &
massfractions
! runtime
call runtime_init(.true.)
! microphysics
call microphysics_init(small_temp=small_temp, small_dens=small_dens)
! Set mass fractions to sanitize inputs for them
massfractions = -1.0e0_rt
! Get initial conditions for the burn
call get_command_argument(1, value = params_file)
open(newunit=params_file_unit, file=params_file, status="old", action="read")
read(unit=params_file_unit, nml=cellparams)
close(unit=params_file_unit)
! Make sure user set all the mass fractions to values in the interval [0, 1]
do i = 1, nspec
if (massfractions(i) .lt. 0 .or. massfractions(i) .gt. 1) then
call amrex_error('mass fraction for ' // short_spec_names(i) // ' not initialized in the interval [0,1]!')
end if
end do
! Calculate grid deltas
delta_density = (density_hi - density_lo)/(density_npts - 1)
delta_temperature = (temperature_hi - temperature_lo)/(temperature_npts - 1)
! Echo initial conditions at burn and fill burn state input
write(*,*) 'State Density Range (g/cm^3): ', density_lo, ' - ', density_hi
write(*,*) 'Number of density points: ', density_npts
write(*,*) 'Delta Density (g/cm^3): ', delta_density
write(*,*) ''
write(*,*) 'State Temperature Range (K): ', temperature_lo, ' - ', temperature_hi
write(*,*) 'Number of temperature points: ', temperature_npts
write(*,*) 'Delta Temperature (K): ', delta_temperature
write(*,*) ''
do i = 1, nspec
write(*,*) 'Mass Fraction (', short_spec_names(i), '): ', massfractions(i)
end do
! Allocate memory for rate evaluations
numpoints = density_npts * temperature_npts
write(*,*) 'Number of total points in rho, T: ', numpoints
allocate(rate_state(numpoints))
i = 1
do irho = 1, density_npts
do itemp = 1, temperature_npts
burn_state % T = temperature_lo + delta_temperature * (itemp - 1)
burn_state % rho = density_lo + delta_density * (irho - 1)
burn_state % xn(:) = massfractions(:)
! normalize -- just in case
!call normalize_abundances_burn(burn_state)
! Initialize initial energy to zero
burn_state % e = ZERO
! Evaluate rates
call evaluate_rates(burn_state, rate_state(i))
i = i + 1
end do
end do
call microphysics_finalize()
call write_rate_grid()
contains
subroutine write_rate_grid
use network, only: nrates, nrat_tabular, i_rate, i_drate_dt, i_scor, i_dscor_dt, nspec
implicit none
character(len=256) :: fname
integer :: file_unit, j, jstart, jend
integer, parameter :: jentries = 2 + 5*nrates + 2*nrat_tabular
character(len=50) :: VDPFMT = ''
real(rt) :: output_vector(jentries)
fname = trim(run_prefix) // "_rates"
open(newunit=file_unit, file=fname, action='WRITE')
write(unit=file_unit, fmt=*) '! Evaluated Rates'
write(unit=file_unit, fmt=*) '! The following fields are of size Number of Rates: '
write(unit=file_unit, fmt=*) '! rates, drates_dt, screening, dscreening_dt, screened_rates'
write(unit=file_unit, fmt=*) '! The following fields are of size Number of Tabular Rates: '
write(unit=file_unit, fmt=*) '! tabular_dqweak, tabular_epart'
write(unit=file_unit, fmt=*) 'Number of Rates: ', nrates
write(unit=file_unit, fmt=*) 'Number of Tabular Rates: ', nrat_tabular
write(unit=file_unit, fmt=*) 'Mass Fractions: '
write(VDPFMT, '("(", I0, "E30.16E5", ")")') nspec
write(unit=file_unit, fmt=VDPFMT) (massfractions(i), i = 1, nspec)
write(VDPFMT, '("(", I0, "A18", ")")') 9
write(unit=file_unit, fmt=VDPFMT) 'rho', 'T', 'rates', 'drates_dt', &
'screening', 'dscreening_dt', &
'screened_rates', 'tabular_dqweak', 'tabular_epart'
write(VDPFMT, '("(", I0, "E30.16E5", ")")') jentries
i = 1
do irho = 1, density_npts
do itemp = 1, temperature_npts
output_vector(1) = density_lo + delta_density * (irho - 1)
output_vector(2) = temperature_lo + delta_temperature * (itemp - 1)
jstart = 3
jend = jstart + nrates - 1
output_vector(jstart:jend) = rate_state(i) % unscreened_rates(i_rate, :)
jstart = jend + 1
jend = jstart + nrates - 1
output_vector(jstart:jend) = rate_state(i) % unscreened_rates(i_drate_dt, :)
jstart = jend + 1
jend = jstart + nrates - 1
output_vector(jstart:jend) = rate_state(i) % unscreened_rates(i_scor, :)
jstart = jend + 1
jend = jstart + nrates - 1
output_vector(jstart:jend) = rate_state(i) % unscreened_rates(i_dscor_dt, :)
jstart = jend + 1
jend = jstart + nrates - 1
output_vector(jstart:jend) = rate_state(i) % screened_rates(:)
jstart = jend + 1
jend = jstart + nrat_tabular - 1
output_vector(jstart:jend) = rate_state(i) % dqweak(:)
jstart = jend + 1
jend = jstart + nrat_tabular - 1
output_vector(jstart:jend) = rate_state(i) % epart(:)
write(unit=file_unit, fmt=VDPFMT) (output_vector(j), j = 1, jentries)
i = i + 1
end do
end do
close(unit=file_unit)
end subroutine write_rate_grid
end program test_rates
subroutine write_rate_t(fname, rate_state)
use network, only: nrates, nrat_tabular, i_rate, i_drate_dt, i_scor, i_dscor_dt
use actual_rhs_module, only: rate_eval_t
implicit none
! Writes contents of rate_eval_t type rate_state to file named fname
character(len=256), intent(in) :: fname
type(rate_eval_t), intent(in) :: rate_state
integer, parameter :: file_unit = 10
character(len=50) :: VDPFMT = ''
integer :: i
open(unit=file_unit, file=fname, action='WRITE')
write(unit=file_unit, fmt=*) '! Rate Eval Type Data'
write(unit=file_unit, fmt=*) 'unscreened rates:'
write(VDPFMT, '("(", I0, "E30.16E5", ")")') nrates
write(unit=file_unit, fmt=VDPFMT) (rate_state % unscreened_rates(i_rate, i), i = 1, nrates)
write(unit=file_unit, fmt=*) 'unscreened drates_dt:'
write(VDPFMT, '("(", I0, "E30.16E5", ")")') nrates
write(unit=file_unit, fmt=VDPFMT) (rate_state % unscreened_rates(i_drate_dt, i), i = 1, nrates)
write(unit=file_unit, fmt=*) 'screening factors:'
write(VDPFMT, '("(", I0, "E30.16E5", ")")') nrates
write(unit=file_unit, fmt=VDPFMT) (rate_state % unscreened_rates(i_scor, i), i = 1, nrates)
write(unit=file_unit, fmt=*) 'screening dfactors_dt:'
write(VDPFMT, '("(", I0, "E30.16E5", ")")') nrates
write(unit=file_unit, fmt=VDPFMT) (rate_state % unscreened_rates(i_dscor_dt, i), i = 1, nrates)
write(unit=file_unit, fmt=*) 'screened rates:'
write(VDPFMT, '("(", I0, "E30.16E5", ")")') nrates
write(unit=file_unit, fmt=VDPFMT) (rate_state % screened_rates(i), i = 1, nrates)
write(unit=file_unit, fmt=*) '(tabular) weak rate dq:'
write(VDPFMT, '("(", I0, "E30.16E5", ")")') nrat_tabular
write(unit=file_unit, fmt=VDPFMT) (rate_state % dqweak(i), i = 1, nrat_tabular)
write(unit=file_unit, fmt=*) '(tabular) weak rate eparticle:'
write(VDPFMT, '("(", I0, "E30.16E5", ")")') nrat_tabular
write(unit=file_unit, fmt=VDPFMT) (rate_state % epart(i), i = 1, nrat_tabular)
close(unit=file_unit)
end subroutine write_rate_t
|
------------------------------------------------------------------------
-- The Agda standard library
--
-- An irrelevant version of ⊥-elim
------------------------------------------------------------------------
{-# OPTIONS --without-K --safe #-}
module Data.Empty.Irrelevant where
open import Data.Empty hiding (⊥-elim)
⊥-elim : ∀ {w} {Whatever : Set w} → .⊥ → Whatever
⊥-elim ()
|
###
#Runs edger on our data.
#args
#1: data file
#2: number of samples in group 1
#3: number of samples in group 2
#4: output filename
#5: temp directory
args <- commandArgs(trailingOnly = TRUE)
source("http://bioconductor.org/biocLite.R")
biocLite("edgeR", lib=args[5])
###
library("edgeR", lib.loc=args[5])
#build sample groupings
groups <- c(rep(1,args[2]), rep(2,args[3]))
#read data into edger
print(args[1])
x <- read.delim(args[1], row.names="Symbol", sep=",")
print(groups)
print(colnames(x))
y <- DGEList(counts=x, group=groups)
#filter
keep <- rowSums(cpm(y)>1) >= 1 #very minimal filter step here, requiring a cpm of 1 in at least 1 sample
y <- y[keep, , keep.lib.sizes=FALSE]
y <- calcNormFactors(y) #performs TMM
design <- model.matrix(~groups)
y <- estimateDisp(y,design)
if(args[2] == 1 || args[3] == 1){
fit <- glmFit(y,design,dispersion=0.04) #TODO: currently this is somewhat less than the recommended 'human' level of 0.16. This should be a user-defineable param.
} else {
fit <- glmFit(y,design)
}
lrt <- glmLRT(fit,coef=2)
write.csv(lrt$table, file=args[4]) |
{-# OPTIONS --safe --warning=error --without-K #-}
open import LogicalFormulae
open import Setoids.Setoids
open import Functions.Definition
open import Sets.EquivalenceRelations
open import Rings.Definition
module Rings.Divisible.Definition {a b : _} {A : Set a} {S : Setoid {a} {b} A} {_+_ _*_ : A → A → A} (R : Ring S _+_ _*_) where
open Setoid S
open Equivalence eq
open Ring R
_∣_ : Rel A
a ∣ b = Sg A (λ c → (a * c) ∼ b)
divisibleWellDefined : {x y a b : A} → (x ∼ y) → (a ∼ b) → x ∣ a → y ∣ b
divisibleWellDefined x=y a=b (c , xc=a) = c , transitive (*WellDefined (symmetric x=y) reflexive) (transitive xc=a a=b)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.