text
stringlengths 0
3.34M
|
---|
import group_theory.group_action
import algebra.group
import category_theory.category.Groupoid
/--
## Let G be a group and X a G-set (i.e a set with an G action), we make the so called 'action groupoid'
## This is a category with obj : X and for x y ∈ X, hom(x,y) = Transporteur (x,y) := { g ∈ G | g • x = y}
## The composition is given by the group law.
-/
def Transporteur (G : Type )[group G](X : Type )[mul_action G X] (x y : X) : set G := { g : G | g • x = y}
lemma mem_transporteur (G : Type )[group G](X : Type )[mul_action G X] (x y : X)(g : G) :
(g ∈ Transporteur G X x y) ↔ g • x = y :=
begin
split,
intro,
cases a,
exact rfl, ---------- Grrrrouhhhhhhhhh : how to simplify
intro,
cases a,
exact rfl,
end
section Transposteur
parameters (G : Type )[group G](X : Type )[mul_action G X]
def one_in_transporteur : ∀ x y : X, (1 : G) ∈ (Transporteur G X x y) ↔ (x = y) :=
begin
intros x y,
rw mem_transporteur (G) (X) (x) (y) (1),
split,
intro,
cases a,
exact eq.symm (one_smul G x ),
intro,
cases a,
exact one_smul G x,
end
lemma transporteur_comp (x y z : X) : (Transporteur G X x y) → (Transporteur G X y z ) → (Transporteur G X x z) :=
λ ⟨g,proof_g⟩ ⟨h, proof_h⟩, begin
have H : (h * g) • x = z,
rw mul_smul,
rw mem_transporteur at proof_g,
rw proof_g,
rw mem_transporteur at proof_h,
rw proof_h,
use (h * g),
exact H,
end
lemma transporteur_inv (x y : X) : (Transporteur G X x y) → (Transporteur G X y x) :=
λ ⟨g,proof_g⟩, begin
rw mem_transporteur at proof_g,
have H : x = g⁻¹ • y,
rw ← proof_g,
rw ← mul_smul,
rw inv_mul_self,
rw one_smul,
use g⁻¹,
exact eq.symm H,
end
end Transposteur
open category_theory
section
variables (G : Type )[group G](X : Type)[mul_action G X]
end
|
theory BarcanDeduce
imports Main QML_S5
begin
lemma BF: "\<lfloor>(\<^bold>\<forall>x. \<^bold>\<box>(\<phi>(x))) \<^bold>\<rightarrow> \<^bold>\<box>(\<^bold>\<forall>x. \<phi>(x))\<rfloor>"
by simp
lemma CBF: "\<lfloor>\<^bold>\<box>(\<^bold>\<forall>x. \<phi>(x)) \<^bold>\<rightarrow> (\<^bold>\<forall>x. \<^bold>\<box>(\<phi>(x)))\<rfloor>"
by simp
consts x::'a y::'a
lemma NE: "valid((mforall(x mbox(mexists(y (y \<^bold>\<leftrightarrow> x))))))"
nitpick
oops
consts big::"'a \<Rightarrow> \<sigma>"
consts smaller::"'a \<Rightarrow> 'a \<Rightarrow> \<sigma>"
lemma "\<lfloor>\<^bold>\<box> (\<^bold>\<exists>x. big x \<^bold>\<and> \<^bold>\<diamond>(\<^bold>\<exists> y. smaller y x))\<rfloor>"
nitpick
oops
end |
import tactic
import data.set
import .lesson2
noncomputable theory
open_locale classical
open PreHilbertPlane
open HilbertPlane
open set
section plane_separation
variables {Ω : Type*} [HilbertPlane Ω]
variables {A B C : Ω}
variables {ℓ r s : Line Ω}
lemma same_side.refl : same_side ℓ A A :=
begin
by_cases hA : A ∈ ℓ,
exact or.inl ⟨hA, hA⟩,
{
unfold same_side,
rw [point_is_segment A, set.singleton_inter_eq_empty],
exact or.inr hA,
}
end
lemma same_side.symm :
same_side ℓ A B → same_side ℓ B A :=
begin
unfold same_side,
intro h,
rw segments_are_symmetric,
tauto,
end
lemma same_side.symm_iff :
same_side ℓ A B ↔ same_side ℓ B A :=
begin
split;
apply same_side.symm,
end
lemma point_not_on_line_of_line_segment_not_intersect_left (h : (pts (A⬝B) ∩ ℓ) = ∅) : A ∉ ℓ :=
begin
intro H,
rw [set.eq_empty_iff_forall_not_mem] at h,
apply h A,
simpa,
end
lemma point_not_on_line_of_line_segment_not_intersect_right (h : pts (A⬝B) ∩ ℓ = ∅) : B ∉ ℓ :=
begin
rw segments_are_symmetric at h,
exact point_not_on_line_of_line_segment_not_intersect_left h,
end
lemma point_on_line_of_same_side (h : same_side ℓ A B) : A ∈ ℓ ↔ B ∈ ℓ :=
begin
unfold same_side at h,
cases h,
tauto,
{
have hcl := point_not_on_line_of_line_segment_not_intersect_left h,
have hcr := point_not_on_line_of_line_segment_not_intersect_right h,
tauto,
}
end
lemma same_side_trans_of_noncollinear (h : ¬ collinear_triple A C B):
same_side ℓ A B → same_side ℓ B C → same_side ℓ A C :=
begin
intros hAB hBC,
unfold same_side at *,
have H1 := point_on_line_of_same_side hAB,
have H2 := point_on_line_of_same_side hBC,
by_cases hA : A ∈ ℓ, by exact or.inl ⟨hA, H2.1 (H1.1 hA)⟩,
replace hAB : pts (A⬝B) ∩ ℓ = ∅, tauto,
have hB : B ∉ ℓ := point_not_on_line_of_line_segment_not_intersect_right hAB,
replace hBC : pts (B⬝C) ∩ ℓ = ∅, tauto,
have hC : C ∉ ℓ := point_not_on_line_of_line_segment_not_intersect_right hBC,
right,
rw set.eq_empty_iff_forall_not_mem,
-- Now the main part of the proof. AC ∩ ℓ = ∅
-- So let D be a point in AC and in ℓ. We'll prove False.
rintro D ⟨ hDAC1, hD⟩,
obtain rfl | hAD := em(D = A), exact hA hD, -- D ≠ A
obtain rfl | hCD := em(D = C), exact hC hD, -- D ≠ C
simp [segments_are_symmetric] at hDAC1,
have hDAC : A * D * C, by tauto,
rcases (B4 h hA hC hB hD hDAC) with
⟨ ⟨E, hE, h1⟩, hF⟩ | ⟨ ⟨E, ⟨ hE, h1⟩ ⟩, hF⟩,
{
suffices l_meets_AB : (pts (A⬝B) ∩ ℓ ≠ ∅), by tauto,
apply set.nmem_singleton_empty.mpr,
exact ⟨E, ⟨or.inr (or.inr h1), hE⟩⟩,
},
{
suffices l_meets_CB : pts (B⬝C) ∩ ℓ ≠ ∅, by tauto,
apply set.nmem_singleton_empty.mpr,
rw [segments_are_symmetric, set.nonempty_def],
exact ⟨E, ⟨or.inr (or.inr h1), hE⟩⟩,
},
end
end plane_separation
|
-- Andreas, 2019-10-01, continuing issue #3855 (erasure modality @0)
-- Test case by Nisse at https://github.com/agda/agda/issues/3855#issuecomment-527164352
-- Occurs check needs to take erasure status of definitions
-- (here: postulates) into account.
postulate
P : Set → Set
p : (A : Set) → P A
@0 A : Set
-- fails : P A
-- fails = p A
test : P A
test = p _
-- Should fail with error like:
--
-- Cannot instantiate the metavariable _2 to solution A
-- since (part of) the solution was created in an erased context
-- when checking that the expression p _ has type P A
|
import numpy as np
import torch
import torchvision.datasets as dsets
import torchvision.transforms as transforms
from torch.utils.data import Subset
def get_dataloader(data_dir, batch_size, split='train', val_split=None):
if split == 'train':
dataset = dsets.MNIST(root=data_dir,
train=True,
transform=transforms.ToTensor(),
download=True)
# Creating data indices for training and validation splits:
dataset_size = len(dataset)
indices = list(range(dataset_size))
split = int(np.floor(val_split * dataset_size))
np.random.shuffle(indices)
train_indices, val_indices = indices[split:], indices[:split]
# Creating PT data samplers and loaders:
train_dataset = Subset(dataset, train_indices)
val_dataset = Subset(dataset, val_indices)
train_dataloader = torch.utils.data.DataLoader(dataset=train_dataset,
batch_size=batch_size,
shuffle=True)
val_dataloader = torch.utils.data.DataLoader(dataset=val_dataset,
batch_size=batch_size,
shuffle=True)
return train_dataloader, val_dataloader
elif split == 'test':
test_dataset = dsets.MNIST(root=data_dir,
train=False,
transform=transforms.ToTensor(),
download=True)
test_dataloader = torch.utils.data.DataLoader(dataset=test_dataset,
batch_size=batch_size,
shuffle=True)
return test_dataloader
else:
raise ValueError('Invalid split: %s' % split)
|
import LMT
variable {I} [Nonempty I] {E} [Nonempty E] [Nonempty (A I E)]
example {a1 a2 a3 : A I E} :
((a2).read i2) ≠ (((a2).write i1 ((a2).read i2)).read i2) → False := by
arr
|
theory BinariesAreForComputersNotPeople
imports Main
begin
lemma "A ⟶ A"
proof
qed
end
|
% !TeX root = 00Book.tex
\subsection{February: Hive Construction}
\begin{apiary}{Add candy block indicator}
\path (4,6) pic{roof=candy};
\path (4,4) pic{brood=8F};
\path (4,2) pic{brood=8F};
\path (4,0) pic{stand};
\path (12,6) pic{roof=candy};
\path (12,4) pic{brood=8F};
\path (12,2) pic{brood=8F};
\path (12,0) pic{stand};
\path (20,6) pic{roof=candy};
\path (20,4) pic{brood=8F};
\path (20,2) pic{brood=8F};
\path (20,0) pic{stand};
\end{apiary}
\subsubsection{Roof}
Space for a rapid feeder.
\subsubsection{Brood Box or Honey Super}
\begin{itemize}
\item Chamfer the edges of the sides.
\item Nail the rail in place, use long nose pliers so you don't hammer your fingers.
\end{itemize}
\subsubsection{Varroa Floor}
\includegraphics[width=0.9\textwidth]{../assets/varroa_floor.png}
\subsubsection{Entrance Block}
\subsubsection{Varroa Slide}
\subsubsection{Hive Stand} |
#=
Problem 4
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
=#
import Primes.factor
function mergeLargest(a::Dict{Int64, Int64}, b::Dict{Int64, Int64})
for k = keys(b)
b_k = b[k]
a_v = get!(a, k, b_k) # Get value or store
if (a_v < b_k)
a[k] = b_k
end
end
end
p = Dict{Int64, Int64}()
for i = 1:20
f = factor(i)
mergeLargest(p, f)
end
@show p
smallest = 1
for k = keys(p)
smallest *= k ^ p[k]
println("key $(k), val $(p[k])")
end
# check
for i = 1:20
if ( smallest % i > 0)
println("Ooops - not divisible by $(i)")
end
end
println("The smallest divisible number is: $(smallest)")
|
lemma closure_closed [simp]: "closed S \<Longrightarrow> closure S = S" |
[STATEMENT]
lemma exits_simps [simp]:
"exits [ADD] = {1}"
"exits [LOADI v] = {1}"
"exits [LOAD x] = {1}"
"exits [STORE x] = {1}"
"i \<noteq> -1 \<Longrightarrow> exits [JMP i] = {1 + i}"
"i \<noteq> -1 \<Longrightarrow> exits [JMPGE i] = {1 + i, 1}"
"i \<noteq> -1 \<Longrightarrow> exits [JMPLESS i] = {1 + i, 1}"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (exits [ADD] = {1} &&& exits [LOADI v] = {1} &&& exits [LOAD x] = {1}) &&& (exits [STORE x] = {1} &&& (i \<noteq> - 1 \<Longrightarrow> exits [JMP i] = {1 + i})) &&& (i \<noteq> - 1 \<Longrightarrow> exits [JMPGE i] = {1 + i, 1}) &&& (i \<noteq> - 1 \<Longrightarrow> exits [JMPLESS i] = {1 + i, 1})
[PROOF STEP]
by (auto simp: exits_def) |
[GOAL]
⊢ (fun n => Real.log ↑n) 0 = 0
[PROOFSTEP]
simp
[GOAL]
⊢ ↑Λ 1 = 0
[PROOFSTEP]
simp [vonMangoldt_apply]
[GOAL]
n : ℕ
⊢ 0 ≤ ↑Λ n
[PROOFSTEP]
rw [vonMangoldt_apply]
[GOAL]
n : ℕ
⊢ 0 ≤ if IsPrimePow n then Real.log ↑(minFac n) else 0
[PROOFSTEP]
split_ifs
[GOAL]
case pos
n : ℕ
h✝ : IsPrimePow n
⊢ 0 ≤ Real.log ↑(minFac n)
[PROOFSTEP]
exact Real.log_nonneg (one_le_cast.2 (Nat.minFac_pos n))
[GOAL]
case neg
n : ℕ
h✝ : ¬IsPrimePow n
⊢ 0 ≤ 0
[PROOFSTEP]
rfl
[GOAL]
n k : ℕ
hk : k ≠ 0
⊢ ↑Λ (n ^ k) = ↑Λ n
[PROOFSTEP]
simp only [vonMangoldt_apply, isPrimePow_pow_iff hk, pow_minFac hk]
[GOAL]
p : ℕ
hp : Prime p
⊢ ↑Λ p = Real.log ↑p
[PROOFSTEP]
rw [vonMangoldt_apply, Prime.minFac_eq hp, if_pos hp.prime.isPrimePow]
[GOAL]
n : ℕ
⊢ ↑Λ n ≠ 0 ↔ IsPrimePow n
[PROOFSTEP]
rcases eq_or_ne n 1 with (rfl | hn)
[GOAL]
case inl
⊢ ↑Λ 1 ≠ 0 ↔ IsPrimePow 1
[PROOFSTEP]
simp [not_isPrimePow_one]
[GOAL]
case inr
n : ℕ
hn : n ≠ 1
⊢ ↑Λ n ≠ 0 ↔ IsPrimePow n
[PROOFSTEP]
exact (Real.log_pos (one_lt_cast.2 (minFac_prime hn).one_lt)).ne'.ite_ne_right_iff
[GOAL]
n : ℕ
⊢ ∑ i in divisors n, ↑Λ i = Real.log ↑n
[PROOFSTEP]
refine' recOnPrimeCoprime _ _ _ n
[GOAL]
case refine'_1
n : ℕ
⊢ ∑ i in divisors 0, ↑Λ i = Real.log ↑0
[PROOFSTEP]
simp
[GOAL]
case refine'_2
n : ℕ
⊢ ∀ (p n : ℕ), Prime p → ∑ i in divisors (p ^ n), ↑Λ i = Real.log ↑(p ^ n)
[PROOFSTEP]
intro p k hp
[GOAL]
case refine'_2
n p k : ℕ
hp : Prime p
⊢ ∑ i in divisors (p ^ k), ↑Λ i = Real.log ↑(p ^ k)
[PROOFSTEP]
rw [sum_divisors_prime_pow hp, cast_pow, Real.log_pow, Finset.sum_range_succ', pow_zero, vonMangoldt_apply_one]
[GOAL]
case refine'_2
n p k : ℕ
hp : Prime p
⊢ ∑ k in range k, ↑Λ (p ^ (k + 1)) + 0 = ↑k * Real.log ↑p
[PROOFSTEP]
simp [vonMangoldt_apply_pow (Nat.succ_ne_zero _), vonMangoldt_apply_prime hp]
[GOAL]
case refine'_3
n : ℕ
⊢ ∀ (a b : ℕ),
1 < a →
1 < b →
coprime a b →
∑ i in divisors a, ↑Λ i = Real.log ↑a →
∑ i in divisors b, ↑Λ i = Real.log ↑b → ∑ i in divisors (a * b), ↑Λ i = Real.log ↑(a * b)
[PROOFSTEP]
intro a b ha' hb' hab ha hb
[GOAL]
case refine'_3
n a b : ℕ
ha' : 1 < a
hb' : 1 < b
hab : coprime a b
ha : ∑ i in divisors a, ↑Λ i = Real.log ↑a
hb : ∑ i in divisors b, ↑Λ i = Real.log ↑b
⊢ ∑ i in divisors (a * b), ↑Λ i = Real.log ↑(a * b)
[PROOFSTEP]
simp only [vonMangoldt_apply, ← sum_filter] at ha hb ⊢
[GOAL]
case refine'_3
n a b : ℕ
ha' : 1 < a
hb' : 1 < b
hab : coprime a b
ha : ∑ a in filter (fun a => IsPrimePow a) (divisors a), Real.log ↑(minFac a) = Real.log ↑a
hb : ∑ a in filter (fun a => IsPrimePow a) (divisors b), Real.log ↑(minFac a) = Real.log ↑b
⊢ ∑ a in filter (fun a => IsPrimePow a) (divisors (a * b)), Real.log ↑(minFac a) = Real.log ↑(a * b)
[PROOFSTEP]
rw [mul_divisors_filter_prime_pow hab, filter_union, sum_union (disjoint_divisors_filter_isPrimePow hab), ha, hb,
Nat.cast_mul, Real.log_mul (cast_ne_zero.2 (pos_of_gt ha').ne') (cast_ne_zero.2 (pos_of_gt hb').ne')]
[GOAL]
⊢ Λ * ↑ζ = log
[PROOFSTEP]
ext n
[GOAL]
case h
n : ℕ
⊢ ↑(Λ * ↑ζ) n = ↑log n
[PROOFSTEP]
rw [coe_mul_zeta_apply, vonMangoldt_sum]
[GOAL]
case h
n : ℕ
⊢ Real.log ↑n = ↑log n
[PROOFSTEP]
rfl
[GOAL]
⊢ ↑ζ * Λ = log
[PROOFSTEP]
rw [mul_comm]
[GOAL]
⊢ Λ * ↑ζ = log
[PROOFSTEP]
simp
[GOAL]
⊢ log * ↑μ = Λ
[PROOFSTEP]
rw [← vonMangoldt_mul_zeta, mul_assoc, coe_zeta_mul_coe_moebius, mul_one]
[GOAL]
⊢ ↑μ * log = Λ
[PROOFSTEP]
rw [mul_comm]
[GOAL]
⊢ log * ↑μ = Λ
[PROOFSTEP]
simp
[GOAL]
n : ℕ
⊢ ∑ d in divisors n, ↑(↑μ d) * ↑log d = -↑Λ n
[PROOFSTEP]
simp only [← log_mul_moebius_eq_vonMangoldt, mul_comm log, mul_apply, log_apply, intCoe_apply, ← Finset.sum_neg_distrib,
neg_mul_eq_mul_neg]
[GOAL]
n : ℕ
⊢ ∑ x in divisors n, ↑(↑μ x) * Real.log ↑x = ∑ x in divisorsAntidiagonal n, ↑(↑μ x.fst) * -Real.log ↑x.snd
[PROOFSTEP]
rw [sum_divisorsAntidiagonal fun i j => (μ i : ℝ) * -Real.log j]
[GOAL]
n : ℕ
⊢ ∑ x in divisors n, ↑(↑μ x) * Real.log ↑x = ∑ i in divisors n, ↑(↑μ i) * -Real.log ↑(n / i)
[PROOFSTEP]
have :
(∑ i : ℕ in n.divisors, (μ i : ℝ) * -Real.log (n / i : ℕ)) =
∑ i : ℕ in n.divisors, ((μ i : ℝ) * Real.log i - μ i * Real.log n) :=
by
apply sum_congr rfl
simp only [and_imp, Int.cast_eq_zero, mul_eq_mul_left_iff, Ne.def, neg_inj, mem_divisors]
intro m mn hn
have : (m : ℝ) ≠ 0 := by
rw [cast_ne_zero]
rintro rfl
exact hn (by simpa using mn)
rw [Nat.cast_div mn this, Real.log_div (cast_ne_zero.2 hn) this, neg_sub, mul_sub]
[GOAL]
n : ℕ
⊢ ∑ i in divisors n, ↑(↑μ i) * -Real.log ↑(n / i) = ∑ i in divisors n, (↑(↑μ i) * Real.log ↑i - ↑(↑μ i) * Real.log ↑n)
[PROOFSTEP]
apply sum_congr rfl
[GOAL]
n : ℕ
⊢ ∀ (x : ℕ), x ∈ divisors n → ↑(↑μ x) * -Real.log ↑(n / x) = ↑(↑μ x) * Real.log ↑x - ↑(↑μ x) * Real.log ↑n
[PROOFSTEP]
simp only [and_imp, Int.cast_eq_zero, mul_eq_mul_left_iff, Ne.def, neg_inj, mem_divisors]
[GOAL]
n : ℕ
⊢ ∀ (x : ℕ), x ∣ n → ¬n = 0 → ↑(↑μ x) * -Real.log ↑(n / x) = ↑(↑μ x) * Real.log ↑x - ↑(↑μ x) * Real.log ↑n
[PROOFSTEP]
intro m mn hn
[GOAL]
n m : ℕ
mn : m ∣ n
hn : ¬n = 0
⊢ ↑(↑μ m) * -Real.log ↑(n / m) = ↑(↑μ m) * Real.log ↑m - ↑(↑μ m) * Real.log ↑n
[PROOFSTEP]
have : (m : ℝ) ≠ 0 := by
rw [cast_ne_zero]
rintro rfl
exact hn (by simpa using mn)
[GOAL]
n m : ℕ
mn : m ∣ n
hn : ¬n = 0
⊢ ↑m ≠ 0
[PROOFSTEP]
rw [cast_ne_zero]
[GOAL]
n m : ℕ
mn : m ∣ n
hn : ¬n = 0
⊢ m ≠ 0
[PROOFSTEP]
rintro rfl
[GOAL]
n : ℕ
hn : ¬n = 0
mn : 0 ∣ n
⊢ False
[PROOFSTEP]
exact hn (by simpa using mn)
[GOAL]
n : ℕ
hn : ¬n = 0
mn : 0 ∣ n
⊢ n = 0
[PROOFSTEP]
simpa using mn
[GOAL]
n m : ℕ
mn : m ∣ n
hn : ¬n = 0
this : ↑m ≠ 0
⊢ ↑(↑μ m) * -Real.log ↑(n / m) = ↑(↑μ m) * Real.log ↑m - ↑(↑μ m) * Real.log ↑n
[PROOFSTEP]
rw [Nat.cast_div mn this, Real.log_div (cast_ne_zero.2 hn) this, neg_sub, mul_sub]
[GOAL]
n : ℕ
this :
∑ i in divisors n, ↑(↑μ i) * -Real.log ↑(n / i) = ∑ i in divisors n, (↑(↑μ i) * Real.log ↑i - ↑(↑μ i) * Real.log ↑n)
⊢ ∑ x in divisors n, ↑(↑μ x) * Real.log ↑x = ∑ i in divisors n, ↑(↑μ i) * -Real.log ↑(n / i)
[PROOFSTEP]
rw [this, sum_sub_distrib, ← sum_mul, ← Int.cast_sum, ← coe_mul_zeta_apply, eq_comm, sub_eq_self, moebius_mul_coe_zeta]
[GOAL]
n : ℕ
this :
∑ i in divisors n, ↑(↑μ i) * -Real.log ↑(n / i) = ∑ i in divisors n, (↑(↑μ i) * Real.log ↑i - ↑(↑μ i) * Real.log ↑n)
⊢ ↑(↑1 n) * Real.log ↑n = 0
[PROOFSTEP]
rcases eq_or_ne n 1 with (hn | hn)
[GOAL]
case inl
n : ℕ
this :
∑ i in divisors n, ↑(↑μ i) * -Real.log ↑(n / i) = ∑ i in divisors n, (↑(↑μ i) * Real.log ↑i - ↑(↑μ i) * Real.log ↑n)
hn : n = 1
⊢ ↑(↑1 n) * Real.log ↑n = 0
[PROOFSTEP]
simp [hn]
[GOAL]
case inr
n : ℕ
this :
∑ i in divisors n, ↑(↑μ i) * -Real.log ↑(n / i) = ∑ i in divisors n, (↑(↑μ i) * Real.log ↑i - ↑(↑μ i) * Real.log ↑n)
hn : n ≠ 1
⊢ ↑(↑1 n) * Real.log ↑n = 0
[PROOFSTEP]
simp [hn]
[GOAL]
⊢ ↑Λ 0 ≤ Real.log ↑0
[PROOFSTEP]
simp
[GOAL]
n : ℕ
⊢ ↑Λ (n + 1) ≤ Real.log ↑(n + 1)
[PROOFSTEP]
rw [← vonMangoldt_sum]
[GOAL]
n : ℕ
⊢ ↑Λ (n + 1) ≤ ∑ i in divisors (n + 1), ↑Λ i
[PROOFSTEP]
exact single_le_sum (by exact fun _ _ => vonMangoldt_nonneg) (mem_divisors_self _ n.succ_ne_zero)
[GOAL]
n : ℕ
⊢ ∀ (i : ℕ), i ∈ divisors (n + 1) → 0 ≤ ↑Λ i
[PROOFSTEP]
exact fun _ _ => vonMangoldt_nonneg
|
------------------------------------------------------------------------------
-- ABP auxiliary lemma
------------------------------------------------------------------------------
{-# OPTIONS --exact-split #-}
{-# OPTIONS --no-sized-types #-}
{-# OPTIONS --no-universe-polymorphism #-}
{-# OPTIONS --without-K #-}
module FOT.FOTC.Program.ABP.StrongerInductionPrinciple.LemmaI where
open import Common.FOL.Relation.Binary.EqReasoning
open import FOTC.Base
open import FOTC.Base.PropertiesI
open import FOTC.Base.List
open import FOTC.Base.Loop
open import FOTC.Base.List.PropertiesI
open import FOTC.Data.Bool
open import FOTC.Data.Bool.PropertiesI
open import FOTC.Data.List
open import FOTC.Data.List.PropertiesI
open import FOTC.Program.ABP.ABP
open import FOTC.Program.ABP.Fair.Type
open import FOTC.Program.ABP.Fair.PropertiesI
open import FOTC.Program.ABP.PropertiesI
open import FOTC.Program.ABP.Terms
------------------------------------------------------------------------------
-- Helper function for the auxiliary lemma
module Helper where
helper : ∀ {b i' is' os₁ os₂ as bs cs ds js} →
Bit b →
Fair os₂ →
S b (i' ∷ is') os₁ os₂ as bs cs ds js →
∀ ft₁ os₁' → F*T ft₁ → Fair os₁' → os₁ ≡ ft₁ ++ os₁' →
∃[ js' ] js ≡ i' ∷ js'
helper {b} {i'} {is'} {os₁} {os₂} {as} {bs} {cs} {ds} {js} Bb Fos₂
(asS , bsS , csS , dsS , jsS)
.(T ∷ []) os₁' f*tnil Fos₁' os₁-eq = js' , js-eq
where
os₁-eq-helper : os₁ ≡ T ∷ os₁'
os₁-eq-helper = os₁ ≡⟨ os₁-eq ⟩
(T ∷ []) ++ os₁' ≡⟨ ++-∷ T [] os₁' ⟩
T ∷ ([] ++ os₁') ≡⟨ ∷-rightCong (++-leftIdentity os₁') ⟩
T ∷ os₁' ∎
as' : D
as' = await b i' is' ds
as-eq : as ≡ < i' , b > ∷ as'
as-eq = trans asS (send-eq b i' is' ds)
bs' : D
bs' = corrupt os₁' · as'
bs-eq : bs ≡ ok < i' , b > ∷ bs'
bs-eq =
bs ≡⟨ bsS ⟩
corrupt os₁ · as
≡⟨ ·-rightCong as-eq ⟩
corrupt os₁ · (< i' , b > ∷ as')
≡⟨ ·-leftCong (corruptCong os₁-eq-helper) ⟩
corrupt (T ∷ os₁') · (< i' , b > ∷ as')
≡⟨ corrupt-T os₁' < i' , b > as' ⟩
ok < i' , b > ∷ corrupt os₁' · as'
≡⟨ refl ⟩
ok < i' , b > ∷ bs' ∎
cs' : D
cs' = ack (not b) · bs'
js' : D
js' = out (not b) · bs'
js-eq : js ≡ i' ∷ js'
js-eq = js ≡⟨ jsS ⟩
out b · bs ≡⟨ ·-rightCong bs-eq ⟩
out b · (ok < i' , b > ∷ bs') ≡⟨ out-ok≡ b b i' bs' refl ⟩
i' ∷ out (not b) · bs' ≡⟨ refl ⟩
i' ∷ js' ∎
ds' : D
ds' = ds
helper {b} {i'} {is'} {os₁} {os₂} {as} {bs} {cs} {ds} {js}
Bb Fos₂ (asS , bsS , csS , dsS , jsS)
.(F ∷ ft₁^) os₁' (f*tcons {ft₁^} FTft₁^) Fos₁' os₁-eq =
helper Bb (tail-Fair Fos₂) ihS ft₁^ os₁' FTft₁^ Fos₁' refl
where
os₁^ : D
os₁^ = ft₁^ ++ os₁'
os₂^ : D
os₂^ = tail₁ os₂
os₁-eq-helper : os₁ ≡ F ∷ os₁^
os₁-eq-helper = os₁ ≡⟨ os₁-eq ⟩
(F ∷ ft₁^) ++ os₁' ≡⟨ ++-∷ F ft₁^ os₁' ⟩
F ∷ ft₁^ ++ os₁' ≡⟨ refl ⟩
F ∷ os₁^ ∎
as^ : D
as^ = await b i' is' ds
as-eq : as ≡ < i' , b > ∷ as^
as-eq = trans asS (send-eq b i' is' ds)
bs^ : D
bs^ = corrupt os₁^ · as^
bs-eq : bs ≡ error ∷ bs^
bs-eq =
bs
≡⟨ bsS ⟩
corrupt os₁ · as
≡⟨ ·-rightCong as-eq ⟩
corrupt os₁ · (< i' , b > ∷ as^)
≡⟨ ·-leftCong (corruptCong os₁-eq-helper) ⟩
corrupt (F ∷ os₁^) · (< i' , b > ∷ as^)
≡⟨ corrupt-F os₁^ < i' , b > as^ ⟩
error ∷ corrupt os₁^ · as^
≡⟨ refl ⟩
error ∷ bs^ ∎
cs^ : D
cs^ = ack b · bs^
cs-eq : cs ≡ not b ∷ cs^
cs-eq = cs ≡⟨ csS ⟩
ack b · bs ≡⟨ ·-rightCong bs-eq ⟩
ack b · (error ∷ bs^) ≡⟨ ack-error b bs^ ⟩
not b ∷ ack b · bs^ ≡⟨ refl ⟩
not b ∷ cs^ ∎
ds^ : D
ds^ = corrupt os₂^ · cs^
ds-eq-helper₁ : os₂ ≡ T ∷ tail₁ os₂ → ds ≡ ok (not b) ∷ ds^
ds-eq-helper₁ h =
ds ≡⟨ dsS ⟩
corrupt os₂ · cs ≡⟨ ·-rightCong cs-eq ⟩
corrupt os₂ · (not b ∷ cs^) ≡⟨ ·-leftCong (corruptCong h) ⟩
corrupt (T ∷ os₂^) · (not b ∷ cs^) ≡⟨ corrupt-T os₂^ (not b) cs^ ⟩
ok (not b) ∷ corrupt os₂^ · cs^ ≡⟨ refl ⟩
ok (not b) ∷ ds^ ∎
ds-eq-helper₂ : os₂ ≡ F ∷ tail₁ os₂ → ds ≡ error ∷ ds^
ds-eq-helper₂ h =
ds ≡⟨ dsS ⟩
corrupt os₂ · cs ≡⟨ ·-rightCong cs-eq ⟩
corrupt os₂ · (not b ∷ cs^) ≡⟨ ·-leftCong (corruptCong h) ⟩
corrupt (F ∷ os₂^) · (not b ∷ cs^) ≡⟨ corrupt-F os₂^ (not b) cs^ ⟩
error ∷ corrupt os₂^ · cs^ ≡⟨ refl ⟩
error ∷ ds^ ∎
ds-eq : ds ≡ ok (not b) ∷ ds^ ∨ ds ≡ error ∷ ds^
ds-eq = case (λ h → inj₁ (ds-eq-helper₁ h))
(λ h → inj₂ (ds-eq-helper₂ h))
(head-tail-Fair Fos₂)
as^-eq-helper₁ : ds ≡ ok (not b) ∷ ds^ → as^ ≡ send b · (i' ∷ is') · ds^
as^-eq-helper₁ h =
await b i' is' ds
≡⟨ awaitCong₄ h ⟩
await b i' is' (ok (not b) ∷ ds^)
≡⟨ await-ok≢ b (not b) i' is' ds^ (x≢not-x Bb) ⟩
< i' , b > ∷ await b i' is' ds^
≡⟨ sym (send-eq b i' is' ds^) ⟩
send b · (i' ∷ is') · ds^ ∎
as^-eq-helper₂ : ds ≡ error ∷ ds^ → as^ ≡ send b · (i' ∷ is') · ds^
as^-eq-helper₂ h =
await b i' is' ds ≡⟨ awaitCong₄ h ⟩
await b i' is' (error ∷ ds^) ≡⟨ await-error b i' is' ds^ ⟩
< i' , b > ∷ await b i' is' ds^ ≡⟨ sym (send-eq b i' is' ds^) ⟩
send b · (i' ∷ is') · ds^ ∎
as^-eq : as^ ≡ send b · (i' ∷ is') · ds^
as^-eq = case as^-eq-helper₁ as^-eq-helper₂ ds-eq
js-eq : js ≡ out b · bs^
js-eq = js ≡⟨ jsS ⟩
out b · bs ≡⟨ ·-rightCong bs-eq ⟩
out b · (error ∷ bs^) ≡⟨ out-error b bs^ ⟩
out b · bs^ ∎
ihS : S b (i' ∷ is') os₁^ os₂^ as^ bs^ cs^ ds^ js
ihS = as^-eq , refl , refl , refl , js-eq
------------------------------------------------------------------------------
-- From Dybjer and Sander's paper: From the assumption that os₁ ∈ Fair
-- and hence by unfolding Fair, we conclude that there are ft₁ : F*T
-- and os₁' : Fair, such that os₁ = ft₁ ++ os₁'.
--
-- We proceed by induction on ft₁ : F*T using helper.
open Helper
lemma : ∀ {b i' is' os₁ os₂ as bs cs ds js} →
Bit b →
Fair os₁ →
Fair os₂ →
S b (i' ∷ is') os₁ os₂ as bs cs ds js →
∃[ js' ] js ≡ i' ∷ js'
lemma Bb Fos₁ Fos₂ s with Fair-out Fos₁
... | ft , os₁' , FTft , prf , Fos₁' = helper Bb Fos₂ s ft os₁' FTft Fos₁' prf
|
chapter {* Generated by Lem from lem/keccak.lem. *}
theory "KeccakAuxiliary"
imports
Main
"/Users/lixm/Documents/lem/library/Lem_pervasives"
"Word8"
"Word256"
"Word64"
"Keccak"
begin
(****************************************************)
(* *)
(* Termination Proofs *)
(* *)
(****************************************************)
termination sha3_update by lexicographic_order
(****************************************************)
(* *)
(* Lemmata *)
(* *)
(****************************************************)
lemma word_rsplit_def_lemma:
" ((\<forall> w. word_rsplit_aux (to_bl w) (( 8 :: nat)) = word_rsplit w)) "
(* Theorem: word_rsplit_def_lemma*)(* try *) by auto
lemma word_of_bytes_def_lemma:
" ((\<forall> lst.
of_bl
(list_fill_left False (( 256 :: nat)) (List.concat (List.map to_bl lst)))
= Word.word_rcat lst)) "
(* Theorem: word_of_bytes_def_lemma*)(* try *) by auto
end
|
module ListThms where
open import Sec4
import Sec2
{-
Definition of a list
-}
data List (A : Set) : Set where
[] : List A -- Empty list
_∷_ : A → List A → List A -- Cons
infixr 4 _∷_
-- Proposition stating what is a non empty list
nelist : {A : Set} → (List A) → Prop
nelist [] = ⊥
nelist (x ∷ x₁) = ⊤
-- Head function that only works on non empty list
head : {A : Set} → (l : List A) → (p : nelist l) → A
head [] () -- This can never happen
head (x ∷ _) ⋆ = x -- This is the head of the list
-- The tail of the list only works on non empty list
tail : {A : Set} → (l : List A) → (p : nelist l) → (List A)
tail [] ()
tail (_ ∷ l) ⋆ = l
-- definition of a map
map : {A B : Set} → (A → B) → (List A) → List B
map f [] = []
map f (x ∷ l) = (f x) ∷ map f l
-- definition of fold left
fold : {A B : Set} → (A → B → B) → B → (List A) → B
fold f x [] = x
fold f x (x₁ ∷ l) = fold f (f x₁ x) l
-- reduce only works on lists of length > 0
reduce : {A : Set} → (l : List A) → (p : nelist l) → (A → A → A) → A
reduce [] ()
reduce (x ∷ l) _ f = fold f x l
-- length of a list
length : {A : Set} → (List A) → Sec2.ℕ
length [] = Sec2.Z
length (x ∷ l) = (Sec2.S Sec2.Z) Sec2.+ (length l)
-- Proposition on ≤
_<=_ : Sec2.ℕ → Sec2.ℕ → Prop
Sec2.Z <= Sec2.Z = ⊤
Sec2.Z <= Sec2.S y = ⊤
Sec2.S x <= y = x <= y
_>=_ : Sec2.ℕ → Sec2.ℕ → Prop
Sec2.Z >= Sec2.Z = ⊤
Sec2.Z >= Sec2.S y = ⊥
Sec2.S x >= y = x >= y
-- Indexing into the list
_!!_ : {A : Set} → ∀ (l : List A) → ∀ (i : Sec2.ℕ) → (nelist l)
→ Exists A (λ _ → ((i >= Sec2.Z) ∧ (i <= (length l))))
([] !! i) ()
((x ∷ l) !! i) ⋆ = [ x , (and (lem1 i) (lem (x ∷ l) i))]
where
cong-<= : (x y : Sec2.ℕ) → (x <= y) → (x <= Sec2.S y)
cong-<= Sec2.Z y p = ⋆
cong-<= (Sec2.S x) Sec2.Z p = cong-<= x Sec2.Z p
cong-<= (Sec2.S x) (Sec2.S y) p = cong-<= x (Sec2.S y) p
lem1 : (i : Sec2.ℕ) → (i >= Sec2.Z)
lem1 Sec2.Z = ⋆
lem1 (Sec2.S i) = lem1 i
lem2 : (i : Sec2.ℕ) → (i <= Sec2.Z)
lem2 Sec2.Z = ⋆
lem2 (Sec2.S i₁) = lem2 i₁
lem : {A : Set} → (l : List A) → (i : Sec2.ℕ) → (i <= (length l))
lem [] Sec2.Z = ⋆
lem [] (Sec2.S i) = lem2 i
lem (x₁ ∷ l₁) i = cong-<= i (length l₁) (lem l₁ i)
data Maybe (A : Set) : Set where
Nothing : Maybe A
Just : A → Maybe A
index : {A : Set} → ∀ (l : List A)
→ (nelist l)
→ ∀ (i : Sec2.ℕ)
→ Sec2.So ((i Sec2.≥ Sec2.Z) Sec2.& (i Sec2.< (length l)))
→ Maybe A
index l _ i _ = index' l i (Sec2.Z)
where
index' : {A : Set} → ∀ (l : List A) → ∀(i : Sec2.ℕ)
→ (c : Sec2.ℕ) → Maybe A
index' [] i₁ c = Nothing
index' (x₁ ∷ l₁) i₁ c with (i₁ Sec2.== c)
index' (x₁ ∷ l₁) i₁ c | Sec2.T = Just x₁
index' (x₁ ∷ l₁) i₁ c | Sec2.F = index' l₁ i₁ (Sec2.S c)
exx1 : Maybe Sec2.ℕ
exx1 = index (1 ∷ []) ⋆ 0 Sec2.ok
index'' : {A : Set} → ∀ (l : List A)
→ ∀ (i : Sec2.ℕ)
→ Sec2.So (i Sec2.< (length l))
→ A
index'' [] Sec2.Z ()
index'' [] (Sec2.S i) ()
index'' (x ∷ l) Sec2.Z Sec2.ok = x
index'' (x ∷ l) (Sec2.S i) p = index'' l i p
-- append two lists
_++_ : {A : Set} → (l : List A) → (l' : List A) → (List A)
[] ++ l' = l'
(x ∷ l) ++ l' = (x ∷ (l ++ l'))
-- composition of two functions
_∘_ : {A B C : Set} → (A → B) → (B → C) → (A → C)
f ∘ g = λ x → (g (f x))
cong : {A : Set} → (x : A) → (l m : List A) → (l Sec2.≡ m) → (x ∷ l) Sec2.≡ (x ∷ m)
cong x l .l Sec2.refl = Sec2.refl
cong2 : {A : Set} → (l m q : List A) → (l Sec2.≡ m) → (l ++ q) Sec2.≡ (m ++ q)
cong2 l .l q Sec2.refl = Sec2.refl
thm1-map : {A B : Set} → (f : A → B) → (l : List A) → (m : List A) → (map f (l ++ m)) Sec2.≡ (map f l) ++ (map f m)
thm1-map f [] m = Sec2.refl
thm1-map f (x ∷ l) m with (f x)
thm1-map f (x ∷ l) m | p = cong p (map f (l ++ m)) (map f l ++ map f m) (thm1-map f l m)
-- map ∘
thm2-map : {A B C : Set} → (f : A → B) → (g : B → C) → (l : List A) → (map (f ∘ g) l Sec2.≡ ((map f) ∘ (map g)) l)
thm2-map f₁ g₁ [] = Sec2.refl
thm2-map f₁ g₁ (x ∷ l) with (thm2-map f₁ g₁ l)
thm2-map f₁ g₁ (x ∷ l) | p = cong (g₁ (f₁ x)) (map (λ z → g₁ (f₁ z)) l) (map g₁ (map f₁ l)) p
-- Non empty list by construction
data NeList (A : Set) : Set where
^_^ : A → NeList A
_∶_ : A → NeList A → NeList A
infixr 60 ^_^
infixr 60 _∶_
-- XXX: Prove these in Coq along with the other theorem from Mike Naha's
-- tutorial in Agda.
|
[STATEMENT]
theorem search_correct [rewrite]:
"is_interval_tree t \<Longrightarrow> is_interval x \<Longrightarrow> search t x \<longleftrightarrow> has_overlap (tree_set t) x"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>is_interval_tree t; is_interval x\<rbrakk> \<Longrightarrow> search t x = has_overlap (tree_set t) x
[PROOF STEP]
@proof
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>is_interval_tree t; is_interval x\<rbrakk> \<Longrightarrow> search t x = has_overlap (tree_set t) x
[PROOF STEP]
@induct t @with
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>is_interval_tree t; is_interval x\<rbrakk> \<Longrightarrow> search t x = has_overlap (tree_set t) x
[PROOF STEP]
@subgoal "t = Node l y m r"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>is_interval_tree t; is_interval x\<rbrakk> \<Longrightarrow> search t x = has_overlap (tree_set t) x
[PROOF STEP]
@let "t = Node l y m r"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>is_interval_tree t; is_interval x\<rbrakk> \<Longrightarrow> search t x = has_overlap (tree_set t) x
[PROOF STEP]
@case "is_overlap (int y) x"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>is_interval_tree t; is_interval x\<rbrakk> \<Longrightarrow> search t x = has_overlap (tree_set t) x
[PROOF STEP]
@case "l \<noteq> Tip \<and> tmax l \<ge> low x" @with
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>is_interval_tree t; is_interval x\<rbrakk> \<Longrightarrow> search t x = has_overlap (tree_set t) x
[PROOF STEP]
@obtain "p\<in>tree_set l" where "high (int p) = tmax l"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>is_interval_tree t; is_interval x\<rbrakk> \<Longrightarrow> search t x = has_overlap (tree_set t) x
[PROOF STEP]
@case "is_overlap (int p) x"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>is_interval_tree t; is_interval x\<rbrakk> \<Longrightarrow> search t x = has_overlap (tree_set t) x
[PROOF STEP]
@end
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>is_interval_tree t; is_interval x\<rbrakk> \<Longrightarrow> search t x = has_overlap (tree_set t) x
[PROOF STEP]
@case "l = Tip"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>is_interval_tree t; is_interval x\<rbrakk> \<Longrightarrow> search t x = has_overlap (tree_set t) x
[PROOF STEP]
@endgoal
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>is_interval_tree t; is_interval x\<rbrakk> \<Longrightarrow> search t x = has_overlap (tree_set t) x
[PROOF STEP]
@end
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>is_interval_tree t; is_interval x\<rbrakk> \<Longrightarrow> search t x = has_overlap (tree_set t) x
[PROOF STEP]
@qed |
#' Get data for particular ORCID's
#'
#' @export
#'
#' @param orcid (character) A single Orcid identifier, of the
#' form XXXX-XXXX-XXXX-XXXX
#' @param ... Curl options passed on to [crul::HttpClient()]
#'
#' @return A named list of results - from a call to [orcid_person()]
#'
#' @examples \dontrun{
#' res <- orcid_id(orcid = "0000-0002-9341-7985")
#' res$`0000-0002-9341-7985`
#' res$`0000-0002-9341-7985`$`name`
#' res$`0000-0002-9341-7985`$`other-names`
#' res$`0000-0002-9341-7985`$`biography`
#' res$`0000-0002-9341-7985`$`researcher-urls`
#' res$`0000-0002-9341-7985`$`emails`
#' res$`0000-0002-9341-7985`$`addresses`
#' res$`0000-0002-9341-7985`$`keywords`
#' res$`0000-0002-9341-7985`$`external-identifiers`
#' res$`0000-0002-9341-7985`$`emails`
#'
#' ids <- c("0000-0003-1620-1408", "0000-0002-9341-7985")
#' res <- lapply(ids, orcid_id)
#' vapply(res, function(x) x[[1]]$name$`family-name`$value, "")
#' }
orcid_id <- function(orcid, ...) {
stopifnot(is.character(orcid))
stopifnot(length(orcid) == 1)
structure(orcid_person(orcid, ...), class = "orcid_id")
}
|
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[margin=1in]{geometry}
\title{PS3}
\author{Daniel Carpenter}
\date{January 2020}
\usepackage{natbib}
\usepackage{graphicx}
\begin{document}
\maketitle
\section{Answers to Question 6}
File Size = 5MB
\\
N Lines Before: 0
\\
N Lines After: 36,634
\end{document} |
from copy import deepcopy
import numpy as np
from settings.config import RECOMMENDATION_LIST_SIZE
from posprocessing.calibrated_methods import linear_calibration
# ################################################################# #
# ############### Surrogate Submodular Optimization ############### #
# ################################################################# #
def surrogate_submodular(user_preference_distribution, reco_items, config, n=RECOMMENDATION_LIST_SIZE,
lmbda=0.5):
"""
start with an empty recommendation list,
loop over the topn cardinality, during each iteration
update the list with the item that maximizes the utility function.
"""
calib_reco_dict = {}
for _ in range(n):
max_utility = -np.inf
best_item = None
best_id = None
for i_id, item in reco_items.items():
if i_id in calib_reco_dict.keys():
continue
temp = deepcopy(calib_reco_dict)
temp[i_id] = item
utility = linear_calibration(temp, user_preference_distribution, config, lmbda)
if utility > max_utility:
max_utility = utility
best_item = item
best_id = i_id
calib_reco_dict[best_id] = best_item
return calib_reco_dict
|
/-
Copyright (c) 2020 Heather Macbeth, Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Heather Macbeth, Patrick Massot
! This file was ported from Lean 3 source module group_theory.archimedean
! leanprover-community/mathlib commit f93c11933efbc3c2f0299e47b8ff83e9b539cbf6
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathlib.Algebra.Order.Archimedean
import Mathlib.GroupTheory.Subgroup.Basic
/-!
# Archimedean groups
This file proves a few facts about ordered groups which satisfy the `Archimedean` property, that is:
`class Archimedean (α) [OrderedAddCommMonoid α] : Prop :=`
`(arch : ∀ (x : α) {y}, 0 < y → ∃ n : ℕ, x ≤ n • y)`
They are placed here in a separate file (rather than incorporated as a continuation of
`Algebra.Order.Archimedean`) because they rely on some imports from `GroupTheory` -- bundled
subgroups in particular.
The main result is `AddSubgroup.cyclic_of_min`: a subgroup of a decidable archimedean abelian
group is cyclic, if its set of positive elements has a minimal element.
This result is used in this file to deduce `Int.subgroup_cyclic`, proving that every subgroup of `ℤ`
is cyclic. (There are several other methods one could use to prove this fact, including more purely
algebraic methods, but none seem to exist in mathlib as of writing. The closest is
`Subgroup.is_cyclic`, but that has not been transferred to `AddSubgroup`.)
The result is also used in `Topology.Instances.Real` as an ingredient in the classification of
subgroups of `ℝ`.
-/
open Set
variable {G : Type _} [LinearOrderedAddCommGroup G] [Archimedean G]
/-- Given a subgroup `H` of a decidable linearly ordered archimedean abelian group `G`, if there
exists a minimal element `a` of `H ∩ G_{>0}` then `H` is generated by `a`. -/
theorem AddSubgroup.cyclic_of_min {H : AddSubgroup G} {a : G}
(ha : IsLeast { g : G | g ∈ H ∧ 0 < g } a) : H = AddSubgroup.closure {a} := by
obtain ⟨⟨a_in, a_pos⟩, a_min⟩ := ha
refine' le_antisymm _ (H.closure_le.mpr <| by simp [a_in])
intro g g_in
obtain ⟨k, ⟨nonneg, lt⟩, _⟩ := existsUnique_zsmul_near_of_pos' a_pos g
have h_zero : g - k • a = 0 := by
by_contra h
have h : a ≤ g - k • a := by
refine' a_min ⟨_, _⟩
· exact AddSubgroup.sub_mem H g_in (AddSubgroup.zsmul_mem H a_in k)
· exact lt_of_le_of_ne nonneg (Ne.symm h)
have h' : ¬a ≤ g - k • a := not_le.mpr lt
contradiction
simp [sub_eq_zero.mp h_zero, AddSubgroup.mem_closure_singleton]
#align add_subgroup.cyclic_of_min AddSubgroup.cyclic_of_min
/-- If a nontrivial additive subgroup of a linear ordered additive commutative group is disjoint
with the interval `Set.Ioo 0 a` for some positive `a`, then the set of positive elements of this
group admits the least element. -/
theorem AddSubgroup.exists_isLeast_pos {H : AddSubgroup G} (hbot : H ≠ ⊥) {a : G} (h₀ : 0 < a)
(hd : Disjoint (H : Set G) (Ioo 0 a)) : ∃ b, IsLeast { g : G | g ∈ H ∧ 0 < g } b := by
-- todo: move to a lemma?
have hex : ∀ g > 0, ∃ n : ℕ, g ∈ Ioc (n • a) ((n + 1) • a) := fun g hg => by
rcases existsUnique_add_zsmul_mem_Ico h₀ 0 (g - a) with ⟨m, ⟨hm, hm'⟩, -⟩
simp only [zero_add, sub_le_iff_le_add, sub_add_cancel, ← add_one_zsmul] at hm hm'
lift m to ℕ
· rw [← Int.lt_add_one_iff, ← zsmul_lt_zsmul_iff h₀, zero_zsmul]
exact hg.trans_le hm
· simp only [← Nat.cast_succ, coe_nat_zsmul] at hm hm'
exact ⟨m, hm', hm⟩
have : ∃ n : ℕ, Set.Nonempty (H ∩ Ioc (n • a) ((n + 1) • a))
· rcases (bot_or_exists_ne_zero H).resolve_left hbot with ⟨g, hgH, hg₀⟩
rcases hex (|g|) (abs_pos.2 hg₀) with ⟨n, hn⟩
exact ⟨n, _, (@abs_mem_iff (AddSubgroup G) G _ _).2 hgH, hn⟩
classical rcases Nat.findX this with ⟨n, ⟨x, hxH, hnx, hxn⟩, hmin⟩
by_contra hxmin
simp only [IsLeast, not_and, mem_setOf_eq, mem_lowerBounds, not_exists, not_forall,
not_le] at hxmin
rcases hxmin x ⟨hxH, (nsmul_nonneg h₀.le _).trans_lt hnx⟩ with ⟨y, ⟨hyH, hy₀⟩, hxy⟩
rcases hex y hy₀ with ⟨m, hm⟩
cases' lt_or_le m n with hmn hnm
· exact hmin m hmn ⟨y, hyH, hm⟩
· refine disjoint_left.1 hd (sub_mem hxH hyH) ⟨sub_pos.2 hxy, sub_lt_iff_lt_add'.2 ?_⟩
calc x ≤ (n + 1) • a := hxn
_ ≤ (m + 1) • a := nsmul_le_nsmul h₀.le (add_le_add_right hnm _)
_ = m • a + a := succ_nsmul' _ _
_ < y + a := add_lt_add_right hm.1 _
/-- If an additive subgroup of a linear ordered additive commutative group is disjoint with the
interval `Set.Ioo 0 a` for some positive `a`, then this is a cyclic subgroup. -/
theorem AddSubgroup.cyclic_of_isolated_zero {H : AddSubgroup G} {a : G} (h₀ : 0 < a)
(hd : Disjoint (H : Set G) (Ioo 0 a)) : ∃ b, H = closure {b} := by
rcases eq_or_ne H ⊥ with rfl | hbot
· exact ⟨0, closure_singleton_zero.symm⟩
· exact (exists_isLeast_pos hbot h₀ hd).imp fun _ => cyclic_of_min
/-- Every subgroup of `ℤ` is cyclic. -/
theorem Int.subgroup_cyclic (H : AddSubgroup ℤ) : ∃ a, H = AddSubgroup.closure {a} :=
have : Ioo (0 : ℤ) 1 = ∅ := eq_empty_of_forall_not_mem fun m hm =>
hm.1.not_le (lt_add_one_iff.1 hm.2)
AddSubgroup.cyclic_of_isolated_zero one_pos <| by simp [this]
#align int.subgroup_cyclic Int.subgroup_cyclic
|
function[varargout]=blurspec(varargin)
%BLURSPEC Returns the blurred and aliased spectrum given the autocovariance.
%
% BLURSPEC is used to rapidly compute blurred, aliased, and other
% modified versions of a spectrum from a known autocovariance.
%
% Performing these calculations in the time domain, making use of
% Fourier relationships between modified versions of the autocovariance
% and spectrum, is much faster than working in the frequency domain.
% __________________________________________________________________
%
% Blurred and aliased spectra
%
% [F,S]=BLURSPEC(R) inverse Fourier transforms a given *one-sided*
% autocovariance R to obtain a spectrum S that incorporates the effects
% of aliasing, as well as blurring by the default taper, the 'boxcar'.
%
% Here F is an array of frequencies and S is the one-sided Fourier
% spectrum. If R is length N, the output arrays will be length (N/2+1)
% if N is even and (N+1)/2 if N is odd.
%
% [F,SPP,SNN]=BLURSPEC(R) for complex-valued R returns SPP and SNN, the
% positive and negative rotary spectra, respectively.
%
% BLURSPEC(DT,R) optionally uses the sample interval DT in computing the
% frequency array F, and in setting the spectral levels.
% __________________________________________________________________
%
% Tapered and aliased spectra
%
% BLURSPEC(R,'tapered',TAPER) incorporates the spectral smoothing due to
% the use of data TAPER, rather than the boxcar taper, in addition to the
% effects of aliasing. TAPER must be the same length as R.
%
% Note that BLURSPEC(R,'tapered',[]) simply returns the blurred spectrum,
% as an empty taper is taken to indicate the periodogram.
%
% BLURSPEC(R,'window',WIN) uses the pre-computed window that is to
% multiply the autocovariance function WIN. This is the half of the
% sequence obtained by convolving the taper with itself. This version
% is primarily used for speed in an internal call from MATERNFIT.
% __________________________________________________________________
%
% Aliased-only spectrum
%
% BLURSPEC(R,'aliased') computes an approximation to *aliased* spectrum,
% without blurring. This approximation will be accurate to the extent
% that R has decayed to zero by the end of its duration.
%
% This is much faster than explicitly summing over aliased frequencies.
% __________________________________________________________________
%
% Differenced spectra
%
% BLURSPEC(R,'difference') returns the blurred and aliased spectrum of
% the first forward difference of the process with autocovariance R. In
% this case the output will be length N-1.
%
% BLURSPEC(R,'seconddifference') returns the blurred and aliases spectrum
% of the second forward difference of the process with autocovariance R.
% The output will be length N-2.
%
% These options can be combined with the 'taper' and 'aliased' options
% described above.
% __________________________________________________________________
%
% 'blurspec --t' runs some tests.
%
% Usage: [f,S]=blurspec(R);
% [f,Spp,Snn]=blurspec(dt,R);
% [f,Spp,Snn]=blurspec(dt,R,'tapered',TAPER);
% [f,Spp,Snn]=blurspec(dt,R,'aliased');
% __________________________________________________________________
% This is part of JLAB --- type 'help jlab' for more information
% (C) 2015--2020 J.M. Lilly and A.M. Sykulski
% --- type 'help jlab_license' for details
if strcmp(varargin{1}, '--t')
blurspec_test,return
end
dt=1;
if length(varargin{1})==1
dt=varargin{1};
varargin=varargin(2:end);
end
R=varargin{1};
ver='standard';
str='blurred';
psi=[];
varargin=varargin(2:end);
for i=1:2
if length(varargin)>0
if ischar(varargin{end})
if strcmpi(varargin{end}(1:3),'sec')||strcmpi(varargin{end}(1:3),'dif')||strcmpi(varargin{end}(1:3),'sta')
ver=varargin{end};
elseif strcmpi(varargin{end}(1:3),'ali')
str=varargin{end};
end
varargin=varargin(1:end-1);
end
end
if length(varargin)>1
%length(varargin)
if ischar(varargin{end-1})
str=lower(varargin{end-1});
psi=varargin{end};
varargin=varargin(1:end-2);
end
end
end
if isempty(psi)&&strcmpi(str(1:3),'tap')
str='blurred';
end
if strcmpi(ver(1:3),'dif')
R=frac(1,dt)*(2*R(1:end-1,:)-R(2:end,:)-[conj(R(2,:));R(1:end-2,:)]);
elseif strcmpi(ver(1:3),'sec')
R=frac(1,dt)*(2*R(1:end-1,:)-R(2:end,:)-[conj(R(2,:));R(1:end-2,:)]);
R=frac(1,dt)*(2*R(1:end-1,:)-R(2:end,:)-[conj(R(2,:));R(1:end-2,:)]);
end
N=size(R,1);
if strcmpi(str(1:3),'win')
R=R.*vrep(psi,size(R,2),2);
elseif strcmpi(str(1:3),'tap')
if length(psi)~=size(R,1)
error('Sizes of R and taper PSI do not match.')
end
win=conv(psi,psi);
win=win(end-N+1:end);
R=R.*vrep(win,size(R,2),2);
elseif strcmpi(str(1:3),'blu')
tri=[N:-1:1]'./N;
if size(R,2)==1
R=R.*tri;
else
R=R.*vrep(tri,size(R,2),2);
end
end %If str='aliased', do nothing
%figure,plot(tri)
R(1,:)=R(1,:)./2; %Don't forget to divide first element by two
S=dt*2*real(fft(R));
S=abs(S); %Sometimes there are small negative parts after blurring
%Note, this is always correct for both even and odd length time series
omega=fourier(N);
Spp=S(1:length(omega),:);
Snn=[S(1,:);S(end:-1:end-length(omega)+2,:)];
%Snn=flipud([S(end-length(omega)+2:end,:);S(1,:)]); %Same but slower
varargout{1}=omega./dt;
varargout{2}=Spp;
varargout{3}=Snn;
function[]=blurspec_test
N=1000;
alpha=1.5;
h=1;
A=1;
[tau,R]=materncov(1,N,A,alpha,h);
[f,Spp,Snn]=maternspec(1,N,A,alpha,h);
tic;[f,Spp2,Snn2]=blurspec(R,'aliased');etime1=toc;
maternspec_spec=@(omega,A,omegao,H,alpha)(frac(H.^(2*alpha-1),materncfun(alpha))*frac(A.^2,((omega-omegao).^2+H.^2).^alpha));
tic;
M=100;
[Sppa,Snna]=vzeros(length(fourier(N)),2*M+1);
for m=-M:M
Sppa(:,m+M+1)=maternspec_spec(fourier(N)+2*pi*m,A,0,h,alpha);
end
Snna=Sppa;
etime2=toc;
vsum(Sppa,Snna,2);
%figure,plot(f,[Spp2 Spp2],'k','linewidth',2),hold on,plot(f,[Sppa Snna],'r')
%figure,plot(f,Spp2-Sppa,'k','linewidth',2),hold,plot(f,Snn2-Snna,'r','linewidth',2)
b1=aresame(Spp2,Sppa,2e-6);
b2=aresame(Snn2,Snna,2e-6);
reporttest('BLURSPEC aliasing with covariance inversion matches direct calculation to 2e-6, even N',b1&&b2)
disp(['BLURSPEC aliasing with covariance inversion was ' num2str(etime2/etime1) ' times faster than direct calculation.'])
N=999;
omegao=1/4;
[tau,R]=materncov(1,N,A,alpha,h,omegao);
[f,Spp,Snn]=maternspec(1,N,A,alpha,h,omegao);
tic;[f,Spp2,Snn2]=blurspec(R,'aliased');etime1=toc;
tic;
M=200;
[Sppa,Snna]=vzeros(length(fourier(N)),2*M+1);
for m=-M:M
Sppa(:,m+M+1)=maternspec_spec(fourier(N)+2*pi*m,A,omegao,h,alpha);
Snna(:,m+M+1)=maternspec_spec(fourier(N)+2*pi*m,A,-omegao,h,alpha);
end
etime2=toc;
vsum(Sppa,Snna,2);
b1=aresame(Spp2,Sppa,1e-6);
b2=aresame(Snn2,Snna,1e-6);
reporttest('BLURSPEC aliasing with covariance inversion matches direct calculation to 1e-6, odd N, frequency shift',b1&&b2)
disp(['BLURSPEC aliasing with covariance inversion was ' num2str(etime2/etime1) ' times faster than direct calculation.'])
x=[10 1.1 0.1];
[tau,acv]=materncov(1,N,x(1),x(2),x(3)); % autocovariance sequence
S=abs(real(2*fft(acv.*(1-([0:N-1]')/N))-acv(1))); % blurred spectrum
Spp2=S(1:floor(N/2)+1);
Snn2=[S(1);S(end:-1:ceil(N/2)+1)];
[tau,R]=materncov(1,N,x(1),x(2),x(3));
[f,Spp,Snn]=blurspec(R);
%[f,Spp,Snn]=maternspec(N,x(1),x(2),x(3),'blurred');
reporttest('BLURSPEC blurring matches alternate version for Matern', aresame(Spp,Spp2,1e-8)&&aresame(Snn,Snn2,1e-8))
% N=1000;
% alpha=10;
% h=1/10;
% sigma=7;
% z=maternoise(1,[N 10000],sigma,-1/2,h,0,alpha);
% psi=sleptap(size(z,1),3,1);
% [f,spp,snn]=mspec(1,z,psi);
%
%
% [tau,R]=materncov(1,N,sigma,-1/2,h,0,alpha);
% [f,Spp,Snn]=blurspec(R,'taper',psi);
% figure,plot(f,vmean([spp snn],2)),hold on,plot(f,Spp)
%
% N=1001;
% z=maternoise(1,[N 10000],sigma,-1/2,h,0,alpha);;
% psi=sleptap(size(z,1),3,1);
% [f,spp,snn]=mspec(1,z,psi);
%
%
% [tau,R]=materncov(1,N,sigma,-1/2,h,0,alpha);
% [f,Spp,Snn]=blurspec(R,'taper',psi);
% %figure,plot(f,vmean([spp snn],2)),hold on,plot(f,Spp)
%
%
% N=1000;
% alpha=1.5;
% h=1;
% A=1;
% psi=sleptap(size(z,1),3,1);
%
% [f,Spp,Snn]=maternspec(dt,N,A,alpha,h/dt);
% [tau,R]=materncov(dt,N,A,alpha,h);
% tic;[f,Spp2,Snn2]=blurspec(dt,R,'tapered',psi);
% tic;[f,Spp3,Snn3]=blurspec(dt,R);
% figure,plot(f,[Spp Spp2 Spp3])
%
%
% dt=7;
% z=maternoise(dt,[N 1000],A,alpha,h/dt);
% psi=sleptap(size(z,1),3,1);
% [f,spphat,snnhat,spn]=mspec(dt,z,psi);
% vmean(spphat,snnhat,2);
%
%
|
Established in 1891 with one building and fewer than 50 students , today the University of Texas Medical Branch ( UTMB ) campus has grown to more than 70 buildings and an enrollment of more than 2 @,@ 500 students . The 84 @-@ acre ( 340 @,@ 000 m2 ) campus includes schools of medicine , nursing , allied health professions , and a graduate school of biomedical sciences , as well as three institutes for advanced studies & medical humanities , a major medical library , seven hospitals , a network of clinics that provide a full range of primary and specialized medical care , and numerous research facilities .
|
#include "extractor.hpp"
#include "variables.hpp"
#include "packet_handler.hpp"
#include <iostream>
#include <pcap.h>
#include <pthread.h>
#include <condition_variable>
#include <mutex>
#include <boost/program_options.hpp>
using namespace std;
std::condition_variable cond;
static bool flow_is_end = false;
static void* sniff_interface(void* ptr) {
//bool *is_server = (bool *)ptr;
Host *host = (Host*) ptr;
char *dev;
pcap_t *handler;
char errbuf[PCAP_ERRBUF_SIZE];
if (*host == Host::Server) {
//dev = server_interface.c_str();
handler = pcap_open_live(server_interface.c_str(), BUFSIZ, 0, 1, errbuf);
server_pcap_t = handler;
} else if (*host == Host::Client){
//dev = client_interface.c_str();
handler = pcap_open_live(client_interface.c_str(), BUFSIZ, 0, 1, errbuf);
client_pcap_t = handler;
} else {
std::cerr << "Can't decide the nif is client or server!" << std::endl;
}
//char *dev = (char * )dev_name;
//dev = pcap_lookupdev(errbuf);
//if (dev == NULL) {
// cout << "pcap_lookupdev() failed: " << errbuf << endl;
// return 1;
//}
//handler = pcap_open_live(dev, BUFSIZ, 0, 1, errbuf);
if (handler == NULL) {
cout << "pcap_open_live() failed: " << errbuf << endl;
return NULL;
}
//if (pcap_loop(descr, -1, server_packet_handler, NULL) < 0) {
// cout << "pcap_loop() failed: " << pcap_geterr(descr);
// return 1;
//}
struct pcap_pkthdr *pkt_header;
u_char *pkt_data;
int retval;
cout << "----------- Start sniffing packet! ------------" << std::endl;
while (!flow_is_end) {
if ((retval = pcap_next_ex(handler, &pkt_header, (const u_char **) &pkt_data)) < 0) break;
///
bool is_end = false;
if(*host == Host::Server) {
is_end = server_packet_handler(pkt_header, pkt_data, handler);
} else if (*host == Host::Client) {
is_end = client_packet_handler(pkt_header, pkt_data, handler);
}
if (is_end) break;
}
flow_is_end = true;
pcap_close(handler);
cond.notify_one();
}
static void smain() {
//char *sdev,*cdev;
//std::vector<pthread_t*> threads;
const char * sdev = server_interface.c_str();
const char * cdev = client_interface.c_str();
Host server = Host::Server;
Host client = Host::Client;
/*
bool * server_is_server = new bool;
*server_is_server = false;
bool * client_is_server = new bool;
*client_is_server = false;
*/
while (!server_filename_queue.empty() && !client_filename_queue.empty()) {
auto server_name = server_filename_queue.front();
auto client_name = client_filename_queue.front();
auto queue_name = queue_filename_queue.front();
queue_filename = queue_name;
server_filename_queue.pop();
client_filename_queue.pop();
queue_filename_queue.pop();
//if (server_name == "" || client_name == ""){
// exit(0);
//}
server_filename_queue.push(server_name);
client_filename_queue.push(client_name);
queue_filename_queue.push(queue_name);
extract_trace(server_name, client_name);
for (int i = 0; i < repeat_times; ++i){
flow_is_end = false;
packet_handler_initiate();
pthread_t* client_thread = new pthread_t;
pthread_t* server_thread = new pthread_t;
// create thread
pthread_create(server_thread, NULL, &sniff_interface, (void *) &server);
pthread_create(client_thread, NULL, &sniff_interface, (void *) &client);
//pthread_create(client_thread, NULL, &sniff_interface, (void *) client_is_server);
//pthread_create(server_thread, NULL, &sniff_interface, (void *) server_is_server);
std::mutex mtx;
std::unique_lock<std::mutex> lck(mtx);
cond.wait(lck);
pthread_cancel(*server_thread);
pthread_cancel(*client_thread);
//server_thread.Destroy();
//client_thread.Destroy();
/// wait for threads to terminate.
pthread_join(*server_thread, NULL);
pthread_join(*client_thread, NULL);
delete server_thread;
delete client_thread;
}
}
}
/// Print the explanatory string of an exception. If the exception is nested,
/// recurses to print the explanatory of the exception it holds.
static void recursive_print_exception(const std::exception& e)
{
std::cerr << e.what() << std::endl;
try {
std::rethrow_if_nested(e);
} catch(const std::exception& e) {
recursive_print_exception(e);
} catch(...) {}
}
/// Print the type of the exception and its message.
template <typename T>
void show_exception_message(T &e) {
auto exception_type = boost::typeindex::type_id<T>().pretty_name();
std::cerr << "Caught an exception of type ["
<< exception_type << "]" << std::endl;
std::cerr << "Exception message:" << std::endl;
recursive_print_exception(e);
}
static void parse_option(int argc, char **argv) {
namespace po = boost::program_options;
po::options_description all_opts("Options");
all_opts.add_options()
("help", "Produce help message.\n")
("drtt", "Delay RTT.\n")
("auto", po::value<std::string>(),
"Circularly use all the traces.\n")
("test", po::value<std::string>(),
"Test functions.\n")
("trace", po::value<std::string>(),
"Trace folder. "
"Defaultly set to ./trace/")
("no", po::value<std::string>(),
"NO. of trace pair.")
("server", po::value<std::string>(),
"Server CSV (from pcap). "
"Defaultly set to 1s.csv\n")
("client", po::value<std::string>(),
"Client CSV (from pcap). "
"Defaultly set to 1c.csv\n")
("sif", po::value<std::string>(),
"Name of the interface connected to server."
"e.g. eth0 .\n")
("cif", po::value<std::string>(),
"Name of the interface connected to client."
"e.g. eth1 .\n")
("sip", po::value<std::string>(),
"Server IP (e.g. 106.58.5.123).\n")
("tsip", po::value<std::string>(),
"Server IP (e.g. 106.58.5.123).\n")
("tcip", po::value<std::string>(),
"Client IP (e.g. 106.58.5.124).\n")
("repeat", po::value<int>()->default_value(1),
"repeating times for each trace."
"Default to 1.\n")
("lte", po::value<std::string>(),
"Mobileinsight XML file.\n");
/// Build the option map and parse options.
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).
options(all_opts).run(), vm);
po::notify(vm);
/// If --help or -h is set, show the help message and exit.
if (vm.count("help")) {
std::cout << "Usage: " + std::string(argv[0])
<< " [options] [input_file ...]" << std::endl;
std::cout << "If no input file is provided, it reads from stdin."
<< std::endl;
std::cout << all_opts << std::endl;
exit(0);
}
if (vm.count("drtt")) {
std::cout << "delay RTT func is on!" << std::endl;
rtt_delay = true;
} else {
std::cout << "delay RTT func is off!" << std::endl;
rtt_delay = false;
}
if (vm.count("repeat")) {
repeat_times = vm["repeat"].as<int>();
}
if (vm.count("sif")) {
server_interface = vm["sif"].as<std::string>();
} else {
server_interface = "ens8";
}
if (vm.count("cif")) {
client_interface = vm["cif"].as<std::string>();
} else {
client_interface = "ens7";
}
if (vm.count("sip")) {
// std::string = vm["sip"].as<std::string>();
stringstream stream(vm["sip"].as<std::string>());
string _sub;
while (getline(stream, _sub, ','))
server_ip_vector.push_back(_sub);
} else {
server_ip_vector.push_back("10.4.112.4");
server_ip_vector.push_back("172.17.0.4");
server_ip_vector.push_back("172.17.0.6");
server_ip_vector.push_back("106.54.147.34");
server_ip_vector.push_back("106.54.147.38");
}
if (vm.count("tsip")) {
// std::string = vm["sip"].as<std::string>();
stringstream stream(vm["tsip"].as<std::string>());
string _sub;
while (getline(stream, _sub, ','))
server_ip_vector.push_back(_sub);
} else {
server_ip = "10.4.112.4";
}
if (vm.count("tcip")) {
client_ip = vm["tcip"].as<std::string>();
} else {
client_ip = "10.4.96.4";
}
std::string folder;
if (vm.count("folder")) {
folder = vm["folder"].as<std::string>();
if (folder[folder.size()-1] != '/') {
folder += "/";
}
} else {
folder = "./trace/";
}
if (vm.count("no")) {
const auto &no = vm["no"].as<std::string>();
auto server_name = folder + no + "s.csv";
auto client_name = folder + no + "c.csv";
server_filename_queue.push(server_name);
client_filename_queue.push(client_name);
queue_filename_queue.push("./tmp/" + no + "c.csv");
//server_filename_vector.emplace_back(std::move(server_name));
//client_filename_vector.emplace_back(std::move(client_name));
} else if (vm.count("server") && vm.count("client")) {
server_filename_queue.push(folder + vm["server"].as<std::string>());
client_filename_queue.push(folder + vm["client"].as<std::string>());
queue_filename_queue.push("./tmp/" + vm["client"].as<std::string>());
} else if (vm.count("auto")) {
int trace_count = std::stoi(vm["auto"].as<std::string>());
for (int i = 1; i <= trace_count; ++i){
std::string no = std::to_string(i);
auto server_name = folder + no + "s.csv";
auto client_name = folder + no + "c.csv";
server_filename_queue.push(server_name);
client_filename_queue.push(client_name);
queue_filename_queue.push("./tmp/" + no + "c.csv");
}
} else{
auto server_name = folder + "1s.csv";
auto client_name = folder + "1c.csv";
server_filename_queue.push(server_name);
client_filename_queue.push(client_name);
}
}
int main(int argc, char **argv) {
try{
parse_option(argc, argv);
smain();
} catch (...) {
std::cerr << "Caught an unknown exception!" << std::endl;
}
return 0;
} |
Require Import Essentials.Notations.
Require Import Essentials.Arith.
Require Import Metrics.UltraMetric.
Require Import Essentials.Omega.
Require Import Essentials.Facts_Tactics.
Local Open Scope order_scope.
Local Open Scope lattice_scope.
Local Open Scope metric_scope.
(** Limit of a sequence in an ultra metric space. *)
Section Limit.
Context {L : MLattice} {U : UltraMetric L} (Seq : Sequence U).
(** The limit of a sequence is an element whose distance from elements of the sequence
decreases below any positive distance as the sequence progresses. *)
Record Limit : Type :=
{
Lim :> U;
Lim_limit :
∀ (ε : (ApprType L)),
{N : nat | ∀ (n : nat), N ≤ n →
δ(Seq n, Lim) ⊏ (projT1 ε)}
}.
Theorem Limit_unique (l l' : Limit) : l = l' :> U.
Proof.
destruct (ML_bottom_dichotomy L) as [dicht|dicht].
{
apply UM_zero_dist_eq.
apply ML_appr_dominate_pos.
intros y H1.
destruct (dicht _ H1) as [y' Hd1 [Hd2 Hd3]].
destruct (Lim_limit l (existT _ _ Hd1)) as [Nl Hl].
destruct (Lim_limit l' (existT _ _ Hd1)) as [Nl' Hl'].
eapply LE_LT_Trans; [apply (UM_ineq L U l l' (Seq (max Nl Nl'))) |].
eapply LE_LT_Trans; [|apply Hd3].
apply lub_lst; intros [|].
+ rewrite UM_dist_sym.
apply Hl.
apply l_le_max.
+ apply Hl'.
apply r_le_max.
}
{
destruct dicht as [ab Hd1 Hd2].
destruct (Lim_limit l (existT _ _ Hd1)) as [Nl Hl].
destruct (Lim_limit l' (existT _ _ Hd1)) as [Nl' Hl'].
apply UM_zero_dist_eq.
apply LE_Bottom_Bottom.
eapply PO_Trans; [apply (UM_ineq L U l l' (Seq (max Nl Nl'))) |].
apply lub_lst; intros [|].
+ rewrite UM_dist_sym.
specialize (Hl (max Nl Nl') (l_le_max _ _)).
apply Hd2 in Hl; rewrite Hl; trivial.
+ specialize (Hl' (max Nl Nl') (r_le_max _ _)).
apply Hd2 in Hl'; rewrite Hl'; trivial.
}
Qed.
End Limit.
Section Eq_Seq_Eq_Limits.
Context {L : MLattice}
{U : UltraMetric L}
(Seq Seq' : Sequence U)
(l : Limit Seq)
(l' : Limit Seq')
.
Theorem Eq_Seq_Eq_Limits : Seq = Seq' → l = l' :> U.
Proof.
intros H.
destruct H.
apply Limit_unique.
Qed.
End Eq_Seq_Eq_Limits.
Arguments Lim {_ _ _} _.
Arguments Lim_limit {_ _ _} _ _.
Section Limit_of_SubSeq.
Context {L : MLattice} {U : UltraMetric L}.
Program Definition Limit_of_SubSeq {Seq : Sequence U} (l : Limit Seq) (m : nat) :
Limit (fun n => Seq (m + n)) :=
{|
Lim := l
|}.
Next Obligation.
Proof.
destruct (Lim_limit l ε) as [N H].
exists (m + N).
intros n H2.
apply H.
abstract omega.
Defined.
Theorem Limit_of_SubSeq_equal_1 {Seq : Sequence U} (l : Limit Seq) (l' : Limit (fun n => Seq (S n))) : l = l' :> U.
Proof.
cut (∀ (ε : (ApprType L)),
{N : nat | ∀ (n : nat),
N ≤ n →
δ(Seq n, l') ⊏ (projT1 ε)}
).
{
intros H.
transitivity ({|Lim := l'; Lim_limit := H|}); trivial.
apply Limit_unique.
}
{
intros ε.
destruct (Lim_limit l' ε) as [m H'].
exists (S m).
intros n H1.
destruct n; [omega|].
cut (m ≤ n); auto; omega.
}
Qed.
Theorem Limit_of_SubSeq_equal {Seq : Sequence U} (l : Limit Seq) (m : nat) (l' : Limit (fun n => Seq (m + n))) : l = l' :> U.
Proof.
induction m.
+ apply Limit_unique.
+ rewrite ((IHm (Limit_of_SubSeq l m))).
set (W := Limit_of_SubSeq_equal_1 (Limit_of_SubSeq l m)).
cbn in W.
replace (fun n : nat => Seq (m + S n)) with (fun n : nat => Seq (S m + n)) in W
by (abstract (FunExt; apply f_equal; omega)).
apply W.
Qed.
End Limit_of_SubSeq.
Section Limit_of_ConstSeq.
Context {L : MLattice} {U : UltraMetric L} (A : U).
Program Definition Limit_of_ConstSeq :
Limit (fun _ => A) :=
{|
Lim := A
|}.
Next Obligation.
Proof.
exists 0.
intros ? ?.
rewrite UM_eq_zero_dist.
apply ML_appr_pos.
apply (projT2 ε).
Qed.
Theorem Limit_of_ConstSeq_equal (l : Limit (fun _ => A)) : l = A :> U.
Proof.
change A with (Lim Limit_of_ConstSeq).
apply Limit_unique.
Qed.
End Limit_of_ConstSeq.
Section Distance_of_Limits.
Context {L : MLattice} {U : UltraMetric L} (Seq Seq' : Sequence U).
Theorem Distance_of_Limits (δ : L) (l : Limit Seq) (l' : Limit Seq') :
⊥ ⊏ δ → (∀ n, δ(Seq n, Seq' n) ⊑ δ) → δ(l, l') ⊑ δ.
Proof.
intros H1 H2.
destruct (ML_all_approximatable _ _ H1) as [δ' H3 H4].
destruct (Lim_limit l (existT _ _ H4)) as [m H5].
destruct (Lim_limit l' (existT _ _ H4)) as [m' H6].
eapply PO_Trans; [apply UM_ineq|].
apply lub_lst; intros [].
{
rewrite UM_dist_sym.
eapply PO_Trans; [|apply H3].
apply (H5 (max m m') (l_le_max _ _)).
}
{
eapply PO_Trans; [apply UM_ineq|].
apply lub_lst; intros [].
{
apply H2.
}
{
eapply PO_Trans; [|apply H3].
apply (H6 (max m m') (r_le_max _ _)).
}
}
Qed.
End Distance_of_Limits. |
#include <ceed.h>
#include <petsc.h>
#include "../problems/problems.h"
PetscErrorCode RegisterProblems(ProblemFunctions problem_functions) {
PetscErrorCode ierr;
PetscFunctionBegin;
SOLIDS_PROBLEM_REGISTER(problem_functions, "Linear", ElasLinear, NH);
SOLIDS_PROBLEM_REGISTER(problem_functions, "SS-NH", ElasSSNH, NH);
SOLIDS_PROBLEM_REGISTER(problem_functions, "FSCurrent-NH1", ElasFSCurrentNH1,
NH);
SOLIDS_PROBLEM_REGISTER(problem_functions, "FSCurrent-NH2", ElasFSCurrentNH2,
NH);
SOLIDS_PROBLEM_REGISTER(problem_functions, "FSInitial-NH1", ElasFSInitialNH1,
NH);
SOLIDS_PROBLEM_REGISTER(problem_functions, "FSInitial-NH2", ElasFSInitialNH2,
NH);
SOLIDS_PROBLEM_REGISTER(problem_functions, "FSInitial-MR1", ElasFSInitialMR1,
MR);
PetscFunctionReturn(0);
};
|
[STATEMENT]
lemma set_iterator_foldri_one [simp, intro!]: "set_iterator (foldri [a]) {a}"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. set_iterator (foldri [a]) {a}
[PROOF STEP]
by (rule set_iterator_I; simp add: foldri_def) |
[GOAL]
⊢ LargeCategory SSet
[PROOFSTEP]
dsimp only [SSet]
[GOAL]
⊢ LargeCategory (SimplicialObject (Type ?u.23))
[PROOFSTEP]
infer_instance
[GOAL]
⊢ HasLimits SSet
[PROOFSTEP]
dsimp only [SSet]
[GOAL]
⊢ HasLimits (SimplicialObject (Type ?u.489))
[PROOFSTEP]
infer_instance
[GOAL]
⊢ HasColimits SSet
[PROOFSTEP]
dsimp only [SSet]
[GOAL]
⊢ HasColimits (SimplicialObject (Type ?u.577))
[PROOFSTEP]
infer_instance
-- Porting note: added an `ext` lemma.
-- See https://github.com/leanprover-community/mathlib4/issues/5229
[GOAL]
n : ℕ
m₁ m₂ : SimplexCategoryᵒᵖ
f : m₁ ⟶ m₂
α : (fun m => { α // ¬Function.Surjective ↑(asOrderHom α) }) m₁
⊢ ¬Function.Surjective ↑(asOrderHom (f.unop ≫ ↑α))
[PROOFSTEP]
intro h
[GOAL]
n : ℕ
m₁ m₂ : SimplexCategoryᵒᵖ
f : m₁ ⟶ m₂
α : (fun m => { α // ¬Function.Surjective ↑(asOrderHom α) }) m₁
h : Function.Surjective ↑(asOrderHom (f.unop ≫ ↑α))
⊢ False
[PROOFSTEP]
apply α.property
[GOAL]
n : ℕ
m₁ m₂ : SimplexCategoryᵒᵖ
f : m₁ ⟶ m₂
α : (fun m => { α // ¬Function.Surjective ↑(asOrderHom α) }) m₁
h : Function.Surjective ↑(asOrderHom (f.unop ≫ ↑α))
⊢ Function.Surjective ↑(asOrderHom ↑α)
[PROOFSTEP]
exact Function.Surjective.of_comp h
[GOAL]
n : ℕ
i : Fin (n + 1)
m₁ m₂ : SimplexCategoryᵒᵖ
f : m₁ ⟶ m₂
α : (fun m => { α // Set.range ↑(asOrderHom α) ∪ {i} ≠ Set.univ }) m₁
⊢ Set.range ↑(asOrderHom (f.unop ≫ ↑α)) ∪ {i} ≠ Set.univ
[PROOFSTEP]
intro h
[GOAL]
n : ℕ
i : Fin (n + 1)
m₁ m₂ : SimplexCategoryᵒᵖ
f : m₁ ⟶ m₂
α : (fun m => { α // Set.range ↑(asOrderHom α) ∪ {i} ≠ Set.univ }) m₁
h : Set.range ↑(asOrderHom (f.unop ≫ ↑α)) ∪ {i} = Set.univ
⊢ False
[PROOFSTEP]
apply α.property
[GOAL]
n : ℕ
i : Fin (n + 1)
m₁ m₂ : SimplexCategoryᵒᵖ
f : m₁ ⟶ m₂
α : (fun m => { α // Set.range ↑(asOrderHom α) ∪ {i} ≠ Set.univ }) m₁
h : Set.range ↑(asOrderHom (f.unop ≫ ↑α)) ∪ {i} = Set.univ
⊢ Set.range ↑(asOrderHom ↑α) ∪ {i} = Set.univ
[PROOFSTEP]
rw [Set.eq_univ_iff_forall] at h ⊢
[GOAL]
n : ℕ
i : Fin (n + 1)
m₁ m₂ : SimplexCategoryᵒᵖ
f : m₁ ⟶ m₂
α : (fun m => { α // Set.range ↑(asOrderHom α) ∪ {i} ≠ Set.univ }) m₁
h : ∀ (x : Fin (n + 1)), x ∈ Set.range ↑(asOrderHom (f.unop ≫ ↑α)) ∪ {i}
⊢ ∀ (x : Fin (n + 1)), x ∈ Set.range ↑(asOrderHom ↑α) ∪ {i}
[PROOFSTEP]
intro j
[GOAL]
n : ℕ
i : Fin (n + 1)
m₁ m₂ : SimplexCategoryᵒᵖ
f : m₁ ⟶ m₂
α : (fun m => { α // Set.range ↑(asOrderHom α) ∪ {i} ≠ Set.univ }) m₁
h : ∀ (x : Fin (n + 1)), x ∈ Set.range ↑(asOrderHom (f.unop ≫ ↑α)) ∪ {i}
j : Fin (n + 1)
⊢ j ∈ Set.range ↑(asOrderHom ↑α) ∪ {i}
[PROOFSTEP]
apply Or.imp _ id (h j)
[GOAL]
n : ℕ
i : Fin (n + 1)
m₁ m₂ : SimplexCategoryᵒᵖ
f : m₁ ⟶ m₂
α : (fun m => { α // Set.range ↑(asOrderHom α) ∪ {i} ≠ Set.univ }) m₁
h : ∀ (x : Fin (n + 1)), x ∈ Set.range ↑(asOrderHom (f.unop ≫ ↑α)) ∪ {i}
j : Fin (n + 1)
⊢ j ∈ Set.range ↑(asOrderHom (f.unop ≫ ↑α)) → j ∈ Set.range ↑(asOrderHom ↑α)
[PROOFSTEP]
intro hj
[GOAL]
n : ℕ
i : Fin (n + 1)
m₁ m₂ : SimplexCategoryᵒᵖ
f : m₁ ⟶ m₂
α : (fun m => { α // Set.range ↑(asOrderHom α) ∪ {i} ≠ Set.univ }) m₁
h : ∀ (x : Fin (n + 1)), x ∈ Set.range ↑(asOrderHom (f.unop ≫ ↑α)) ∪ {i}
j : Fin (n + 1)
hj : j ∈ Set.range ↑(asOrderHom (f.unop ≫ ↑α))
⊢ j ∈ Set.range ↑(asOrderHom ↑α)
[PROOFSTEP]
exact Set.range_comp_subset_range _ _ hj
[GOAL]
n : ℕ
⊢ LargeCategory (Truncated n)
[PROOFSTEP]
dsimp only [Truncated]
[GOAL]
n : ℕ
⊢ LargeCategory (SimplicialObject.Truncated (Type ?u.74955) n)
[PROOFSTEP]
infer_instance
[GOAL]
n : ℕ
⊢ HasLimits (Truncated n)
[PROOFSTEP]
dsimp only [Truncated]
[GOAL]
n : ℕ
⊢ HasLimits (SimplicialObject.Truncated (Type ?u.75436) n)
[PROOFSTEP]
infer_instance
[GOAL]
n : ℕ
⊢ HasColimits (Truncated n)
[PROOFSTEP]
dsimp only [Truncated]
[GOAL]
n : ℕ
⊢ HasColimits (SimplicialObject.Truncated (Type ?u.75544) n)
[PROOFSTEP]
infer_instance
-- Porting note: added an `ext` lemma.
-- See https://github.com/leanprover-community/mathlib4/issues/5229
|
import data.nat.basic
import data.nat.prime
import number_theory.padics.padic_norm
theorem padic_norm_primes {p q: ℕ} [p_prime: fact (nat.prime p)] [q_prime: fact (nat.prime q)]
(neq: p ≠ q): padic_norm p q = 1 :=
begin
have p: padic_val_rat p q = 0,
exact_mod_cast @padic_val_nat_primes p q p_prime q_prime neq,
simp [padic_norm, p, q_prime.1, nat.prime.ne_zero _],
end
|
Formal statement is: lemma content_primitive_part [simp]: fixes p :: "'a :: {normalization_semidom_multiplicative, semiring_gcd} poly" assumes "p \<noteq> 0" shows "content (primitive_part p) = 1" Informal statement is: If $p$ is a nonzero polynomial, then the content of its primitive part is $1$. |
[STATEMENT]
lemma sum_list_not_infI:
"sum_list xs < \<infinity>" if "\<forall> x \<in> set xs. x < \<infinity>" for xs :: "int extended list"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. sum_list xs < \<infinity>
[PROOF STEP]
using that
[PROOF STATE]
proof (prove)
using this:
\<forall>x\<in>set xs. x < \<infinity>
goal (1 subgoal):
1. sum_list xs < \<infinity>
[PROOF STEP]
apply (induction xs)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<forall>x\<in>set []. x < \<infinity> \<Longrightarrow> sum_list [] < \<infinity>
2. \<And>a xs. \<lbrakk>\<forall>x\<in>set xs. x < \<infinity> \<Longrightarrow> sum_list xs < \<infinity>; \<forall>x\<in>set (a # xs). x < \<infinity>\<rbrakk> \<Longrightarrow> sum_list (a # xs) < \<infinity>
[PROOF STEP]
apply (simp add: zero_extended_def)+
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>a xs. \<lbrakk>sum_list xs < \<infinity>; a < \<infinity> \<and> (\<forall>x\<in>set xs. x < \<infinity>)\<rbrakk> \<Longrightarrow> a + sum_list xs < \<infinity>
[PROOF STEP]
by (smt less_extended_simps(2) plus_extended.elims) |
%language ElabReflection
triv : Elab ()
triv =
do
compute
g <- getGoal
case (snd g) of
`(() : Type) =>
do
fill `(() : ())
solve
otherGoal =>
fail [
TermPart otherGoal,
TextPart "is not trivial"
]
mkId : Elab ()
mkId =
do
intro `{{x}}
fill (Var `{{x}})
solve
idNat : Nat -> Nat
idNat = %runElab mkId
idUnit : () -> ()
idUnit = %runElab mkId
idString : String -> String
idString = %runElab mkId
|
Require Import Raxiom Rconvenient IZR Repsilon Rapprox.
Require Import Arith.
Module Rorder (Import T : CReals).
Module Rconvenient := Rconvenient T. Import Rconvenient.
Module IZR := IZR T. Import IZR.
Module Repsilon := Repsilon T. Import Repsilon.
Module Rapprox := Rapprox T. Import Rapprox.
Section weak_constructive_eps.
Inductive exT {A : Set} (P : A -> Type) : Prop :=
exT_intro : forall a, P a -> exT P.
Variable P : nat -> Type.
Hypothesis P_weak_decidable : forall n : nat, P (S n) + (P n -> False).
Let R (x y : nat) : Prop := x = S (S y) /\ (P y -> False).
Lemma P_Acc : forall n, P n -> Acc R n.
Proof.
intros; constructor.
intros [] []; tauto.
Qed.
Lemma P_later_Acc : forall n x, P (n + x) -> Acc R x.
Proof.
intros n; induction n.
apply P_Acc.
intros x Pnx; constructor; intros y (exy, npx).
apply IHn; subst.
do 2 rewrite <- plus_n_Sm.
destruct (P_weak_decidable (S (n + x))); [ auto | ].
tauto.
Qed.
Corollary exT_Acc_0 : exT P -> Acc R O.
Proof.
intros (n, Hn).
apply (P_later_Acc n).
rewrite <- plus_n_O; assumption.
Qed.
Lemma Acc_0_sigT : Acc R 0%nat -> sigT P.
Proof.
intros HO.
pattern O.
apply (@Fix_F _ R); auto.
clear HO; intros x IHx.
destruct (P_weak_decidable x) as [ px | npx ].
exists (S x); auto.
assert (Rx : R (S (S x)) x); unfold R; eauto.
Qed.
Lemma exT_sigT : exT P -> sigT P.
Proof.
intros exP; apply Acc_0_sigT, exT_Acc_0; auto.
Qed.
End weak_constructive_eps.
Section DiscretePos.
Variable x : R.
Hypothesis xpos : inhabited (Rlt R0 x).
Definition pos_nat : nat -> Type := fun n => R1 < x * po n.
Lemma pos_nat_weak_decidable : forall n, (pos_nat (S n)) + (pos_nat n -> False).
Proof.
intros n.
unfold pos_nat.
pose (xn := x * po (S (S n))); fold xn.
pose proof Rup_spec xn as Hzn.
set (zn := Rup xn); fold zn in Hzn.
destruct Hzn as (uxn, lxn).
destruct (Z_dec zn 3%Z) as [ [ lzn | gzn ] | ezn ].
right.
apply Rlt_asym.
apply Rmul_lt_cancel_r with ((R1 + R1) + (R1 + R1)).
do 2 apply Radd_pos_compat; apply Rlt_0_1.
apply (Req_lt_compat xn (IZR 4)); simpl.
unfold xn, po; simpl; ring.
ring.
apply Rlt_trans with (R1 + IZR zn).
apply (Radd_lt_compat_r (IZR zn)) in uxn.
apply Rle_lt_trans with (xn - IZR zn + IZR zn).
right. ring. apply uxn.
IZRrel.
left.
apply Rmul_lt_cancel_r with (R1 + R1).
IZRrel.
apply (Req_lt_compat (IZR 2) xn); simpl.
apply Rmul_comm.
unfold xn, po; simpl; ring.
apply Rlt_trans with (IZR zn - R1).
IZRrel.
apply (Radd_lt_compat_l (IZR zn)) in lxn.
apply Rlt_le_trans with (IZR zn + (xn - IZR zn)).
apply lxn. right. ring.
(* both right and left? *)
subst.
rewrite ezn in *.
left.
apply Rmul_lt_cancel_r with (R1 + R1).
IZRrel.
apply (Req_lt_compat (IZR 2) xn); simpl.
apply Rmul_comm.
unfold xn, po; simpl; ring.
apply Radd_lt_cancel_r with (- IZR 3).
eapply Req_lt_compat; [ | | apply lxn ]; simpl.
ring.
ring_simplify.
apply Radd_eq_compat_l.
IZRrel.
Qed.
Lemma sigT_pos_nat : sigT pos_nat.
Proof.
apply exT_sigT.
apply pos_nat_weak_decidable.
destruct xpos as [ xposT ].
destruct (Rpos_witness _ xposT) as (n, Hn).
exists n; specialize (Hn n (le_n _)).
apply (Rmul_lt_compat_r (po n) _ _ (Rpos_IPR _)) in Hn.
unfold pos_nat.
eapply Req_lt_compat; [ | | apply Hn ]; simpl.
apply Rinv_l.
reflexivity.
Qed.
Lemma Rlt_0_x : Rlt R0 x.
Proof.
destruct sigT_pos_nat as (n, Hn); unfold pos_nat in *.
apply Rmul_lt_cancel_r with (po n).
apply Rpos_IPR.
apply Rlt_trans with R1.
eapply Req_lt_compat_l; [ | apply Rlt_0_1 ]; symmetry; apply Rmul_0_l.
auto.
Qed.
End DiscretePos.
Theorem Rpos_witness : forall x, inhabited (R0 < x) -> R0 < x.
Proof.
apply Rlt_0_x.
Qed.
Theorem Rlt_witness : forall x y, inhabited (x < y) -> x < y.
Proof.
intros x y L.
apply Rpos_lt, Rpos_witness.
destruct L; constructor.
apply Rlt_pos; auto.
Qed.
End Rorder.
|
module IdrisScript.Objects
import IdrisScript
%access public export
infixl 6 !!
Object : JS_IO (JSValue JSFunction)
Object = do
obj <- jscall "Object" (JS_IO Ptr)
pure $ MkJSFunction obj
||| Creates an empty JavaScript object.
empty : JS_IO (JSValue (JSObject "Object"))
empty = do
obj <- jscall "new Object()" (JS_IO Ptr)
pure $ MkJSObject obj
||| Sets the property `prop` to the value `val` for an object `obj`. Modifies
||| the original value.
setProperty : (prop : String)
-> (val : JSValue a)
-> (obj : JSValue (JSObject c))
-> JS_IO (JSValue (JSObject c))
setProperty prop val obj = do
jscall "%0[%1] = %2" (Ptr -> String -> Ptr -> JS_IO Ptr)
(unpack obj) prop (unpack val)
pure obj
||| Gets the property `prop` from an object `obj`.
getProperty : (prop : String)
-> (obj : JSValue (JSObject c))
-> JS_IO (Maybe (t ** JSValue t))
getProperty prop obj = do
elm <- jscall "%0[%1]" (Ptr -> String -> JS_IO Ptr) (unpack obj) prop
case !(typeOf elm) of
JSUndefined => pure Nothing
_ => pure $ Just !(pack elm)
||| Gets the property `prop` from an object `obj`.
(!!) : (obj : JSValue (JSObject c))
-> (prop : String)
-> JS_IO (Maybe (t : JSType ** JSValue t))
obj !! prop = getProperty prop obj
||| Checks if an object `obj` has the property `prop`.
hasOwnProperty : (prop : String)
-> (obj : JSValue (JSObject c))
-> JS_IO Bool
hasOwnProperty prop obj = do
res <- jscall "%0.hasOwnProperty(%1)" (Ptr -> String -> JS_IO Int)
(unpack obj) prop
pure $ res == 1
||| Returns the keys of an object.
keys : JSValue (JSObject c) -> JS_IO (JSValue JSArray)
keys obj = do
keys <- jscall "Object.keys(%0)" (Ptr -> JS_IO Ptr) (unpack obj)
pure $ MkJSObject keys
||| Returns the constructor of an object.
constr : JSValue (JSObject c) -> JS_IO (JSValue JSFunction)
constr obj = do
con <- jscall "%0.constructor" (Ptr -> JS_IO Ptr) (unpack obj)
pure $ MkJSFunction con
||| Transforms a `Traversable` to an object.
toJSObject : (Traversable f, ToJS from to)
=> f (String, from)
-> JS_IO (JSValue (JSObject "Object"))
toJSObject {from} {to} xs = do
obj <- empty
traverse_ (\x =>
setProperty (fst x) (toJS {from} {to} (snd x)) obj
) xs
pure obj
|
myTestRule {
#Input parameter is:
# Options - currently none are specified for controlling server backup
#Output parameter is:
# Result - a keyvalpair structure holding number of files and size
#
# This will take a while to run.
# Backup files are stored in a directory as hostname_timestamp:
#
# $ ils system_backups
# /tempZone/home/rods/system_backups:
# C- /tempZone/home/rods/system_backups/localhost_2011-08-19.16:00:29
#
#
msiServerBackup(*Opt,*Result);
writeKeyValPairs("stdout",*Result, " : ");
}
INPUT *Opt=""
OUTPUT ruleExecOut
|
From RecordUpdate Require Import RecordSet.
From Perennial.program_proof Require Import disk_lib.
From Perennial.program_proof Require Import wal.invariant wal.common_proof.
Section goose_lang.
Context `{!heapGS Σ}.
Context `{!walG Σ}.
Implicit Types (v:val) (z:Z).
Implicit Types (γ: wal_names).
Implicit Types (s: log_state.t) (memLog: list update.t) (txns: list (u64 * list update.t)).
Implicit Types (pos: u64) (txn_id: nat).
Context (P: log_state.t -> iProp Σ).
Let N := walN.
Let innerN := walN .@ "wal".
Let circN := walN .@ "circ".
Theorem wal_wf_update_durable :
relation.wf_preserved (update_durable) wal_wf.
Proof.
intros s1 s2 [] Hwf ?; simpl in *; monad_inv.
destruct Hwf as (Hwf1&Hwf2&Hwf3).
destruct s1; split; unfold log_state.updates in *; simpl in *; eauto.
split; eauto.
lia.
Qed.
(* just an example, to work out the Flush proof without all the complications *)
Theorem wp_updateDurable (Q: iProp Σ) l γ dinit :
{{{ is_wal P l γ dinit ∗
(∀ σ σ' b,
⌜wal_wf σ⌝ -∗
⌜relation.denote (update_durable) σ σ' b⌝ -∗
(P σ ={⊤ ∖ ↑N}=∗ P σ' ∗ Q))
}}}
Skip
{{{ RET #(); Q}}}.
Proof.
iIntros (Φ) "[#Hwal Hfupd] HΦ".
iDestruct "Hwal" as "[Hwal Hcirc]".
iInv "Hwal" as "Hinv".
wp_call.
iDestruct "Hinv" as (σ) "(Hinner&HP)".
iNamed "Hinner".
iNamed "Hdisk".
iNamed "Hdisk".
iNamed "circ.end".
pose proof (is_txn_bound _ _ _ Hend_txn) as Hend_bound.
iMod (fupd_mask_subseteq (⊤ ∖ ↑N)) as "HinnerN"; first by solve_ndisj.
iMod ("Hfupd" $! σ (set log_state.durable_lb (λ _, (σ.(log_state.durable_lb) `max` diskEnd_txn_id)%nat) σ)
with "[% //] [%] [$HP]") as "[HP HQ]".
{ simpl.
econstructor; monad_simpl.
econstructor; monad_simpl; lia. }
iMod "HinnerN" as "_".
iSpecialize ("HΦ" with "HQ").
iFrame "HΦ".
iIntros "!> !>".
iExists _; iFrame "HP".
iSplit.
- iPureIntro.
eapply wal_wf_update_durable; eauto.
{ simpl; monad_simpl.
econstructor; monad_simpl.
econstructor; monad_simpl; lia. }
- simpl.
iFrame.
iExists _. iFrame "Howncs".
iExists installed_txn_id, _, _. simpl. iFrame "# ∗ %".
iExists _, diskEnd_txn_id.
rewrite (Nat.max_l (_ `max` _)%nat _); last by lia.
iFrame "# %".
iPureIntro.
split; first by lia.
split; first by lia.
destruct (decide (σ.(log_state.durable_lb) ≤ diskEnd_txn_id)).
{
rewrite Nat.max_r; last by lia.
rewrite subslice_zero_length.
apply Forall_nil_2.
}
rewrite Nat.max_l; last by lia.
rewrite -(subslice_app_contig _ (S diskEnd_txn_id)) in Hdurable_nils;
last by lia.
apply Forall_app in Hdurable_nils.
intuition.
Qed.
Theorem simulate_flush l γ Q σ dinit pos txn_id nextDiskEnd_txn_id mutable :
is_circular circN (circular_pred γ) γ.(circ_name) -∗
(is_wal_inner l γ σ dinit ∗ P σ) -∗
diskEnd_at_least γ.(circ_name) (int.Z pos) -∗
txn_pos γ txn_id pos -∗
memLog_linv_nextDiskEnd_txn_id γ mutable nextDiskEnd_txn_id -∗
(∀ (σ σ' : log_state.t) (b : ()),
⌜wal_wf σ⌝
-∗ ⌜relation.denote (log_flush pos txn_id) σ σ' b⌝ -∗ P σ ={⊤ ∖ ↑N}=∗ P σ' ∗ Q) -∗
|NC={⊤ ∖ ↑innerN}=>
∃ σ' nextDiskEnd_txn_id',
is_wal_inner l γ σ' dinit ∗ P σ' ∗ Q ∗
memLog_linv_nextDiskEnd_txn_id γ mutable nextDiskEnd_txn_id' ∗
⌜nextDiskEnd_txn_id ≤ nextDiskEnd_txn_id' < length σ.(log_state.txns)⌝ ∗
⌜Forall (λ x, x.2 = []) (
subslice (S nextDiskEnd_txn_id) (S nextDiskEnd_txn_id')
σ.(log_state.txns)
)⌝.
Proof.
iIntros "#Hcirc Hinv #Hlb #Hpos_txn HstableSet Hfupd".
iDestruct "Hinv" as "[Hinner HP]".
iNamed "Hinner".
iNamed "Hdisk".
iNamed "Hdisk".
iNamed "circ.end".
iMod (is_circular_diskEnd_lb_agree with "Hlb Hcirc Howncs") as "(%Hlb&Howncs)"; first by solve_ndisj.
iDestruct (txn_pos_valid_general with "Htxns_ctx Hpos_txn") as %His_txn.
pose proof (is_txn_bound _ _ _ His_txn).
pose proof (is_txn_bound _ _ _ Hend_txn).
pose proof (wal_wf_txns_mono_pos Hwf His_txn Hend_txn) as Hpos_diskEnd.
iMod (fupd_mask_subseteq (⊤ ∖ ↑N)) as "HinnerN"; first by solve_ndisj.
iMod ("Hfupd" $!
σ
(
set log_state.durable_lb (λ _,
(diskEnd_txn_id `max` (σ.(log_state.durable_lb) `max` txn_id))%nat
) σ
)
with "[% //] [%] HP"
) as "[HP HQ]".
{ simpl; monad_simpl.
repeat (econstructor; monad_simpl; eauto); lia.
}
iMod "HinnerN" as "_".
iFrame "HQ".
iAssert (⌜
int.Z pos = int.Z diskEnd →
Forall (λ x, x.2 = []) (
subslice
(S (σ.(log_state.durable_lb) `max` diskEnd_txn_id))
(S txn_id)
σ.(log_state.txns)
)
⌝)%I with "[HstableSet HnextDiskEnd_inv]" as "%Hpos_diskEnd_nils".
{
iApply pure_impl_2.
iIntros (Hpos_diskEnd_eq).
apply word.unsigned_inj in Hpos_diskEnd_eq.
rewrite Hpos_diskEnd_eq in His_txn.
iPoseProof (subslice_stable_nils2 with "[HstableSet HnextDiskEnd_inv]")
as "Hnils".
1: eassumption.
1: apply Hdurable_lb_pos.
1: apply His_txn.
{
iSplit; first by iFrame.
iFrame "#".
}
iFrame.
}
iAssert (|==>
⌜Forall (λ x, x.2 = []) (
subslice
(S diskEnd_txn_id)
(S (diskEnd_txn_id `max` (txn_id)))
σ.(log_state.txns)
)⌝ ∗
(diskEnd_txn_id `max` (txn_id))%nat
[[γ.(stable_txn_ids_name)]]↦ro tt ∗
nextDiskEnd_inv γ σ.(log_state.txns) ∗
txns_ctx γ σ.(log_state.txns) ∗
∃ nextDiskEnd_txn_id',
memLog_linv_nextDiskEnd_txn_id γ mutable nextDiskEnd_txn_id' ∗
⌜nextDiskEnd_txn_id ≤ nextDiskEnd_txn_id' < length σ.(log_state.txns)⌝ ∗
⌜Forall (λ x, x.2 = []) (
subslice (S nextDiskEnd_txn_id) (S nextDiskEnd_txn_id')
σ.(log_state.txns)
)⌝
)%I
with "[HstableSet HnextDiskEnd_inv Htxns_ctx]"
as "H".
{
destruct (decide (
txn_id ≤ diskEnd_txn_id
)%nat).
{ rewrite -> (max_l diskEnd_txn_id _) by lia.
rewrite ?subslice_zero_length. iSplitR; first by done.
iAssert (⌜nextDiskEnd_txn_id < length σ.(log_state.txns)⌝)%I as "%HnextDiskEnd_txn_bound".
{
iNamed "HstableSet".
iDestruct (txn_pos_valid_general with "Htxns_ctx HnextDiskEnd_txn") as %HnextDiskEnd_txn_bound.
eapply is_txn_bound in HnextDiskEnd_txn_bound. iPureIntro. lia.
}
iFrame "Hend_txn_stable".
iFrame "HnextDiskEnd_inv".
iFrame "Htxns_ctx".
iExists nextDiskEnd_txn_id.
rewrite ?subslice_zero_length.
iFrame "HstableSet".
iModIntro.
iSplit; first by iPureIntro; lia.
iPureIntro.
eauto.
}
pose proof (wal_wf_txns_mono_pos Hwf His_txn Hend_txn).
replace diskEnd with pos in * by word.
iMod (stable_txn_id_advance _ _ _ txn_id
with "HstableSet HnextDiskEnd_inv Hend_txn_stable Htxns_ctx")
as "H"; eauto.
{ lia. }
iDestruct "H" as "(#Hstable & HnextDiskEnd_inv & Htxns_ctx & H)".
iDestruct "H" as (nextDiskEnd_txn_id') "(HstableSet & %Hle & %Hnils')".
iModIntro.
iSplit.
{
iDestruct (subslice_stable_nils with "[$HnextDiskEnd_inv $Hend_txn_stable]") as "%Hnils_txn".
1: eassumption.
2: eassumption.
2: eapply His_txn.
1: lia.
iPureIntro.
destruct (decide (diskEnd_txn_id ≤ txn_id)%nat).
{
rewrite Nat.max_r; last by lia.
assumption.
}
rewrite Nat.max_l; last by lia.
rewrite subslice_zero_length.
apply Forall_nil_2.
}
iFrame "HnextDiskEnd_inv".
iSplitR.
{
destruct (decide (diskEnd_txn_id ≤ txn_id)%nat).
{
rewrite (Nat.max_r _ txn_id); last by lia.
iFrame "#".
}
rewrite (Nat.max_l _ txn_id); last by lia.
iFrame "#".
}
iFrame "Htxns_ctx".
iExists nextDiskEnd_txn_id'.
iFrame "HstableSet".
done.
}
iMod "H" as "(%Hnils & #Hstable & HnextDiskEnd_inv & Htxns_ctx & H)".
iDestruct "H" as (nextDiskEnd_txn_id') "(HstableSet & %Hle & %Hnils')".
iModIntro.
iExists _, _; iFrame "HP".
iFrame (Hle Hnils') "HstableSet".
iSplit; auto.
{ iPureIntro.
eapply wal_wf_update_durable; eauto.
simpl; monad_simpl.
repeat (econstructor; monad_simpl; eauto); lia.
}
simpl.
iFrame.
iExists _; iFrame.
iExists installed_txn_id, _, _. iFrame "# ∗".
iSplitL.
2: {
iPureIntro.
auto with lia.
}
iExists _, diskEnd_txn_id.
simpl.
iSplit; first by (iPureIntro; lia).
iSplit; first by (iPureIntro; lia).
iSplit.
{
iPureIntro.
destruct (decide (
(diskEnd_txn_id `max` txn_id) ≤ σ.(log_state.durable_lb)
)%nat).
{
rewrite Nat.max_r; last by lia.
rewrite Nat.max_l; last by lia.
destruct (decide (S diskEnd_txn_id ≤ txn_id)%nat).
{
rewrite Nat.max_r in Hnils; last by lia.
rewrite -(subslice_app_contig _ (S diskEnd_txn_id)) in Hdurable_nils;
last by lia.
apply Forall_app in Hdurable_nils.
intuition.
}
rewrite -(subslice_app_contig _ (S diskEnd_txn_id)) in Hdurable_nils;
last by lia.
apply Forall_app in Hdurable_nils.
intuition.
}
replace (_ `max` (_ `max` _))%nat with (diskEnd_txn_id `max` txn_id)%nat
by lia.
assumption.
}
iSplit.
{
iPureIntro.
destruct (decide (int.Z pos < int.Z diskEnd)) as [Hcmp|Hcmp].
{
apply Hpos_diskEnd in Hcmp.
replace (_ `max` _)%nat
with (σ.(log_state.durable_lb) `max` diskEnd_txn_id)%nat
by lia.
eassumption.
}
rewrite -HdiskEnd_val in Hlb.
assert (int.Z pos = int.Z diskEnd) as Hpos_diskEnd_eq by lia.
apply word.unsigned_inj in Hpos_diskEnd_eq.
subst pos.
rewrite Nat.max_l; last by lia.
destruct (decide
((σ.(log_state.durable_lb) `max` diskEnd_txn_id) ≤ txn_id)%nat
).
{
rewrite Nat.max_r; last by lia.
rewrite Nat.max_r; last by lia.
assumption.
}
replace (_ `max` _)%nat
with (σ.(log_state.durable_lb) `max` diskEnd_txn_id)%nat; last by lia.
assumption.
}
iSplit; first by (iPureIntro; assumption).
iSplit; first by (iPureIntro; assumption).
destruct (decide (
txn_id ≤ (σ.(log_state.durable_lb) `max` diskEnd_txn_id)
)%nat).
{
replace ((_ `max` _) `max` _)%nat
with (σ.(log_state.durable_lb) `max` diskEnd_txn_id)%nat;
last by lia.
iFrame "#".
}
replace ((_ `max` _) `max` _)%nat
with (diskEnd_txn_id `max` txn_id)%nat; last by lia.
iFrame "#".
Unshelve.
all: try constructor.
Qed.
(* this is a dumb memory safety proof for loading nextDiskEnd when its value
doesn't matter for correctness *)
Theorem wp_load_some_nextDiskEnd st γ :
{{{ wal_linv st γ }}}
struct.loadF sliding "mutable"
(struct.loadF WalogState "memLog" #st)
{{{ (nextDiskEnd:u64), RET #nextDiskEnd; wal_linv st γ }}}.
Proof.
iIntros (Φ) "Hinv HΦ".
iNamed "Hinv".
iNamed "Hfields".
iNamed "Hfield_ptsto".
wp_loadField.
(* this is very bad, breaks sliding abstraction boundary *)
iNamed "His_memLog"; iNamed "Hinv". wp_loadField.
iApply "HΦ".
iExists _; iFrame "# ∗".
iExists _; iFrame "# ∗".
iSplit; auto.
iSplit; auto.
iExists _, _; iFrame "# ∗".
Qed.
Theorem wp_Walog__Flush (Q: iProp Σ) l γ dinit txn_id pos :
{{{ is_wal P l γ dinit ∗
txn_pos γ txn_id pos ∗
(∀ σ σ' b,
⌜wal_wf σ⌝ -∗
⌜relation.denote (log_flush pos txn_id) σ σ' b⌝ -∗
(P σ ={⊤ ∖ ↑N}=∗ P σ' ∗ Q))
}}}
Walog__Flush #l #pos
{{{ RET #(); Q}}}.
Proof.
iIntros (Φ) "(#Hwal & #Hpos_txn & Hfupd) HΦ".
destruct_is_wal.
wp_apply util_proof.wp_DPrintf.
wp_loadField.
wp_apply (acquire_spec with "lk"). iIntros "(Hlocked&Hlkinv)".
wp_loadField.
wp_apply (wp_condBroadcast with "cond_logger").
wp_loadField.
wp_apply (wp_load_some_nextDiskEnd with "Hlkinv"); iIntros (x) "Hlkinv".
wp_pures.
wp_apply (wp_If_optional with "[] [Hlkinv Hlocked]"); [ | iAccu | ].
{
iIntros (Φ') "(Hlkinv&Hlocked) HΦ".
wp_loadField.
wp_apply (wp_endGroupTxn with "Hlkinv").
iIntros "Hlkinv".
wp_pures.
iApply ("HΦ" with "[$]").
}
iIntros "(Hlkinv&Hlocked)".
wp_pures.
wp_bind (For _ _ _).
wp_apply (wp_forBreak_cond (λ b,
wal_linv σₛ.(wal_st) γ ∗ locked #σₛ.(memLock) ∗
if b then ⊤ else diskEnd_at_least γ.(circ_name) (int.Z pos)
)%I with "[] [$Hlkinv $Hlocked]").
{ iIntros "!>" (Φ') "(Hlkinv&Hlocked&_) HΦ".
wp_loadField.
iNamed "Hlkinv".
iNamed "Hfields".
iNamed "Hfield_ptsto".
wp_loadField.
wp_pures.
wp_if_destruct.
- wp_loadField.
wp_apply (wp_condWait with "[-HΦ $cond_logger $lk $Hlocked]").
{ iExists _; iFrame "∗ #".
iExists _; by iFrame "∗ #". }
iIntros "(Hlocked&Hlockin)".
wp_pures.
iApply "HΦ"; by iFrame.
- iApply "HΦ".
iFrame "Hlocked".
iNamed "HdiskEnd_circ".
iSplitL.
{ iExists _; iFrame "# ∗".
iExists _; by iFrame "# ∗". }
iApply (diskEnd_at_least_mono with "HdiskEnd_at_least"); auto.
}
iIntros "(Hlkinv&Hlocked&#HdiskEnd_lb)".
wp_seq.
wp_bind Skip.
iDestruct "Hwal" as "[Hwal Hcirc]".
iInv "Hwal" as "Hinv".
iApply wp_ncfupd.
wp_call.
iDestruct "Hinv" as (σ) "[Hinner HP]".
iNamed "Hlkinv".
iNamed "HmemLog_linv".
iAssert (⌜txns = σ.(log_state.txns)⌝)%I as "%Htxnseq".
{
iNamed "Hinner".
iDestruct (ghost_var_agree with "Howntxns γtxns") as "%Htxnseq".
done.
}
subst.
iMod (simulate_flush with "Hcirc [$Hinner $HP] HdiskEnd_lb Hpos_txn HnextDiskEnd Hfupd") as "H".
iDestruct "H" as (σ' nextDiskEnd_txn_id') "(Hinner & HP & HQ & HnextDiskEnd & %Hle & %Hnils)".
iApply fupd_ncfupd. iApply fupd_intro.
iModIntro.
iSplitL "Hinner HP".
{ iNext. iExists _. iFrame. }
wp_loadField.
wp_apply (release_spec with "[-HQ HΦ]").
{ iFrame "lk". iFrame "Hlocked". iNext. iExists _.
iFrame "Hfields HdiskEnd_circ Hstart_circ".
iExists _, _, _, _, _, _, _.
iFrame "∗#%".
iNamed "Hlinv_pers".
iFrame "#%".
iPureIntro.
split; first by (intuition (eauto; try lia)).
pose proof Htxns as [Hbnds Hregs].
split.
{
intros bndry Hbndry.
specialize (Hbnds bndry).
apply elem_of_list_lookup in Hbndry.
destruct Hbndry as [i Hbndry].
do 4 (destruct i; first by (
simpl in Hbndry; inversion Hbndry; subst bndry; clear Hbndry;
apply Hbnds; set_solver
)).
destruct i.
2: {
destruct i; first by (
simpl in Hbndry; inversion Hbndry; subst bndry; clear Hbndry;
apply Hbnds; set_solver
).
inversion Hbndry.
}
simpl in Hbndry; inversion Hbndry; subst bndry; clear Hbndry.
simpl.
clear Hbnds.
pose proof Htxns as [Hbnds _].
unshelve (epose proof (Hbnds _ _) as Hbnd).
2: {
apply elem_of_list_lookup.
exists mwrb_us.
reflexivity.
}
simpl in Hbnd.
lia.
}
intros i bndry1 bndry2 Hbndry1 Hbndry2.
specialize (Hregs i bndry1 bndry2).
do 3 (destruct i; first by (
simpl in Hbndry1; inversion Hbndry1; subst bndry1; clear Hbndry1;
simpl in Hbndry2; inversion Hbndry2; subst bndry2; clear Hbndry2;
simpl; apply Hregs; reflexivity
)).
clear Hregs.
unshelve (epose proof (
is_memLog_boundaries_region_consec mwrb_uss _ _ _ _ _ Htxns _ _
) as Hreg1).
3-4: reflexivity.
unshelve (epose proof (
is_memLog_boundaries_region_consec mwrb_us _ _ _ _ _ Htxns _ _
) as Hreg2).
3-4: reflexivity.
simpl in Hreg1.
simpl in Hreg2.
destruct i.
{
simpl in Hbndry1; inversion Hbndry1; subst bndry1; clear Hbndry1;
simpl in Hbndry2; inversion Hbndry2; subst bndry2; clear Hbndry2.
simpl.
split; first by lia.
split; first by lia.
rewrite -(subslice_app_contig _ (S nextDiskEnd_txn_id)); last by lia.
apply is_memLog_region_append_nils; first by assumption.
intuition.
}
destruct i; last by inversion Hbndry2.
simpl in Hbndry1; inversion Hbndry1; subst bndry1; clear Hbndry1;
simpl in Hbndry2; inversion Hbndry2; subst bndry2; clear Hbndry2.
simpl.
split; first by lia.
split; first by lia.
eapply is_memLog_region_prepend_nils; first by eassumption.
rewrite subslice_app_contig; last by lia.
intuition.
}
wp_pures. by iApply ("HΦ" with "HQ").
Qed.
End goose_lang.
|
module ContriverText.Tests
import Data.SortedSet
import Effects
import Effect.System
import ContriverText
import ContriverText.JsUtil
quoteListOfStrings : List String -> TT
quoteListOfStrings [] = `([] : List String)
quoteListOfStrings (x :: xs) =
`((~(TConst (Str x)) :: ~(quoteListOfStrings xs)) : List String)
bindingToStrings : (TTName, Binder TT) -> List String
bindingToStrings (UN v, t) = [v]
bindingToStrings _ = []
-- The failure message is based on idris-dev's
-- test/quasiquote004/Quasiquote004.idr
currentLocalVars : List (TTName, Binder TT) -> TT -> Tactic
currentLocalVars ctxt `(List String) =
Exact (quoteListOfStrings (ctxt >>= bindingToStrings))
currentLocalVars _ _ = Fail [TextPart "Not a List String goal"]
someLocalVars : List String
someLocalVars = proof
let myVariable : String = "foo"
let myOtherVariable : String = "bar"
applyTactic currentLocalVars
runTests : {auto f : FFI} -> IO' f ()
runTests = do
putStrLn ("Hello tests " ++ show (myInc 4000))
putStrLn
("Number of facts in the initial story state " ++
show (length (Data.SortedSet.toList initialStoryState)))
putStrLn (show someLocalVars)
-- NOTE: This will only work in a non-JS build.
-- putStrLn (show !(run time))
-- NOTE: Some of these tests are very memory-intensive to compile, so
-- we actually can't uncomment the tests all at once (on my machine).
--
-- TODO: See if this will cause problems for actual application
-- development.
--
runJsTests : JS_IO ()
runJsTests = do
jsf0 """
console.log( "hello" )
"""
let foo = jsft (Int -> Int -> JS_IO ()) """
console.log( "heya " + (%0 + %1) )
"""
foo 5 6
foo2 <- jsf0 """function (a, b) {
console.log( "heya2 " + (a + b) )
}"""
jsft (Ptr -> Int -> Int -> JS_IO ()) """
%0( %1, %2 )
""" foo2 5 6
jsc2 foo2 !(jsint 5) !(jsint 10)
{-
jsm1 !(jsf0 "console") "log"
!(jsm1 !(jsf0 "JSON") "stringify"
!(jso2_i
"foo" !(jsint 1)
"bar" !(jsint 2)))
-}
{-
jsft (JsFn (Int -> Int) -> JS_IO ()) """
console.log(%0(4))
""" (MkJsFn (\a => unsafePerformIO (do
jsf0 """
console.log( "inside 1" )
"""
return (a + 1))))
-}
{-
jsm1 !(jsf0 "console") "log"
!(jsc0 !(jsfn0 (do
jsf0 """
console.log( "inside 2" )
"""
jsptr "outside 2"
)))
-}
{-
jsm1 !(jsf0 "console") "log"
!(jsc1 !(jsfn1 (\s0 => do
jsf1 """
console.log( "inside 3 " + %0 )
""" s0
jsptr "outside 3"
)) !(jsptr "world"))
-}
jsm1 !(jsf0 "console") "log"
!(jsc2 !(jsfn2_f (\s0, s1 => do
jsf2 """
console.log( "inside 4 " + %0 + " " + %1 )
""" s0 s1
jsptr "outside 4"
)) !(jsptr "world") !(jsptr "tour"))
jsf1 """
window.onload = function () {
function arrEach( arr, body ) {
for ( var i = 0, n = arr.length; i < n; i++ )
body( arr[ i ], i );
}
function arrMappend( arr, check ) {
var result = [];
arrEach( arr, function ( item, i ) {
arrEach( check( item, i ), function ( itemItem ) {
result.push( itemItem );
} );
} );
return result;
}
var hereEl = document.createElement( "div" );
var focusEl = document.createElement( "div" );
document.html.appendChild( hereEl );
document.html.appendChild( focusEl );
var currentTime = 0;
var storyState = %0;
function setContent( containerEl, content ) {
while ( containerEl.hasChildNodes() )
containerEl.removeChild( containerEl.firstChild );
var innerContainerEl = document.createElement( "div" );
arrEach( content, function ( para ) {
var paraEl = document.createElement( "p" );
arrEach( para, function ( span ) {
var spanEl = document.createTextNode( span.text );
if ( span.link !== null ) {
var newSpanEl = document.createElement( "a" );
newSpanEl.setAttribute( "href", "#" );
newSpanEl.onclick = function () {
setContent( focusEl,
getDescription( span.link.val ) );
};
newSpanEl.appendChild( spanEl );
spanEl = newSpanEl;
}
paraEl.appendChild( spanEl );
} );
innerContainerEl.appendChild( paraEl );
} );
containerEl.appendChild( innerContainerEl );
}
function getDescription( topic ) {
var descriptions = arrMappend( storyState,
function ( temporalFact ) {
if ( currentTime < temporalFact.startTime )
return [];
var end = temporalFact.endTime;
if ( end.type === "knownEndTime" ) {
if ( end.time <= currentTime )
return [];
} else if ( end.type === "assumeAfter" ) {
if ( end.time <= currentTime && !end.assumption )
return [];
} else {
throw new Error();
}
var fact = temporalFact.fact;
if ( fact.type === "describes"
&& fact.pov === "you"
&& fact.topic === "here" )
return [ fact.description ];
else
return [];
} );
if ( descriptions.length !== 1 )
throw new Error();
return descriptions[ 0 ];
}
setContent( hereEl, getDescription( topic ) );
};
""" !(jsa_i $ for (
Data.SortedSet.toList initialStoryState
) (\(MkTemporalFact (MkStartTime startTime) endTime fact) =>
jso3_i
"startTime" !(jsint $ toInt startTime)
"endTime"
!(case endTime of
KnownEndTime time => jso2_i
"type" !(jsptr "knownEndTime")
"time" !(jsint $ toInt time)
AssumeAfter time assumption => jso3_i
"type" !(jsptr "assumeAfter")
"time" !(jsint $ toInt time)
"assumption"
(ifThenElse assumption !(jsf0 "true") !(jsf0 "false")))
"fact"
!(case fact of
ExistsPov pov => jso2_i
"type" !(jsptr "existsPov")
"pov" !(jsptr pov)
ExistsTopic topic => jso2_i
"type" !(jsptr "existsTopic")
"topic" !(jsptr topic)
Describes pov topic (MkHtextBlocks desc) => jso3_i
"type" !(jsptr "describes")
"pov" !(jsptr pov)
"topic" !(jsptr topic)
"desc"
!(jsa_i $ for desc $ \(MkHtextBlock para) =>
jsa_i $ for para $ \(MkHtextSpan maybeLink text) =>
jso2_i
"link"
!(case maybeLink of
MyNothing => jsf0 "null"
MyJust topic =>
jso1_i "val" !(jsptr topic))
"text" text))
))
return ()
testMain : {auto f : FFI} -> IO' f ()
testMain = do
putStrLn "Running the tests"
runTests
appMain : {auto f : FFI} -> IO' f ()
appMain = do
putStrLn "Running the main app (which runs the tests)"
runTests
|
/-
Copyright (c) 2022 Moritz Doll. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Moritz Doll, Mario Carneiro, Robert Y. Lewis
-/
import Mathlib.Tactic.Basic
import Mathlib.Tactic.NormCast
import Mathlib.Tactic.Zify.Attr
import Mathlib.Data.Int.Basic
/-!
# `zify` tactic
The `zify` tactic is used to shift propositions from `ℕ` to `ℤ`.
This is often useful since `ℤ` has well-behaved subtraction.
```
example (a b c x y z : ℕ) (h : ¬ x*y*z < 0) : c < a + 3*b := by
zify
zify at h
/-
h : ¬↑x * ↑y * ↑z < 0
⊢ ↑c < ↑a + 3 * ↑b
-/
```
-/
namespace Mathlib.Tactic.Zify
open Lean
open Lean.Meta
open Lean.Parser.Tactic
open Lean.Elab.Tactic
/--
The `zify` tactic is used to shift propositions from `ℕ` to `ℤ`.
This is often useful since `ℤ` has well-behaved subtraction.
```
example (a b c x y z : ℕ) (h : ¬ x*y*z < 0) : c < a + 3*b := by
zify
zify at h
/-
h : ¬↑x * ↑y * ↑z < 0
⊢ ↑c < ↑a + 3 * ↑b
-/
```
`zify` can be given extra lemmas to use in simplification. This is especially useful in the
presence of nat subtraction: passing `≤` arguments will allow `push_cast` to do more work.
```
example (a b c : ℕ) (h : a - b < c) (hab : b ≤ a) : false := by
zify [hab] at h
/- h : ↑a - ↑b < ↑c -/
```
`zify` makes use of the `@[zify_simps]` attribute to move propositions,
and the `push_cast` tactic to simplify the `ℤ`-valued expressions.
`zify` is in some sense dual to the `lift` tactic. `lift (z : ℤ) to ℕ` will change the type of an
integer `z` (in the supertype) to `ℕ` (the subtype), given a proof that `z ≥ 0`;
propositions concerning `z` will still be over `ℤ`. `zify` changes propositions about `ℕ` (the
subtype) to propositions about `ℤ` (the supertype), without changing the type of any variable.
-/
syntax (name := zify) "zify" (simpArgs)? (ppSpace location)? : tactic
macro_rules
| `(tactic| zify $[[$simpArgs,*]]? $[at $location]?) =>
let args := simpArgs.map (·.getElems) |>.getD #[]
`(tactic|
simp (config := {decide := false}) only [zify_simps, push_cast, $args,*] $[at $location]?)
/-- The `Simp.Context` generated by `zify`. -/
def mkZifyContext (simpArgs : Option (Syntax.TSepArray `Lean.Parser.Tactic.simpStar ",")) :
TacticM MkSimpContextResult := do
let args := simpArgs.map (·.getElems) |>.getD #[]
mkSimpContext
(← `(tactic| simp (config := {decide := false}) only [zify_simps, push_cast, $args,*])) false
/-- A variant of `applySimpResultToProp` that cannot close the goal, but does not need a meta
variable and returns a tuple of a proof and the corresponding simplified proposition. -/
def applySimpResultToProp' (proof : Expr) (prop : Expr) (r : Simp.Result) : MetaM (Expr × Expr) :=
do
match r.proof? with
| some eqProof => return (← mkExpectedTypeHint (← mkEqMP eqProof proof) r.expr, r.expr)
| none =>
if r.expr != prop then
return (← mkExpectedTypeHint proof r.expr, r.expr)
else
return (proof, r.expr)
/-- Translate a proof and the proposition into a zified form. -/
def zifyProof (simpArgs : Option (Syntax.TSepArray `Lean.Parser.Tactic.simpStar ","))
(proof : Expr) (prop : Expr) : TacticM (Expr × Expr) := do
let ctx_result ← mkZifyContext simpArgs
let (r, _) ← simp prop ctx_result.ctx
applySimpResultToProp' proof prop r
@[zify_simps] lemma nat_cast_eq (a b : ℕ) : a = b ↔ (a : ℤ) = (b : ℤ) := Int.ofNat_inj.symm
@[zify_simps] lemma nat_cast_le (a b : ℕ) : a ≤ b ↔ (a : ℤ) ≤ (b : ℤ) := Int.ofNat_le.symm
@[zify_simps] lemma nat_cast_lt (a b : ℕ) : a < b ↔ (a : ℤ) < (b : ℤ) := Int.ofNat_lt.symm
@[zify_simps] lemma nat_cast_ne (a b : ℕ) : a ≠ b ↔ (a : ℤ) ≠ (b : ℤ) := by
simp only [ne_eq, Int.cast_eq_cast_iff_Nat]
|
/-
Copyright (c) 2022 Jun Yoshida. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
-/
/-!
# Basic definitions
-/
universe u v
inductive DEq {α : Type u} (β : α → Type v) : {a₁ a₂ : α} → β a₁ → β a₂ → Prop
| refl {a : α} (b : β a) : DEq β b b
namespace DEq
variable {α : Type u} {β : α → Type v}
theorem trans {a₁ a₂ a₃ : α} : ∀ {x₁ : β a₁} {x₂ : β a₂} {x₃ : β a₃}, DEq β x₁ x₂ → DEq β x₂ x₃ → DEq β x₁ x₃
| _, _, _, DEq.refl _, DEq.refl _ => DEq.refl _
instance instTransDEq (a₁ a₂ a₃ : α) : Trans (DEq β (a₁:=a₁) (a₂:=a₂)) (DEq β (a₁:=a₂) (a₂:=a₃)) (DEq β (a₁:=a₁) (a₂:=a₃)) where
trans hxy hyz := DEq.trans hxy hyz
theorem symm : ∀ {a₁ a₂ : α} {b₁ : β a₁} {b₂ : β a₂}, DEq β b₁ b₂ → DEq β b₂ b₁
| _, _, _, _, DEq.refl _ => DEq.refl _
theorem subst_deq : ∀ {a₁ a₂ : α} {h : a₁ = a₂} {b : β a₁}, DEq β (h ▸ b) b
| _, _, Eq.refl _, _ => DEq.refl _
theorem eq_param : ∀ {a₁ a₂ : α} {x₁ : β a₁} {x₂ : β a₂}, DEq β x₁ x₂ → a₁ = a₂
| _, _, _, _, DEq.refl _ => rfl
theorem deq_of_eq : ∀ {a : α} {x₁ x₂ : β a}, x₁ = x₂ → DEq β x₁ x₂
| _, _, _, rfl => DEq.refl _
theorem eq_of_deq : ∀ {a : α} {x₁ x₂ : β a}, DEq β x₁ x₂ → x₁ = x₂
| _, _, _, DEq.refl _ => rfl
end DEq |
module Oscar.Data.Vec.Properties where
open import Oscar.Data.Vec
open import Data.Vec.Properties public
open import Data.Nat
open import Data.Product renaming (map to mapP)
open import Relation.Binary.PropositionalEquality
open import Data.Fin
map-∈ : ∀ {a b} {A : Set a} {B : Set b} {y : B} {f : A → B} {n} {xs : Vec A n} → y ∈ map f xs → ∃ λ x → f x ≡ y
map-∈ {xs = []} ()
map-∈ {xs = x ∷ xs} here = x , refl
map-∈ {xs = x ∷ xs} (there y∈mapfxs) = map-∈ y∈mapfxs
∈-map₂ : ∀ {a b} {A : Set a} {B : Set b} {m n : ℕ}
→ ∀ {c} {F : Set c} (f : A → B → F)
{xs : Vec A m} {ys : Vec B n}
{x y} → x ∈ xs → y ∈ ys → (f x y) ∈ map₂ f xs ys
∈-map₂ f {xs = x ∷ xs} {ys} here y∈ys =
∈-++ₗ (∈-map (f x) y∈ys)
∈-map₂ f {xs = x ∷ xs} {ys} (there x∈xs) y∈ys =
∈-++ᵣ (map (f x) ys) (∈-map₂ f x∈xs y∈ys)
lookup-delete-thin : ∀ {a n} {A : Set a} (x : Fin (suc n)) (y : Fin n) (v : Vec A (suc n)) →
lookup y (delete x v) ≡ lookup (thin x y) v
lookup-delete-thin zero zero (_ ∷ _) = refl
lookup-delete-thin zero (suc _) (_ ∷ _) = refl
lookup-delete-thin (suc _) zero (_ ∷ _) = refl
lookup-delete-thin (suc x) (suc y) (_ ∷ v) = lookup-delete-thin x y v
|
From aneris.examples.transaction_commit Require Export
two_phase_runner_code.
From aneris.examples.transaction_commit Require Import
two_phase_runner_code two_phase_prelude two_phase_tm two_phase_rm.
(** * A simple runner (without aux. clients), proving safety *)
Section runner.
Open Scope nat_scope.
Definition tm_addr := SocketAddressInet "tm" 80.
Definition rm1_addr := SocketAddressInet "rm.01" 80.
Definition rm2_addr := SocketAddressInet "rm.02" 80.
Definition rm3_addr := SocketAddressInet "rm.03" 80.
Definition rms : gset socket_address :=
{[ rm1_addr; rm2_addr; rm3_addr ]}.
Definition addrs : gset socket_address := {[ tm_addr ]} ∪ rms.
Definition ips : gset string := {[ "tm"; "rm.01"; "rm.02"; "rm.03" ]}.
Program Instance my_topo : network_topo :=
{| RMs := rms; tm := tm_addr |}.
Solve All Obligations with set_solver.
Context `{!anerisG (TC_model rms) Σ, !tcG Σ}.
Notation pending_frac := (dfrac_oneshot.pending tc_oneshot_gname).
Lemma RMs_size :
size RMs = 3.
Proof. rewrite /RMs !size_union ?size_singleton //; set_solver. Qed.
Lemma runner_spec :
{{{ inv tcN tc_inv ∗
tm_addr ⤇ tm_si ∗
tm_addr ⤳ (∅, ∅) ∗
([∗ set] rm ∈ rms, rm ⤇ rm_si) ∗
([∗ set] rm ∈ rms, rm ↦●{1/2} WORKING) ∗
([∗ set] ip ∈ ips, free_ip ip) ∗
pending_frac 1 }}}
runner @["system"]
{{{ v, RET v; True }}}.
Proof.
iIntros (Φ) "(#Hinv & #Htm_si & Htm_a & #Hrms_si & Hwork & Hips & Hpend) HΦ".
rewrite /runner.
do 4 (wp_makeaddress; wp_let).
wp_apply (wp_set_empty socket_address); [done|]; iIntros (?) "%H".
do 3 (wp_apply (wp_set_add (A := socket_address) with "[//]");
iIntros (?) "%").
wp_pures.
rewrite (pending_split_N _ (size RMs + 1)); [|lia].
iDestruct (big_sepS_delete _ _ "rm.01" with "Hips") as "(Hrm1 & Hips)"; [set_solver|].
iDestruct (big_sepS_delete _ _ "rm.02" with "Hips") as "(Hrm2 & Hips)"; [set_solver|].
iDestruct (big_sepS_delete _ _ "rm.03" with "Hips") as "(Hrm3 & Hips)"; [set_solver|].
iDestruct (big_sepS_delete _ _ "tm" with "Hips") as "(Htm & _)"; [set_solver|].
iDestruct (big_sepS_delete _ _ rm1_addr with "Hwork") as "(Hw1 & Hwork)"; [set_solver|].
iDestruct (big_sepS_delete _ _ rm2_addr with "Hwork") as "(Hw2 & Hwork)"; [set_solver|].
iDestruct (big_sepS_delete _ _ rm3_addr with "Hwork") as "(Hw3 & _)"; [set_solver|].
rewrite RMs_size.
iDestruct (big_sepS_delete _ _ 0 with "Hpend") as "(Hp1 & Hpend)"; [set_solver|].
iDestruct (big_sepS_delete _ _ 1 with "Hpend") as "(Hp2 & Hpend)"; [set_solver|].
iDestruct (big_sepS_delete _ _ 2 with "Hpend") as "(Hp3 & Hpend)"; [set_solver|].
iDestruct (big_sepS_delete _ _ 3 with "Hpend") as "(Ht & _)"; [set_solver|].
rewrite -RMs_size.
wp_apply (aneris_wp_start {[port_of_address rm1_addr]}); iFrame.
iSplitR "Hw1 Hp1"; last first.
{ iIntros "!> Hport".
wp_apply (resource_manager_spec rm1_addr with "[$] [$] [] [$] [$]");
[set_solver| |done].
iApply (big_sepS_elem_of with "Hrms_si"); set_solver. }
iModIntro; wp_seq.
wp_apply (aneris_wp_start {[port_of_address rm2_addr]}); iFrame.
iSplitR "Hw2 Hp2"; last first.
{ iIntros "!> Hport".
wp_apply (resource_manager_spec rm2_addr with "[$] [$] [] [$] [$] ");
[set_solver| |done].
iApply (big_sepS_elem_of with "Hrms_si"); set_solver. }
iModIntro; wp_seq.
wp_apply (aneris_wp_start {[port_of_address rm3_addr]}); iFrame.
iSplitR "Hw3 Hp3"; last first.
{ iIntros "!> Hport".
wp_apply (resource_manager_spec rm3_addr with "[$] [$] [] [$] [$] ");
[set_solver| |done].
iApply (big_sepS_elem_of with "Hrms_si"); set_solver. }
iModIntro; wp_seq.
wp_apply (aneris_wp_start {[port_of_address tm_addr]}); iFrame.
iSplitL "HΦ"; [by iApply "HΦ"|].
iIntros "!> Hport".
wp_apply aneris_wp_wand_r; iSplitL.
{ wp_apply (transaction_manager_spec
with "[$] [$] [$] [$] [$]").
by rewrite !union_assoc_L union_empty_r_L in H2. }
by iIntros (?) "?".
Qed.
End runner.
|
[STATEMENT]
lemma lemma_2_10_24:
"a \<le> (a l\<rightarrow> b) r\<rightarrow> b"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. a \<le> (a l\<rightarrow> b) r\<rightarrow> b
[PROOF STEP]
by (simp add: right_residual [THEN sym] inf_l_def [THEN sym]) |
import .le
namespace hidden
namespace myint
open myring
open ordered_myring
theorem intduction (p : myint → Prop) :
p 0 → (∀ {n}, p n → p (n + 1)) → (∀ {n}, p n → p (n - 1)) →
∀ n, p n :=
begin
assume h0 hnext hprev,
intro n,
cases le_total_order (0: myint) n with h0n hn0, {
rw le_iff_exists_nat at h0n,
cases h0n with d hd,
rw zero_add at hd,
subst hd,
induction d with n hn, {
from h0,
}, {
from hnext hn,
},
}, {
rw le_iff_exists_nat at hn0,
cases hn0 with d hd,
have: n = -↑d, {
rw ←sub_to_zero_iff_eq,
rw hd,
change n + - -↑d = n + ↑d,
rw neg_neg,
},
subst this,
clear hd,
induction d with n hn, {
from h0,
}, {
from hprev hn,
},
},
end
theorem intduction_from {m : myint} (p : myint → Prop):
(∀ {n}, p n → p (n + 1)) → (∀ {n}, p n → p (n - 1)) →
p m → ∀ n, p n :=
begin
assume hnext hprev hex,
suffices : p 0,
apply intduction, repeat {assumption},
revert m,
apply intduction (λ m, p m → p 0), {
assume h, assumption,
}, {
intro n,
assume h,
assume hpsn,
have := hprev hpsn,
rw sub_def at this,
rw add_assoc at this,
rw add_neg at this,
rw add_zero at this,
from h this,
}, {
intro n,
assume h,
assume hpsn,
have := hnext hpsn,
rw sub_def at this,
rw add_assoc at this,
rw neg_add at this,
rw add_zero at this,
from h this,
},
end
end myint
end hidden
|
lemma compact_empty[simp]: "compact {}" |
State Before: α : Type u
β : Type v
G : Type w
H : Type x
inst✝⁶ : TopologicalSpace G
inst✝⁵ : Group G
inst✝⁴ : TopologicalGroup G
inst✝³ : TopologicalSpace α
f : α → G
s : Set α
x : α
inst✝² : TopologicalSpace H
inst✝¹ : OrderedCommGroup H
inst✝ : ContinuousInv H
a : H
⊢ Tendsto Inv.inv (𝓝[Iic a⁻¹] a⁻¹) (𝓝[Ici a] a) State After: no goals Tactic: simpa only [inv_inv] using @tendsto_inv_nhdsWithin_Iic _ _ _ _ a⁻¹ |
lemma of_real_eq_id [simp]: "of_real = (id :: real \<Rightarrow> real)" |
import tools.super
theorem iff.of_eq {a b : Prop} (h : a = b) : a ↔ b :=
eq.rec_on h iff.rfl
theorem and.left_distrib (a b c : Prop) : a ∧ (b ∨ c) ↔ (a ∧ b) ∨ (a ∧ c) := by super
theorem and.right_distrib (a b c : Prop) : (a ∨ b) ∧ c ↔ (a ∧ c) ∨ (b ∧ c) := by super
theorem or.left_distrib (a b c : Prop) : a ∨ (b ∧ c) ↔ (a ∨ b) ∧ (a ∨ c) := by super
theorem or.right_distrib (a b c : Prop) : (a ∧ b) ∨ c ↔ (a ∨ c) ∧ (b ∨ c) := by super
|
import Common
list : Iso a b -> Iso (List a) (List b)
list (MkIso abto abfrom abtf abft) = MkIso to from tf ft
where
to : List a -> List b
to [] = []
to (x :: xs) = abto x :: to xs
from : List b -> List a
from [] = []
from (x :: xs) = abfrom x :: from xs
tf [] = Refl
tf (x :: xs) = rewrite (abtf x) in cong (tf xs)
ft [] = Refl
ft (x :: xs) = rewrite (abft x) in cong (ft xs)
dep_to : Iso b c -> a -> b -> (a, c)
dep_to (MkIso to' from' tf' ft') x y = (x, (to' y))
dep_from : Iso b c -> a -> c -> (a, b)
dep_from (MkIso to' from' tf' ft') x y = (x, (from' y))
dep : (a -> Iso b c) -> Iso (a, b) (a, c)
dep f = MkIso to from tf ft
where
to : (a, b) -> (a, c)
to (x, y) = dep_to (f x) x y
from : (a, c) -> (a, b)
from (x, y) = dep_from (f x) x y
tf (x, y) = case (inspect $ f x) of
(match (MkIso to' from' tf' ft') {eq=fx}) => rewrite fx in
case (dep_from (MkIso to' from' tf' ft') x y) of
(x', y') => rewrite fx in
case (dep_to (MkIso to' from' tf' ft') x (from' y)) of
(x'', y'') => rewrite (tf' y) in Refl
ft (x, y) = case (inspect $ f x) of
(match (MkIso to' from' tf' ft') {eq=fx}) => rewrite fx in
case (dep_to (MkIso to' from' tf' ft') x y) of
(x', y') => rewrite fx in
case (dep_from (MkIso to' from' tf' ft') x (to' y)) of
(x'', y'') => rewrite (ft' y) in Refl
|
/-
Copyright (c) 2022 Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang
! This file was ported from Lean 3 source module algebraic_geometry.morphisms.quasi_compact
! leanprover-community/mathlib commit d39590fc8728fbf6743249802486f8c91ffe07bc
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.AlgebraicGeometry.Morphisms.Basic
import Mathbin.Topology.Spectral.Hom
import Mathbin.AlgebraicGeometry.Limits
/-!
# Quasi-compact morphisms
A morphism of schemes is quasi-compact if the preimages of quasi-compact open sets are
quasi-compact.
It suffices to check that preimages of affine open sets are compact
(`quasi_compact_iff_forall_affine`).
-/
noncomputable section
open CategoryTheory CategoryTheory.Limits Opposite TopologicalSpace
universe u
open AlgebraicGeometry
namespace AlgebraicGeometry
variable {X Y : Scheme.{u}} (f : X ⟶ Y)
/--
A morphism is `quasi-compact` if the underlying map of topological spaces is, i.e. if the preimages
of quasi-compact open sets are quasi-compact.
-/
@[mk_iff]
class QuasiCompact (f : X ⟶ Y) : Prop where
isCompact_preimage : ∀ U : Set Y.carrier, IsOpen U → IsCompact U → IsCompact (f.1.base ⁻¹' U)
#align algebraic_geometry.quasi_compact AlgebraicGeometry.QuasiCompact
theorem quasiCompact_iff_spectral : QuasiCompact f ↔ IsSpectralMap f.1.base :=
⟨fun ⟨h⟩ => ⟨by continuity, h⟩, fun h => ⟨h.2⟩⟩
#align algebraic_geometry.quasi_compact_iff_spectral AlgebraicGeometry.quasiCompact_iff_spectral
/-- The `affine_target_morphism_property` corresponding to `quasi_compact`, asserting that the
domain is a quasi-compact scheme. -/
def QuasiCompact.affineProperty : AffineTargetMorphismProperty := fun X Y f hf =>
CompactSpace X.carrier
#align algebraic_geometry.quasi_compact.affine_property AlgebraicGeometry.QuasiCompact.affineProperty
instance (priority := 900) quasiCompactOfIsIso {X Y : Scheme} (f : X ⟶ Y) [IsIso f] :
QuasiCompact f := by
constructor
intro U hU hU'
convert hU'.image (inv f.1.base).continuous_toFun using 1
rw [Set.image_eq_preimage_of_inverse]
delta Function.LeftInverse
exacts[is_iso.inv_hom_id_apply f.1.base, is_iso.hom_inv_id_apply f.1.base]
#align algebraic_geometry.quasi_compact_of_is_iso AlgebraicGeometry.quasiCompactOfIsIso
instance quasiCompactComp {X Y Z : Scheme} (f : X ⟶ Y) (g : Y ⟶ Z) [QuasiCompact f]
[QuasiCompact g] : QuasiCompact (f ≫ g) :=
by
constructor
intro U hU hU'
rw [Scheme.comp_val_base, coe_comp, Set.preimage_comp]
apply quasi_compact.is_compact_preimage
· exact Continuous.isOpen_preimage (by continuity) _ hU
apply quasi_compact.is_compact_preimage <;> assumption
#align algebraic_geometry.quasi_compact_comp AlgebraicGeometry.quasiCompactComp
theorem isCompact_open_iff_eq_finset_affine_union {X : Scheme} (U : Set X.carrier) :
IsCompact U ∧ IsOpen U ↔
∃ s : Set X.affineOpens, s.Finite ∧ U = ⋃ (i : X.affineOpens) (h : i ∈ s), i :=
by
apply opens.is_basis.is_compact_open_iff_eq_finite_Union (coe : X.affine_opens → opens X.carrier)
· rw [Subtype.range_coe]
exact is_basis_affine_open X
· exact fun i => i.2.IsCompact
#align algebraic_geometry.is_compact_open_iff_eq_finset_affine_union AlgebraicGeometry.isCompact_open_iff_eq_finset_affine_union
theorem isCompact_open_iff_eq_basicOpen_union {X : Scheme} [IsAffine X] (U : Set X.carrier) :
IsCompact U ∧ IsOpen U ↔
∃ s : Set (X.Presheaf.obj (op ⊤)),
s.Finite ∧ U = ⋃ (i : X.Presheaf.obj (op ⊤)) (h : i ∈ s), X.basicOpen i :=
(isBasis_basicOpen X).isCompact_open_iff_eq_finite_unionᵢ _
(fun i => ((top_isAffineOpen _).basicOpen_is_affine _).IsCompact) _
#align algebraic_geometry.is_compact_open_iff_eq_basic_open_union AlgebraicGeometry.isCompact_open_iff_eq_basicOpen_union
theorem quasiCompact_iff_forall_affine :
QuasiCompact f ↔
∀ U : Opens Y.carrier, IsAffineOpen U → IsCompact (f.1.base ⁻¹' (U : Set Y.carrier)) :=
by
rw [quasi_compact_iff]
refine' ⟨fun H U hU => H U U.IsOpen hU.IsCompact, _⟩
intro H U hU hU'
obtain ⟨S, hS, rfl⟩ := (is_compact_open_iff_eq_finset_affine_union U).mp ⟨hU', hU⟩
simp only [Set.preimage_unionᵢ, Subtype.val_eq_coe]
exact hS.is_compact_bUnion fun i _ => H i i.Prop
#align algebraic_geometry.quasi_compact_iff_forall_affine AlgebraicGeometry.quasiCompact_iff_forall_affine
@[simp]
theorem QuasiCompact.affineProperty_toProperty {X Y : Scheme} (f : X ⟶ Y) :
(QuasiCompact.affineProperty : _).toProperty f ↔ IsAffine Y ∧ CompactSpace X.carrier :=
by
delta affine_target_morphism_property.to_property quasi_compact.affine_property
simp
#align algebraic_geometry.quasi_compact.affine_property_to_property AlgebraicGeometry.QuasiCompact.affineProperty_toProperty
theorem quasiCompact_iff_affineProperty :
QuasiCompact f ↔ targetAffineLocally QuasiCompact.affineProperty f :=
by
rw [quasi_compact_iff_forall_affine]
trans ∀ U : Y.affine_opens, IsCompact (f.1.base ⁻¹' (U : Set Y.carrier))
· exact ⟨fun h U => h U U.Prop, fun h U hU => h ⟨U, hU⟩⟩
apply forall_congr'
exact fun _ => isCompact_iff_compactSpace
#align algebraic_geometry.quasi_compact_iff_affine_property AlgebraicGeometry.quasiCompact_iff_affineProperty
theorem quasiCompact_eq_affineProperty :
@QuasiCompact = targetAffineLocally QuasiCompact.affineProperty :=
by
ext
exact quasi_compact_iff_affine_property _
#align algebraic_geometry.quasi_compact_eq_affine_property AlgebraicGeometry.quasiCompact_eq_affineProperty
theorem isCompact_basicOpen (X : Scheme) {U : Opens X.carrier} (hU : IsCompact (U : Set X.carrier))
(f : X.Presheaf.obj (op U)) : IsCompact (X.basicOpen f : Set X.carrier) := by
classical
refine' ((is_compact_open_iff_eq_finset_affine_union _).mpr _).1
obtain ⟨s, hs, e⟩ := (is_compact_open_iff_eq_finset_affine_union _).mp ⟨hU, U.is_open⟩
let g : s → X.affine_opens := by
intro V
use V.1 ⊓ X.basic_open f
have : V.1.1 ⟶ U := by
apply hom_of_le
change _ ⊆ (U : Set X.carrier)
rw [e]
[email protected]_unionᵢ₂ _ _ _ (fun (U : X.affine_opens) (h : U ∈ s) => ↑U) V V.prop using
1
rfl
erw [← X.to_LocallyRingedSpace.to_RingedSpace.basic_open_res this.op]
exact is_affine_open.basic_open_is_affine V.1.Prop _
haveI : Finite s := hs.to_subtype
refine' ⟨Set.range g, Set.finite_range g, _⟩
refine'
(set.inter_eq_right_iff_subset.mpr
(SetLike.coe_subset_coe.2 <| RingedSpace.basic_open_le _ _)).symm.trans
_
rw [e, Set.unionᵢ₂_inter]
apply le_antisymm <;> apply Set.unionᵢ₂_subset
· intro i hi
refine' Set.Subset.trans _ (Set.subset_unionᵢ₂ _ (Set.mem_range_self ⟨i, hi⟩))
exact Set.Subset.rfl
· rintro ⟨i, hi⟩ ⟨⟨j, hj⟩, hj'⟩
rw [← hj']
refine' Set.Subset.trans _ (Set.subset_unionᵢ₂ j hj)
exact Set.Subset.rfl
#align algebraic_geometry.is_compact_basic_open AlgebraicGeometry.isCompact_basicOpen
theorem QuasiCompact.affinePropertyIsLocal : (QuasiCompact.affineProperty : _).IsLocal :=
by
constructor
· apply affine_target_morphism_property.respects_iso_mk <;> rintro X Y Z _ _ _ H
exacts[@Homeomorph.compactSpace _ _ H (TopCat.homeoOfIso (as_iso e.inv.1.base)), H]
· introv H
delta quasi_compact.affine_property at H⊢
change CompactSpace ((opens.map f.val.base).obj (Y.basic_open r))
rw [Scheme.preimage_basic_open f r]
erw [← isCompact_iff_compactSpace]
rw [← isCompact_univ_iff] at H
exact is_compact_basic_open X H _
· rintro X Y H f S hS hS'
skip
rw [← is_affine_open.basic_open_union_eq_self_iff] at hS
delta quasi_compact.affine_property
rw [← isCompact_univ_iff]
change IsCompact ((opens.map f.val.base).obj ⊤).1
rw [← hS]
dsimp [opens.map]
simp only [opens.coe_supr, Set.preimage_unionᵢ, Subtype.val_eq_coe]
exacts[isCompact_unionᵢ fun i => is_compact_iff_compact_space.mpr (hS' i), top_is_affine_open _]
#align algebraic_geometry.quasi_compact.affine_property_is_local AlgebraicGeometry.QuasiCompact.affinePropertyIsLocal
theorem QuasiCompact.affine_openCover_tFAE {X Y : Scheme.{u}} (f : X ⟶ Y) :
TFAE
[QuasiCompact f,
∃ (𝒰 : Scheme.OpenCover.{u} Y)(_ : ∀ i, IsAffine (𝒰.obj i)),
∀ i : 𝒰.J, CompactSpace (pullback f (𝒰.map i)).carrier,
∀ (𝒰 : Scheme.OpenCover.{u} Y) [∀ i, IsAffine (𝒰.obj i)] (i : 𝒰.J),
CompactSpace (pullback f (𝒰.map i)).carrier,
∀ {U : Scheme} (g : U ⟶ Y) [IsAffine U] [IsOpenImmersion g],
CompactSpace (pullback f g).carrier,
∃ (ι : Type u)(U : ι → Opens Y.carrier)(hU : supᵢ U = ⊤)(hU' : ∀ i, IsAffineOpen (U i)),
∀ i, CompactSpace (f.1.base ⁻¹' (U i).1)] :=
quasiCompact_eq_affineProperty.symm ▸ QuasiCompact.affinePropertyIsLocal.affine_openCover_tFAE f
#align algebraic_geometry.quasi_compact.affine_open_cover_tfae AlgebraicGeometry.QuasiCompact.affine_openCover_tFAE
theorem QuasiCompact.isLocalAtTarget : PropertyIsLocalAtTarget @QuasiCompact :=
quasiCompact_eq_affineProperty.symm ▸
QuasiCompact.affinePropertyIsLocal.targetAffineLocallyIsLocal
#align algebraic_geometry.quasi_compact.is_local_at_target AlgebraicGeometry.QuasiCompact.isLocalAtTarget
theorem QuasiCompact.openCover_tFAE {X Y : Scheme.{u}} (f : X ⟶ Y) :
TFAE
[QuasiCompact f,
∃ 𝒰 : Scheme.OpenCover.{u} Y,
∀ i : 𝒰.J, QuasiCompact (pullback.snd : (𝒰.pullbackCover f).obj i ⟶ 𝒰.obj i),
∀ (𝒰 : Scheme.OpenCover.{u} Y) (i : 𝒰.J),
QuasiCompact (pullback.snd : (𝒰.pullbackCover f).obj i ⟶ 𝒰.obj i),
∀ U : Opens Y.carrier, QuasiCompact (f ∣_ U),
∀ {U : Scheme} (g : U ⟶ Y) [IsOpenImmersion g],
QuasiCompact (pullback.snd : pullback f g ⟶ _),
∃ (ι : Type u)(U : ι → Opens Y.carrier)(hU : supᵢ U = ⊤), ∀ i, QuasiCompact (f ∣_ U i)] :=
quasiCompact_eq_affineProperty.symm ▸
QuasiCompact.affinePropertyIsLocal.targetAffineLocallyIsLocal.openCover_tFAE f
#align algebraic_geometry.quasi_compact.open_cover_tfae AlgebraicGeometry.QuasiCompact.openCover_tFAE
theorem quasiCompact_over_affine_iff {X Y : Scheme} (f : X ⟶ Y) [IsAffine Y] :
QuasiCompact f ↔ CompactSpace X.carrier :=
quasiCompact_eq_affineProperty.symm ▸ QuasiCompact.affinePropertyIsLocal.affine_target_iff f
#align algebraic_geometry.quasi_compact_over_affine_iff AlgebraicGeometry.quasiCompact_over_affine_iff
theorem compactSpace_iff_quasiCompact (X : Scheme) :
CompactSpace X.carrier ↔ QuasiCompact (terminal.from X) :=
(quasiCompact_over_affine_iff _).symm
#align algebraic_geometry.compact_space_iff_quasi_compact AlgebraicGeometry.compactSpace_iff_quasiCompact
theorem QuasiCompact.affine_openCover_iff {X Y : Scheme.{u}} (𝒰 : Scheme.OpenCover.{u} Y)
[∀ i, IsAffine (𝒰.obj i)] (f : X ⟶ Y) :
QuasiCompact f ↔ ∀ i, CompactSpace (pullback f (𝒰.map i)).carrier :=
quasiCompact_eq_affineProperty.symm ▸ QuasiCompact.affinePropertyIsLocal.affine_openCover_iff f 𝒰
#align algebraic_geometry.quasi_compact.affine_open_cover_iff AlgebraicGeometry.QuasiCompact.affine_openCover_iff
theorem QuasiCompact.openCover_iff {X Y : Scheme.{u}} (𝒰 : Scheme.OpenCover.{u} Y) (f : X ⟶ Y) :
QuasiCompact f ↔ ∀ i, QuasiCompact (pullback.snd : pullback f (𝒰.map i) ⟶ _) :=
quasiCompact_eq_affineProperty.symm ▸
QuasiCompact.affinePropertyIsLocal.targetAffineLocallyIsLocal.openCover_iff f 𝒰
#align algebraic_geometry.quasi_compact.open_cover_iff AlgebraicGeometry.QuasiCompact.openCover_iff
theorem quasiCompact_respectsIso : MorphismProperty.RespectsIso @QuasiCompact :=
quasiCompact_eq_affineProperty.symm ▸
targetAffineLocally_respectsIso QuasiCompact.affinePropertyIsLocal.1
#align algebraic_geometry.quasi_compact_respects_iso AlgebraicGeometry.quasiCompact_respectsIso
theorem quasiCompact_stableUnderComposition :
MorphismProperty.StableUnderComposition @QuasiCompact := fun _ _ _ _ _ _ _ => inferInstance
#align algebraic_geometry.quasi_compact_stable_under_composition AlgebraicGeometry.quasiCompact_stableUnderComposition
attribute [-simp] PresheafedSpace.as_coe SheafedSpace.as_coe
theorem QuasiCompact.affineProperty_stableUnderBaseChange :
QuasiCompact.affineProperty.StableUnderBaseChange :=
by
intro X Y S _ _ f g h
rw [quasi_compact.affine_property] at h⊢
skip
let 𝒰 := Scheme.pullback.open_cover_of_right Y.affine_cover.finite_subcover f g
have : Finite 𝒰.J := by
dsimp [𝒰]
infer_instance
have : ∀ i, CompactSpace (𝒰.obj i).carrier :=
by
intro i
dsimp
infer_instance
exact 𝒰.compact_space
#align algebraic_geometry.quasi_compact.affine_property_stable_under_base_change AlgebraicGeometry.QuasiCompact.affineProperty_stableUnderBaseChange
theorem quasiCompact_stableUnderBaseChange : MorphismProperty.StableUnderBaseChange @QuasiCompact :=
quasiCompact_eq_affineProperty.symm ▸
QuasiCompact.affinePropertyIsLocal.StableUnderBaseChange
QuasiCompact.affineProperty_stableUnderBaseChange
#align algebraic_geometry.quasi_compact_stable_under_base_change AlgebraicGeometry.quasiCompact_stableUnderBaseChange
variable {Z : Scheme.{u}}
instance (f : X ⟶ Z) (g : Y ⟶ Z) [QuasiCompact g] :
QuasiCompact (pullback.fst : pullback f g ⟶ X) :=
quasiCompact_stableUnderBaseChange.fst f g inferInstance
instance (f : X ⟶ Z) (g : Y ⟶ Z) [QuasiCompact f] :
QuasiCompact (pullback.snd : pullback f g ⟶ Y) :=
quasiCompact_stableUnderBaseChange.snd f g inferInstance
@[elab_as_elim]
theorem compact_open_induction_on {P : Opens X.carrier → Prop} (S : Opens X.carrier)
(hS : IsCompact S.1) (h₁ : P ⊥)
(h₂ : ∀ (S : Opens X.carrier) (hS : IsCompact S.1) (U : X.affineOpens), P S → P (S ⊔ U)) :
P S := by
classical
obtain ⟨s, hs, hs'⟩ := (is_compact_open_iff_eq_finset_affine_union S.1).mp ⟨hS, S.2⟩
replace hs' : S = supᵢ fun i : s => (i : opens X.carrier) :=
by
ext1
simpa using hs'
subst hs'
apply hs.induction_on
· convert h₁
rw [supᵢ_eq_bot]
rintro ⟨_, h⟩
exact h.elim
· intro x s h₃ hs h₄
have : IsCompact (⨆ i : s, (i : opens X.carrier)).1 :=
by
refine' ((is_compact_open_iff_eq_finset_affine_union _).mpr _).1
exact ⟨s, hs, by simp⟩
convert h₂ _ this x h₄
simp only [coe_coe]
rw [supᵢ_subtype, sup_comm]
conv_rhs => rw [supᵢ_subtype]
exact supᵢ_insert
#align algebraic_geometry.compact_open_induction_on AlgebraicGeometry.compact_open_induction_on
theorem exists_pow_mul_eq_zero_of_res_basicOpen_eq_zero_of_isAffineOpen (X : Scheme)
{U : Opens X.carrier} (hU : IsAffineOpen U) (x f : X.Presheaf.obj (op U))
(H : x |_ X.basicOpen f = 0) : ∃ n : ℕ, f ^ n * x = 0 :=
by
rw [← map_zero (X.presheaf.map (hom_of_le <| X.basic_open_le f : X.basic_open f ⟶ U).op)] at H
have := (is_localization_basic_open hU f).3
obtain ⟨⟨_, n, rfl⟩, e⟩ := this.mp H
exact ⟨n, by simpa [mul_comm x] using e⟩
#align algebraic_geometry.exists_pow_mul_eq_zero_of_res_basic_open_eq_zero_of_is_affine_open AlgebraicGeometry.exists_pow_mul_eq_zero_of_res_basicOpen_eq_zero_of_isAffineOpen
/-- If `x : Γ(X, U)` is zero on `D(f)` for some `f : Γ(X, U)`, and `U` is quasi-compact, then
`f ^ n * x = 0` for some `n`. -/
theorem exists_pow_mul_eq_zero_of_res_basicOpen_eq_zero_of_isCompact (X : Scheme)
{U : Opens X.carrier} (hU : IsCompact U.1) (x f : X.Presheaf.obj (op U))
(H : x |_ X.basicOpen f = 0) : ∃ n : ℕ, f ^ n * x = 0 :=
by
obtain ⟨s, hs, e⟩ := (is_compact_open_iff_eq_finset_affine_union U.1).mp ⟨hU, U.2⟩
replace e : U = supᵢ fun i : s => (i : opens X.carrier)
· ext1
simpa using e
have h₁ : ∀ i : s, i.1.1 ≤ U := by
intro i
change (i : opens X.carrier) ≤ U
rw [e]
exact le_supᵢ _ _
have H' := fun i : s =>
exists_pow_mul_eq_zero_of_res_basic_open_eq_zero_of_is_affine_open X i.1.2
(X.presheaf.map (hom_of_le (h₁ i)).op x) (X.presheaf.map (hom_of_le (h₁ i)).op f) _
swap
· delta TopCat.Presheaf.restrictOpen TopCat.Presheaf.restrict at H⊢
convert congr_arg (X.presheaf.map (hom_of_le _).op) H
· simp only [← comp_apply, ← functor.map_comp]
congr
· rw [map_zero]
· rw [X.basic_open_res]
exact Set.inter_subset_right _ _
choose n hn using H'
haveI := hs.to_subtype
cases nonempty_fintype s
use finset.univ.sup n
suffices ∀ i : s, X.presheaf.map (hom_of_le (h₁ i)).op (f ^ finset.univ.sup n * x) = 0
by
subst e
apply X.sheaf.eq_of_locally_eq fun i : s => (i : opens X.carrier)
intro i
rw [map_zero]
apply this
intro i
replace hn :=
congr_arg (fun x => X.presheaf.map (hom_of_le (h₁ i)).op (f ^ (finset.univ.sup n - n i)) * x)
(hn i)
dsimp at hn
simp only [← map_mul, ← map_pow] at hn
rwa [MulZeroClass.mul_zero, ← mul_assoc, ← pow_add, tsub_add_cancel_of_le] at hn
apply Finset.le_sup (Finset.mem_univ i)
#align algebraic_geometry.exists_pow_mul_eq_zero_of_res_basic_open_eq_zero_of_is_compact AlgebraicGeometry.exists_pow_mul_eq_zero_of_res_basicOpen_eq_zero_of_isCompact
end AlgebraicGeometry
|
= = Winning percentages = =
|
{-# OPTIONS --allow-unsolved-metas #-} -- FIXME
open import Everything
module Test.Test1 where
test-functor-transextensionality : ∀
{𝔬₁ 𝔯₁ ℓ₁ 𝔬₂ 𝔯₂ ℓ₂}
⦃ functor : Functor 𝔬₁ 𝔯₁ ℓ₁ 𝔬₂ 𝔯₂ ℓ₂ ⦄
(open Functor functor)
→ {!Transextensionality!.type _∼₁_ _∼̇₁_!}
test-functor-transextensionality = transextensionality
-- test-functor-transextensionality ⦃ functor ⦄ = let open Functor ⦃ … ⦄ in transextensionality1
|
A function $f$ is in $O[F](\lambda x. 0)$ if and only if $f$ is eventually zero on $F$. |
[GOAL]
n : ℕ
h : n ≠ 0
d m : ℕ
⊢ ((fun a => a + d) ∘ fun x => n • id x) m ≡ d [MOD n]
[PROOFSTEP]
simp [Nat.modEq_iff_dvd, ← sub_sub]
[GOAL]
d n : ℕ
h : d < n
⊢ ∃ᶠ (m : ℕ) in atTop, m % n = d
[PROOFSTEP]
simpa only [Nat.ModEq, mod_eq_of_lt h] using frequently_modEq h.ne_bot d
[GOAL]
⊢ ∃ᶠ (m : ℕ) in atTop, Even m
[PROOFSTEP]
simpa only [even_iff] using frequently_mod_eq zero_lt_two
[GOAL]
⊢ ∃ᶠ (m : ℕ) in atTop, Odd m
[PROOFSTEP]
simpa only [odd_iff] using frequently_mod_eq one_lt_two
|
universes u v w
-- We can typically set up the simplifier so that most theorems
-- can be proven by induction + simp
@[simp]
lemma reverse_nil {α : Type u} : [].reverse = ([] : list α) :=
rfl
lemma reverse_core {α : Type u} (xs ys : list α) :
list.reverse_core xs ys = xs.reverse ++ ys :=
by induction xs generalizing ys;
simp [list.reverse_core, list.reverse]; simp *
@[simp]
lemma reverse_cons {α : Type u} (x : α) (xs : list α) :
(x :: xs).reverse = xs.reverse ++ [x] :=
by simp [list.reverse, list.reverse_core]; simp [reverse_core]
@[simp]
lemma reverse_concat {α : Type u} (xs ys : list α) :
(xs ++ ys).reverse = ys.reverse ++ xs.reverse :=
by induction xs generalizing ys; simp *
@[simp]
lemma reverse_reverse {α : Type u} (xs : list α) : xs.reverse.reverse = xs :=
by induction xs; simp *
example {α : Type u} (xs ys : list α) :
(xs.reverse ++ ys).reverse = ys.reverse ++ xs :=
by simp
@[simp]
lemma map_reverse {α : Type u} {β : Type v} (f : α → β) (xs : list α) :
list.map f (list.reverse xs) = list.reverse (list.map f xs) :=
by induction xs; simp [*, list.map]
@[simp]
lemma map_id {α : Type u} (xs : list α) : list.map (λ x, x) xs = xs :=
by apply list.map_id
@[simp]
lemma map_map {α : Type u} {β : Type v} {γ : Type w} (f : α → β) (g : β → γ) (xs : list α) :
list.map g (list.map f xs) = list.map (g ∘ f) xs :=
by apply list.map_map
example (xs : list ℕ) :
(list.reverse $
list.map (λ x, x - 2) $
list.reverse $
list.map (λ x, x + 2) xs)
= xs :=
by simp [(∘)]
-- What lemmas do we need to add to prove the following?
example (xs : list ℕ) :
let xs := xs.filter (λ x, x > 0) in
let xs := xs.map (λ x, 3 * x / x) in
∀ x ∈ xs, x = 3 :=
by simp {contextual := tt} |
St. John the Baptist ; central banner panel , <unk> church , 1943
|
lemma measure_cases[cases type: measure]: obtains (measure) \<Omega> A \<mu> where "x = Abs_measure (\<Omega>, A, \<mu>)" "\<forall>a\<in>-A. \<mu> a = 0" "measure_space \<Omega> A \<mu>" |
/-
Copyright (c) 2022 Joël Riou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joël Riou
! This file was ported from Lean 3 source module algebraic_topology.dold_kan.degeneracies
! leanprover-community/mathlib commit ec1c7d810034d4202b0dd239112d1792be9f6fdc
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.AlgebraicTopology.DoldKan.Decomposition
import Mathbin.Tactic.FinCases
/-!
# Behaviour of P_infty with respect to degeneracies
For any `X : simplicial_object C` where `C` is an abelian category,
the projector `P_infty : K[X] ⟶ K[X]` is supposed to be the projection
on the normalized subcomplex, parallel to the degenerate subcomplex, i.e.
the subcomplex generated by the images of all `X.σ i`.
In this file, we obtain `degeneracy_comp_P_infty` which states that
if `X : simplicial_object C` with `C` a preadditive category,
`θ : [n] ⟶ Δ'` is a non injective map in `simplex_category`, then
`X.map θ.op ≫ P_infty.f n = 0`. It follows from the more precise
statement vanishing statement `σ_comp_P_eq_zero` for the `P q`.
-/
open
CategoryTheory CategoryTheory.Category CategoryTheory.Limits CategoryTheory.Preadditive Opposite
open Simplicial DoldKan
namespace AlgebraicTopology
namespace DoldKan
variable {C : Type _} [Category C] [Preadditive C]
theorem HigherFacesVanish.comp_σ {Y : C} {X : SimplicialObject C} {n b q : ℕ} {φ : Y ⟶ X _[n + 1]}
(v : HigherFacesVanish q φ) (hnbq : n + 1 = b + q) :
HigherFacesVanish q
(φ ≫
X.σ ⟨b, by simpa only [hnbq, Nat.lt_succ_iff, le_add_iff_nonneg_right] using zero_le q⟩) :=
fun j hj =>
by
rw [assoc, simplicial_object.δ_comp_σ_of_gt', Fin.pred_succ, v.comp_δ_eq_zero_assoc _ _ hj,
zero_comp]
· intro hj'
simpa only [hj', hnbq, Fin.val_zero, zero_add, add_comm b, add_assoc, false_and_iff,
add_le_iff_nonpos_right, le_zero_iff, add_eq_zero_iff, Nat.one_ne_zero] using hj
· simp only [Fin.lt_iff_val_lt_val, Nat.lt_iff_add_one_le, Fin.succ_mk, Fin.val_mk, Fin.val_succ,
add_le_add_iff_right]
linarith
#align algebraic_topology.dold_kan.higher_faces_vanish.comp_σ AlgebraicTopology.DoldKan.HigherFacesVanish.comp_σ
theorem σ_comp_p_eq_zero (X : SimplicialObject C) {n q : ℕ} (i : Fin (n + 1)) (hi : n + 1 ≤ i + q) :
X.σ i ≫ (p q).f (n + 1) = 0 :=
by
induction' q with q hq generalizing i hi
· exfalso
have h := Fin.is_lt i
linarith
· by_cases n + 1 ≤ (i : ℕ) + q
· unfold P
simp only [HomologicalComplex.comp_f, ← assoc]
rw [hq i h, zero_comp]
· have hi' : n = (i : ℕ) + q :=
by
cases' le_iff_exists_add.mp hi with j hj
rw [← Nat.lt_succ_iff, Nat.succ_eq_add_one, add_assoc, hj, not_lt, add_le_iff_nonpos_right,
nonpos_iff_eq_zero] at h
rw [← add_left_inj 1, add_assoc, hj, self_eq_add_right, h]
cases n
· fin_cases i
rw [show q = 0 by linarith]
unfold P
simp only [id_comp, HomologicalComplex.add_f_apply, comp_add, HomologicalComplex.id_f, Hσ,
Homotopy.nullHomotopicMap'_f (c_mk 2 1 rfl) (c_mk 1 0 rfl),
alternating_face_map_complex.obj_d_eq]
erw [hσ'_eq' (zero_add 0).symm, hσ'_eq' (add_zero 1).symm, comp_id, Fin.sum_univ_two,
Fin.sum_univ_succ, Fin.sum_univ_two]
simp only [pow_zero, pow_one, pow_two, Fin.val_zero, Fin.val_one, Fin.val_two, one_zsmul,
neg_zsmul, Fin.mk_zero, Fin.mk_one, Fin.val_succ, pow_add, one_mul, neg_mul, neg_neg,
Fin.succ_zero_eq_one, Fin.succ_one_eq_two, comp_neg, neg_comp, add_comp, comp_add]
erw [simplicial_object.δ_comp_σ_self, simplicial_object.δ_comp_σ_self_assoc,
simplicial_object.δ_comp_σ_succ, comp_id,
simplicial_object.δ_comp_σ_of_le X
(show (0 : Fin 2) ≤ Fin.castSucc 0 by rw [Fin.castSucc_zero]),
simplicial_object.δ_comp_σ_self_assoc, simplicial_object.δ_comp_σ_succ_assoc]
abel
· rw [← id_comp (X.σ i), ← (P_add_Q_f q n.succ : _ = 𝟙 (X.obj _)), add_comp, add_comp]
have v : higher_faces_vanish q ((P q).f n.succ ≫ X.σ i) :=
(higher_faces_vanish.of_P q n).comp_σ hi'
unfold P
erw [← assoc, v.comp_P_eq_self, HomologicalComplex.add_f_apply, preadditive.comp_add,
comp_id, v.comp_Hσ_eq hi', assoc, simplicial_object.δ_comp_σ_succ'_assoc, Fin.eta,
decomposition_Q n q, sum_comp, sum_comp, Finset.sum_eq_zero, add_zero, add_neg_eq_zero]
swap
· ext
simp only [Fin.val_mk, Fin.val_succ]
· intro j hj
simp only [true_and_iff, Finset.mem_univ, Finset.mem_filter] at hj
simp only [Nat.succ_eq_add_one] at hi'
obtain ⟨k, hk⟩ := Nat.le.dest (nat.lt_succ_iff.mp (Fin.is_lt j))
rw [add_comm] at hk
have hi'' : i = Fin.castSucc ⟨i, by linarith⟩ :=
by
ext
simp only [Fin.castSucc_mk, Fin.eta]
have eq :=
hq j.rev.succ
(by
simp only [← hk, Fin.rev_eq j hk.symm, Nat.succ_eq_add_one, Fin.succ_mk, Fin.val_mk]
linarith)
rw [HomologicalComplex.comp_f, assoc, assoc, assoc, hi'',
simplicial_object.σ_comp_σ_assoc, reassoc_of Eq, zero_comp, comp_zero, comp_zero,
comp_zero]
simp only [Fin.rev_eq j hk.symm, Fin.le_iff_val_le_val, Fin.val_mk]
linarith
#align algebraic_topology.dold_kan.σ_comp_P_eq_zero AlgebraicTopology.DoldKan.σ_comp_p_eq_zero
@[simp, reassoc.1]
theorem σ_comp_pInfty (X : SimplicialObject C) {n : ℕ} (i : Fin (n + 1)) :
X.σ i ≫ pInfty.f (n + 1) = 0 :=
by
rw [P_infty_f, σ_comp_P_eq_zero X i]
simp only [le_add_iff_nonneg_left, zero_le]
#align algebraic_topology.dold_kan.σ_comp_P_infty AlgebraicTopology.DoldKan.σ_comp_pInfty
@[reassoc.1]
theorem degeneracy_comp_pInfty (X : SimplicialObject C) (n : ℕ) {Δ' : SimplexCategory}
(θ : [n] ⟶ Δ') (hθ : ¬Mono θ) : X.map θ.op ≫ pInfty.f n = 0 :=
by
rw [SimplexCategory.mono_iff_injective] at hθ
cases n
· exfalso
apply hθ
intro x y h
fin_cases x
fin_cases y
· obtain ⟨i, α, h⟩ := SimplexCategory.eq_σ_comp_of_not_injective θ hθ
rw [h, op_comp, X.map_comp, assoc, show X.map (SimplexCategory.σ i).op = X.σ i by rfl,
σ_comp_P_infty, comp_zero]
#align algebraic_topology.dold_kan.degeneracy_comp_P_infty AlgebraicTopology.DoldKan.degeneracy_comp_pInfty
end DoldKan
end AlgebraicTopology
|
theorem ex1 (x : Nat) (y : { v // v > x }) (z : Nat) : Nat :=
by {
clear y x;
exact z
}
theorem ex2 (x : Nat) (y : { v // v > x }) (z : Nat) : Nat :=
by {
clear x y;
exact z
}
theorem ex3 (x y z : Nat) (h₁ : x = y) (h₂ : z = y) : x = z :=
by {
have : y = z := h₂.symm;
apply Eq.trans;
exact h₁;
assumption
}
theorem ex4 (x y z : Nat) (h₁ : x = y) (h₂ : z = y) : x = z :=
by {
let h₃ : y = z := h₂.symm;
apply Eq.trans;
exact h₁;
exact h₃
}
theorem ex5 (x y z : Nat) (h₁ : x = y) (h₂ : z = y) : x = z :=
by {
have h₃ : y = z := h₂.symm;
apply Eq.trans;
exact h₁;
exact h₃
}
theorem ex6 (x y z : Nat) (h₁ : x = y) (h₂ : z = y) : id (x + 0 = z) :=
by {
show x = z;
have h₃ : y = z := h₂.symm;
apply Eq.trans;
exact h₁;
exact h₃
}
theorem ex7 (x y z : Nat) (h₁ : x = y) (h₂ : z = y) : x = z := by
have : y = z := by apply Eq.symm; assumption
apply Eq.trans
exact h₁
assumption
theorem ex8 (x y z : Nat) (h₁ : x = y) (h₂ : z = y) : x = z :=
by apply Eq.trans h₁;
have : y = z := by
apply Eq.symm;
assumption;
exact this
example (x y z : Nat) (h₁ : x = y) (h₂ : z = y) : x = z := by
sorry
example (x y z : Nat) (h₁ : x = y) (h₂ : z = y) : x = z := by
apply Eq.trans
. sorry
. sorry
. sorry
example (x y z : Nat) (h₁ : x = y) (h₂ : z = y) : x = z := by
apply Eq.trans <;> sorry
|
lemma countable_Un_Int[measurable (raw)]: "(\<And>i :: 'i :: countable. i \<in> I \<Longrightarrow> N i \<in> sets M) \<Longrightarrow> (\<Union>i\<in>I. N i) \<in> sets M" "I \<noteq> {} \<Longrightarrow> (\<And>i :: 'i :: countable. i \<in> I \<Longrightarrow> N i \<in> sets M) \<Longrightarrow> (\<Inter>i\<in>I. N i) \<in> sets M" |
Require Import little_w_string parser.
Require Import List BinIntDef.
Open Scope list_scope.
Open Scope Z_scope.
Open Scope string_scope.
Import String str intervals syntax AB A D L B.
Definition state1 := (("n",(cZ 0,cZ 500))::("x",(cZ 0,cZ 0))::("y",(cZ 0,cZ 0))::nil).
Definition sum_i_to_n :=
Eval vm_compute in un_annot (parse_instr'
"while x < n do [le(x,n)/\pp(y,x)] x:=x+1; y:=x+y done").
Check and.
Eval vm_compute in
let (i',e) := B.abstract_i sum_i_to_n state1 in
string_of_a_instr i'.
|
[GOAL]
p✝ p : ℕ → Prop
n : ℕ
⊢ ℕ
[PROOFSTEP]
classical exact
if h : Set.Finite (setOf p) then (h.toFinset.sort (· ≤ ·)).getD n 0
else @Nat.Subtype.orderIsoOfNat (setOf p) (Set.Infinite.to_subtype h) n
[GOAL]
p✝ p : ℕ → Prop
n : ℕ
⊢ ℕ
[PROOFSTEP]
exact
if h : Set.Finite (setOf p) then (h.toFinset.sort (· ≤ ·)).getD n 0
else @Nat.Subtype.orderIsoOfNat (setOf p) (Set.Infinite.to_subtype h) n
[GOAL]
p : ℕ → Prop
hf : Set.Finite (setOf p)
n : ℕ
hn : card (Set.Finite.toFinset hf) ≤ n
⊢ nth p n = 0
[PROOFSTEP]
rw [nth, dif_pos hf, List.getD_eq_default]
[GOAL]
case hn
p : ℕ → Prop
hf : Set.Finite (setOf p)
n : ℕ
hn : card (Set.Finite.toFinset hf) ≤ n
⊢ List.length (sort (fun x x_1 => x ≤ x_1) (Set.Finite.toFinset hf)) ≤ n
[PROOFSTEP]
rwa [Finset.length_sort]
[GOAL]
p : ℕ → Prop
hf : Set.Finite (setOf p)
n : ℕ
hn : n < card (Set.Finite.toFinset hf)
⊢ nth p n =
↑(orderEmbOfFin (Set.Finite.toFinset hf) (_ : card (Set.Finite.toFinset hf) = card (Set.Finite.toFinset hf)))
{ val := n, isLt := hn }
[PROOFSTEP]
rw [nth_eq_getD_sort hf, Finset.orderEmbOfFin_apply, List.getD_eq_get]
[GOAL]
p : ℕ → Prop
hf : Set.Finite (setOf p)
n : ℕ
hn : n < card (Set.Finite.toFinset hf)
⊢ List.get (sort (fun x x_1 => x ≤ x_1) (Set.Finite.toFinset hf)) { val := n, isLt := ?hn } =
List.nthLe (sort (fun x x_1 => x ≤ x_1) (Set.Finite.toFinset hf)) ↑{ val := n, isLt := hn }
(_ : ↑{ val := n, isLt := hn } < List.length (sort (fun x x_1 => x ≤ x_1) (Set.Finite.toFinset hf)))
case hn
p : ℕ → Prop
hf : Set.Finite (setOf p)
n : ℕ
hn : n < card (Set.Finite.toFinset hf)
⊢ n < List.length (sort (fun x x_1 => x ≤ x_1) (Set.Finite.toFinset hf))
[PROOFSTEP]
rfl
[GOAL]
p : ℕ → Prop
hf : Set.Finite (setOf p)
⊢ StrictMonoOn (nth p) (Set.Iio (card (Set.Finite.toFinset hf)))
[PROOFSTEP]
rintro m (hm : m < _) n (hn : n < _) h
[GOAL]
p : ℕ → Prop
hf : Set.Finite (setOf p)
m : ℕ
hm : m < card (Set.Finite.toFinset hf)
n : ℕ
hn : n < card (Set.Finite.toFinset hf)
h : m < n
⊢ nth p m < nth p n
[PROOFSTEP]
simp only [nth_eq_orderEmbOfFin, *]
[GOAL]
p : ℕ → Prop
hf : Set.Finite (setOf p)
m : ℕ
hm : m < card (Set.Finite.toFinset hf)
n : ℕ
hn : n < card (Set.Finite.toFinset hf)
h : m < n
⊢ ↑(orderEmbOfFin (Set.Finite.toFinset (_ : Set.Finite (setOf p)))
(_ :
card (Set.Finite.toFinset (_ : Set.Finite (setOf p))) =
card (Set.Finite.toFinset (_ : Set.Finite (setOf p)))))
{ val := m, isLt := (_ : m < card (Set.Finite.toFinset hf)) } <
↑(orderEmbOfFin (Set.Finite.toFinset (_ : Set.Finite (setOf p)))
(_ :
card (Set.Finite.toFinset (_ : Set.Finite (setOf p))) =
card (Set.Finite.toFinset (_ : Set.Finite (setOf p)))))
{ val := n, isLt := (_ : n < card (Set.Finite.toFinset hf)) }
[PROOFSTEP]
exact OrderEmbedding.strictMono _ h
[GOAL]
p : ℕ → Prop
hf : Set.Finite (setOf p)
⊢ Set.range (nth p) = insert 0 (setOf p)
[PROOFSTEP]
simpa only [← nth_eq_getD_sort hf, mem_sort, Set.Finite.mem_toFinset] using
Set.range_list_getD (hf.toFinset.sort (· ≤ ·)) 0
[GOAL]
p : ℕ → Prop
hf : Set.Finite (setOf p)
⊢ nth p '' Set.Iio (card (Set.Finite.toFinset hf)) =
Set.range
↑(orderEmbOfFin (Set.Finite.toFinset hf) (_ : card (Set.Finite.toFinset hf) = card (Set.Finite.toFinset hf)))
[PROOFSTEP]
ext x
[GOAL]
case h
p : ℕ → Prop
hf : Set.Finite (setOf p)
x : ℕ
⊢ x ∈ nth p '' Set.Iio (card (Set.Finite.toFinset hf)) ↔
x ∈
Set.range
↑(orderEmbOfFin (Set.Finite.toFinset hf) (_ : card (Set.Finite.toFinset hf) = card (Set.Finite.toFinset hf)))
[PROOFSTEP]
simp only [Set.mem_image, Set.mem_range, Fin.exists_iff, ← nth_eq_orderEmbOfFin hf, Set.mem_Iio, exists_prop]
[GOAL]
p : ℕ → Prop
hf : Set.Finite (setOf p)
⊢ Set.range
↑(orderEmbOfFin (Set.Finite.toFinset hf) (_ : card (Set.Finite.toFinset hf) = card (Set.Finite.toFinset hf))) =
setOf p
[PROOFSTEP]
rw [range_orderEmbOfFin, Set.Finite.coe_toFinset]
[GOAL]
p : ℕ → Prop
hf : Set.Finite (setOf p)
x : ℕ
h : p x
⊢ ∃ n, n < card (Set.Finite.toFinset hf) ∧ nth p n = x
[PROOFSTEP]
rwa [← @Set.mem_setOf_eq _ _ p, ← image_nth_Iio_card hf] at h
[GOAL]
p : ℕ → Prop
hf : Set.Infinite (setOf p)
n : ℕ
⊢ nth p n = ↑(↑(Subtype.orderIsoOfNat (setOf p)) n)
[PROOFSTEP]
rw [nth, dif_neg hf]
[GOAL]
p : ℕ → Prop
hf : Set.Infinite (setOf p)
⊢ StrictMono (nth p)
[PROOFSTEP]
rw [nth_eq_orderIsoOfNat hf]
[GOAL]
p : ℕ → Prop
hf : Set.Infinite (setOf p)
⊢ StrictMono (Subtype.val ∘ ↑(Subtype.orderIsoOfNat (setOf p)))
[PROOFSTEP]
exact (Subtype.strictMono_coe _).comp (OrderIso.strictMono _)
[GOAL]
p : ℕ → Prop
hf : Set.Infinite (setOf p)
⊢ Set.range (nth p) = setOf p
[PROOFSTEP]
rw [nth_eq_orderIsoOfNat hf]
[GOAL]
p : ℕ → Prop
hf : Set.Infinite (setOf p)
⊢ Set.range (Subtype.val ∘ ↑(Subtype.orderIsoOfNat (setOf p))) = setOf p
[PROOFSTEP]
haveI := hf.to_subtype
[GOAL]
p : ℕ → Prop
hf : Set.Infinite (setOf p)
this : Infinite ↑(setOf p)
⊢ Set.range (Subtype.val ∘ ↑(Subtype.orderIsoOfNat (setOf p))) = setOf p
[PROOFSTEP]
classical exact Nat.Subtype.coe_comp_ofNat_range
[GOAL]
p : ℕ → Prop
hf : Set.Infinite (setOf p)
this : Infinite ↑(setOf p)
⊢ Set.range (Subtype.val ∘ ↑(Subtype.orderIsoOfNat (setOf p))) = setOf p
[PROOFSTEP]
exact Nat.Subtype.coe_comp_ofNat_range
[GOAL]
p : ℕ → Prop
x : ℕ
h : p x
⊢ ∃ n, (∀ (hf : Set.Finite (setOf p)), n < card (Set.Finite.toFinset hf)) ∧ nth p n = x
[PROOFSTEP]
refine' (setOf p).finite_or_infinite.elim (fun hf => _) fun hf => _
[GOAL]
case refine'_1
p : ℕ → Prop
x : ℕ
h : p x
hf : Set.Finite (setOf p)
⊢ ∃ n, (∀ (hf : Set.Finite (setOf p)), n < card (Set.Finite.toFinset hf)) ∧ nth p n = x
[PROOFSTEP]
rcases exists_lt_card_finite_nth_eq hf h with ⟨n, hn, hx⟩
[GOAL]
case refine'_1.intro.intro
p : ℕ → Prop
x : ℕ
h : p x
hf : Set.Finite (setOf p)
n : ℕ
hn : n < card (Set.Finite.toFinset hf)
hx : nth p n = x
⊢ ∃ n, (∀ (hf : Set.Finite (setOf p)), n < card (Set.Finite.toFinset hf)) ∧ nth p n = x
[PROOFSTEP]
exact ⟨n, fun _ => hn, hx⟩
[GOAL]
case refine'_2
p : ℕ → Prop
x : ℕ
h : p x
hf : Set.Infinite (setOf p)
⊢ ∃ n, (∀ (hf : Set.Finite (setOf p)), n < card (Set.Finite.toFinset hf)) ∧ nth p n = x
[PROOFSTEP]
rw [← @Set.mem_setOf_eq _ _ p, ← range_nth_of_infinite hf] at h
[GOAL]
case refine'_2
p : ℕ → Prop
x : ℕ
h : x ∈ Set.range (nth p)
hf : Set.Infinite (setOf p)
⊢ ∃ n, (∀ (hf : Set.Finite (setOf p)), n < card (Set.Finite.toFinset hf)) ∧ nth p n = x
[PROOFSTEP]
rcases h with ⟨n, hx⟩
[GOAL]
case refine'_2.intro
p : ℕ → Prop
x : ℕ
hf : Set.Infinite (setOf p)
n : ℕ
hx : nth p n = x
⊢ ∃ n, (∀ (hf : Set.Finite (setOf p)), n < card (Set.Finite.toFinset hf)) ∧ nth p n = x
[PROOFSTEP]
exact ⟨n, fun hf' => absurd hf' hf, hx⟩
[GOAL]
p✝ p : ℕ → Prop
n : ℕ
⊢ nth p n = sInf {x | p x ∧ ∀ (k : ℕ), k < n → nth p k < x}
[PROOFSTEP]
by_cases hn : ∀ hf : (setOf p).Finite, n < hf.toFinset.card
[GOAL]
case pos
p✝ p : ℕ → Prop
n : ℕ
hn : ∀ (hf : Set.Finite (setOf p)), n < card (Set.Finite.toFinset hf)
⊢ nth p n = sInf {x | p x ∧ ∀ (k : ℕ), k < n → nth p k < x}
[PROOFSTEP]
exact (isLeast_nth hn).csInf_eq.symm
[GOAL]
case neg
p✝ p : ℕ → Prop
n : ℕ
hn : ¬∀ (hf : Set.Finite (setOf p)), n < card (Set.Finite.toFinset hf)
⊢ nth p n = sInf {x | p x ∧ ∀ (k : ℕ), k < n → nth p k < x}
[PROOFSTEP]
push_neg at hn
[GOAL]
case neg
p✝ p : ℕ → Prop
n : ℕ
hn : ∃ h, card (Set.Finite.toFinset (_ : Set.Finite (setOf p))) ≤ n
⊢ nth p n = sInf {x | p x ∧ ∀ (k : ℕ), k < n → nth p k < x}
[PROOFSTEP]
rcases hn with ⟨hf, hn⟩
[GOAL]
case neg.intro
p✝ p : ℕ → Prop
n : ℕ
hf : Set.Finite (setOf p)
hn : card (Set.Finite.toFinset (_ : Set.Finite (setOf p))) ≤ n
⊢ nth p n = sInf {x | p x ∧ ∀ (k : ℕ), k < n → nth p k < x}
[PROOFSTEP]
rw [nth_of_card_le _ hn]
[GOAL]
case neg.intro
p✝ p : ℕ → Prop
n : ℕ
hf : Set.Finite (setOf p)
hn : card (Set.Finite.toFinset (_ : Set.Finite (setOf p))) ≤ n
⊢ 0 = sInf {x | p x ∧ ∀ (k : ℕ), k < n → nth p k < x}
[PROOFSTEP]
refine' ((congr_arg sInf <| Set.eq_empty_of_forall_not_mem fun k hk => _).trans sInf_empty).symm
[GOAL]
case neg.intro
p✝ p : ℕ → Prop
n : ℕ
hf : Set.Finite (setOf p)
hn : card (Set.Finite.toFinset (_ : Set.Finite (setOf p))) ≤ n
k : ℕ
hk : k ∈ {x | p x ∧ ∀ (k : ℕ), k < n → nth p k < x}
⊢ False
[PROOFSTEP]
rcases exists_lt_card_nth_eq hk.1 with ⟨k, hlt, rfl⟩
[GOAL]
case neg.intro.intro.intro
p✝ p : ℕ → Prop
n : ℕ
hf : Set.Finite (setOf p)
hn : card (Set.Finite.toFinset (_ : Set.Finite (setOf p))) ≤ n
k : ℕ
hlt : ∀ (hf : Set.Finite (setOf p)), k < card (Set.Finite.toFinset hf)
hk : nth p k ∈ {x | p x ∧ ∀ (k : ℕ), k < n → nth p k < x}
⊢ False
[PROOFSTEP]
exact (hk.2 _ ((hlt hf).trans_le hn)).false
[GOAL]
p : ℕ → Prop
⊢ nth p 0 = sInf (setOf p)
[PROOFSTEP]
rw [nth_eq_sInf]
[GOAL]
p : ℕ → Prop
⊢ sInf {x | p x ∧ ∀ (k : ℕ), k < 0 → nth p k < x} = sInf (setOf p)
[PROOFSTEP]
simp
[GOAL]
p : ℕ → Prop
h : p 0
⊢ nth p 0 = 0
[PROOFSTEP]
simp [nth_zero, h]
[GOAL]
p : ℕ → Prop
inst✝ : DecidablePred p
h : ∃ n, p n
⊢ nth p 0 = Nat.find h
[PROOFSTEP]
rw [nth_zero]
[GOAL]
p : ℕ → Prop
inst✝ : DecidablePred p
h : ∃ n, p n
⊢ sInf (setOf p) = Nat.find h
[PROOFSTEP]
convert Nat.sInf_def h
[GOAL]
p : ℕ → Prop
n : ℕ
⊢ nth p n = 0 ↔ p 0 ∧ n = 0 ∨ ∃ hf, card (Set.Finite.toFinset hf) ≤ n
[PROOFSTEP]
refine' ⟨fun h => _, _⟩
[GOAL]
case refine'_1
p : ℕ → Prop
n : ℕ
h : nth p n = 0
⊢ p 0 ∧ n = 0 ∨ ∃ hf, card (Set.Finite.toFinset hf) ≤ n
[PROOFSTEP]
simp only [or_iff_not_imp_right, not_exists, not_le]
[GOAL]
case refine'_1
p : ℕ → Prop
n : ℕ
h : nth p n = 0
⊢ (∀ (x : Set.Finite (setOf p)), n < card (Set.Finite.toFinset x)) → p 0 ∧ n = 0
[PROOFSTEP]
exact fun hn => ⟨h ▸ nth_mem _ hn, nonpos_iff_eq_zero.1 <| h ▸ le_nth hn⟩
[GOAL]
case refine'_2
p : ℕ → Prop
n : ℕ
⊢ (p 0 ∧ n = 0 ∨ ∃ hf, card (Set.Finite.toFinset hf) ≤ n) → nth p n = 0
[PROOFSTEP]
rintro (⟨h₀, rfl⟩ | ⟨hf, hle⟩)
[GOAL]
case refine'_2.inl.intro
p : ℕ → Prop
h₀ : p 0
⊢ nth p 0 = 0
case refine'_2.inr.intro
p : ℕ → Prop
n : ℕ
hf : Set.Finite (setOf p)
hle : card (Set.Finite.toFinset hf) ≤ n
⊢ nth p n = 0
[PROOFSTEP]
exacts [nth_zero_of_zero h₀, nth_of_card_le hf hle]
[GOAL]
p : ℕ → Prop
h₀ : ¬p 0
a b : ℕ
hab : a ≤ b
ha : nth p a = 0
⊢ nth p b = 0
[PROOFSTEP]
simp only [nth_eq_zero, h₀, false_and_iff, false_or_iff] at ha ⊢
[GOAL]
p : ℕ → Prop
h₀ : ¬p 0
a b : ℕ
hab : a ≤ b
ha : ∃ hf, card (Set.Finite.toFinset hf) ≤ a
⊢ ∃ hf, card (Set.Finite.toFinset hf) ≤ b
[PROOFSTEP]
exact ha.imp fun hf hle => hle.trans hab
[GOAL]
p : ℕ → Prop
k a : ℕ
h : a < nth p (k + 1)
ha : p a
⊢ a ≤ nth p k
[PROOFSTEP]
cases' (setOf p).finite_or_infinite with hf hf
[GOAL]
case inl
p : ℕ → Prop
k a : ℕ
h : a < nth p (k + 1)
ha : p a
hf : Set.Finite (setOf p)
⊢ a ≤ nth p k
[PROOFSTEP]
rcases exists_lt_card_finite_nth_eq hf ha with ⟨n, hn, rfl⟩
[GOAL]
case inl.intro.intro
p : ℕ → Prop
k : ℕ
hf : Set.Finite (setOf p)
n : ℕ
hn : n < card (Set.Finite.toFinset hf)
h : nth p n < nth p (k + 1)
ha : p (nth p n)
⊢ nth p n ≤ nth p k
[PROOFSTEP]
cases' lt_or_le (k + 1) hf.toFinset.card with hk hk
[GOAL]
case inl.intro.intro.inl
p : ℕ → Prop
k : ℕ
hf : Set.Finite (setOf p)
n : ℕ
hn : n < card (Set.Finite.toFinset hf)
h : nth p n < nth p (k + 1)
ha : p (nth p n)
hk : k + 1 < card (Set.Finite.toFinset hf)
⊢ nth p n ≤ nth p k
[PROOFSTEP]
rwa [(nth_strictMonoOn hf).lt_iff_lt hn hk, lt_succ_iff, ←
(nth_strictMonoOn hf).le_iff_le hn (k.lt_succ_self.trans hk)] at h
[GOAL]
case inl.intro.intro.inr
p : ℕ → Prop
k : ℕ
hf : Set.Finite (setOf p)
n : ℕ
hn : n < card (Set.Finite.toFinset hf)
h : nth p n < nth p (k + 1)
ha : p (nth p n)
hk : card (Set.Finite.toFinset hf) ≤ k + 1
⊢ nth p n ≤ nth p k
[PROOFSTEP]
rw [nth_of_card_le _ hk] at h
[GOAL]
case inl.intro.intro.inr
p : ℕ → Prop
k : ℕ
hf : Set.Finite (setOf p)
n : ℕ
hn : n < card (Set.Finite.toFinset hf)
h : nth p n < 0
ha : p (nth p n)
hk : card (Set.Finite.toFinset hf) ≤ k + 1
⊢ nth p n ≤ nth p k
[PROOFSTEP]
exact absurd h (zero_le _).not_lt
[GOAL]
case inr
p : ℕ → Prop
k a : ℕ
h : a < nth p (k + 1)
ha : p a
hf : Set.Infinite (setOf p)
⊢ a ≤ nth p k
[PROOFSTEP]
rcases subset_range_nth ha with ⟨n, rfl⟩
[GOAL]
case inr.intro
p : ℕ → Prop
k : ℕ
hf : Set.Infinite (setOf p)
n : ℕ
h : nth p n < nth p (k + 1)
ha : p (nth p n)
⊢ nth p n ≤ nth p k
[PROOFSTEP]
rwa [nth_lt_nth hf, lt_succ_iff, ← nth_le_nth hf] at h
[GOAL]
p : ℕ → Prop
inst✝ : DecidablePred p
⊢ count p (nth p 0) = 0
[PROOFSTEP]
rw [count_eq_card_filter_range, card_eq_zero, filter_eq_empty_iff, nth_zero]
[GOAL]
p : ℕ → Prop
inst✝ : DecidablePred p
⊢ ∀ (x : ℕ), x ∈ range (sInf (setOf p)) → ¬p x
[PROOFSTEP]
exact fun n h₁ h₂ => (mem_range.1 h₁).not_le (Nat.sInf_le h₂)
[GOAL]
p : ℕ → Prop
inst✝ : DecidablePred p
k : ℕ
⊢ filter p (range (nth p (k + 1))) ⊆ insert (nth p k) (filter p (range (nth p k)))
[PROOFSTEP]
intro a ha
[GOAL]
p : ℕ → Prop
inst✝ : DecidablePred p
k a : ℕ
ha : a ∈ filter p (range (nth p (k + 1)))
⊢ a ∈ insert (nth p k) (filter p (range (nth p k)))
[PROOFSTEP]
simp only [mem_insert, mem_filter, mem_range] at ha ⊢
[GOAL]
p : ℕ → Prop
inst✝ : DecidablePred p
k a : ℕ
ha : a < nth p (k + 1) ∧ p a
⊢ a = nth p k ∨ a < nth p k ∧ p a
[PROOFSTEP]
exact (le_nth_of_lt_nth_succ ha.1 ha.2).eq_or_lt.imp_right fun h => ⟨h, ha.2⟩
[GOAL]
p : ℕ → Prop
inst✝ : DecidablePred p
k : ℕ
hlt : ∀ (hf : Set.Finite (setOf p)), k + 1 < card (Set.Finite.toFinset hf)
⊢ filter p (range (nth p (k + 1))) = insert (nth p k) (filter p (range (nth p k)))
[PROOFSTEP]
refine' (filter_range_nth_subset_insert p k).antisymm fun a ha => _
[GOAL]
p : ℕ → Prop
inst✝ : DecidablePred p
k : ℕ
hlt : ∀ (hf : Set.Finite (setOf p)), k + 1 < card (Set.Finite.toFinset hf)
a : ℕ
ha : a ∈ insert (nth p k) (filter p (range (nth p k)))
⊢ a ∈ filter p (range (nth p (k + 1)))
[PROOFSTEP]
simp only [mem_insert, mem_filter, mem_range] at ha ⊢
[GOAL]
p : ℕ → Prop
inst✝ : DecidablePred p
k : ℕ
hlt : ∀ (hf : Set.Finite (setOf p)), k + 1 < card (Set.Finite.toFinset hf)
a : ℕ
ha : a = nth p k ∨ a < nth p k ∧ p a
⊢ a < nth p (k + 1) ∧ p a
[PROOFSTEP]
have : nth p k < nth p (k + 1) := nth_lt_nth' k.lt_succ_self hlt
[GOAL]
p : ℕ → Prop
inst✝ : DecidablePred p
k : ℕ
hlt : ∀ (hf : Set.Finite (setOf p)), k + 1 < card (Set.Finite.toFinset hf)
a : ℕ
ha : a = nth p k ∨ a < nth p k ∧ p a
this : nth p k < nth p (k + 1)
⊢ a < nth p (k + 1) ∧ p a
[PROOFSTEP]
rcases ha with (rfl | ⟨hlt, hpa⟩)
[GOAL]
case inl
p : ℕ → Prop
inst✝ : DecidablePred p
k : ℕ
hlt : ∀ (hf : Set.Finite (setOf p)), k + 1 < card (Set.Finite.toFinset hf)
this : nth p k < nth p (k + 1)
⊢ nth p k < nth p (k + 1) ∧ p (nth p k)
[PROOFSTEP]
exact ⟨this, nth_mem _ fun hf => k.lt_succ_self.trans (hlt hf)⟩
[GOAL]
case inr.intro
p : ℕ → Prop
inst✝ : DecidablePred p
k : ℕ
hlt✝ : ∀ (hf : Set.Finite (setOf p)), k + 1 < card (Set.Finite.toFinset hf)
a : ℕ
this : nth p k < nth p (k + 1)
hlt : a < nth p k
hpa : p a
⊢ a < nth p (k + 1) ∧ p a
[PROOFSTEP]
exact ⟨hlt.trans this, hpa⟩
[GOAL]
p : ℕ → Prop
inst✝ : DecidablePred p
n : ℕ
hn : ∀ (hf : Set.Finite (setOf p)), n < card (Set.Finite.toFinset hf)
⊢ count p (nth p n) = n
[PROOFSTEP]
induction' n with k ihk
[GOAL]
case zero
p : ℕ → Prop
inst✝ : DecidablePred p
n : ℕ
hn✝ : ∀ (hf : Set.Finite (setOf p)), n < card (Set.Finite.toFinset hf)
hn : ∀ (hf : Set.Finite (setOf p)), zero < card (Set.Finite.toFinset hf)
⊢ count p (nth p zero) = zero
[PROOFSTEP]
exact count_nth_zero _
[GOAL]
case succ
p : ℕ → Prop
inst✝ : DecidablePred p
n : ℕ
hn✝ : ∀ (hf : Set.Finite (setOf p)), n < card (Set.Finite.toFinset hf)
k : ℕ
ihk : (∀ (hf : Set.Finite (setOf p)), k < card (Set.Finite.toFinset hf)) → count p (nth p k) = k
hn : ∀ (hf : Set.Finite (setOf p)), succ k < card (Set.Finite.toFinset hf)
⊢ count p (nth p (succ k)) = succ k
[PROOFSTEP]
rw [count_eq_card_filter_range, filter_range_nth_eq_insert hn, card_insert_of_not_mem, ← count_eq_card_filter_range,
ihk fun hf => lt_of_succ_lt (hn hf)]
[GOAL]
case succ
p : ℕ → Prop
inst✝ : DecidablePred p
n : ℕ
hn✝ : ∀ (hf : Set.Finite (setOf p)), n < card (Set.Finite.toFinset hf)
k : ℕ
ihk : (∀ (hf : Set.Finite (setOf p)), k < card (Set.Finite.toFinset hf)) → count p (nth p k) = k
hn : ∀ (hf : Set.Finite (setOf p)), succ k < card (Set.Finite.toFinset hf)
⊢ ¬nth p k ∈ filter p (range (nth p k))
[PROOFSTEP]
simp
[GOAL]
p : ℕ → Prop
inst✝ : DecidablePred p
n : ℕ
hn : ∀ (hf : Set.Finite (setOf p)), n < card (Set.Finite.toFinset hf)
⊢ count p (nth p n + 1) = n + 1
[PROOFSTEP]
rw [count_succ, count_nth hn, if_pos (nth_mem _ hn)]
[GOAL]
p : ℕ → Prop
inst✝ : DecidablePred p
n k : ℕ
h : k < count p n
⊢ nth p k < n
[PROOFSTEP]
refine' (count_monotone p).reflect_lt _
[GOAL]
p : ℕ → Prop
inst✝ : DecidablePred p
n k : ℕ
h : k < count p n
⊢ count p (nth p k) < count p n
[PROOFSTEP]
rwa [count_nth]
[GOAL]
p : ℕ → Prop
inst✝ : DecidablePred p
n k : ℕ
h : k < count p n
⊢ ∀ (hf : Set.Finite (setOf p)), k < card (Set.Finite.toFinset hf)
[PROOFSTEP]
exact fun hf => h.trans_le (count_le_card hf n)
[GOAL]
p : ℕ → Prop
inst✝ : DecidablePred p
n : ℕ
⊢ nth p (count p n) = sInf {i | p i ∧ n ≤ i}
[PROOFSTEP]
refine' (nth_eq_sInf _ _).trans (congr_arg sInf _)
[GOAL]
p : ℕ → Prop
inst✝ : DecidablePred p
n : ℕ
⊢ {x | p x ∧ ∀ (k : ℕ), k < count p n → nth p k < x} = {i | p i ∧ n ≤ i}
[PROOFSTEP]
refine' Set.ext fun a => and_congr_right fun hpa => _
[GOAL]
p : ℕ → Prop
inst✝ : DecidablePred p
n a : ℕ
hpa : p a
⊢ (∀ (k : ℕ), k < count p n → nth p k < a) ↔ n ≤ a
[PROOFSTEP]
refine' ⟨fun h => not_lt.1 fun ha => _, fun hn k hk => lt_of_lt_of_le (nth_lt_of_lt_count hk) hn⟩
[GOAL]
p : ℕ → Prop
inst✝ : DecidablePred p
n a : ℕ
hpa : p a
h : ∀ (k : ℕ), k < count p n → nth p k < a
ha : a < n
⊢ False
[PROOFSTEP]
have hn : nth p (count p a) < a := h _ (count_strict_mono hpa ha)
[GOAL]
p : ℕ → Prop
inst✝ : DecidablePred p
n a : ℕ
hpa : p a
h : ∀ (k : ℕ), k < count p n → nth p k < a
ha : a < n
hn : nth p (count p a) < a
⊢ False
[PROOFSTEP]
rwa [nth_count hpa, lt_self_iff_false] at hn
|
lemmas Cauchy_Re = bounded_linear.Cauchy [OF bounded_linear_Re] |
/-
Copyright (c) 2022 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
! This file was ported from Lean 3 source module analysis.normed_space.matrix_exponential
! leanprover-community/mathlib commit 1e3201306d4d9eb1fd54c60d7c4510ad5126f6f9
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Analysis.NormedSpace.Exponential
import Mathbin.Analysis.Matrix
import Mathbin.LinearAlgebra.Matrix.Zpow
import Mathbin.LinearAlgebra.Matrix.Hermitian
import Mathbin.LinearAlgebra.Matrix.Symmetric
import Mathbin.Topology.UniformSpace.Matrix
/-!
# Lemmas about the matrix exponential
In this file, we provide results about `exp` on `matrix`s over a topological or normed algebra.
Note that generic results over all topological spaces such as `exp_zero` can be used on matrices
without issue, so are not repeated here. The topological results specific to matrices are:
* `matrix.exp_transpose`
* `matrix.exp_conj_transpose`
* `matrix.exp_diagonal`
* `matrix.exp_block_diagonal`
* `matrix.exp_block_diagonal'`
Lemmas like `exp_add_of_commute` require a canonical norm on the type; while there are multiple
sensible choices for the norm of a `matrix` (`matrix.normed_add_comm_group`,
`matrix.frobenius_normed_add_comm_group`, `matrix.linfty_op_normed_add_comm_group`), none of them
are canonical. In an application where a particular norm is chosen using
`local attribute [instance]`, then the usual lemmas about `exp` are fine. When choosing a norm is
undesirable, the results in this file can be used.
In this file, we copy across the lemmas about `exp`, but hide the requirement for a norm inside the
proof.
* `matrix.exp_add_of_commute`
* `matrix.exp_sum_of_commute`
* `matrix.exp_nsmul`
* `matrix.is_unit_exp`
* `matrix.exp_units_conj`
* `matrix.exp_units_conj'`
Additionally, we prove some results about `matrix.has_inv` and `matrix.div_inv_monoid`, as the
results for general rings are instead stated about `ring.inverse`:
* `matrix.exp_neg`
* `matrix.exp_zsmul`
* `matrix.exp_conj`
* `matrix.exp_conj'`
## Implementation notes
This file runs into some sharp edges on typeclass search in lean 3, especially regarding pi types.
To work around this, we copy a handful of instances for when lean can't find them by itself.
Hopefully we will be able to remove these in Lean 4.
## TODO
* Show that `matrix.det (exp 𝕂 A) = exp 𝕂 (matrix.trace A)`
## References
* https://en.wikipedia.org/wiki/Matrix_exponential
-/
open Matrix BigOperators
section HacksForPiInstanceSearch
/-- A special case of `pi.topological_ring` for when `R` is not dependently typed. -/
instance Function.topologicalRing (I : Type _) (R : Type _) [NonUnitalRing R] [TopologicalSpace R]
[TopologicalRing R] : TopologicalRing (I → R) :=
Pi.topologicalRing
#align function.topological_ring Function.topologicalRing
/-- A special case of `function.algebra` for when A is a `ring` not a `semiring` -/
instance Function.algebraRing (I : Type _) {R : Type _} (A : Type _) [CommSemiring R] [Ring A]
[Algebra R A] : Algebra R (I → A) :=
Pi.algebra _ _
#align function.algebra_ring Function.algebraRing
/-- A special case of `pi.algebra` for when `f = λ i, matrix (m i) (m i) A`. -/
instance Pi.matrixAlgebra (I R A : Type _) (m : I → Type _) [CommSemiring R] [Semiring A]
[Algebra R A] [∀ i, Fintype (m i)] [∀ i, DecidableEq (m i)] :
Algebra R (∀ i, Matrix (m i) (m i) A) :=
@Pi.algebra I R (fun i => Matrix (m i) (m i) A) _ _ fun i => Matrix.algebra
#align pi.matrix_algebra Pi.matrixAlgebra
/-- A special case of `pi.topological_ring` for when `f = λ i, matrix (m i) (m i) A`. -/
instance Pi.matrix_topologicalRing (I A : Type _) (m : I → Type _) [Ring A] [TopologicalSpace A]
[TopologicalRing A] [∀ i, Fintype (m i)] : TopologicalRing (∀ i, Matrix (m i) (m i) A) :=
@Pi.topologicalRing _ (fun i => Matrix (m i) (m i) A) _ _ fun i => Matrix.topologicalRing
#align pi.matrix_topological_ring Pi.matrix_topologicalRing
end HacksForPiInstanceSearch
variable (𝕂 : Type _) {m n p : Type _} {n' : m → Type _} {𝔸 : Type _}
namespace Matrix
section Topological
section Ring
variable [Fintype m] [DecidableEq m] [Fintype n] [DecidableEq n] [∀ i, Fintype (n' i)]
[∀ i, DecidableEq (n' i)] [Field 𝕂] [Ring 𝔸] [TopologicalSpace 𝔸] [TopologicalRing 𝔸]
[Algebra 𝕂 𝔸] [T2Space 𝔸]
theorem exp_diagonal (v : m → 𝔸) : exp 𝕂 (diagonal v) = diagonal (exp 𝕂 v) := by
simp_rw [exp_eq_tsum, diagonal_pow, ← diagonal_smul, ← diagonal_tsum]
#align matrix.exp_diagonal Matrix.exp_diagonal
theorem exp_blockDiagonal (v : m → Matrix n n 𝔸) :
exp 𝕂 (blockDiagonal v) = blockDiagonal (exp 𝕂 v) := by
simp_rw [exp_eq_tsum, ← block_diagonal_pow, ← block_diagonal_smul, ← block_diagonal_tsum]
#align matrix.exp_block_diagonal Matrix.exp_blockDiagonal
theorem exp_blockDiagonal' (v : ∀ i, Matrix (n' i) (n' i) 𝔸) :
exp 𝕂 (blockDiagonal' v) = blockDiagonal' (exp 𝕂 v) := by
simp_rw [exp_eq_tsum, ← block_diagonal'_pow, ← block_diagonal'_smul, ← block_diagonal'_tsum]
#align matrix.exp_block_diagonal' Matrix.exp_blockDiagonal'
theorem exp_conjTranspose [StarRing 𝔸] [ContinuousStar 𝔸] (A : Matrix m m 𝔸) :
exp 𝕂 Aᴴ = (exp 𝕂 A)ᴴ :=
(star_exp A).symm
#align matrix.exp_conj_transpose Matrix.exp_conjTranspose
theorem IsHermitian.exp [StarRing 𝔸] [ContinuousStar 𝔸] {A : Matrix m m 𝔸} (h : A.IsHermitian) :
(exp 𝕂 A).IsHermitian :=
(exp_conjTranspose _ _).symm.trans <| congr_arg _ h
#align matrix.is_hermitian.exp Matrix.IsHermitian.exp
end Ring
section CommRing
variable [Fintype m] [DecidableEq m] [Field 𝕂] [CommRing 𝔸] [TopologicalSpace 𝔸] [TopologicalRing 𝔸]
[Algebra 𝕂 𝔸] [T2Space 𝔸]
theorem exp_transpose (A : Matrix m m 𝔸) : exp 𝕂 Aᵀ = (exp 𝕂 A)ᵀ := by
simp_rw [exp_eq_tsum, transpose_tsum, transpose_smul, transpose_pow]
#align matrix.exp_transpose Matrix.exp_transpose
theorem IsSymm.exp {A : Matrix m m 𝔸} (h : A.IsSymm) : (exp 𝕂 A).IsSymm :=
(exp_transpose _ _).symm.trans <| congr_arg _ h
#align matrix.is_symm.exp Matrix.IsSymm.exp
end CommRing
end Topological
section Normed
variable [IsROrC 𝕂] [Fintype m] [DecidableEq m] [Fintype n] [DecidableEq n] [∀ i, Fintype (n' i)]
[∀ i, DecidableEq (n' i)] [NormedRing 𝔸] [NormedAlgebra 𝕂 𝔸] [CompleteSpace 𝔸]
theorem exp_add_of_commute (A B : Matrix m m 𝔸) (h : Commute A B) :
exp 𝕂 (A + B) = exp 𝕂 A ⬝ exp 𝕂 B :=
by
letI : SeminormedRing (Matrix m m 𝔸) := Matrix.linftyOpSemiNormedRing
letI : NormedRing (Matrix m m 𝔸) := Matrix.linftyOpNormedRing
letI : NormedAlgebra 𝕂 (Matrix m m 𝔸) := Matrix.linftyOpNormedAlgebra
exact exp_add_of_commute h
#align matrix.exp_add_of_commute Matrix.exp_add_of_commute
theorem exp_sum_of_commute {ι} (s : Finset ι) (f : ι → Matrix m m 𝔸)
(h : (s : Set ι).Pairwise fun i j => Commute (f i) (f j)) :
exp 𝕂 (∑ i in s, f i) =
s.noncommProd (fun i => exp 𝕂 (f i)) fun i hi j hj _ => (h.of_refl hi hj).exp 𝕂 :=
by
letI : SeminormedRing (Matrix m m 𝔸) := Matrix.linftyOpSemiNormedRing
letI : NormedRing (Matrix m m 𝔸) := Matrix.linftyOpNormedRing
letI : NormedAlgebra 𝕂 (Matrix m m 𝔸) := Matrix.linftyOpNormedAlgebra
exact exp_sum_of_commute s f h
#align matrix.exp_sum_of_commute Matrix.exp_sum_of_commute
theorem exp_nsmul (n : ℕ) (A : Matrix m m 𝔸) : exp 𝕂 (n • A) = exp 𝕂 A ^ n :=
by
letI : SeminormedRing (Matrix m m 𝔸) := Matrix.linftyOpSemiNormedRing
letI : NormedRing (Matrix m m 𝔸) := Matrix.linftyOpNormedRing
letI : NormedAlgebra 𝕂 (Matrix m m 𝔸) := Matrix.linftyOpNormedAlgebra
exact exp_nsmul n A
#align matrix.exp_nsmul Matrix.exp_nsmul
theorem isUnit_exp (A : Matrix m m 𝔸) : IsUnit (exp 𝕂 A) :=
by
letI : SeminormedRing (Matrix m m 𝔸) := Matrix.linftyOpSemiNormedRing
letI : NormedRing (Matrix m m 𝔸) := Matrix.linftyOpNormedRing
letI : NormedAlgebra 𝕂 (Matrix m m 𝔸) := Matrix.linftyOpNormedAlgebra
exact isUnit_exp _ A
#align matrix.is_unit_exp Matrix.isUnit_exp
theorem exp_units_conj (U : (Matrix m m 𝔸)ˣ) (A : Matrix m m 𝔸) :
exp 𝕂 (↑U ⬝ A ⬝ ↑U⁻¹ : Matrix m m 𝔸) = ↑U ⬝ exp 𝕂 A ⬝ ↑U⁻¹ :=
by
letI : SeminormedRing (Matrix m m 𝔸) := Matrix.linftyOpSemiNormedRing
letI : NormedRing (Matrix m m 𝔸) := Matrix.linftyOpNormedRing
letI : NormedAlgebra 𝕂 (Matrix m m 𝔸) := Matrix.linftyOpNormedAlgebra
exact exp_units_conj _ U A
#align matrix.exp_units_conj Matrix.exp_units_conj
theorem exp_units_conj' (U : (Matrix m m 𝔸)ˣ) (A : Matrix m m 𝔸) :
exp 𝕂 (↑U⁻¹ ⬝ A ⬝ U : Matrix m m 𝔸) = ↑U⁻¹ ⬝ exp 𝕂 A ⬝ U :=
exp_units_conj 𝕂 U⁻¹ A
#align matrix.exp_units_conj' Matrix.exp_units_conj'
end Normed
section NormedComm
variable [IsROrC 𝕂] [Fintype m] [DecidableEq m] [Fintype n] [DecidableEq n] [∀ i, Fintype (n' i)]
[∀ i, DecidableEq (n' i)] [NormedCommRing 𝔸] [NormedAlgebra 𝕂 𝔸] [CompleteSpace 𝔸]
theorem exp_neg (A : Matrix m m 𝔸) : exp 𝕂 (-A) = (exp 𝕂 A)⁻¹ :=
by
rw [nonsing_inv_eq_ring_inverse]
letI : SeminormedRing (Matrix m m 𝔸) := Matrix.linftyOpSemiNormedRing
letI : NormedRing (Matrix m m 𝔸) := Matrix.linftyOpNormedRing
letI : NormedAlgebra 𝕂 (Matrix m m 𝔸) := Matrix.linftyOpNormedAlgebra
exact (Ring.inverse_exp _ A).symm
#align matrix.exp_neg Matrix.exp_neg
theorem exp_zsmul (z : ℤ) (A : Matrix m m 𝔸) : exp 𝕂 (z • A) = exp 𝕂 A ^ z :=
by
obtain ⟨n, rfl | rfl⟩ := z.eq_coe_or_neg
· rw [zpow_ofNat, coe_nat_zsmul, exp_nsmul]
· have : IsUnit (exp 𝕂 A).det := (Matrix.isUnit_iff_isUnit_det _).mp (isUnit_exp _ _)
rw [Matrix.zpow_neg this, zpow_ofNat, neg_smul, exp_neg, coe_nat_zsmul, exp_nsmul]
#align matrix.exp_zsmul Matrix.exp_zsmul
theorem exp_conj (U : Matrix m m 𝔸) (A : Matrix m m 𝔸) (hy : IsUnit U) :
exp 𝕂 (U ⬝ A ⬝ U⁻¹) = U ⬝ exp 𝕂 A ⬝ U⁻¹ :=
let ⟨u, hu⟩ := hy
hu ▸ by simpa only [Matrix.coe_units_inv] using exp_units_conj 𝕂 u A
#align matrix.exp_conj Matrix.exp_conj
theorem exp_conj' (U : Matrix m m 𝔸) (A : Matrix m m 𝔸) (hy : IsUnit U) :
exp 𝕂 (U⁻¹ ⬝ A ⬝ U) = U⁻¹ ⬝ exp 𝕂 A ⬝ U :=
let ⟨u, hu⟩ := hy
hu ▸ by simpa only [Matrix.coe_units_inv] using exp_units_conj' 𝕂 u A
#align matrix.exp_conj' Matrix.exp_conj'
end NormedComm
end Matrix
|
State Before: s : Set ℤ
h : ¬BddBelow s
⊢ ¬(Set.Nonempty s ∧ BddBelow s) State After: no goals Tactic: simp [h] |
Require Import ZArith.
Require Import Psatz.
Require Import Coq.Classes.RelationClasses.
Require Import TLC.LibTactics.
Require Import TLC.LibOrder.
Require Import LibFunOrd LibZExtra.
Require Import Filter.
(* todo: move *)
Lemma preorder_of_PreOrder A (R : A -> A -> Prop) :
PreOrder R ->
preorder R.
Proof.
intros (HR & HT). constructor.
- apply HR.
- intros y x z H1 H2. apply HT with (y := y); assumption.
Qed.
Section General_facts.
Context {A} (leA : A -> A -> Prop) {OA : preorder leA}.
Context {B} (leB : B -> B -> Prop) {OB : preorder leB}.
Context {C} (leC : C -> C -> Prop) {OC : preorder leC}.
Lemma monotonic_eq : forall f g,
monotonic leA leB f ->
(forall a, f a = g a) ->
monotonic leA leB g.
Proof.
introv M E.
intros a1 a2 H. rewrite <-!E. apply M. auto.
Qed.
Lemma monotonic_id :
monotonic leA leA (fun (x: A) => x).
Proof. intros a1 a2. auto. Qed.
Lemma monotonic_comp : forall (f : B -> C) (g : A -> B),
monotonic leB leC f ->
monotonic leA leB g ->
monotonic leA leC (fun x => f (g x)).
Proof. introv Hf Hg. intros a1 a2 ?. auto. Qed.
Lemma monotonic_cst : forall b,
monotonic leA leB (fun (_ : A) => b).
Proof. intros b a1 a2 ?. applys OB. Qed.
Lemma monotonic_after_of_monotonic : forall (f : A -> B),
monotonic leA leB f ->
(forall (a : A), monotonic (le_after a leA) leB f).
Proof.
intros f fmon a.
intros a1 a2 H. apply fmon. apply H.
Qed.
Lemma monotonic_of_monotonic_after : forall (f : A -> B),
(forall a, monotonic (le_after a leA) leB f) ->
monotonic leA leB f.
Proof.
intros f fmon.
intros a1 a2 H. eapply fmon.
splits; try (apply preorder_refl; typeclass); assumption.
Qed.
Lemma monotonic_after_weaken : forall (f : A -> B) (a1 a2 : A),
leA a1 a2 ->
monotonic (le_after a1 leA) leB f ->
monotonic (le_after a2 leA) leB f.
Proof.
intros f a1 a2 H fmon.
intros x y Hxy. apply fmon.
splits; try apply Hxy;
eapply (preorder_trans a2); first [apply H | apply Hxy].
Unshelve. typeclass. typeclass.
Qed.
End General_facts.
Lemma ultimately_monotonic_of_monotonic :
forall (A : filterType) B
(leA : A -> A -> Prop) (leB : B -> B -> Prop)
(f : A -> B),
monotonic leA leB f ->
ultimately A (fun a => monotonic (le_after a leA) leB f).
Proof.
introv fmon. applys filter_universe_alt.
eapply monotonic_after_of_monotonic. apply fmon.
Qed.
Section Z_facts.
Local Open Scope Z.
Context {A} (leA: A -> A -> Prop) {OA: preorder leA}.
Lemma monotonic_sum : forall (f g : A -> Z),
monotonic leA Z.le f ->
monotonic leA Z.le g ->
monotonic leA Z.le (fun x => f x + g x).
Proof.
introv Hf Hg. intros a1 a2 ?.
forwards~: Hf a1 a2. forwards~: Hg a1 a2. lia.
Qed.
Lemma monotonic_max : forall (f g : A -> Z),
monotonic leA Z.le f ->
monotonic leA Z.le g ->
monotonic leA Z.le (fun x => Z.max (f x) (g x)).
Proof.
introv Hf Hg. intros a1 a2 ?.
forwards~: Hf a1 a2. forwards~: Hg a1 a2. lia.
Qed.
Lemma monotonic_mul : forall (f g : A -> Z),
(forall x, 0 <= f x) ->
(forall x, 0 <= g x) ->
monotonic leA Z.le f ->
monotonic leA Z.le g ->
monotonic leA Z.le (fun x => f x * g x).
Proof.
introv Pf Pg Hf Hg. intros a1 a2 ?.
forwards~: Pf a1. forwards~: Pf a2. forwards~: Pg a1. forwards~: Pg a2.
forwards~: Hf a1 a2. forwards~: Hg a1 a2. nia.
Qed.
Lemma monotonic_mul_cst_l : forall (f : A -> Z) (c : Z),
0 <= c ->
monotonic leA Z.le f ->
monotonic leA Z.le (fun x => c * f x).
Proof.
introv cpos Hf. intros a1 a2 H.
forwards~: Hf a1 a2. nia.
Qed.
Lemma monotonic_mul_cst_r : forall (f : A -> Z) (c : Z),
0 <= c ->
monotonic leA Z.le f ->
monotonic leA Z.le (fun x => f x * c).
Proof.
introv cpos Hf.
intros a1 a2 H. forwards~: Hf a1 a2. nia.
Qed.
Lemma monotonic_log2 : monotonic Z.le Z.le Z.log2.
Proof.
intros a1 a2 H. apply~ Z.log2_le_mono.
Qed.
Lemma monotonic_pow_l : forall e,
monotonic (le_after 0 Z.le) Z.le (fun b => b ^ e).
Proof.
intros e a1 a2 H. apply~ Z.pow_le_mono_l. splits; apply H.
Qed.
Lemma monotonic_pow_r : forall b,
0 < b ->
monotonic Z.le Z.le (Z.pow b).
Proof.
intros b a1 a2 H. apply~ Z.pow_le_mono_r.
Qed.
Lemma monotonic_Z_to_ZZ : forall f g,
monotonic Z.le Z.le f ->
monotonic Z.le Z.le g ->
monotonic Z.le ZZle (fun x => (f x, g x)).
Proof.
intros f g Hf Hg x y H. unfold ZZle. auto.
Qed.
End Z_facts.
Section Ultimately_Z_facts.
Local Open Scope Z.
Lemma ultimately_monotonic_mul :
forall (A : filterType) (leA : A -> A -> Prop)
{OA: preorder leA}
(f g : A -> Z),
ultimately A (fun x => 0 <= f x) ->
ultimately A (fun x => 0 <= g x) ->
ultimately A (fun a => monotonic (le_after a leA) Z.le f) ->
ultimately A (fun a => monotonic (le_after a leA) Z.le g) ->
ultimately A (fun a => monotonic (le_after a leA) Z.le (fun x => f x * g x)).
Proof.
introv OA. introv. filter_closed_under_intersection.
introv (Pf & Pg & Hf & Hg). intros a1 a2 (a_le_a1 & a_le_a2 & a1_le_a2).
forwards~: Hf a a1; forwards~: Hg a a1;
forwards~: Hf a1 a2; forwards~: Hg a1 a2;
try (splits; first [apply OA | assumption]).
nia.
Qed.
End Ultimately_Z_facts.
(******************************************************************************)
(* Add lemmas to a [monotonic] hint base. *)
Hint Resolve monotonic_cst : monotonic.
Hint Resolve monotonic_id : monotonic.
Hint Resolve monotonic_sum : monotonic.
Hint Extern 1 (monotonic _ _ (fun _ => Z.sub _ ?y)) =>
apply monotonic_sum : monotonic.
Hint Extern 1 (monotonic _ _ (Z.sub ?y)) =>
apply monotonic_sum : monotonic.
Hint Resolve monotonic_max : monotonic.
Hint Resolve monotonic_mul : monotonic.
Hint Resolve monotonic_mul_cst_l : monotonic.
Hint Resolve monotonic_mul_cst_r : monotonic.
Hint Resolve monotonic_log2 : monotonic.
Hint Resolve monotonic_pow_l : monotonic.
Hint Resolve monotonic_pow_r : monotonic.
Hint Extern 1 (monotonic _ _ (fun _ => Z.log2 _)) =>
apply monotonic_comp with (leB := Z.le);
[ apply monotonic_log2 | ] : monotonic.
Hint Extern 2 (monotonic _ _ (fun _ => Z.pow ?b _)) =>
apply monotonic_comp with (leB := Z.le);
[ apply monotonic_pow_r | ].
Hint Extern 2 (monotonic _ _ (Z.pow ?b)) =>
apply monotonic_comp with (leB := Z.le);
[ apply monotonic_pow_r | ].
(* todo: Z.pow _ ?e *)
Hint Resolve monotonic_Z_to_ZZ : monotonic.
Hint Extern 1 (monotonic _ _ (fun _ => ?f _)) =>
match goal with
| H: monotonic ?le _ f |- _ =>
apply monotonic_comp with (leB := le); [ apply H | ]
end : monotonic.
Hint Extern 0 (preorder _) =>
first [ typeclass
| apply preorder_of_PreOrder; typeclass ]
: monotonic.
Hint Extern 100 => try (intros; omega) : monotonic_sidegoals.
Hint Extern 999 (monotonic _ _ _) => shelve : monotonic_fallback.
Hint Extern 999 (preorder _) => shelve : monotonic_fallback.
(******************************************************************************)
(* TODO: make the search depth customisable *)
Ltac monotonic :=
unshelve (auto 20 with zarith typeclass_instances
monotonic
monotonic_sidegoals
monotonic_fallback).
Ltac monotonic_trysolve :=
auto 20 with zarith typeclass_instances
monotonic_sidegoals
monotonic.
(* TODO: extend monotonic_Z to handle monotonic (le_after ..) .., and ultimately
(fun a => monotonic (le_after a ..) ..) *)
(* Ltac monotonic_Z_auto_step := *)
(* match goal with *)
(* | |- @monotonic _ _ _ _ _ => *)
(* let a := fresh "a" in *)
(* apply monotonic_of_monotonic_after; [ *)
(* eauto; typeclass *)
(* | intro a; *)
(* monotonic_after_Z_auto; *)
(* try apply monotonic_after_of_monotonic ] *)
(* | |- @monotonic_after _ _ _ _ _ _ => *)
(* eapply monotonic_after_of_monotonic; eauto *)
(* | |- context [ @monotonic_after _ _ _ _ _ ] => *)
(* eapply ultimately_monotonic_of_monotonic; *)
(* eauto; try typeclass *)
(* end. *)
|
c An example Fortran subroutine to calculate
c the summation of two complex*16 numbers
SUBROUTINE F_XWSUB(a, b, c)
implicit none
complex*16 a, b, c
c = a + b
WRITE(6,*) "in fortran: ", real(c), aimag(c)
RETURN
END |
/-
Copyright (c) 2019 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou, Frédéric Dupuis, Heather Macbeth
! This file was ported from Lean 3 source module analysis.inner_product_space.projection
! leanprover-community/mathlib commit 6e272cd89fa32c72a25dbefd319394c48dce1576
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Analysis.Convex.Basic
import Mathbin.Analysis.InnerProductSpace.Orthogonal
import Mathbin.Analysis.InnerProductSpace.Symmetric
import Mathbin.Analysis.NormedSpace.IsROrC
import Mathbin.Data.IsROrC.Lemmas
/-!
# The orthogonal projection
Given a nonempty complete subspace `K` of an inner product space `E`, this file constructs
`orthogonal_projection K : E →L[𝕜] K`, the orthogonal projection of `E` onto `K`. This map
satisfies: for any point `u` in `E`, the point `v = orthogonal_projection K u` in `K` minimizes the
distance `‖u - v‖` to `u`.
Also a linear isometry equivalence `reflection K : E ≃ₗᵢ[𝕜] E` is constructed, by choosing, for
each `u : E`, the point `reflection K u` to satisfy
`u + (reflection K u) = 2 • orthogonal_projection K u`.
Basic API for `orthogonal_projection` and `reflection` is developed.
Next, the orthogonal projection is used to prove a series of more subtle lemmas about the
the orthogonal complement of complete subspaces of `E` (the orthogonal complement itself was
defined in `analysis.inner_product_space.basic`); the lemma
`submodule.sup_orthogonal_of_is_complete`, stating that for a complete subspace `K` of `E` we have
`K ⊔ Kᗮ = ⊤`, is a typical example.
## References
The orthogonal projection construction is adapted from
* [Clément & Martin, *The Lax-Milgram Theorem. A detailed proof to be formalized in Coq*]
* [Clément & Martin, *A Coq formal proof of the Lax–Milgram theorem*]
The Coq code is available at the following address: <http://www.lri.fr/~sboldo/elfic/index.html>
-/
noncomputable section
open IsROrC Real Filter
open LinearMap (ker range)
open BigOperators Topology
variable {𝕜 E F : Type _} [IsROrC 𝕜]
variable [NormedAddCommGroup E] [NormedAddCommGroup F]
variable [InnerProductSpace 𝕜 E] [InnerProductSpace ℝ F]
-- mathport name: «expr⟪ , ⟫»
local notation "⟪" x ", " y "⟫" => @inner 𝕜 _ _ x y
-- mathport name: exprabsR
local notation "absR" => Abs.abs
/-! ### Orthogonal projection in inner product spaces -/
-- FIXME this monolithic proof causes a deterministic timeout with `-T50000`
-- It should be broken in a sequence of more manageable pieces,
-- perhaps with individual statements for the three steps below.
/-- Existence of minimizers
Let `u` be a point in a real inner product space, and let `K` be a nonempty complete convex subset.
Then there exists a (unique) `v` in `K` that minimizes the distance `‖u - v‖` to `u`.
-/
theorem exists_norm_eq_infᵢ_of_complete_convex {K : Set F} (ne : K.Nonempty) (h₁ : IsComplete K)
(h₂ : Convex ℝ K) : ∀ u : F, ∃ v ∈ K, ‖u - v‖ = ⨅ w : K, ‖u - w‖ := fun u =>
by
let δ := ⨅ w : K, ‖u - w‖
letI : Nonempty K := ne.to_subtype
have zero_le_δ : 0 ≤ δ := le_cinfᵢ fun _ => norm_nonneg _
have δ_le : ∀ w : K, δ ≤ ‖u - w‖ := cinfᵢ_le ⟨0, Set.forall_range_iff.2 fun _ => norm_nonneg _⟩
have δ_le' : ∀ w ∈ K, δ ≤ ‖u - w‖ := fun w hw => δ_le ⟨w, hw⟩
-- Step 1: since `δ` is the infimum, can find a sequence `w : ℕ → K` in `K`
-- such that `‖u - w n‖ < δ + 1 / (n + 1)` (which implies `‖u - w n‖ --> δ`);
-- maybe this should be a separate lemma
have exists_seq : ∃ w : ℕ → K, ∀ n, ‖u - w n‖ < δ + 1 / (n + 1) :=
by
have hδ : ∀ n : ℕ, δ < δ + 1 / (n + 1) := fun n =>
lt_add_of_le_of_pos le_rfl Nat.one_div_pos_of_nat
have h := fun n => exists_lt_of_cinfᵢ_lt (hδ n)
let w : ℕ → K := fun n => Classical.choose (h n)
exact ⟨w, fun n => Classical.choose_spec (h n)⟩
rcases exists_seq with ⟨w, hw⟩
have norm_tendsto : tendsto (fun n => ‖u - w n‖) at_top (nhds δ) :=
by
have h : tendsto (fun n : ℕ => δ) at_top (nhds δ) := tendsto_const_nhds
have h' : tendsto (fun n : ℕ => δ + 1 / (n + 1)) at_top (nhds δ) :=
by
convert h.add tendsto_one_div_add_atTop_nhds_0_nat
simp only [add_zero]
exact tendsto_of_tendsto_of_tendsto_of_le_of_le h h' (fun x => δ_le _) fun x => le_of_lt (hw _)
-- Step 2: Prove that the sequence `w : ℕ → K` is a Cauchy sequence
have seq_is_cauchy : CauchySeq fun n => (w n : F) :=
by
rw [cauchySeq_iff_le_tendsto_0]
-- splits into three goals
let b := fun n : ℕ => 8 * δ * (1 / (n + 1)) + 4 * (1 / (n + 1)) * (1 / (n + 1))
use fun n => sqrt (b n)
constructor
-- first goal : `∀ (n : ℕ), 0 ≤ sqrt (b n)`
intro n
exact sqrt_nonneg _
constructor
-- second goal : `∀ (n m N : ℕ), N ≤ n → N ≤ m → dist ↑(w n) ↑(w m) ≤ sqrt (b N)`
intro p q N hp hq
let wp := (w p : F)
let wq := (w q : F)
let a := u - wq
let b := u - wp
let half := 1 / (2 : ℝ)
let div := 1 / ((N : ℝ) + 1)
have :
4 * ‖u - half • (wq + wp)‖ * ‖u - half • (wq + wp)‖ + ‖wp - wq‖ * ‖wp - wq‖ =
2 * (‖a‖ * ‖a‖ + ‖b‖ * ‖b‖) :=
calc
4 * ‖u - half • (wq + wp)‖ * ‖u - half • (wq + wp)‖ + ‖wp - wq‖ * ‖wp - wq‖ =
2 * ‖u - half • (wq + wp)‖ * (2 * ‖u - half • (wq + wp)‖) + ‖wp - wq‖ * ‖wp - wq‖ :=
by ring
_ =
absR (2 : ℝ) * ‖u - half • (wq + wp)‖ * (absR (2 : ℝ) * ‖u - half • (wq + wp)‖) +
‖wp - wq‖ * ‖wp - wq‖ :=
by
rw [_root_.abs_of_nonneg]
exact zero_le_two
_ =
‖(2 : ℝ) • (u - half • (wq + wp))‖ * ‖(2 : ℝ) • (u - half • (wq + wp))‖ +
‖wp - wq‖ * ‖wp - wq‖ :=
by simp [norm_smul]
_ = ‖a + b‖ * ‖a + b‖ + ‖a - b‖ * ‖a - b‖ :=
by
rw [smul_sub, smul_smul, mul_one_div_cancel (_root_.two_ne_zero : (2 : ℝ) ≠ 0), ←
one_add_one_eq_two, add_smul]
simp only [one_smul]
have eq₁ : wp - wq = a - b := (sub_sub_sub_cancel_left _ _ _).symm
have eq₂ : u + u - (wq + wp) = a + b
show u + u - (wq + wp) = u - wq + (u - wp)
abel
rw [eq₁, eq₂]
_ = 2 * (‖a‖ * ‖a‖ + ‖b‖ * ‖b‖) := parallelogram_law_with_norm ℝ _ _
have eq : δ ≤ ‖u - half • (wq + wp)‖ := by
rw [smul_add]
apply δ_le'
apply h₂
repeat' exact Subtype.mem _
repeat' exact le_of_lt one_half_pos
exact add_halves 1
have eq₁ : 4 * δ * δ ≤ 4 * ‖u - half • (wq + wp)‖ * ‖u - half • (wq + wp)‖ :=
by
simp_rw [mul_assoc]
exact mul_le_mul_of_nonneg_left (mul_self_le_mul_self zero_le_δ Eq) zero_le_four
have eq₂ : ‖a‖ * ‖a‖ ≤ (δ + div) * (δ + div) :=
mul_self_le_mul_self (norm_nonneg _)
(le_trans (le_of_lt <| hw q) (add_le_add_left (Nat.one_div_le_one_div hq) _))
have eq₂' : ‖b‖ * ‖b‖ ≤ (δ + div) * (δ + div) :=
mul_self_le_mul_self (norm_nonneg _)
(le_trans (le_of_lt <| hw p) (add_le_add_left (Nat.one_div_le_one_div hp) _))
rw [dist_eq_norm]
apply nonneg_le_nonneg_of_sq_le_sq
· exact sqrt_nonneg _
rw [mul_self_sqrt]
calc
‖wp - wq‖ * ‖wp - wq‖ =
2 * (‖a‖ * ‖a‖ + ‖b‖ * ‖b‖) - 4 * ‖u - half • (wq + wp)‖ * ‖u - half • (wq + wp)‖ :=
by
rw [← this]
simp
_ ≤ 2 * (‖a‖ * ‖a‖ + ‖b‖ * ‖b‖) - 4 * δ * δ := (sub_le_sub_left eq₁ _)
_ ≤ 2 * ((δ + div) * (δ + div) + (δ + div) * (δ + div)) - 4 * δ * δ :=
(sub_le_sub_right (mul_le_mul_of_nonneg_left (add_le_add eq₂ eq₂') (by norm_num)) _)
_ = 8 * δ * div + 4 * div * div := by ring
exact
add_nonneg (mul_nonneg (mul_nonneg (by norm_num) zero_le_δ) (le_of_lt Nat.one_div_pos_of_nat))
(mul_nonneg (mul_nonneg (by norm_num) nat.one_div_pos_of_nat.le) nat.one_div_pos_of_nat.le)
-- third goal : `tendsto (λ (n : ℕ), sqrt (b n)) at_top (𝓝 0)`
apply tendsto.comp
· convert continuous_sqrt.continuous_at
exact sqrt_zero.symm
have eq₁ : tendsto (fun n : ℕ => 8 * δ * (1 / (n + 1))) at_top (nhds (0 : ℝ)) :=
by
convert(@tendsto_const_nhds _ _ _ (8 * δ) _).mul tendsto_one_div_add_atTop_nhds_0_nat
simp only [MulZeroClass.mul_zero]
have : tendsto (fun n : ℕ => (4 : ℝ) * (1 / (n + 1))) at_top (nhds (0 : ℝ)) :=
by
convert(@tendsto_const_nhds _ _ _ (4 : ℝ) _).mul tendsto_one_div_add_atTop_nhds_0_nat
simp only [MulZeroClass.mul_zero]
have eq₂ :
tendsto (fun n : ℕ => (4 : ℝ) * (1 / (n + 1)) * (1 / (n + 1))) at_top (nhds (0 : ℝ)) :=
by
convert this.mul tendsto_one_div_add_atTop_nhds_0_nat
simp only [MulZeroClass.mul_zero]
convert eq₁.add eq₂
simp only [add_zero]
-- Step 3: By completeness of `K`, let `w : ℕ → K` converge to some `v : K`.
-- Prove that it satisfies all requirements.
rcases cauchySeq_tendsto_of_isComplete h₁ (fun n => _) seq_is_cauchy with ⟨v, hv, w_tendsto⟩
use v
use hv
have h_cont : Continuous fun v => ‖u - v‖ :=
Continuous.comp continuous_norm (Continuous.sub continuous_const continuous_id)
have : tendsto (fun n => ‖u - w n‖) at_top (nhds ‖u - v‖)
convert tendsto.comp h_cont.continuous_at w_tendsto
exact tendsto_nhds_unique this norm_tendsto
exact Subtype.mem _
#align exists_norm_eq_infi_of_complete_convex exists_norm_eq_infᵢ_of_complete_convex
/-- Characterization of minimizers for the projection on a convex set in a real inner product
space. -/
theorem norm_eq_infᵢ_iff_real_inner_le_zero {K : Set F} (h : Convex ℝ K) {u : F} {v : F}
(hv : v ∈ K) : (‖u - v‖ = ⨅ w : K, ‖u - w‖) ↔ ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0 :=
Iff.intro
(by
intro eq w hw
let δ := ⨅ w : K, ‖u - w‖
let p := ⟪u - v, w - v⟫_ℝ
let q := ‖w - v‖ ^ 2
letI : Nonempty K := ⟨⟨v, hv⟩⟩
have zero_le_δ : 0 ≤ δ
apply le_cinfᵢ
intro
exact norm_nonneg _
have δ_le : ∀ w : K, δ ≤ ‖u - w‖
intro w
apply cinfᵢ_le
use (0 : ℝ)
rintro _ ⟨_, rfl⟩
exact norm_nonneg _
have δ_le' : ∀ w ∈ K, δ ≤ ‖u - w‖ := fun w hw => δ_le ⟨w, hw⟩
have : ∀ θ : ℝ, 0 < θ → θ ≤ 1 → 2 * p ≤ θ * q
intro θ hθ₁ hθ₂
have : ‖u - v‖ ^ 2 ≤ ‖u - v‖ ^ 2 - 2 * θ * ⟪u - v, w - v⟫_ℝ + θ * θ * ‖w - v‖ ^ 2 :=
calc
‖u - v‖ ^ 2 ≤ ‖u - (θ • w + (1 - θ) • v)‖ ^ 2 :=
by
simp only [sq]; apply mul_self_le_mul_self (norm_nonneg _)
rw [Eq]; apply δ_le'
apply h hw hv
exacts[le_of_lt hθ₁, sub_nonneg.2 hθ₂, add_sub_cancel'_right _ _]
_ = ‖u - v - θ • (w - v)‖ ^ 2 :=
by
have : u - (θ • w + (1 - θ) • v) = u - v - θ • (w - v) :=
by
rw [smul_sub, sub_smul, one_smul]
simp only [sub_eq_add_neg, add_comm, add_left_comm, add_assoc, neg_add_rev]
rw [this]
_ = ‖u - v‖ ^ 2 - 2 * θ * inner (u - v) (w - v) + θ * θ * ‖w - v‖ ^ 2 :=
by
rw [@norm_sub_sq ℝ, inner_smul_right, norm_smul]
simp only [sq]
show
‖u - v‖ * ‖u - v‖ - 2 * (θ * inner (u - v) (w - v)) +
absR θ * ‖w - v‖ * (absR θ * ‖w - v‖) =
‖u - v‖ * ‖u - v‖ - 2 * θ * inner (u - v) (w - v) + θ * θ * (‖w - v‖ * ‖w - v‖)
rw [abs_of_pos hθ₁]; ring
have eq₁ :
‖u - v‖ ^ 2 - 2 * θ * inner (u - v) (w - v) + θ * θ * ‖w - v‖ ^ 2 =
‖u - v‖ ^ 2 + (θ * θ * ‖w - v‖ ^ 2 - 2 * θ * inner (u - v) (w - v)) :=
by abel
rw [eq₁, le_add_iff_nonneg_right] at this
have eq₂ :
θ * θ * ‖w - v‖ ^ 2 - 2 * θ * inner (u - v) (w - v) =
θ * (θ * ‖w - v‖ ^ 2 - 2 * inner (u - v) (w - v))
ring
rw [eq₂] at this
have := le_of_sub_nonneg (nonneg_of_mul_nonneg_right this hθ₁)
exact this
by_cases hq : q = 0
· rw [hq] at this
have : p ≤ 0
have := this (1 : ℝ) (by norm_num) (by norm_num)
linarith
exact this
· have q_pos : 0 < q
apply lt_of_le_of_ne
exact sq_nonneg _
intro h
exact hq h.symm
by_contra hp
rw [not_le] at hp
let θ := min (1 : ℝ) (p / q)
have eq₁ : θ * q ≤ p :=
calc
θ * q ≤ p / q * q := mul_le_mul_of_nonneg_right (min_le_right _ _) (sq_nonneg _)
_ = p := div_mul_cancel _ hq
have : 2 * p ≤ p :=
calc
2 * p ≤ θ * q := by
refine' this θ (lt_min (by norm_num) (div_pos hp q_pos)) (by norm_num)
_ ≤ p := eq₁
linarith)
(by
intro h
letI : Nonempty K := ⟨⟨v, hv⟩⟩
apply le_antisymm
· apply le_cinfᵢ
intro w
apply nonneg_le_nonneg_of_sq_le_sq (norm_nonneg _)
have := h w w.2
calc
‖u - v‖ * ‖u - v‖ ≤ ‖u - v‖ * ‖u - v‖ - 2 * inner (u - v) ((w : F) - v) := by linarith
_ ≤ ‖u - v‖ ^ 2 - 2 * inner (u - v) ((w : F) - v) + ‖(w : F) - v‖ ^ 2 :=
by
rw [sq]
refine' le_add_of_nonneg_right _
exact sq_nonneg _
_ = ‖u - v - (w - v)‖ ^ 2 := (@norm_sub_sq ℝ _ _ _ _ _ _).symm
_ = ‖u - w‖ * ‖u - w‖ := by
have : u - v - (w - v) = u - w
abel
rw [this, sq]
· show (⨅ w : K, ‖u - w‖) ≤ (fun w : K => ‖u - w‖) ⟨v, hv⟩
apply cinfᵢ_le
use 0
rintro y ⟨z, rfl⟩
exact norm_nonneg _)
#align norm_eq_infi_iff_real_inner_le_zero norm_eq_infᵢ_iff_real_inner_le_zero
variable (K : Submodule 𝕜 E)
/-- Existence of projections on complete subspaces.
Let `u` be a point in an inner product space, and let `K` be a nonempty complete subspace.
Then there exists a (unique) `v` in `K` that minimizes the distance `‖u - v‖` to `u`.
This point `v` is usually called the orthogonal projection of `u` onto `K`.
-/
theorem exists_norm_eq_infᵢ_of_complete_subspace (h : IsComplete (↑K : Set E)) :
∀ u : E, ∃ v ∈ K, ‖u - v‖ = ⨅ w : (K : Set E), ‖u - w‖ :=
by
letI : InnerProductSpace ℝ E := InnerProductSpace.isROrCToReal 𝕜 E
letI : Module ℝ E := RestrictScalars.module ℝ 𝕜 E
let K' : Submodule ℝ E := Submodule.restrictScalars ℝ K
exact exists_norm_eq_infᵢ_of_complete_convex ⟨0, K'.zero_mem⟩ h K'.convex
#align exists_norm_eq_infi_of_complete_subspace exists_norm_eq_infᵢ_of_complete_subspace
/-- Characterization of minimizers in the projection on a subspace, in the real case.
Let `u` be a point in a real inner product space, and let `K` be a nonempty subspace.
Then point `v` minimizes the distance `‖u - v‖` over points in `K` if and only if
for all `w ∈ K`, `⟪u - v, w⟫ = 0` (i.e., `u - v` is orthogonal to the subspace `K`).
This is superceded by `norm_eq_infi_iff_inner_eq_zero` that gives the same conclusion over
any `is_R_or_C` field.
-/
theorem norm_eq_infᵢ_iff_real_inner_eq_zero (K : Submodule ℝ F) {u : F} {v : F} (hv : v ∈ K) :
(‖u - v‖ = ⨅ w : (↑K : Set F), ‖u - w‖) ↔ ∀ w ∈ K, ⟪u - v, w⟫_ℝ = 0 :=
Iff.intro
(by
intro h
have h : ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0 :=
by
rwa [norm_eq_infᵢ_iff_real_inner_le_zero] at h
exacts[K.convex, hv]
intro w hw
have le : ⟪u - v, w⟫_ℝ ≤ 0
let w' := w + v
have : w' ∈ K := Submodule.add_mem _ hw hv
have h₁ := h w' this
have h₂ : w' - v = w
simp only [add_neg_cancel_right, sub_eq_add_neg]
rw [h₂] at h₁
exact h₁
have ge : ⟪u - v, w⟫_ℝ ≥ 0
let w'' := -w + v
have : w'' ∈ K := Submodule.add_mem _ (Submodule.neg_mem _ hw) hv
have h₁ := h w'' this
have h₂ : w'' - v = -w
simp only [neg_inj, add_neg_cancel_right, sub_eq_add_neg]
rw [h₂, inner_neg_right] at h₁
linarith
exact le_antisymm le GE.ge)
(by
intro h
have : ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0
intro w hw
let w' := w - v
have : w' ∈ K := Submodule.sub_mem _ hw hv
have h₁ := h w' this
exact le_of_eq h₁
rwa [norm_eq_infᵢ_iff_real_inner_le_zero]
exacts[Submodule.convex _, hv])
#align norm_eq_infi_iff_real_inner_eq_zero norm_eq_infᵢ_iff_real_inner_eq_zero
/-- Characterization of minimizers in the projection on a subspace.
Let `u` be a point in an inner product space, and let `K` be a nonempty subspace.
Then point `v` minimizes the distance `‖u - v‖` over points in `K` if and only if
for all `w ∈ K`, `⟪u - v, w⟫ = 0` (i.e., `u - v` is orthogonal to the subspace `K`)
-/
theorem norm_eq_infᵢ_iff_inner_eq_zero {u : E} {v : E} (hv : v ∈ K) :
(‖u - v‖ = ⨅ w : K, ‖u - w‖) ↔ ∀ w ∈ K, ⟪u - v, w⟫ = 0 :=
by
letI : InnerProductSpace ℝ E := InnerProductSpace.isROrCToReal 𝕜 E
letI : Module ℝ E := RestrictScalars.module ℝ 𝕜 E
let K' : Submodule ℝ E := K.restrict_scalars ℝ
constructor
· intro H
have A : ∀ w ∈ K, re ⟪u - v, w⟫ = 0 := (norm_eq_infᵢ_iff_real_inner_eq_zero K' hv).1 H
intro w hw
apply ext
· simp [A w hw]
· symm
calc
im (0 : 𝕜) = 0 := im.map_zero
_ = re ⟪u - v, -I • w⟫ := (A _ (K.smul_mem (-I) hw)).symm
_ = re (-I * ⟪u - v, w⟫) := by rw [inner_smul_right]
_ = im ⟪u - v, w⟫ := by simp
· intro H
have : ∀ w ∈ K', ⟪u - v, w⟫_ℝ = 0 := by
intro w hw
rw [real_inner_eq_re_inner, H w hw]
exact zero_re'
exact (norm_eq_infᵢ_iff_real_inner_eq_zero K' hv).2 this
#align norm_eq_infi_iff_inner_eq_zero norm_eq_infᵢ_iff_inner_eq_zero
section orthogonalProjection
variable [CompleteSpace K]
/-- The orthogonal projection onto a complete subspace, as an
unbundled function. This definition is only intended for use in
setting up the bundled version `orthogonal_projection` and should not
be used once that is defined. -/
def orthogonalProjectionFn (v : E) :=
(exists_norm_eq_infᵢ_of_complete_subspace K (completeSpace_coe_iff_isComplete.mp ‹_›) v).some
#align orthogonal_projection_fn orthogonalProjectionFn
variable {K}
/-- The unbundled orthogonal projection is in the given subspace.
This lemma is only intended for use in setting up the bundled version
and should not be used once that is defined. -/
theorem orthogonalProjectionFn_mem (v : E) : orthogonalProjectionFn K v ∈ K :=
(exists_norm_eq_infᵢ_of_complete_subspace K (completeSpace_coe_iff_isComplete.mp ‹_›)
v).choose_spec.some
#align orthogonal_projection_fn_mem orthogonalProjectionFn_mem
/-- The characterization of the unbundled orthogonal projection. This
lemma is only intended for use in setting up the bundled version
and should not be used once that is defined. -/
theorem orthogonalProjectionFn_inner_eq_zero (v : E) :
∀ w ∈ K, ⟪v - orthogonalProjectionFn K v, w⟫ = 0 :=
by
rw [← norm_eq_infᵢ_iff_inner_eq_zero K (orthogonalProjectionFn_mem v)]
exact
(exists_norm_eq_infᵢ_of_complete_subspace K (complete_space_coe_iff_is_complete.mp ‹_›)
v).choose_spec.choose_spec
#align orthogonal_projection_fn_inner_eq_zero orthogonalProjectionFn_inner_eq_zero
/-- The unbundled orthogonal projection is the unique point in `K`
with the orthogonality property. This lemma is only intended for use
in setting up the bundled version and should not be used once that is
defined. -/
theorem eq_orthogonalProjectionFn_of_mem_of_inner_eq_zero {u v : E} (hvm : v ∈ K)
(hvo : ∀ w ∈ K, ⟪u - v, w⟫ = 0) : orthogonalProjectionFn K u = v :=
by
rw [← sub_eq_zero, ← @inner_self_eq_zero 𝕜]
have hvs : orthogonalProjectionFn K u - v ∈ K :=
Submodule.sub_mem K (orthogonalProjectionFn_mem u) hvm
have huo : ⟪u - orthogonalProjectionFn K u, orthogonalProjectionFn K u - v⟫ = 0 :=
orthogonalProjectionFn_inner_eq_zero u _ hvs
have huv : ⟪u - v, orthogonalProjectionFn K u - v⟫ = 0 := hvo _ hvs
have houv : ⟪u - v - (u - orthogonalProjectionFn K u), orthogonalProjectionFn K u - v⟫ = 0 := by
rw [inner_sub_left, huo, huv, sub_zero]
rwa [sub_sub_sub_cancel_left] at houv
#align eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero eq_orthogonalProjectionFn_of_mem_of_inner_eq_zero
variable (K)
theorem orthogonalProjectionFn_norm_sq (v : E) :
‖v‖ * ‖v‖ =
‖v - orthogonalProjectionFn K v‖ * ‖v - orthogonalProjectionFn K v‖ +
‖orthogonalProjectionFn K v‖ * ‖orthogonalProjectionFn K v‖ :=
by
set p := orthogonalProjectionFn K v
have h' : ⟪v - p, p⟫ = 0 :=
orthogonalProjectionFn_inner_eq_zero _ _ (orthogonalProjectionFn_mem v)
convert norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero (v - p) p h' using 2 <;> simp
#align orthogonal_projection_fn_norm_sq orthogonalProjectionFn_norm_sq
/-- The orthogonal projection onto a complete subspace. -/
def orthogonalProjection : E →L[𝕜] K :=
LinearMap.mkContinuous
{ toFun := fun v => ⟨orthogonalProjectionFn K v, orthogonalProjectionFn_mem v⟩
map_add' := fun x y =>
by
have hm : orthogonalProjectionFn K x + orthogonalProjectionFn K y ∈ K :=
Submodule.add_mem K (orthogonalProjectionFn_mem x) (orthogonalProjectionFn_mem y)
have ho :
∀ w ∈ K, ⟪x + y - (orthogonalProjectionFn K x + orthogonalProjectionFn K y), w⟫ = 0 :=
by
intro w hw
rw [add_sub_add_comm, inner_add_left, orthogonalProjectionFn_inner_eq_zero _ w hw,
orthogonalProjectionFn_inner_eq_zero _ w hw, add_zero]
ext
simp [eq_orthogonalProjectionFn_of_mem_of_inner_eq_zero hm ho]
map_smul' := fun c x =>
by
have hm : c • orthogonalProjectionFn K x ∈ K :=
Submodule.smul_mem K _ (orthogonalProjectionFn_mem x)
have ho : ∀ w ∈ K, ⟪c • x - c • orthogonalProjectionFn K x, w⟫ = 0 :=
by
intro w hw
rw [← smul_sub, inner_smul_left, orthogonalProjectionFn_inner_eq_zero _ w hw,
MulZeroClass.mul_zero]
ext
simp [eq_orthogonalProjectionFn_of_mem_of_inner_eq_zero hm ho] }
1 fun x => by
simp only [one_mul, LinearMap.coe_mk]
refine' le_of_pow_le_pow 2 (norm_nonneg _) (by norm_num) _
change ‖orthogonalProjectionFn K x‖ ^ 2 ≤ ‖x‖ ^ 2
nlinarith [orthogonalProjectionFn_norm_sq K x]
#align orthogonal_projection orthogonalProjection
variable {K}
@[simp]
theorem orthogonalProjectionFn_eq (v : E) :
orthogonalProjectionFn K v = (orthogonalProjection K v : E) :=
rfl
#align orthogonal_projection_fn_eq orthogonalProjectionFn_eq
/-- The characterization of the orthogonal projection. -/
@[simp]
theorem orthogonalProjection_inner_eq_zero (v : E) :
∀ w ∈ K, ⟪v - orthogonalProjection K v, w⟫ = 0 :=
orthogonalProjectionFn_inner_eq_zero v
#align orthogonal_projection_inner_eq_zero orthogonalProjection_inner_eq_zero
/-- The difference of `v` from its orthogonal projection onto `K` is in `Kᗮ`. -/
@[simp]
theorem sub_orthogonalProjection_mem_orthogonal (v : E) : v - orthogonalProjection K v ∈ Kᗮ :=
by
intro w hw
rw [inner_eq_zero_symm]
exact orthogonalProjection_inner_eq_zero _ _ hw
#align sub_orthogonal_projection_mem_orthogonal sub_orthogonalProjection_mem_orthogonal
/-- The orthogonal projection is the unique point in `K` with the
orthogonality property. -/
theorem eq_orthogonalProjection_of_mem_of_inner_eq_zero {u v : E} (hvm : v ∈ K)
(hvo : ∀ w ∈ K, ⟪u - v, w⟫ = 0) : (orthogonalProjection K u : E) = v :=
eq_orthogonalProjectionFn_of_mem_of_inner_eq_zero hvm hvo
#align eq_orthogonal_projection_of_mem_of_inner_eq_zero eq_orthogonalProjection_of_mem_of_inner_eq_zero
/-- The orthogonal projection of `y` on `U` minimizes the distance `‖y - x‖` for `x ∈ U`. -/
theorem orthogonalProjection_minimal {U : Submodule 𝕜 E} [CompleteSpace U] (y : E) :
‖y - orthogonalProjection U y‖ = ⨅ x : U, ‖y - x‖ :=
by
rw [norm_eq_infᵢ_iff_inner_eq_zero _ (Submodule.coe_mem _)]
exact orthogonalProjection_inner_eq_zero _
#align orthogonal_projection_minimal orthogonalProjection_minimal
/-- The orthogonal projections onto equal subspaces are coerced back to the same point in `E`. -/
theorem eq_orthogonalProjection_of_eq_submodule {K' : Submodule 𝕜 E} [CompleteSpace K'] (h : K = K')
(u : E) : (orthogonalProjection K u : E) = (orthogonalProjection K' u : E) :=
by
change orthogonalProjectionFn K u = orthogonalProjectionFn K' u
congr
exact h
#align eq_orthogonal_projection_of_eq_submodule eq_orthogonalProjection_of_eq_submodule
/-- The orthogonal projection sends elements of `K` to themselves. -/
@[simp]
theorem orthogonalProjection_mem_subspace_eq_self (v : K) : orthogonalProjection K v = v :=
by
ext
apply eq_orthogonalProjection_of_mem_of_inner_eq_zero <;> simp
#align orthogonal_projection_mem_subspace_eq_self orthogonalProjection_mem_subspace_eq_self
/-- A point equals its orthogonal projection if and only if it lies in the subspace. -/
theorem orthogonalProjection_eq_self_iff {v : E} : (orthogonalProjection K v : E) = v ↔ v ∈ K :=
by
refine' ⟨fun h => _, fun h => eq_orthogonalProjection_of_mem_of_inner_eq_zero h _⟩
· rw [← h]
simp
· simp
#align orthogonal_projection_eq_self_iff orthogonalProjection_eq_self_iff
theorem LinearIsometry.map_orthogonalProjection {E E' : Type _} [NormedAddCommGroup E]
[NormedAddCommGroup E'] [InnerProductSpace 𝕜 E] [InnerProductSpace 𝕜 E'] (f : E →ₗᵢ[𝕜] E')
(p : Submodule 𝕜 E) [CompleteSpace p] (x : E) :
f (orthogonalProjection p x) = orthogonalProjection (p.map f.toLinearMap) (f x) :=
by
refine' (eq_orthogonalProjection_of_mem_of_inner_eq_zero _ fun y hy => _).symm
refine' Submodule.apply_coe_mem_map _ _
rcases hy with ⟨x', hx', rfl : f x' = y⟩
rw [← f.map_sub, f.inner_map_map, orthogonalProjection_inner_eq_zero x x' hx']
#align linear_isometry.map_orthogonal_projection LinearIsometry.map_orthogonalProjection
theorem LinearIsometry.map_orthogonal_projection' {E E' : Type _} [NormedAddCommGroup E]
[NormedAddCommGroup E'] [InnerProductSpace 𝕜 E] [InnerProductSpace 𝕜 E'] (f : E →ₗᵢ[𝕜] E')
(p : Submodule 𝕜 E) [CompleteSpace p] (x : E) :
f (orthogonalProjection p x) = orthogonalProjection (p.map f) (f x) :=
by
refine' (eq_orthogonalProjection_of_mem_of_inner_eq_zero _ fun y hy => _).symm
refine' Submodule.apply_coe_mem_map _ _
rcases hy with ⟨x', hx', rfl : f x' = y⟩
rw [← f.map_sub, f.inner_map_map, orthogonalProjection_inner_eq_zero x x' hx']
#align linear_isometry.map_orthogonal_projection' LinearIsometry.map_orthogonal_projection'
/-- Orthogonal projection onto the `submodule.map` of a subspace. -/
theorem orthogonalProjection_map_apply {E E' : Type _} [NormedAddCommGroup E]
[NormedAddCommGroup E'] [InnerProductSpace 𝕜 E] [InnerProductSpace 𝕜 E'] (f : E ≃ₗᵢ[𝕜] E')
(p : Submodule 𝕜 E) [CompleteSpace p] (x : E') :
(orthogonalProjection (p.map (f.toLinearEquiv : E →ₗ[𝕜] E')) x : E') =
f (orthogonalProjection p (f.symm x)) :=
by
simpa only [f.coe_to_linear_isometry, f.apply_symm_apply] using
(f.to_linear_isometry.map_orthogonal_projection p (f.symm x)).symm
#align orthogonal_projection_map_apply orthogonalProjection_map_apply
/-- The orthogonal projection onto the trivial submodule is the zero map. -/
@[simp]
theorem orthogonalProjection_bot : orthogonalProjection (⊥ : Submodule 𝕜 E) = 0 := by ext
#align orthogonal_projection_bot orthogonalProjection_bot
variable (K)
/-- The orthogonal projection has norm `≤ 1`. -/
theorem orthogonalProjection_norm_le : ‖orthogonalProjection K‖ ≤ 1 :=
LinearMap.mkContinuous_norm_le _ (by norm_num) _
#align orthogonal_projection_norm_le orthogonalProjection_norm_le
variable (𝕜)
theorem smul_orthogonalProjection_singleton {v : E} (w : E) :
(‖v‖ ^ 2 : 𝕜) • (orthogonalProjection (𝕜 ∙ v) w : E) = ⟪v, w⟫ • v :=
by
suffices ↑(orthogonalProjection (𝕜 ∙ v) ((‖v‖ ^ 2 : 𝕜) • w)) = ⟪v, w⟫ • v by simpa using this
apply eq_orthogonalProjection_of_mem_of_inner_eq_zero
· rw [Submodule.mem_span_singleton]
use ⟪v, w⟫
· intro x hx
obtain ⟨c, rfl⟩ := submodule.mem_span_singleton.mp hx
have hv : ↑‖v‖ ^ 2 = ⟪v, v⟫ := by
norm_cast
simp [@norm_sq_eq_inner 𝕜]
simp [inner_sub_left, inner_smul_left, inner_smul_right, map_div₀, mul_comm, hv,
InnerProductSpace.conj_symm, hv]
#align smul_orthogonal_projection_singleton smul_orthogonalProjection_singleton
/-- Formula for orthogonal projection onto a single vector. -/
theorem orthogonalProjection_singleton {v : E} (w : E) :
(orthogonalProjection (𝕜 ∙ v) w : E) = (⟪v, w⟫ / ‖v‖ ^ 2) • v :=
by
by_cases hv : v = 0
· rw [hv, eq_orthogonalProjection_of_eq_submodule (Submodule.span_zero_singleton 𝕜)]
· simp
· infer_instance
have hv' : ‖v‖ ≠ 0 := ne_of_gt (norm_pos_iff.mpr hv)
have key :
((‖v‖ ^ 2 : 𝕜)⁻¹ * ‖v‖ ^ 2) • ↑(orthogonalProjection (𝕜 ∙ v) w) =
((‖v‖ ^ 2 : 𝕜)⁻¹ * ⟪v, w⟫) • v :=
by simp [mul_smul, smul_orthogonalProjection_singleton 𝕜 w]
convert key <;> field_simp [hv']
#align orthogonal_projection_singleton orthogonalProjection_singleton
/-- Formula for orthogonal projection onto a single unit vector. -/
theorem orthogonalProjection_unit_singleton {v : E} (hv : ‖v‖ = 1) (w : E) :
(orthogonalProjection (𝕜 ∙ v) w : E) = ⟪v, w⟫ • v :=
by
rw [← smul_orthogonalProjection_singleton 𝕜 w]
simp [hv]
#align orthogonal_projection_unit_singleton orthogonalProjection_unit_singleton
end orthogonalProjection
section reflection
variable {𝕜} (K) [CompleteSpace K]
/-- Auxiliary definition for `reflection`: the reflection as a linear equivalence. -/
def reflectionLinearEquiv : E ≃ₗ[𝕜] E :=
LinearEquiv.ofInvolutive
(bit0 (K.Subtype.comp (orthogonalProjection K).toLinearMap) - LinearMap.id) fun x => by
simp [bit0]
#align reflection_linear_equiv reflectionLinearEquiv
/-- Reflection in a complete subspace of an inner product space. The word "reflection" is
sometimes understood to mean specifically reflection in a codimension-one subspace, and sometimes
more generally to cover operations such as reflection in a point. The definition here, of
reflection in a subspace, is a more general sense of the word that includes both those common
cases. -/
def reflection : E ≃ₗᵢ[𝕜] E :=
{ reflectionLinearEquiv K with
norm_map' := by
intro x
let w : K := orthogonalProjection K x
let v := x - w
have : ⟪v, w⟫ = 0 := orthogonalProjection_inner_eq_zero x w w.2
convert norm_sub_eq_norm_add this using 2
· rw [LinearEquiv.coe_mk, reflectionLinearEquiv, LinearEquiv.toFun_eq_coe,
LinearEquiv.coe_ofInvolutive, LinearMap.sub_apply, LinearMap.id_apply, bit0,
LinearMap.add_apply, LinearMap.comp_apply, Submodule.subtype_apply,
ContinuousLinearMap.toLinearMap_eq_coe, ContinuousLinearMap.coe_coe]
dsimp [w, v]
abel
· simp only [add_sub_cancel'_right, eq_self_iff_true] }
#align reflection reflection
variable {K}
/-- The result of reflecting. -/
theorem reflection_apply (p : E) : reflection K p = bit0 ↑(orthogonalProjection K p) - p :=
rfl
#align reflection_apply reflection_apply
/-- Reflection is its own inverse. -/
@[simp]
theorem reflection_symm : (reflection K).symm = reflection K :=
rfl
#align reflection_symm reflection_symm
/-- Reflection is its own inverse. -/
@[simp]
theorem reflection_inv : (reflection K)⁻¹ = reflection K :=
rfl
#align reflection_inv reflection_inv
variable (K)
/-- Reflecting twice in the same subspace. -/
@[simp]
theorem reflection_reflection (p : E) : reflection K (reflection K p) = p :=
(reflection K).left_inv p
#align reflection_reflection reflection_reflection
/-- Reflection is involutive. -/
theorem reflection_involutive : Function.Involutive (reflection K) :=
reflection_reflection K
#align reflection_involutive reflection_involutive
/-- Reflection is involutive. -/
@[simp]
theorem reflection_trans_reflection :
(reflection K).trans (reflection K) = LinearIsometryEquiv.refl 𝕜 E :=
LinearIsometryEquiv.ext <| reflection_involutive K
#align reflection_trans_reflection reflection_trans_reflection
/-- Reflection is involutive. -/
@[simp]
theorem reflection_mul_reflection : reflection K * reflection K = 1 :=
reflection_trans_reflection _
#align reflection_mul_reflection reflection_mul_reflection
variable {K}
/-- A point is its own reflection if and only if it is in the subspace. -/
theorem reflection_eq_self_iff (x : E) : reflection K x = x ↔ x ∈ K :=
by
rw [← orthogonalProjection_eq_self_iff, reflection_apply, sub_eq_iff_eq_add', ← two_smul 𝕜, ←
two_smul' 𝕜]
refine' (smul_right_injective E _).eq_iff
exact two_ne_zero
#align reflection_eq_self_iff reflection_eq_self_iff
theorem reflection_mem_subspace_eq_self {x : E} (hx : x ∈ K) : reflection K x = x :=
(reflection_eq_self_iff x).mpr hx
#align reflection_mem_subspace_eq_self reflection_mem_subspace_eq_self
/-- Reflection in the `submodule.map` of a subspace. -/
theorem reflection_map_apply {E E' : Type _} [NormedAddCommGroup E] [NormedAddCommGroup E']
[InnerProductSpace 𝕜 E] [InnerProductSpace 𝕜 E'] (f : E ≃ₗᵢ[𝕜] E') (K : Submodule 𝕜 E)
[CompleteSpace K] (x : E') :
reflection (K.map (f.toLinearEquiv : E →ₗ[𝕜] E')) x = f (reflection K (f.symm x)) := by
simp [bit0, reflection_apply, orthogonalProjection_map_apply f K x]
#align reflection_map_apply reflection_map_apply
/-- Reflection in the `submodule.map` of a subspace. -/
theorem reflection_map {E E' : Type _} [NormedAddCommGroup E] [NormedAddCommGroup E']
[InnerProductSpace 𝕜 E] [InnerProductSpace 𝕜 E'] (f : E ≃ₗᵢ[𝕜] E') (K : Submodule 𝕜 E)
[CompleteSpace K] :
reflection (K.map (f.toLinearEquiv : E →ₗ[𝕜] E')) = f.symm.trans ((reflection K).trans f) :=
LinearIsometryEquiv.ext <| reflection_map_apply f K
#align reflection_map reflection_map
/-- Reflection through the trivial subspace {0} is just negation. -/
@[simp]
theorem reflection_bot : reflection (⊥ : Submodule 𝕜 E) = LinearIsometryEquiv.neg 𝕜 := by
ext <;> simp [reflection_apply]
#align reflection_bot reflection_bot
end reflection
section Orthogonal
/-- If `K₁` is complete and contained in `K₂`, `K₁` and `K₁ᗮ ⊓ K₂` span `K₂`. -/
theorem Submodule.sup_orthogonal_inf_of_completeSpace {K₁ K₂ : Submodule 𝕜 E} (h : K₁ ≤ K₂)
[CompleteSpace K₁] : K₁ ⊔ K₁ᗮ ⊓ K₂ = K₂ := by
ext x
rw [Submodule.mem_sup]
let v : K₁ := orthogonalProjection K₁ x
have hvm : x - v ∈ K₁ᗮ := sub_orthogonalProjection_mem_orthogonal x
constructor
· rintro ⟨y, hy, z, hz, rfl⟩
exact K₂.add_mem (h hy) hz.2
· exact fun hx => ⟨v, v.prop, x - v, ⟨hvm, K₂.sub_mem hx (h v.prop)⟩, add_sub_cancel'_right _ _⟩
#align submodule.sup_orthogonal_inf_of_complete_space Submodule.sup_orthogonal_inf_of_completeSpace
variable {K}
/-- If `K` is complete, `K` and `Kᗮ` span the whole space. -/
theorem Submodule.sup_orthogonal_of_completeSpace [CompleteSpace K] : K ⊔ Kᗮ = ⊤ :=
by
convert Submodule.sup_orthogonal_inf_of_completeSpace (le_top : K ≤ ⊤)
simp
#align submodule.sup_orthogonal_of_complete_space Submodule.sup_orthogonal_of_completeSpace
variable (K)
/-- If `K` is complete, any `v` in `E` can be expressed as a sum of elements of `K` and `Kᗮ`. -/
theorem Submodule.exists_sum_mem_mem_orthogonal [CompleteSpace K] (v : E) :
∃ y ∈ K, ∃ z ∈ Kᗮ, v = y + z :=
by
have h_mem : v ∈ K ⊔ Kᗮ := by simp [Submodule.sup_orthogonal_of_completeSpace]
obtain ⟨y, hy, z, hz, hyz⟩ := submodule.mem_sup.mp h_mem
exact ⟨y, hy, z, hz, hyz.symm⟩
#align submodule.exists_sum_mem_mem_orthogonal Submodule.exists_sum_mem_mem_orthogonal
/-- If `K` is complete, then the orthogonal complement of its orthogonal complement is itself. -/
@[simp]
theorem Submodule.orthogonal_orthogonal [CompleteSpace K] : Kᗮᗮ = K :=
by
ext v
constructor
· obtain ⟨y, hy, z, hz, rfl⟩ := K.exists_sum_mem_mem_orthogonal v
intro hv
have hz' : z = 0 :=
by
have hyz : ⟪z, y⟫ = 0 := by simp [hz y hy, inner_eq_zero_symm]
simpa [inner_add_right, hyz] using hv z hz
simp [hy, hz']
· intro hv w hw
rw [inner_eq_zero_symm]
exact hw v hv
#align submodule.orthogonal_orthogonal Submodule.orthogonal_orthogonal
theorem Submodule.orthogonal_orthogonal_eq_closure [CompleteSpace E] : Kᗮᗮ = K.topologicalClosure :=
by
refine' le_antisymm _ _
· convert Submodule.orthogonal_orthogonal_monotone K.le_topological_closure
haveI : CompleteSpace K.topological_closure :=
K.is_closed_topological_closure.complete_space_coe
rw [K.topological_closure.orthogonal_orthogonal]
· exact K.topological_closure_minimal K.le_orthogonal_orthogonal Kᗮ.isClosed_orthogonal
#align submodule.orthogonal_orthogonal_eq_closure Submodule.orthogonal_orthogonal_eq_closure
variable {K}
/-- If `K` is complete, `K` and `Kᗮ` are complements of each other. -/
theorem Submodule.isCompl_orthogonal_of_completeSpace [CompleteSpace K] : IsCompl K Kᗮ :=
⟨K.orthogonal_disjoint, codisjoint_iff.2 Submodule.sup_orthogonal_of_completeSpace⟩
#align submodule.is_compl_orthogonal_of_complete_space Submodule.isCompl_orthogonal_of_completeSpace
@[simp]
theorem Submodule.orthogonal_eq_bot_iff [CompleteSpace (K : Set E)] : Kᗮ = ⊥ ↔ K = ⊤ :=
by
refine' ⟨_, fun h => by rw [h, Submodule.top_orthogonal_eq_bot]⟩
intro h
have : K ⊔ Kᗮ = ⊤ := Submodule.sup_orthogonal_of_completeSpace
rwa [h, sup_comm, bot_sup_eq] at this
#align submodule.orthogonal_eq_bot_iff Submodule.orthogonal_eq_bot_iff
/-- A point in `K` with the orthogonality property (here characterized in terms of `Kᗮ`) must be the
orthogonal projection. -/
theorem eq_orthogonalProjection_of_mem_orthogonal [CompleteSpace K] {u v : E} (hv : v ∈ K)
(hvo : u - v ∈ Kᗮ) : (orthogonalProjection K u : E) = v :=
eq_orthogonalProjectionFn_of_mem_of_inner_eq_zero hv fun w => inner_eq_zero_symm.mp ∘ hvo w
#align eq_orthogonal_projection_of_mem_orthogonal eq_orthogonalProjection_of_mem_orthogonal
/-- A point in `K` with the orthogonality property (here characterized in terms of `Kᗮ`) must be the
orthogonal projection. -/
theorem eq_orthogonalProjection_of_mem_orthogonal' [CompleteSpace K] {u v z : E} (hv : v ∈ K)
(hz : z ∈ Kᗮ) (hu : u = v + z) : (orthogonalProjection K u : E) = v :=
eq_orthogonalProjection_of_mem_orthogonal hv (by simpa [hu] )
#align eq_orthogonal_projection_of_mem_orthogonal' eq_orthogonalProjection_of_mem_orthogonal'
/-- The orthogonal projection onto `K` of an element of `Kᗮ` is zero. -/
theorem orthogonalProjection_mem_subspace_orthogonal_complement_eq_zero [CompleteSpace K] {v : E}
(hv : v ∈ Kᗮ) : orthogonalProjection K v = 0 :=
by
ext
convert eq_orthogonalProjection_of_mem_orthogonal _ _ <;> simp [hv]
#align orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero orthogonalProjection_mem_subspace_orthogonal_complement_eq_zero
theorem orthogonalProjection_eq_linear_proj [CompleteSpace K] (x : E) :
orthogonalProjection K x =
K.linearProjOfIsCompl _ Submodule.isCompl_orthogonal_of_completeSpace x :=
by
have : IsCompl K Kᗮ := Submodule.isCompl_orthogonal_of_completeSpace
nth_rw 1 [← Submodule.linear_proj_add_linearProjOfIsCompl_eq_self this x]
rw [map_add, orthogonalProjection_mem_subspace_eq_self,
orthogonalProjection_mem_subspace_orthogonal_complement_eq_zero (Submodule.coe_mem _), add_zero]
#align orthogonal_projection_eq_linear_proj orthogonalProjection_eq_linear_proj
theorem orthogonalProjection_coe_linearMap_eq_linear_proj [CompleteSpace K] :
(orthogonalProjection K : E →ₗ[𝕜] K) =
K.linearProjOfIsCompl _ Submodule.isCompl_orthogonal_of_completeSpace :=
LinearMap.ext <| orthogonalProjection_eq_linear_proj
#align orthogonal_projection_coe_linear_map_eq_linear_proj orthogonalProjection_coe_linearMap_eq_linear_proj
/-- The reflection in `K` of an element of `Kᗮ` is its negation. -/
theorem reflection_mem_subspace_orthogonal_complement_eq_neg [CompleteSpace K] {v : E}
(hv : v ∈ Kᗮ) : reflection K v = -v := by
simp [reflection_apply, orthogonalProjection_mem_subspace_orthogonal_complement_eq_zero hv]
#align reflection_mem_subspace_orthogonal_complement_eq_neg reflection_mem_subspace_orthogonal_complement_eq_neg
/-- The orthogonal projection onto `Kᗮ` of an element of `K` is zero. -/
theorem orthogonalProjection_mem_subspace_orthogonal_precomplement_eq_zero [CompleteSpace E] {v : E}
(hv : v ∈ K) : orthogonalProjection Kᗮ v = 0 :=
orthogonalProjection_mem_subspace_orthogonal_complement_eq_zero (K.le_orthogonal_orthogonal hv)
#align orthogonal_projection_mem_subspace_orthogonal_precomplement_eq_zero orthogonalProjection_mem_subspace_orthogonal_precomplement_eq_zero
/-- If `U ≤ V`, then projecting on `V` and then on `U` is the same as projecting on `U`. -/
theorem orthogonalProjection_orthogonalProjection_of_le {U V : Submodule 𝕜 E} [CompleteSpace U]
[CompleteSpace V] (h : U ≤ V) (x : E) :
orthogonalProjection U (orthogonalProjection V x) = orthogonalProjection U x :=
Eq.symm <| by
simpa only [sub_eq_zero, map_sub] using
orthogonalProjection_mem_subspace_orthogonal_complement_eq_zero
(Submodule.orthogonal_le h (sub_orthogonalProjection_mem_orthogonal x))
#align orthogonal_projection_orthogonal_projection_of_le orthogonalProjection_orthogonalProjection_of_le
/-- Given a monotone family `U` of complete submodules of `E` and a fixed `x : E`,
the orthogonal projection of `x` on `U i` tends to the orthogonal projection of `x` on
`(⨆ i, U i).topological_closure` along `at_top`. -/
theorem orthogonalProjection_tendsto_closure_supᵢ [CompleteSpace E] {ι : Type _} [SemilatticeSup ι]
(U : ι → Submodule 𝕜 E) [∀ i, CompleteSpace (U i)] (hU : Monotone U) (x : E) :
Filter.Tendsto (fun i => (orthogonalProjection (U i) x : E)) atTop
(𝓝 (orthogonalProjection (⨆ i, U i).topologicalClosure x : E)) :=
by
cases isEmpty_or_nonempty ι
· rw [filter_eq_bot_of_is_empty (at_top : Filter ι)]
exact tendsto_bot
let y := (orthogonalProjection (⨆ i, U i).topologicalClosure x : E)
have proj_x : ∀ i, orthogonalProjection (U i) x = orthogonalProjection (U i) y := fun i =>
(orthogonalProjection_orthogonalProjection_of_le
((le_supᵢ U i).trans (supᵢ U).le_topologicalClosure) _).symm
suffices ∀ ε > 0, ∃ I, ∀ i ≥ I, ‖(orthogonalProjection (U i) y : E) - y‖ < ε by
simpa only [proj_x, NormedAddCommGroup.tendsto_atTop] using this
intro ε hε
obtain ⟨a, ha, hay⟩ : ∃ a ∈ ⨆ i, U i, dist y a < ε :=
by
have y_mem : y ∈ (⨆ i, U i).topologicalClosure := Submodule.coe_mem _
rw [← SetLike.mem_coe, Submodule.topologicalClosure_coe, Metric.mem_closure_iff] at y_mem
exact y_mem ε hε
rw [dist_eq_norm] at hay
obtain ⟨I, hI⟩ : ∃ I, a ∈ U I := by rwa [Submodule.mem_supᵢ_of_directed _ hU.directed_le] at ha
refine' ⟨I, fun i (hi : I ≤ i) => _⟩
rw [norm_sub_rev, orthogonalProjection_minimal]
refine' lt_of_le_of_lt _ hay
change _ ≤ ‖y - (⟨a, hU hi hI⟩ : U i)‖
exact cinfᵢ_le ⟨0, set.forall_range_iff.mpr fun _ => norm_nonneg _⟩ _
#align orthogonal_projection_tendsto_closure_supr orthogonalProjection_tendsto_closure_supᵢ
/-- Given a monotone family `U` of complete submodules of `E` with dense span supremum,
and a fixed `x : E`, the orthogonal projection of `x` on `U i` tends to `x` along `at_top`. -/
theorem orthogonalProjection_tendsto_self [CompleteSpace E] {ι : Type _} [SemilatticeSup ι]
(U : ι → Submodule 𝕜 E) [∀ t, CompleteSpace (U t)] (hU : Monotone U) (x : E)
(hU' : ⊤ ≤ (⨆ t, U t).topologicalClosure) :
Filter.Tendsto (fun t => (orthogonalProjection (U t) x : E)) atTop (𝓝 x) :=
by
rw [← eq_top_iff] at hU'
convert orthogonalProjection_tendsto_closure_supᵢ U hU x
rw [orthogonal_projection_eq_self_iff.mpr _]
rw [hU']
trivial
#align orthogonal_projection_tendsto_self orthogonalProjection_tendsto_self
/-- The orthogonal complement satisfies `Kᗮᗮᗮ = Kᗮ`. -/
theorem Submodule.triorthogonal_eq_orthogonal [CompleteSpace E] : Kᗮᗮᗮ = Kᗮ :=
by
rw [Kᗮ.orthogonal_orthogonal_eq_closure]
exact K.is_closed_orthogonal.submodule_topological_closure_eq
#align submodule.triorthogonal_eq_orthogonal Submodule.triorthogonal_eq_orthogonal
/-- The closure of `K` is the full space iff `Kᗮ` is trivial. -/
theorem Submodule.topologicalClosure_eq_top_iff [CompleteSpace E] :
K.topologicalClosure = ⊤ ↔ Kᗮ = ⊥ :=
by
rw [← Submodule.orthogonal_orthogonal_eq_closure]
constructor <;> intro h
· rw [← Submodule.triorthogonal_eq_orthogonal, h, Submodule.top_orthogonal_eq_bot]
· rw [h, Submodule.bot_orthogonal_eq_top]
#align submodule.topological_closure_eq_top_iff Submodule.topologicalClosure_eq_top_iff
namespace Dense
open Submodule
variable {x y : E} [CompleteSpace E]
/-- If `S` is dense and `x - y ∈ Kᗮ`, then `x = y`. -/
theorem eq_of_sub_mem_orthogonal (hK : Dense (K : Set E)) (h : x - y ∈ Kᗮ) : x = y :=
by
rw [dense_iff_topological_closure_eq_top, topological_closure_eq_top_iff] at hK
rwa [hK, Submodule.mem_bot, sub_eq_zero] at h
#align dense.eq_of_sub_mem_orthogonal Dense.eq_of_sub_mem_orthogonal
theorem eq_zero_of_mem_orthogonal (hK : Dense (K : Set E)) (h : x ∈ Kᗮ) : x = 0 :=
hK.eq_of_sub_mem_orthogonal (by rwa [sub_zero])
#align dense.eq_zero_of_mem_orthogonal Dense.eq_zero_of_mem_orthogonal
theorem eq_of_inner_left (hK : Dense (K : Set E)) (h : ∀ v : K, ⟪x, v⟫ = ⟪y, v⟫) : x = y :=
hK.eq_of_sub_mem_orthogonal (Submodule.sub_mem_orthogonal_of_inner_left h)
#align dense.eq_of_inner_left Dense.eq_of_inner_left
theorem eq_zero_of_inner_left (hK : Dense (K : Set E)) (h : ∀ v : K, ⟪x, v⟫ = 0) : x = 0 :=
hK.eq_of_inner_left fun v => by rw [inner_zero_left, h v]
#align dense.eq_zero_of_inner_left Dense.eq_zero_of_inner_left
theorem eq_of_inner_right (hK : Dense (K : Set E)) (h : ∀ v : K, ⟪(v : E), x⟫ = ⟪(v : E), y⟫) :
x = y :=
hK.eq_of_sub_mem_orthogonal (Submodule.sub_mem_orthogonal_of_inner_right h)
#align dense.eq_of_inner_right Dense.eq_of_inner_right
theorem eq_zero_of_inner_right (hK : Dense (K : Set E)) (h : ∀ v : K, ⟪(v : E), x⟫ = 0) : x = 0 :=
hK.eq_of_inner_right fun v => by rw [inner_zero_right, h v]
#align dense.eq_zero_of_inner_right Dense.eq_zero_of_inner_right
end Dense
/-- The reflection in `Kᗮ` of an element of `K` is its negation. -/
theorem reflection_mem_subspace_orthogonal_precomplement_eq_neg [CompleteSpace E] {v : E}
(hv : v ∈ K) : reflection Kᗮ v = -v :=
reflection_mem_subspace_orthogonal_complement_eq_neg (K.le_orthogonal_orthogonal hv)
#align reflection_mem_subspace_orthogonal_precomplement_eq_neg reflection_mem_subspace_orthogonal_precomplement_eq_neg
/-- The orthogonal projection onto `(𝕜 ∙ v)ᗮ` of `v` is zero. -/
theorem orthogonalProjection_orthogonal_complement_singleton_eq_zero [CompleteSpace E] (v : E) :
orthogonalProjection (𝕜 ∙ v)ᗮ v = 0 :=
orthogonalProjection_mem_subspace_orthogonal_precomplement_eq_zero
(Submodule.mem_span_singleton_self v)
#align orthogonal_projection_orthogonal_complement_singleton_eq_zero orthogonalProjection_orthogonal_complement_singleton_eq_zero
/-- The reflection in `(𝕜 ∙ v)ᗮ` of `v` is `-v`. -/
theorem reflection_orthogonal_complement_singleton_eq_neg [CompleteSpace E] (v : E) :
reflection (𝕜 ∙ v)ᗮ v = -v :=
reflection_mem_subspace_orthogonal_precomplement_eq_neg (Submodule.mem_span_singleton_self v)
#align reflection_orthogonal_complement_singleton_eq_neg reflection_orthogonal_complement_singleton_eq_neg
theorem reflection_sub [CompleteSpace F] {v w : F} (h : ‖v‖ = ‖w‖) :
reflection (ℝ ∙ v - w)ᗮ v = w :=
by
set R : F ≃ₗᵢ[ℝ] F := reflection (ℝ ∙ v - w)ᗮ
suffices R v + R v = w + w
by
apply smul_right_injective F (by norm_num : (2 : ℝ) ≠ 0)
simpa [two_smul] using this
have h₁ : R (v - w) = -(v - w) := reflection_orthogonal_complement_singleton_eq_neg (v - w)
have h₂ : R (v + w) = v + w :=
by
apply reflection_mem_subspace_eq_self
rw [Submodule.mem_orthogonal_singleton_iff_inner_left]
rw [real_inner_add_sub_eq_zero_iff]
exact h
convert congr_arg₂ (· + ·) h₂ h₁ using 1
· simp
· abel
#align reflection_sub reflection_sub
variable (K)
/-- In a complete space `E`, a vector splits as the sum of its orthogonal projections onto a
complete submodule `K` and onto the orthogonal complement of `K`.-/
theorem eq_sum_orthogonalProjection_self_orthogonal_complement [CompleteSpace E] [CompleteSpace K]
(w : E) : w = (orthogonalProjection K w : E) + (orthogonalProjection Kᗮ w : E) :=
by
obtain ⟨y, hy, z, hz, hwyz⟩ := K.exists_sum_mem_mem_orthogonal w
convert hwyz
· exact eq_orthogonalProjection_of_mem_orthogonal' hy hz hwyz
· rw [add_comm] at hwyz
refine' eq_orthogonalProjection_of_mem_orthogonal' hz _ hwyz
simp [hy]
#align eq_sum_orthogonal_projection_self_orthogonal_complement eq_sum_orthogonalProjection_self_orthogonal_complement
/-- The Pythagorean theorem, for an orthogonal projection.-/
theorem norm_sq_eq_add_norm_sq_projection (x : E) (S : Submodule 𝕜 E) [CompleteSpace E]
[CompleteSpace S] :
‖x‖ ^ 2 = ‖orthogonalProjection S x‖ ^ 2 + ‖orthogonalProjection Sᗮ x‖ ^ 2 :=
by
let p1 := orthogonalProjection S
let p2 := orthogonalProjection Sᗮ
have x_decomp : x = p1 x + p2 x := eq_sum_orthogonalProjection_self_orthogonal_complement S x
have x_orth : ⟪(p1 x : E), p2 x⟫ = 0 :=
Submodule.inner_right_of_mem_orthogonal (SetLike.coe_mem (p1 x)) (SetLike.coe_mem (p2 x))
nth_rw 1 [x_decomp]
simp only [sq, norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero (p1 x : E) (p2 x) x_orth,
add_left_inj, mul_eq_mul_left_iff, norm_eq_zero, true_or_iff, eq_self_iff_true,
Submodule.coe_norm, Submodule.coe_eq_zero]
#align norm_sq_eq_add_norm_sq_projection norm_sq_eq_add_norm_sq_projection
/-- In a complete space `E`, the projection maps onto a complete subspace `K` and its orthogonal
complement sum to the identity. -/
theorem id_eq_sum_orthogonalProjection_self_orthogonal_complement [CompleteSpace E]
[CompleteSpace K] :
ContinuousLinearMap.id 𝕜 E =
K.subtypeL.comp (orthogonalProjection K) + Kᗮ.subtypeL.comp (orthogonalProjection Kᗮ) :=
by
ext w
exact eq_sum_orthogonalProjection_self_orthogonal_complement K w
#align id_eq_sum_orthogonal_projection_self_orthogonal_complement id_eq_sum_orthogonalProjection_self_orthogonal_complement
@[simp]
theorem inner_orthogonalProjection_eq_of_mem_right [CompleteSpace K] (u : K) (v : E) :
⟪orthogonalProjection K v, u⟫ = ⟪v, u⟫ :=
calc
⟪orthogonalProjection K v, u⟫ = ⟪(orthogonalProjection K v : E), u⟫ := K.coe_inner _ _
_ = ⟪(orthogonalProjection K v : E), u⟫ + ⟪v - orthogonalProjection K v, u⟫ := by
rw [orthogonalProjection_inner_eq_zero _ _ (Submodule.coe_mem _), add_zero]
_ = ⟪v, u⟫ := by rw [← inner_add_left, add_sub_cancel'_right]
#align inner_orthogonal_projection_eq_of_mem_right inner_orthogonalProjection_eq_of_mem_right
@[simp]
theorem inner_orthogonalProjection_eq_of_mem_left [CompleteSpace K] (u : K) (v : E) :
⟪u, orthogonalProjection K v⟫ = ⟪(u : E), v⟫ := by
rw [← inner_conj_symm, ← inner_conj_symm (u : E), inner_orthogonalProjection_eq_of_mem_right]
#align inner_orthogonal_projection_eq_of_mem_left inner_orthogonalProjection_eq_of_mem_left
/-- The orthogonal projection is self-adjoint. -/
theorem inner_orthogonalProjection_left_eq_right [CompleteSpace K] (u v : E) :
⟪↑(orthogonalProjection K u), v⟫ = ⟪u, orthogonalProjection K v⟫ := by
rw [← inner_orthogonalProjection_eq_of_mem_left, inner_orthogonalProjection_eq_of_mem_right]
#align inner_orthogonal_projection_left_eq_right inner_orthogonalProjection_left_eq_right
/-- The orthogonal projection is symmetric. -/
theorem orthogonalProjection_isSymmetric [CompleteSpace K] :
(K.subtypeL ∘L orthogonalProjection K : E →ₗ[𝕜] E).IsSymmetric :=
inner_orthogonalProjection_left_eq_right K
#align orthogonal_projection_is_symmetric orthogonalProjection_isSymmetric
open FiniteDimensional
/-- Given a finite-dimensional subspace `K₂`, and a subspace `K₁`
containined in it, the dimensions of `K₁` and the intersection of its
orthogonal subspace with `K₂` add to that of `K₂`. -/
theorem Submodule.finrank_add_inf_finrank_orthogonal {K₁ K₂ : Submodule 𝕜 E}
[FiniteDimensional 𝕜 K₂] (h : K₁ ≤ K₂) :
finrank 𝕜 K₁ + finrank 𝕜 (K₁ᗮ ⊓ K₂ : Submodule 𝕜 E) = finrank 𝕜 K₂ :=
by
haveI := Submodule.finiteDimensional_of_le h
haveI := proper_is_R_or_C 𝕜 K₁
have hd := Submodule.dim_sup_add_dim_inf_eq K₁ (K₁ᗮ ⊓ K₂)
rw [← inf_assoc, (Submodule.orthogonal_disjoint K₁).eq_bot, bot_inf_eq, finrank_bot,
Submodule.sup_orthogonal_inf_of_completeSpace h] at hd
rw [add_zero] at hd
exact hd.symm
#align submodule.finrank_add_inf_finrank_orthogonal Submodule.finrank_add_inf_finrank_orthogonal
/-- Given a finite-dimensional subspace `K₂`, and a subspace `K₁`
containined in it, the dimensions of `K₁` and the intersection of its
orthogonal subspace with `K₂` add to that of `K₂`. -/
theorem Submodule.finrank_add_inf_finrank_orthogonal' {K₁ K₂ : Submodule 𝕜 E}
[FiniteDimensional 𝕜 K₂] (h : K₁ ≤ K₂) {n : ℕ} (h_dim : finrank 𝕜 K₁ + n = finrank 𝕜 K₂) :
finrank 𝕜 (K₁ᗮ ⊓ K₂ : Submodule 𝕜 E) = n :=
by
rw [← add_right_inj (finrank 𝕜 K₁)]
simp [Submodule.finrank_add_inf_finrank_orthogonal h, h_dim]
#align submodule.finrank_add_inf_finrank_orthogonal' Submodule.finrank_add_inf_finrank_orthogonal'
/-- Given a finite-dimensional space `E` and subspace `K`, the dimensions of `K` and `Kᗮ` add to
that of `E`. -/
theorem Submodule.finrank_add_finrank_orthogonal [FiniteDimensional 𝕜 E] (K : Submodule 𝕜 E) :
finrank 𝕜 K + finrank 𝕜 Kᗮ = finrank 𝕜 E :=
by
convert Submodule.finrank_add_inf_finrank_orthogonal (le_top : K ≤ ⊤) using 1
· rw [inf_top_eq]
· simp
#align submodule.finrank_add_finrank_orthogonal Submodule.finrank_add_finrank_orthogonal
/-- Given a finite-dimensional space `E` and subspace `K`, the dimensions of `K` and `Kᗮ` add to
that of `E`. -/
theorem Submodule.finrank_add_finrank_orthogonal' [FiniteDimensional 𝕜 E] {K : Submodule 𝕜 E}
{n : ℕ} (h_dim : finrank 𝕜 K + n = finrank 𝕜 E) : finrank 𝕜 Kᗮ = n :=
by
rw [← add_right_inj (finrank 𝕜 K)]
simp [Submodule.finrank_add_finrank_orthogonal, h_dim]
#align submodule.finrank_add_finrank_orthogonal' Submodule.finrank_add_finrank_orthogonal'
attribute [local instance] fact_finite_dimensional_of_finrank_eq_succ
/-- In a finite-dimensional inner product space, the dimension of the orthogonal complement of the
span of a nonzero vector is one less than the dimension of the space. -/
theorem finrank_orthogonal_span_singleton {n : ℕ} [_i : Fact (finrank 𝕜 E = n + 1)] {v : E}
(hv : v ≠ 0) : finrank 𝕜 (𝕜 ∙ v)ᗮ = n :=
Submodule.finrank_add_finrank_orthogonal' <| by
simp [finrank_span_singleton hv, _i.elim, add_comm]
#align finrank_orthogonal_span_singleton finrank_orthogonal_span_singleton
/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/
/-- An element `φ` of the orthogonal group of `F` can be factored as a product of reflections, and
specifically at most as many reflections as the dimension of the complement of the fixed subspace
of `φ`. -/
theorem LinearIsometryEquiv.reflections_generate_dim_aux [FiniteDimensional ℝ F] {n : ℕ}
(φ : F ≃ₗᵢ[ℝ] F) (hn : finrank ℝ (ker (ContinuousLinearMap.id ℝ F - φ))ᗮ ≤ n) :
∃ l : List F, l.length ≤ n ∧ φ = (l.map fun v => reflection (ℝ ∙ v)ᗮ).Prod :=
by
-- We prove this by strong induction on `n`, the dimension of the orthogonal complement of the
-- fixed subspace of the endomorphism `φ`
induction' n with n IH generalizing φ
· -- Base case: `n = 0`, the fixed subspace is the whole space, so `φ = id`
refine' ⟨[], rfl.le, show φ = 1 from _⟩
have : ker (ContinuousLinearMap.id ℝ F - φ) = ⊤ := by
rwa [le_zero_iff, finrank_eq_zero, Submodule.orthogonal_eq_bot_iff] at hn
symm
ext x
have := LinearMap.congr_fun (linear_map.ker_eq_top.mp this) x
simpa only [sub_eq_zero, ContinuousLinearMap.toLinearMap_eq_coe, ContinuousLinearMap.coe_sub,
LinearMap.sub_apply, LinearMap.zero_apply] using this
· -- Inductive step. Let `W` be the fixed subspace of `φ`. We suppose its complement to have
-- dimension at most n + 1.
let W := ker (ContinuousLinearMap.id ℝ F - φ)
have hW : ∀ w ∈ W, φ w = w := fun w hw => (sub_eq_zero.mp hw).symm
by_cases hn' : finrank ℝ Wᗮ ≤ n
· obtain ⟨V, hV₁, hV₂⟩ := IH φ hn'
exact ⟨V, hV₁.trans n.le_succ, hV₂⟩
-- Take a nonzero element `v` of the orthogonal complement of `W`.
haveI : Nontrivial Wᗮ := nontrivial_of_finrank_pos (by linarith [zero_le n] : 0 < finrank ℝ Wᗮ)
obtain ⟨v, hv⟩ := exists_ne (0 : Wᗮ)
have hφv : φ v ∈ Wᗮ := by
intro w hw
rw [← hW w hw, LinearIsometryEquiv.inner_map_map]
exact v.prop w hw
have hv' : (v : F) ∉ W := by
intro h
exact hv ((Submodule.mem_left_iff_eq_zero_of_disjoint W.orthogonal_disjoint).mp h)
-- Let `ρ` be the reflection in `v - φ v`; this is designed to swap `v` and `φ v`
let x : F := v - φ v
let ρ := reflection (ℝ ∙ x)ᗮ
-- Notation: Let `V` be the fixed subspace of `φ.trans ρ`
let V := ker (ContinuousLinearMap.id ℝ F - φ.trans ρ)
have hV : ∀ w, ρ (φ w) = w → w ∈ V := by
intro w hw
change w - ρ (φ w) = 0
rw [sub_eq_zero, hw]
-- Everything fixed by `φ` is fixed by `φ.trans ρ`
have H₂V : W ≤ V := by
intro w hw
apply hV
rw [hW w hw]
refine' reflection_mem_subspace_eq_self _
rw [Submodule.mem_orthogonal_singleton_iff_inner_left]
exact Submodule.sub_mem _ v.prop hφv _ hw
-- `v` is also fixed by `φ.trans ρ`
have H₁V : (v : F) ∈ V := by
apply hV
have : ρ v = φ v := reflection_sub (φ.norm_map v).symm
rw [← this]
exact reflection_reflection _ _
-- By dimension-counting, the complement of the fixed subspace of `φ.trans ρ` has dimension at
-- most `n`
have : finrank ℝ Vᗮ ≤ n := by
change finrank ℝ Wᗮ ≤ n + 1 at hn
have : finrank ℝ W + 1 ≤ finrank ℝ V :=
Submodule.finrank_lt_finrank_of_lt (SetLike.lt_iff_le_and_exists.2 ⟨H₂V, v, H₁V, hv'⟩)
have : finrank ℝ V + finrank ℝ Vᗮ = finrank ℝ F := V.finrank_add_finrank_orthogonal
have : finrank ℝ W + finrank ℝ Wᗮ = finrank ℝ F := W.finrank_add_finrank_orthogonal
linarith
-- So apply the inductive hypothesis to `φ.trans ρ`
obtain ⟨l, hl, hφl⟩ := IH (ρ * φ) this
-- Prepend `ρ` to the factorization into reflections obtained for `φ.trans ρ`; this gives a
-- factorization into reflections for `φ`.
refine' ⟨x::l, Nat.succ_le_succ hl, _⟩
rw [List.map_cons, List.prod_cons]
have := congr_arg ((· * ·) ρ) hφl
rwa [← mul_assoc, reflection_mul_reflection, one_mul] at this
#align linear_isometry_equiv.reflections_generate_dim_aux LinearIsometryEquiv.reflections_generate_dim_aux
/-- The orthogonal group of `F` is generated by reflections; specifically each element `φ` of the
orthogonal group is a product of at most as many reflections as the dimension of `F`.
Special case of the **Cartan–Dieudonné theorem**. -/
theorem LinearIsometryEquiv.reflections_generate_dim [FiniteDimensional ℝ F] (φ : F ≃ₗᵢ[ℝ] F) :
∃ l : List F, l.length ≤ finrank ℝ F ∧ φ = (l.map fun v => reflection (ℝ ∙ v)ᗮ).Prod :=
let ⟨l, hl₁, hl₂⟩ := φ.reflections_generate_dim_aux le_rfl
⟨l, hl₁.trans (Submodule.finrank_le _), hl₂⟩
#align linear_isometry_equiv.reflections_generate_dim LinearIsometryEquiv.reflections_generate_dim
/-- The orthogonal group of `F` is generated by reflections. -/
theorem LinearIsometryEquiv.reflections_generate [FiniteDimensional ℝ F] :
Subgroup.closure (Set.range fun v : F => reflection (ℝ ∙ v)ᗮ) = ⊤ :=
by
rw [Subgroup.eq_top_iff']
intro φ
rcases φ.reflections_generate_dim with ⟨l, _, rfl⟩
apply (Subgroup.closure _).list_prod_mem
intro x hx
rcases list.mem_map.mp hx with ⟨a, _, hax⟩
exact Subgroup.subset_closure ⟨a, hax⟩
#align linear_isometry_equiv.reflections_generate LinearIsometryEquiv.reflections_generate
end Orthogonal
section OrthogonalFamily
variable {ι : Type _}
/-- An orthogonal family of subspaces of `E` satisfies `direct_sum.is_internal` (that is,
they provide an internal direct sum decomposition of `E`) if and only if their span has trivial
orthogonal complement. -/
theorem OrthogonalFamily.isInternal_iff_of_isComplete [DecidableEq ι] {V : ι → Submodule 𝕜 E}
(hV : OrthogonalFamily 𝕜 (fun i => V i) fun i => (V i).subtypeₗᵢ)
(hc : IsComplete (↑(supᵢ V) : Set E)) : DirectSum.IsInternal V ↔ (supᵢ V)ᗮ = ⊥ :=
by
haveI : CompleteSpace ↥(supᵢ V) := hc.complete_space_coe
simp only [DirectSum.isInternal_submodule_iff_independent_and_supᵢ_eq_top, hV.independent,
true_and_iff, Submodule.orthogonal_eq_bot_iff]
#align orthogonal_family.is_internal_iff_of_is_complete OrthogonalFamily.isInternal_iff_of_isComplete
/-- An orthogonal family of subspaces of `E` satisfies `direct_sum.is_internal` (that is,
they provide an internal direct sum decomposition of `E`) if and only if their span has trivial
orthogonal complement. -/
theorem OrthogonalFamily.isInternal_iff [DecidableEq ι] [FiniteDimensional 𝕜 E]
{V : ι → Submodule 𝕜 E} (hV : OrthogonalFamily 𝕜 (fun i => V i) fun i => (V i).subtypeₗᵢ) :
DirectSum.IsInternal V ↔ (supᵢ V)ᗮ = ⊥ :=
haveI h := FiniteDimensional.proper_isROrC 𝕜 ↥(supᵢ V)
hV.is_internal_iff_of_is_complete (complete_space_coe_iff_is_complete.mp inferInstance)
#align orthogonal_family.is_internal_iff OrthogonalFamily.isInternal_iff
end OrthogonalFamily
section OrthonormalBasis
variable {𝕜 E} {v : Set E}
open FiniteDimensional Submodule Set
/- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (u «expr ⊇ » v) -/
/-- An orthonormal set in an `inner_product_space` is maximal, if and only if the orthogonal
complement of its span is empty. -/
theorem maximal_orthonormal_iff_orthogonal_complement_eq_bot (hv : Orthonormal 𝕜 (coe : v → E)) :
(∀ (u) (_ : u ⊇ v), Orthonormal 𝕜 (coe : u → E) → u = v) ↔ (span 𝕜 v)ᗮ = ⊥ :=
by
rw [Submodule.eq_bot_iff]
constructor
· contrapose!
-- ** direction 1: nonempty orthogonal complement implies nonmaximal
rintro ⟨x, hx', hx⟩
-- take a nonzero vector and normalize it
let e := (‖x‖⁻¹ : 𝕜) • x
have he : ‖e‖ = 1 := by simp [e, norm_smul_inv_norm hx]
have he' : e ∈ (span 𝕜 v)ᗮ := smul_mem' _ _ hx'
have he'' : e ∉ v := by
intro hev
have : e = 0 := by
have : e ∈ span 𝕜 v ⊓ (span 𝕜 v)ᗮ := ⟨subset_span hev, he'⟩
simpa [(span 𝕜 v).inf_orthogonal_eq_bot] using this
have : e ≠ 0 := hv.ne_zero ⟨e, hev⟩
contradiction
-- put this together with `v` to provide a candidate orthonormal basis for the whole space
refine' ⟨insert e v, v.subset_insert e, ⟨_, _⟩, (v.ne_insert_of_not_mem he'').symm⟩
· -- show that the elements of `insert e v` have unit length
rintro ⟨a, ha'⟩
cases' eq_or_mem_of_mem_insert ha' with ha ha
· simp [ha, he]
· exact hv.1 ⟨a, ha⟩
· -- show that the elements of `insert e v` are orthogonal
have h_end : ∀ a ∈ v, ⟪a, e⟫ = 0 := by
intro a ha
exact he' a (Submodule.subset_span ha)
rintro ⟨a, ha'⟩
cases' eq_or_mem_of_mem_insert ha' with ha ha
· rintro ⟨b, hb'⟩ hab'
have hb : b ∈ v := by
refine' mem_of_mem_insert_of_ne hb' _
intro hbe'
apply hab'
simp [ha, hbe']
rw [inner_eq_zero_symm]
simpa [ha] using h_end b hb
rintro ⟨b, hb'⟩ hab'
cases' eq_or_mem_of_mem_insert hb' with hb hb
· simpa [hb] using h_end a ha
have : (⟨a, ha⟩ : v) ≠ ⟨b, hb⟩ := by
intro hab''
apply hab'
simpa using hab''
exact hv.2 this
· -- ** direction 2: empty orthogonal complement implies maximal
simp only [subset.antisymm_iff]
rintro h u (huv : v ⊆ u) hu
refine' ⟨_, huv⟩
intro x hxu
refine' ((mt (h x)) (hu.ne_zero ⟨x, hxu⟩)).imp_symm _
intro hxv y hy
have hxv' : (⟨x, hxu⟩ : u) ∉ (coe ⁻¹' v : Set u) := by simp [huv, hxv]
obtain ⟨l, hl, rfl⟩ :
∃ l ∈ Finsupp.supported 𝕜 𝕜 (coe ⁻¹' v : Set u), (Finsupp.total (↥u) E 𝕜 coe) l = y :=
by
rw [← Finsupp.mem_span_image_iff_total]
simp [huv, inter_eq_self_of_subset_left, hy]
exact hu.inner_finsupp_eq_zero hxv' hl
#align maximal_orthonormal_iff_orthogonal_complement_eq_bot maximal_orthonormal_iff_orthogonal_complement_eq_bot
variable [FiniteDimensional 𝕜 E]
/- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (u «expr ⊇ » v) -/
/-- An orthonormal set in a finite-dimensional `inner_product_space` is maximal, if and only if it
is a basis. -/
theorem maximal_orthonormal_iff_basis_of_finiteDimensional (hv : Orthonormal 𝕜 (coe : v → E)) :
(∀ (u) (_ : u ⊇ v), Orthonormal 𝕜 (coe : u → E) → u = v) ↔ ∃ b : Basis v 𝕜 E, ⇑b = coe :=
by
haveI := proper_is_R_or_C 𝕜 (span 𝕜 v)
rw [maximal_orthonormal_iff_orthogonal_complement_eq_bot hv]
have hv_compl : IsComplete (span 𝕜 v : Set E) := (span 𝕜 v).complete_of_finiteDimensional
rw [Submodule.orthogonal_eq_bot_iff]
have hv_coe : range (coe : v → E) = v := by simp
constructor
· refine' fun h => ⟨Basis.mk hv.linear_independent _, Basis.coe_mk _ _⟩
convert h.ge
· rintro ⟨h, coe_h⟩
rw [← h.span_eq, coe_h, hv_coe]
#align maximal_orthonormal_iff_basis_of_finite_dimensional maximal_orthonormal_iff_basis_of_finiteDimensional
end OrthonormalBasis
|
import data.complex.basic
variables p q r : ℂ
theorem Q6a : (p+q)+r=p+(q+r) := sorry
theorem Q6b : p*q=q*p := sorry
theorem Q6c : complex.conjugate p * complex.conjugate q = complex.conjugate (p*q) := sorry
|
Pattycake 's birth caught the attention of the city and brought crowds of thousands of New Yorkers to the Central Park Zoo . Reporter N. R. <unk> called her a child star whose " furry face served as a bit of a respite at a time when the city found itself grappling with high crime rates and an intensifying financial crisis . " Six months after Pattycake was born , the director of the zoo estimated that based on the crowds , she might draw an additional 500 @,@ 000 visitors by the time of her first birthday .
|
import number_theory.bernoulli
--OUTPUT 1
theorem bernoulli_eval_one_add (n : ℕ) (x : ℚ) :
(polynomial.bernoulli n).eval (1 + x) = (polynomial.bernoulli n).eval x + n * x^(n - 1) :=
begin
have h1 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1),
from by {
assume m : ℕ,
assume hm : m < n,
induction m with d hd,
{show (polynomial.bernoulli 0).eval (1 + x) = (polynomial.bernoulli 0).eval x + 0 * x^(0 - 1), from by ring},
{have h1 : (polynomial.bernoulli d).eval (1 + x) = (polynomial.bernoulli d).eval x + d * x^(d - 1), from by {
have h2 : (d + 1) * (polynomial.bernoulli (d + 1)).eval (1 + x) - (d + 1) * (polynomial.bernoulli (d + 1)).eval x =
∑ (k : ℕ) in finset.range (d + 1), (d + 1) * C (d + 1) k * (polynomial.bernoulli k).eval x * x^(k - 1),
from by {
rw ← polynomial.eval_add,
rw ← polynomial.eval_mul,
rw ← polynomial.eval_mul,
rw ← polynomial.eval_mul,
rw ← polynomial.eval_add,
rw ← polynomial.eval_mul,
rw ← polynomial.eval_mul,
rw ← polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_add,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul,
rw polynomial.eval_pow,
rw polynomial.eval_one,
rw polynomial.eval_mul,
rw polynomial.eval_mul
end --Needs more than 2000 tokens!
--OUTPUT 2
theorem bernoulli_eval_one_add (n : ℕ) (x : ℚ) :
(polynomial.bernoulli n).eval (1 + x) = (polynomial.bernoulli n).eval x + n * x^(n - 1) :=
begin
induction n with d hd,
{
rw polynomial.bernoulli_zero,
rw polynomial.eval_C,
ring,
},
{
rw polynomial.bernoulli_succ,
rw polynomial.eval_add,
rw polynomial.eval_mul,
rw polynomial.eval_X,
rw polynomial.eval_C,
rw polynomial.eval_add,
rw polynomial.eval_mul,
rw polynomial.eval_X,
rw polynomial.eval_C,
rw polynomial.eval_sub,
rw polynomial.eval_C,
rw polynomial.eval_X,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_X,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
rw polynomial.eval_C,
end --Needs more than 2000 tokens!
--OUTPUT 3
theorem bernoulli_eval_one_add (n : ℕ) (x : ℚ) :
(polynomial.bernoulli n).eval (1 + x) = (polynomial.bernoulli n).eval x + n * x^(n - 1) :=
begin
have h1 : ∀ m : ℕ, m < n → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from
assume (m : ℕ) (h : m < n),
begin
induction m with m hm,
show (polynomial.bernoulli 0).eval (1 + x) = (polynomial.bernoulli 0).eval x + 0 * x^(0 - 1), from
by {rw [polynomial.bernoulli_zero,polynomial.bernoulli_zero,zero_pow],ring,},
assume h1 : ∀ m : ℕ, m < m → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1),
show (polynomial.bernoulli (m + 1)).eval (1 + x) = (polynomial.bernoulli (m + 1)).eval x + (m + 1) * x^((m + 1) - 1), from
begin
have h2 : ∀ l : ℕ, (polynomial.bernoulli l).eval (1 + x) = (polynomial.bernoulli l).eval x + l * x^(l - 1), from
assume l : ℕ,
begin
induction l with l hl,
show (polynomial.bernoulli 0).eval (1 + x) = (polynomial.bernoulli 0).eval x + 0 * x^(0 - 1), from
by {rw [polynomial.bernoulli_zero,polynomial.bernoulli_zero,zero_pow],ring,},
assume h2 : (polynomial.bernoulli l).eval (1 + x) = (polynomial.bernoulli l).eval x + l * x^(l - 1),
show (polynomial.bernoulli (l + 1)).eval (1 + x) = (polynomial.bernoulli (l + 1)).eval x + (l + 1) * x^((l + 1) - 1), from
by {rw [polynomial.bernoulli_succ,polynomial.bernoulli_succ],rw [h2,h2],ring,},
end,
have h3 : ∀ l : ℕ, (polynomial.bernoulli l).eval (1 + x) = (polynomial.bernoulli l).eval x + l * x^(l - 1), from
assume l : ℕ,
begin
induction l with l hl,
show (polynomial.bernoulli 0).eval (1 + x) = (polynomial.bernoulli 0).eval x + 0 * x^(0 - 1), from
by {rw [polynomial.bernoulli_zero,polynomial.bernoulli_zero,zero_pow],ring,},
assume h3 : (polynomial.bernoulli l).eval (1 + x) = (polynomial.bernoulli l).eval x + l * x^(l - 1),
show (polynomial.bernoulli (l + 1)).eval (1 + x) = (polynomial.bernoulli (l + 1)).eval x + (l + 1) * x^((l + 1) - 1), from
by {rw [polynomial.bernoulli_succ,polynomial.bernoulli_succ],rw [h3,h3],ring,},
end,
have h4 : (polynomial.bernoulli (m + 1)).eval (1 + x) = (polynomial.bernoulli (m + 1)).eval x + (m + 1) * x^((m + 1) - 1), from
begin
rw [polynomial.bernoulli_succ,polynomial.bernoulli_succ],
have h5 : ∀ l : ℕ, (polynomial.bernoulli l).eval (1 + x) = (polynomial.bernoulli l).eval x + l * x^(l - 1), from
assume l : ℕ,
begin
induction l with l hl,
show (polynomial.bernoulli 0).eval (1 + x) = (polynomial.bernoulli 0).eval x + 0 * x^(0 - 1), from
by {rw [polynomial.bernoulli_zero,polynomial.bernoulli_zero,zero_pow],ring,},
assume h5 : (polynomial.bernoulli l).eval (1 + x) = (polynomial.bernoulli l).eval x + l * x^(l - 1),
show (polynomial.bernoulli (l + 1)).eval (1 + x) = (polynomial.bernoulli (l + 1)).eval x + (l + 1) * x^((l + 1) - 1), from
by {rw [polynomial.bernoulli_succ,polynomial.bernoulli_succ],rw [h5,h5],ring,},
end,
have h6 : ∀ l : ℕ, (polynomial.bernoulli l).eval (1 + x) = (polynomial.bernoulli l).eval x + l * x^(l - 1), from
assume l : ℕ,
begin
induction l with l hl,
show (polynomial.bernoulli 0).eval (1 + x) = (polynomial.bernoulli 0).eval x + 0 * x^(0 - 1), from
by {rw [polynomial.bernoulli_zero,polynomial.bernoulli_zero,zero_pow],ring,},
assume h6 : (polynomial.bernoulli l).eval (1 + x) = (polynomial.bernoulli l).eval x + l * x^(l - 1),
show (polynomial.bernoulli (l + 1)).eval (1 + x) = (polynomial.bernoulli (l + 1)).eval x + (l + 1) * x^((l + 1) - 1), from
by {rw [polynomial.bernoulli_succ,polynomial.bernoulli_succ],rw [h6,h6],ring,},
end,
have h7 : ∀ l : ℕ, (polynomial.bernoulli l).eval (1 + x) = (polynomial.bernoulli l).eval x + l * x^(l - 1), from
assume l : ℕ,
begin
induction l with l hl,
show (polynomial.bernoulli 0).eval (1 + x) = (polynomial.bernoulli 0).eval x + 0 * x^(0 - 1), from
by {rw [polynomial.bernoulli_zero,polynomial.bernoulli_zero,zero_pow],ring,},
assume h7 : (polynomial.bernoulli l).eval (1 + x) = (polynomial.bernoulli l).eval x + l * x^(l - 1),
show (polynomial.bernoulli (l + 1)).eval (1 + x) = (polynomial.bernoulli (l + 1)).eval x + (l + 1) * x^((l + 1) - 1), from
by {rw [polynomial.bernoulli_succ,polynomial.bernoulli_succ],rw [h7,h7],ring,},
end,
have h8 : ∀ l : ℕ, (polynomial.bernoulli l).eval (1 + x) = (polynomial.bernoulli l).eval x + l * x^(l - 1), from
assume l : ℕ,
begin
induction l with l hl,
show (polynomial.bernoulli 0).eval (1 + x) = (polynomial.bernoulli 0).eval x + 0 * x^(0 - 1), from
by {rw [polynomial.bernoulli_zero,polynomial.bernoulli_zero,zero_pow],
end --Needs more than 2000 tokens!
--OUTPUT 4
theorem bernoulli_eval_one_add (n : ℕ) (x : ℚ) :
(polynomial.bernoulli n).eval (1 + x) = (polynomial.bernoulli n).eval x + n * x^(n - 1) :=
begin
have h1 : ∀ m : ℕ, (m < n) → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from assume (m : ℕ) (h : m < n),
begin
induction m with d hd,
{
show (polynomial.bernoulli 0).eval (1 + x) = (polynomial.bernoulli 0).eval x + 0 * x^(0 - 1), from by {
rw [← polynomial.bernoulli_zero, ← polynomial.bernoulli_zero],
ring,
},
},
{
have h1 : ∀ m : ℕ, (m < d) → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from assume (m : ℕ) (h : m < d), hd h,
have h2 : (polynomial.bernoulli d).eval (1 + x) = (polynomial.bernoulli d).eval x + d * x^(d - 1), from by {
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
have h3 : (d + 1) * (1 + x)^d - (d + 1) * x^d = (d + 1) * (1 + x)^d - (d + 1) * x^d, from by {
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
ring,
},
rw [h3],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial.bernoulli_succ, ← polynomial.bernoulli_succ],
rw [← polynomial
end --Needs more than 2000 tokens!
--OUTPUT 5
theorem bernoulli_eval_one_add (n : ℕ) (x : ℚ) :
(polynomial.bernoulli n).eval (1 + x) = (polynomial.bernoulli n).eval x + n * x^(n - 1) :=
begin
induction n with d hd,
{
show (polynomial.bernoulli 0).eval (1 + x) = (polynomial.bernoulli 0).eval x + 0 * x^(0 - 1), from
begin
rw polynomial.bernoulli,
rw polynomial.eval_C,
rw polynomial.eval_C,
ring,
end,
},
{
have h1 : ∀ (m : ℕ) (x : ℚ), m < d → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from
assume (m : ℕ) (x : ℚ) (h : m < d), hd m h,
have h2 : ∀ (m : ℕ) (x : ℚ), m < d → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from
assume (m : ℕ) (x : ℚ) (h : m < d), hd m h,
have h3 : ∀ (m : ℕ) (x : ℚ), m < d → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from
assume (m : ℕ) (x : ℚ) (h : m < d), hd m h,
have h4 : ∀ (m : ℕ) (x : ℚ), m < d → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from
assume (m : ℕ) (x : ℚ) (h : m < d), hd m h,
have h5 : ∀ (m : ℕ) (x : ℚ), m < d → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from
assume (m : ℕ) (x : ℚ) (h : m < d), hd m h,
have h6 : ∀ (m : ℕ) (x : ℚ), m < d → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from
assume (m : ℕ) (x : ℚ) (h : m < d), hd m h,
have h7 : ∀ (m : ℕ) (x : ℚ), m < d → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from
assume (m : ℕ) (x : ℚ) (h : m < d), hd m h,
have h8 : ∀ (m : ℕ) (x : ℚ), m < d → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from
assume (m : ℕ) (x : ℚ) (h : m < d), hd m h,
have h9 : ∀ (m : ℕ) (x : ℚ), m < d → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from
assume (m : ℕ) (x : ℚ) (h : m < d), hd m h,
have h10 : ∀ (m : ℕ) (x : ℚ), m < d → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from
assume (m : ℕ) (x : ℚ) (h : m < d), hd m h,
have h11 : ∀ (m : ℕ) (x : ℚ), m < d → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from
assume (m : ℕ) (x : ℚ) (h : m < d), hd m h,
have h12 : ∀ (m : ℕ) (x : ℚ), m < d → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from
assume (m : ℕ) (x : ℚ) (h : m < d), hd m h,
have h13 : ∀ (m : ℕ) (x : ℚ), m < d → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from
assume (m : ℕ) (x : ℚ) (h : m < d), hd m h,
have h14 : ∀ (m : ℕ) (x : ℚ), m < d → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from
assume (m : ℕ) (x : ℚ) (h : m < d), hd m h,
have h15 : ∀ (m : ℕ) (x : ℚ), m < d → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from
assume (m : ℕ) (x : ℚ) (h : m < d), hd m h,
have h16 : ∀ (m : ℕ) (x : ℚ), m < d → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from
assume (m : ℕ) (x : ℚ) (h : m < d), hd m h,
have h17 : ∀ (m : ℕ) (x : ℚ), m < d → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from
assume (m : ℕ) (x : ℚ) (h : m < d), hd m h,
have h18 : ∀ (m : ℕ) (x : ℚ), m < d → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from
assume (m : ℕ) (x : ℚ) (h : m < d), hd m h,
have h19 : ∀ (m : ℕ) (x : ℚ), m < d → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from
assume (m : ℕ) (x : ℚ) (h : m < d), hd m h,
have h20 : ∀ (m : ℕ) (x : ℚ), m < d → (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1), from
assume (m : ℕ) (x : ℚ) (h
end --Needs more than 2000 tokens!
--OUTPUT 6
theorem bernoulli_eval_one_add (n : ℕ) (x : ℚ) :
(polynomial.bernoulli n).eval (1 + x) = (polynomial.bernoulli n).eval x + n * x^(n - 1) :=
begin
apply nat.strong_induction_on n,
assume (d : ℕ) (h : ∀ m < d, (polynomial.bernoulli m).eval (1 + x) = (polynomial.bernoulli m).eval x + m * x^(m - 1)),
have h1 : (polynomial.bernoulli d).eval (1 + x) = (polynomial.bernoulli d).eval x + d * x^(d - 1),
begin
have h2 : (d + 1) * (1 + x)^d = (d + 1) * x^d + (d + 1) * (d - 1) * x^(d - 1),
begin
rw [pow_add,pow_one,mul_add,mul_one,← mul_assoc,← mul_assoc,← mul_assoc],
rw [← pow_two,← pow_one,← pow_add,← pow_one,← pow_add,← pow_one],
ring,
end,
have h3 : (polynomial.bernoulli d).eval (1 + x) = (d + 1) * (1 + x)^d - (d + 1) * x^d,
begin
rw [← polynomial.eval_C_mul,← polynomial.eval_C_mul,← polynomial.eval_C_add,polynomial.eval_C_mul,polynomial.eval_C_pow,polynomial.eval_C_mul,polynomial.eval_C_pow,polynomial.eval_C_add],
ring,
end,
have h4 : (polynomial.bernoulli d).eval (1 + x) = (d + 1) * x^d + (d + 1) * (d - 1) * x^(d - 1), from by rw [h3,h2],
have h5 : (polynomial.bernoulli d).eval (1 + x) = (d + 1) * x^d + (d + 1) * (d - 1) * x^(d - 1) + d * x^(d - 1), from by ring,
have h6 : (polynomial.bernoulli d).eval (1 + x) = (polynomial.bernoulli d).eval x + d * x^(d - 1), from by rw [h4,h5],
show (polynomial.bernoulli d).eval (1 + x) = (polynomial.bernoulli d).eval x + d * x^(d - 1), from h6,
end,
show (polynomial.bernoulli d).eval (1 + x) = (polynomial.bernoulli d).eval x + d * x^(d - 1), from h1,
end
/- FEW SHOT PROMPTS TO CODEX(START)
/--`theorem`
Power Set is Closed under Intersection
Let $S$ be a set.
Let $\powerset S$ be the power set of $S$.
Then:
:$\forall A, B \in \powerset S: A \cap B \in \powerset S$
`proof`
Let $A, B \in \powerset S$.
Then by the definition of power set, $A \subseteq S$ and $B \subseteq S$.
From Intersection is Subset we have that $A \cap B \subseteq A$.
It follows from Subset Relation is Transitive that $A \cap B \subseteq S$.
Thus $A \cap B \in \powerset S$ and closure is proved.
{{qed}}
-/
theorem power_set_intersection_closed {α : Type*} (S : set α) : ∀ A B ∈ 𝒫 S, (A ∩ B) ∈ 𝒫 S :=
begin
assume (A : set α) (hA : A ∈ 𝒫 S) (B : set α) (hB : B ∈ 𝒫 S),
have h1 : (A ⊆ S) ∧ (B ⊆ S), from by {split,apply set.subset_of_mem_powerset,exact hA,apply set.subset_of_mem_powerset,exact hB},
have h2 : (A ∩ B) ⊆ A, from by apply set.inter_subset_left,
have h3 : (A ∩ B) ⊆ S, from by {apply set.subset.trans h2 h1.left},
show (A ∩ B) ∈ 𝒫 S, from by {apply set.mem_powerset h3},
end
/--`theorem`
Square of Sum
:$\forall x, y \in \R: \paren {x + y}^2 = x^2 + 2 x y + y^2$
`proof`
Follows from the distribution of multiplication over addition:
{{begin-eqn}}
{{eqn | l = \left({x + y}\right)^2
| r = \left({x + y}\right) \cdot \left({x + y}\right)
}}
{{eqn | r = x \cdot \left({x + y}\right) + y \cdot \left({x + y}\right)
| c = Real Multiplication Distributes over Addition
}}
{{eqn | r = x \cdot x + x \cdot y + y \cdot x + y \cdot y
| c = Real Multiplication Distributes over Addition
}}
{{eqn | r = x^2 + 2xy + y^2
| c =
}}
{{end-eqn}}
{{qed}}
-/
theorem square_of_sum (x y : ℝ) : (x + y)^2 = (x^2 + 2*x*y + y^2) :=
begin
calc (x + y)^2 = (x+y)*(x+y) : by rw sq
... = x*(x+y) + y*(x+y) : by rw add_mul
... = x*x + x*y + y*x + y*y : by {rw [mul_comm x (x+y),mul_comm y (x+y)], rw [add_mul,add_mul], ring}
... = x^2 + 2*x*y + y^2 : by {repeat {rw ← sq}, rw mul_comm y x, ring}
end
/--`theorem`
Identity of Group is Unique
Let $\struct {G, \circ}$ be a group. Then there is a unique identity element $e \in G$.
`proof`
From Group has Latin Square Property, there exists a unique $x \in G$ such that:
:$a x = b$
and there exists a unique $y \in G$ such that:
:$y a = b$
Setting $b = a$, this becomes:
There exists a unique $x \in G$ such that:
:$a x = a$
and there exists a unique $y \in G$ such that:
:$y a = a$
These $x$ and $y$ are both $e$, by definition of identity element.
{{qed}}
-/
theorem group_identity_unique {G : Type*} [group G] : ∃! e : G, ∀ a : G, e * a = a ∧ a * e = a :=
begin
have h1 : ∀ a b : G, ∃! x : G, a * x = b, from by {
assume a b : G, use a⁻¹ * b, obviously, },
have h2 : ∀ a b : G, ∃! y : G, y * a = b, from by {
assume a b : G, use b * a⁻¹, obviously, },
have h3 : ∀ a : G, ∃! x : G, a * x = a, from
assume a : G, h1 a a,
have h4 : ∀ a : G, ∃! y : G, y * a = a, from
assume a : G, h2 a a,
have h5 : ∀ a : G, classical.some (h3 a).exists = (1 : G), from assume a :G,
exists_unique.unique (h3 a) (classical.some_spec (exists_unique.exists (h3 a)))
(mul_one a),
have h6 : ∀ a : G, classical.some (h4 a).exists = (1 : G), from assume a : G,
exists_unique.unique (h4 a) (classical.some_spec (exists_unique.exists (h4 a))) (one_mul a),
show ∃! e : G, ∀ a : G, e * a = a ∧ a * e = a, from by {
use (1 : G),
have h7 : ∀ e : G, (∀ a : G, e * a = a ∧ a * e = a) → e = 1, from by {
assume (e : G) (hident : ∀ a : G, e * a = a ∧ a * e = a),
have h8 : ∀ a : G, e = classical.some (h3 a).exists, from assume (a : G),
exists_unique.unique (h3 a) (hident a).right
(classical.some_spec (exists_unique.exists (h3 a))),
have h9 : ∀ a : G, e = classical.some (h4 a).exists, from assume (a : G),
exists_unique.unique (h4 a) (hident a).left
(classical.some_spec (exists_unique.exists (h4 a))),
show e = (1 : G), from eq.trans (h9 e) (h6 _),
},
exact ⟨by obviously, h7⟩,
}
end
/--`theorem`
Bernoulli polynomial evaluation
Given a natural number $n$ and a rational $x$, let $B_n (x)$ denote the $n$-th Bernoulli polynomial evaluated at $x$. Then, $$B_n (1 + x) = B_n (x) + n x^{n - 1}$$
`proof`
We apply strong induction on $n$. So, for all $m < d$, we have $B_{m} (1 + x) = B_{m} (x) + m x^{m - 1}$ and we want to show that $$B_{d} (1 + x) = B_{d} (x) + d x^{d - 1}$$
Multiplying both sides by $d + 1$, and using the fact that, for all $l \in \mathbb{N}$, $\sum_{k = 0}^{l} {l + 1 \choose k} B_k = (l + 1) X^l$ (where $B_k$ is the $k$-th Bernoulli number), we get that
$$ (d + 1) (1 + x)^d - (d + 1) x^d = \sum_{l = 0}^{d} {d + 1 \choose l} l x^{l - 1} $$
The conclusion then follows easily.
QED
-/
theorem bernoulli_eval_one_add (n : ℕ) (x : ℚ) :
(polynomial.bernoulli n).eval (1 + x) = (polynomial.bernoulli n).eval x + n * x^(n - 1) :=
FEW SHOT PROMPTS TO CODEX(END)-/
|
function fibonacci(x::Int)
if x <= 1
return x
else
return fibonacci(x - 1) + fibonacci(x - 2)
end
return 0
end
|
Require Import
Coq.ZArith.ZArith
Coq.Strings.String
Coq.Vectors.Vector.
Require Import
Fiat.Common.DecideableEnsembles
Fiat.Computation
Fiat.Narcissus.Common.Specs.
Section ComposeFormat.
Context {S : Type}. (* Source Type *)
Context {T : Type}. (* Target Type *)
Context {cache : Cache}. (* State Type *)
Context {S' : Type}. (* Transformed Type *)
Definition Compose_Format
(format : FormatM S' T)
(f : S -> S' -> Prop) (* Transformation Relation *)
: FormatM S T :=
fun s env benv' =>
exists s', format s' env ∋ benv' /\ f s s'.
Definition Compose_Decode {S' : Type}
(decode : DecodeM S' T)
(g : S' -> S) (* Transformation Function *)
: DecodeM S T :=
fun b env => `(s, env') <- decode b env; Ok (g s, env').
Definition Compose_Decode' {S' : Type}
(decode : DecodeM S' T)
(g : S' -> Hopefully S) (* Transformation Function *)
: DecodeM S T :=
fun b env => `(s', env') <- decode b env; match g s' with Ok s => Ok (s, env') | Error e => Error e end.
Definition Compose_Encode
{S' : Type}
(encode : EncodeM S' T)
(f' : S -> Hopefully S')
: EncodeM S T :=
fun s c => HBind f' s as s' With encode s' c.
Lemma CorrectEncoder_Compose
(format : FormatM S' T)
(encode : EncodeM S' T)
(f : S -> S' -> Prop)
(f' : S -> Hopefully S')
(f'_refines_f_1 :
forall s s',
f' s = Ok s' ->
f s s')
(f'_refines_f_2 :
forall s,
is_error (f' s) ->
forall s', ~ f s s')
(f'_sound_choice :
forall s s',
f' s = Ok s' ->
forall x env benv,
format x env ∋ benv
-> f s x
-> format s' env ∋ benv)
: CorrectEncoder format encode
-> CorrectEncoder (Compose_Format format f) (Compose_Encode encode f').
Proof.
unfold CorrectEncoder, Compose_Encode, Compose_Format in *; split; intros.
- apply unfold_computes.
destruct (f' a) eqn: ?; simpl in *; try discriminate.
eapply H in H0; eexists; intuition eauto.
- rewrite unfold_computes; intro; destruct_ex; split_and.
destruct (f' a) eqn: ?; simpl in *.
+ eapply H4; eauto.
+ eapply f'_refines_f_2; eauto.
rewrite Heqh; constructor.
Qed.
End ComposeFormat.
Section ComposeSpecializations.
Context {S : Type}. (* Source Type *)
Context {T : Type}. (* Target Type *)
Context {cache : Cache}. (* State Type *)
Context {S' : Type}. (* Transformed Type *)
Definition Restrict_Format
(P : S -> Prop)
(format : FormatM S T)
: FormatM S T
:= Compose_Format format (fun s s' => s = s' /\ P s').
Corollary CorrectEncoder_Restrict_Format
(format : FormatM S T)
(encode : EncodeM S T)
(P : S -> Prop)
(decideable_P : DecideableEnsemble P)
: CorrectEncoder format encode
-> CorrectEncoder
(Restrict_Format P format)
(fun s => if (DecideableEnsembles.dec s) then encode s else fun _ => Error DecideableEnsembles).
Proof.
intros; replace
(fun s : S => if DecideableEnsembles.dec s then encode s else fun _ : CacheFormat => Error DecideableEnsembles)
with (Compose_Encode encode (fun s => if DecideableEnsembles.dec s then Ok s else Error DecideableEnsembles)).
eapply CorrectEncoder_Compose; intros;
try (destruct (DecideableEnsembles.dec s) eqn: ?; first [discriminate | injections]);
intuition eauto.
- eapply dec_decides_P; eauto.
- eapply Decides_false; subst; eauto.
- subst; eauto.
- apply functional_extensionality; intros; unfold Compose_Encode;
find_if_inside; reflexivity.
Qed.
Definition Projection_Format
(format : FormatM S' T)
(f : S -> S')
: FormatM S T :=
Compose_Format format (fun s s' => f s = s').
Lemma EquivFormat_Projection_Format
(format : FormatM S' T)
(f : S -> S')
: EquivFormat (Projection_Format format f)
(fun s => format (f s)).
Proof.
unfold EquivFormat, Projection_Format, Compose_Format; split; intros ? ?.
apply unfold_computes.
eexists; eauto.
rewrite unfold_computes in H; destruct_ex; intuition; subst; eauto.
Qed.
Corollary CorrectEncoder_Projection_Format
(format : FormatM S' T)
(encode : EncodeM S' T)
(g : S -> S')
: CorrectEncoder format encode
-> CorrectEncoder (Projection_Format format g) (compose encode g).
Proof.
intros; replace
(compose encode g)
with (Compose_Encode encode (fun s => Ok (g s))).
eapply CorrectEncoder_Compose; intros;
try (destruct (DecideableEnsembles.dec s') eqn: ?; first [discriminate | injections]);
intuition eauto.
apply functional_extensionality; intros; reflexivity.
Qed.
End ComposeSpecializations.
Lemma Projection_format_compose
{S S' S'' T}
{monoid : Monoid T}
{cache : Cache}
: forall (f : S -> S')
(f' : S' -> S'')
(formatS'' : FormatM S'' T)
(formatS : FormatM S T),
EquivFormat (Projection_Format (Projection_Format formatS'' f') f)
(Projection_Format formatS'' (f' ∘ f)).
Proof.
unfold EquivFormat, refineEquiv; intros.
unfold Projection_Format, Compose_Format; split;
intros ? ?.
- apply unfold_computes.
apply (proj1 (unfold_computes _ _)) in H; simpl in *.
destruct_ex; eexists; intuition eauto.
apply unfold_computes.
eexists; intuition eauto.
- apply (proj2 (unfold_computes _ _)); simpl in *.
apply (proj1 (unfold_computes _ _)) in H; simpl in *.
destruct_ex; intuition.
apply (proj1 (unfold_computes _ _)) in H0; simpl in *.
destruct_ex; intuition eauto.
eexists.
split; eauto.
unfold Basics.compose; congruence.
Qed.
Lemma Compose_decode_correct {S V T}
{cache : Cache}
{P : CacheDecode -> Prop}
{monoid : Monoid T}
(view : S -> V -> Prop)
(Source_Predicate : S -> Prop)
(View_Predicate : V -> Prop)
(format : FormatM V T)
(view_format : FormatM V T)
(decode_V : DecodeM (V * T) T)
(decode_V_OK : CorrectDecoder monoid View_Predicate View_Predicate eq format decode_V P
view_format)
(View_Predicate_OK : forall s v, view s v -> Source_Predicate s -> View_Predicate v)
: CorrectDecoder monoid Source_Predicate View_Predicate view
(Compose_Format format view) decode_V P view_format.
Proof.
unfold CorrectDecoder, Projection_Format, Compose_Format; split; intros.
{ rewrite @unfold_computes in H1; destruct_ex; intuition.
apply proj1 in decode_V_OK; eapply decode_V_OK with (ext := ext) in H2; eauto.
destruct_ex; intuition; subst; eauto.
eexists _, _; intuition eauto. }
{ apply proj2 in decode_V_OK; eapply decode_V_OK in H1;
clear decode_V_OK; eauto. }
Qed.
Lemma projection_decode_correct {S V T}
{cache : Cache}
{P : CacheDecode -> Prop}
{monoid : Monoid T}
(project : S -> V)
(Source_Predicate : S -> Prop)
(View_Predicate : V -> Prop)
(format : FormatM V T)
(view_format : FormatM V T)
(decode_V : DecodeM (V * T) T)
(decode_V_OK : CorrectDecoder monoid View_Predicate View_Predicate eq format decode_V P view_format)
(View_Predicate_OK : forall (s : S), Source_Predicate s -> View_Predicate (project s))
: CorrectDecoder monoid Source_Predicate View_Predicate (fun s v => project s = v)
(Projection_Format format project) decode_V P view_format.
Proof.
eapply Compose_decode_correct; intros; eauto.
subst; eauto.
Qed.
Lemma constant_decode_correct {S V T}
{cache : Cache}
{P : CacheDecode -> Prop}
{monoid : Monoid T}
(view : S -> V -> Prop)
(Source_Predicate : S -> Prop)
(View_Predicate : V -> Prop)
(format : FormatM V T)
(view_format : FormatM V T)
(decode_V : DecodeM (V * T) T)
(const_v : V)
(decode_V_OK : CorrectDecoder monoid View_Predicate View_Predicate eq format decode_V P
view_format)
(const_v_OK : View_Predicate const_v)
: CorrectDecoder monoid Source_Predicate View_Predicate (fun _ v' => const_v = v')
(Projection_Format format (constant const_v)) decode_V P view_format.
Proof.
eapply projection_decode_correct; eauto.
Qed.
Lemma refine_Projection_Format
{cache : Cache}
{S S' T : Type}
(f : S -> S')
(format : FormatM S' T)
: forall s env,
refineEquiv (Projection_Format format f s env)
(format (f s) env).
Proof.
unfold Projection_Format, Compose_Format; intros; split.
- intros v Comp_v.
apply unfold_computes; eexists; intuition eauto.
- intros v Comp_v.
rewrite unfold_computes in Comp_v; destruct_ex; intuition eauto.
subst; eauto.
Qed.
Lemma injection_decode_correct' {S V V' T}
{cache : Cache}
{P : CacheDecode -> Prop}
{monoid : Monoid T}
(inj : V -> Hopefully V')
(Source_Predicate : S -> Prop)
(View_Predicate : V -> Prop)
(View'_Predicate : V' -> Prop)
(format : FormatM S T)
(view : S -> V -> Prop)
(view' : S -> V' -> Prop)
(view_format : FormatM V T)
(view'_format : FormatM V' T)
(decode_V : DecodeM (V * T) T)
(decode_V_OK : CorrectDecoder monoid Source_Predicate View_Predicate
view format decode_V P view_format)
(view'_OK : forall s v, Source_Predicate s -> view s v -> exists v', inj v = Ok v' /\ view' s v')
(View'_Predicate_OK : forall v, View_Predicate v
-> forall v', inj v = Ok v' -> View'_Predicate v')
(view'_format_OK : forall v env t,
computes_to (view_format v env) t
-> forall v', inj v = Ok v' -> computes_to (view'_format v' env) t)
: CorrectDecoder monoid Source_Predicate View'_Predicate
view'
format (Compose_Decode' decode_V (fun s => match inj (fst s) with
| Ok s' => Ok (s', snd s)
| Error e => Error e
end))
P view'_format.
Proof.
unfold CorrectDecoder, Projection_Format, Compose_Decode'; split; intros.
{ apply proj1 in decode_V_OK; eapply decode_V_OK with (ext := ext) in H1; eauto.
destruct_ex; intuition; subst; eauto.
destruct (view'_OK s x); eauto. intuition.
eexists _, _; intuition eauto; rewrite H2; simpl; eauto.
rewrite H7; auto.
}
{ destruct (decode_V t env') as [ [ [? ?] ?] |] eqn: ? ;
simpl in *; try discriminate; destruct inj eqn:?; try discriminate; injections.
apply proj2 in decode_V_OK;
eapply decode_V_OK in Heqh; eauto.
intuition; destruct_ex; split_and; eexists _, _; intuition eauto.
}
Qed.
Lemma injection_decode_correct {S V V' T}
{cache : Cache}
{P : CacheDecode -> Prop}
{monoid : Monoid T}
(inj : V -> V')
(Source_Predicate : S -> Prop)
(View_Predicate : V -> Prop)
(View'_Predicate : V' -> Prop)
(format : FormatM S T)
(view : S -> V -> Prop)
(view' : S -> V' -> Prop)
(view_format : FormatM V T)
(view'_format : FormatM V' T)
(decode_V : DecodeM (V * T) T)
(decode_V_OK : CorrectDecoder monoid Source_Predicate View_Predicate
view format decode_V P view_format)
(view'_OK : forall s v, Source_Predicate s -> view s v -> view' s (inj v))
(View'_Predicate_OK : forall v, View_Predicate v
-> View'_Predicate (inj v))
(view'_format_OK : forall v env t,
computes_to (view_format v env) t
-> computes_to (view'_format (inj v) env) t)
: CorrectDecoder monoid Source_Predicate View'_Predicate
view'
format (Compose_Decode decode_V (fun s => (inj (fst s), snd s)))
P view'_format.
Proof.
eapply (injection_decode_correct' (fun v => Ok (inj v)));
intuition eauto; injections; intuition eauto.
Qed.
Lemma bijection_decode_correct' {S V T}
{cache : Cache}
{P : CacheDecode -> Prop}
{monoid : Monoid T}
(proj : S -> V)
(inj : V -> Hopefully S)
(Source_Predicate : S -> Prop)
(View_Predicate : V -> Prop)
(view_format : FormatM V T)
(decode_V : DecodeM (V * T) T)
(decode_V_OK : CorrectDecoder monoid View_Predicate View_Predicate
eq view_format decode_V P view_format)
(view_OK : forall s, Source_Predicate s -> inj (proj s) = Ok s)
(view_OK' : forall v s, inj v = Ok s -> proj s = v)
(View_Predicate_OK : forall s, Source_Predicate s -> View_Predicate (proj s))
(View_Predicate_OK' : forall v s, View_Predicate v -> inj v = Ok s -> Source_Predicate s)
: CorrectDecoder monoid Source_Predicate Source_Predicate
eq
(Projection_Format view_format proj)
(Compose_Decode' decode_V (fun s => match inj (fst s) with
| Ok s' => Ok (s', snd s)
| Error e => Error e
end))
P
(Projection_Format view_format proj).
Proof.
eapply injection_decode_correct'.
- apply projection_decode_correct; eauto.
- simpl; intros. subst. eexists. intuition eauto.
- eauto.
- intros. apply (EquivFormat_sym (EquivFormat_Projection_Format _ _)).
erewrite view_OK'; eauto.
Qed.
Lemma bijection_decode_correct {S V T}
{cache : Cache}
{P : CacheDecode -> Prop}
{monoid : Monoid T}
(proj : S -> V)
(inj : V -> S)
(Source_Predicate : S -> Prop)
(View_Predicate : V -> Prop)
(view_format : FormatM V T)
(decode_V : DecodeM (V * T) T)
(decode_V_OK : CorrectDecoder monoid View_Predicate View_Predicate
eq view_format decode_V P view_format)
(view_OK : forall s, Source_Predicate s -> inj (proj s) = s)
(view_OK' : forall v, proj (inj v) = v)
(View_Predicate_OK : forall s, Source_Predicate s -> View_Predicate (proj s))
(View_Predicate_OK' : forall v, View_Predicate v -> Source_Predicate (inj v))
: CorrectDecoder monoid Source_Predicate Source_Predicate
eq
(Projection_Format view_format proj)
(Compose_Decode decode_V (fun s => (inj (fst s), snd s)))
P
(Projection_Format view_format proj).
Proof.
eapply (bijection_decode_correct' _ (fun v => Ok (inj v)));
intuition eauto; injections; f_equal; intuition eauto.
Qed.
(* Do we have something similar already? *)
Ltac derive_decoder_equiv :=
unfold flip, pointwise_relation,
Compose_Decode, Compose_Decode', DecodeBindOpt2, DecodeBindOpt, BindOpt;
intros; try reflexivity;
let tac x := (destruct x eqn:?; cbn; destruct_pairs; intuition eauto) in
repeat match goal with
| |- context[If_Opt_Then_Else ?x _ _] => tac x
| |- context[If_Then_Else ?x _ _] => tac x
| |- context[if ?x then _ else _] => tac x
| |- context[hbind ?x _] => tac x
end.
Ltac _apply_bijection_rule tac :=
match goal with
| |- CorrectDecoder _ _ _ _ ?f ?d _ ?f =>
try unfold f; try unfold d
end;
match goal with
| |- CorrectDecoder _ _ _ _ ?f _ _ ?f =>
match f with
| Projection_Format _ _ => idtac
| _ => eapply format_decode_correct_EquivFormatAndView;
[solve [apply EquivFormat_sym; apply EquivFormat_Projection_Format] |]
end;
tac ||
(eapply format_decode_correct_EquivDecoder;
[| tac]; cycle 1)
end.
Ltac apply_bijection_rule :=
_apply_bijection_rule ltac:(eapply bijection_decode_correct).
Tactic Notation "apply_bijection_rule" "with" uconstr(t) :=
_apply_bijection_rule ltac:(eapply bijection_decode_correct with (inj:=t)).
Ltac apply_bijection_rule' :=
_apply_bijection_rule ltac:(eapply bijection_decode_correct').
Tactic Notation "apply_bijection_rule'" "with" uconstr(t) :=
_apply_bijection_rule ltac:(eapply bijection_decode_correct' with (inj:=t)).
Notation "format ◦ f" := (Projection_Format format f) (at level 55) : format_scope.
Notation "P ∩ format" := (Restrict_Format P format) (at level 55) : format_scope.
|
import category_theory.equivalence
open category_theory
variables {C : Type*} [category C]
variables {D : Type*} [category D]
lemma equiv_reflects_mono {X Y : C} (f : X ⟶ Y) (e : C ≌ D)
(hef : mono (e.functor.map f)) : mono f :=
-- Hint: when `e : C ≌ D`, `e.functor.map_injective` says
-- `∀ f g, e.functor.map f = e.functor.map g → f = g`
-- Hint: use `cancel_mono`.
-- sorry
begin
tidy,
apply e.functor.map_injective,
apply (cancel_mono (e.functor.map f)).1,
apply e.inverse.map_injective,
simp,
assumption
end
-- sorry
lemma equiv_preserves_mono {X Y : C} (f : X ⟶ Y) [mono f] (e : C ≌ D) :
mono (e.functor.map f) :=
-- Hint: if `w : f = g`, to obtain `F.map f = F.map G`,
-- you can use `have w' := congr_arg (λ k, F.map k) w`.
-- sorry
begin
tidy,
replace w := congr_arg (λ k, e.inverse.map k) w,
simp at w,
simp only [←category.assoc, cancel_mono] at w,
simp at w,
exact w,
end
-- sorry
/-!
There are some further hints in
`hints/category_theory/exercise3/`
-/
|
import data.set.lattice
open set
theorem compl_lt_compl {α : Type*} (U V : set α) : -U < -V → V < U :=
λ H, ⟨compl_subset_compl.1 H.1, λ H1, H.2 (compl_subset_compl.2 H1)⟩ |
function [ys, scores] = predict_matconvnet(ims, net, batchsize)
ys = zeros(size(ims, 4), 1);
scores = zeros(1000, size(ims, 4)); % Number of classes
for b = 1:batchsize:size(ims, 4)
res = vl_simplenn(net, gpuArray(ims(:, :, :, b:(b+batchsize-1))), [], [], 'Mode', 'test');
cc = squeeze(gather(res(end).x));
scores(:, b:(b+batchsize-1)) = cc;
[~, ys(b:(b+batchsize-1))] = max(squeeze(gather(res(end).x)));
end
end |
The clinical rehabilitation counseling specialization will prepare you to work in state organizations, hospitals, rehabilitation agencies, and private practices, as well as in insurance rehabilitation, for advocacy groups, or as a consultant.
Drake University's clinical rehabilitation counseling program is accredited by CACREP, so you will be eligible to take the Certified Rehabilitation Counselor exam—which leads to certification in every state—during your last semester of coursework.
The rehabilitation program has strong ties to the community. Professionals from the community are often invited to teach classes or be guest speakers.
Drake is also committed to advancing the field. The National Rehabilitation Institute was established at Drake in 1976. The Institute conducts research, manages federal research and training grants, and provides pre-service and in-service training in the areas of rehabilitation counseling, placement, and leadership. Drake is also a member of National Council on Rehabilitation Education. Faculty are members of the Iowa Rehabilitation Association, National Rehabilitation Association, the American Counseling Association, and Nation Council on Rehabilitation Education.
The American Counseling Association (ACA) recently conducted a comprehensive survey looking at counselor compensation and benefits across the profession. Survey results indicated that, Rehabilitation Counselors were named the highest paid specialty in the counseling profession and additionally earned better overall benefits.
The mission of the Clinical Rehabilitation Counseling specialization is to support activities that improve the lives of people with disabilities. To this end we will offer degree programs, provide university and community services, and conduct research on issues related to rehabilitation. Close collaboration will occur between the program, students, local rehabilitation provider, and consumers to ensure a well-rounded and practical learning experience. Students will graduate from the Clinical Rehabilitation Counseling program having met all of the competencies established by Drake University, the Council on Rehabilitation Education (CORE), and the Commission on Rehabilitation Counselor Certification (CRCC).
The Clinical Rehabilitation Counseling specialization shall prepare students to enter the rehabilitation profession as clinical rehabilitation counseling professionals as defined by CORE and expose them to professional issues relevant to participation in professional associations and work settings.
The Clinical Rehabilitation Counseling specialization shall actively involve people from the community on its boards, as guest lecturers, and instructors. These shall include people with disabilities; people from diverse backgrounds; people working in public rehabilitation, not for-profit rehabilitation, for-profit rehabilitation; and employers.
The Clinical Rehabilitation Counseling specialization shall periodically conduct follow-up with graduates and area needs assessments. It will incorporate those results into its curriculum planning to ensure it meets the needs of local consumers and employers.
Clinical Rehabilitation Counseling faculty will work closely with rehabilitation agencies through in-service training, consulting, and research.
Outcome Measures for the Rehabilitation Counseling Specialization.
Click here for rehabilitation counseling coursework information. For more information on certification, visit the website for the Commission on Rehabilitation Counselor Certification. |
------------------------------------------------------------------------
-- Some examples
------------------------------------------------------------------------
module Contractive.Examples where
open import Codata.Musical.Notation
open import Codata.Musical.Stream
open import Data.Nat
open import Data.Nat.Properties
import Data.Vec as Vec
open Vec using (_∷_; [])
open import Function
open import Contractive
import Contractive.Stream as S
open import StreamProg using (Ord; lt; eq; gt; merge)
open import Relation.Binary.PropositionalEquality
open ≡-Reasoning
open COFE (S.cofe 0)
fibF : ContractiveFun (S.cofe 0)
fibF = record
{ F = F
; isContractive = isCon _ _ _
}
where
F = λ xs → 0 ∷ ♯ (1 ∷ ♯ zipWith _+_ xs (tail xs))
lemma₁ : ∀ _∙_ (xs ys : Stream ℕ) n →
take n (zipWith _∙_ xs ys) ≡
Vec.zipWith _∙_ (take n xs) (take n ys)
lemma₁ _∙_ _ _ zero = refl
lemma₁ _∙_ (x ∷ xs) (y ∷ ys) (suc n) =
cong (_∷_ (x ∙ y)) (lemma₁ _∙_ (♭ xs) (♭ ys) n)
lemma₂ : ∀ (xs ys : Stream ℕ) n →
Eq n xs ys → take n xs ≡ take n ys
lemma₂ _ _ zero _ = refl
lemma₂ (x ∷ xs) ( y ∷ ys) (suc n) hyp
with cong Vec.head hyp | take n (♭ xs) | lemma₂ (♭ xs) (♭ ys) n (cong Vec.tail hyp)
lemma₂ (x ∷ xs) (.x ∷ ys) (suc n) hyp | refl | .(take n (♭ ys)) | refl = refl
isCon : ∀ (xs ys : Stream ℕ) n →
(∀ {m} → m <′ n → Eq m xs ys) →
Eq n (F xs) (F ys)
isCon _ _ zero _ = refl
isCon (x ∷ xs) (y ∷ ys) (suc n) hyp = cong (λ zs → 0 ∷ 1 ∷ zs) (begin
take n (zipWith _+_ (x ∷ xs) (♭ xs)) ≡⟨ lemma₁ _+_ (x ∷ xs) (♭ xs) n ⟩
Vec.zipWith _+_ (take n (x ∷ xs)) (take n (♭ xs)) ≡⟨ cong₂ (Vec.zipWith _+_)
(lemma₂ _ _ n (hyp ≤′-refl))
(cong Vec.tail (hyp ≤′-refl)) ⟩
Vec.zipWith _+_ (take n (y ∷ ys)) (take n (♭ ys)) ≡⟨ sym $ lemma₁ _+_ (y ∷ ys) (♭ ys) n ⟩
take n (zipWith _+_ (y ∷ ys) (♭ ys)) ∎)
fib : Stream ℕ
fib = ContractiveFun.fixpoint fibF
-- Note that I could not be bothered to finish the following
-- definition.
hammingF : ContractiveFun (S.cofe 0)
hammingF = record
{ F = F
; isContractive = isCon _ _ _
}
where
toOrd : ∀ {m n} → Ordering m n → Ord
toOrd (less _ _) = lt
toOrd (equal _) = eq
toOrd (greater _ _) = gt
cmp : ℕ → ℕ → Ord
cmp m n = toOrd (compare m n)
F = λ (xs : _) → 0 ∷ ♯ merge cmp (map (_*_ 2) xs) (map (_*_ 3) xs)
postulate
lemma : ∀ n → cmp (2 * suc n) (3 * suc n) ≡ lt
isCon : ∀ (xs ys : Stream ℕ) n →
(∀ {m} → m <′ n → Eq m xs ys) →
Eq n (F xs) (F ys)
isCon _ _ zero _ = refl
isCon (x ∷ xs) (y ∷ ys) (suc n) hyp with cong Vec.head (hyp (s≤′s z≤′n))
isCon (0 ∷ xs) (.0 ∷ ys) (suc n) hyp | refl =
cong (λ zs → 0 ∷ 0 ∷ zs) (begin
take n (merge cmp (map (_*_ 2) (♭ xs)) (map (_*_ 3) (♭ xs))) ≡⟨ iCantBeBothered ⟩
take n (merge cmp (map (_*_ 2) (♭ ys)) (map (_*_ 3) (♭ ys))) ∎)
where postulate iCantBeBothered : _
isCon (suc x ∷ xs) (.(suc x) ∷ ys) (suc n) hyp | refl
with cmp (2 * suc x) (3 * suc x) | lemma x
isCon (suc x ∷ xs) (.(suc x) ∷ ys) (suc n) hyp | refl | .lt | refl =
cong (λ zs → 0 ∷ 2 * suc x ∷ zs) (begin
take n (merge cmp (map (_*_ 2) (♭ xs))
(map (_*_ 3) (suc x ∷ xs))) ≡⟨ iCantBeBothered ⟩
take n (merge cmp (map (_*_ 2) (♭ ys))
(map (_*_ 3) (suc x ∷ ys))) ∎)
where postulate iCantBeBothered : _
hamming : Stream ℕ
hamming = ContractiveFun.fixpoint hammingF
|
Require Import OptionSumbool.
Require Import Morphisms.
Require Import AccessRights.
Require Import References.
Require Import Capabilities.
Require Import Indices.
Require Import Objects.
Require Import ObjectLabels.
Require Import SystemState.
Require Import SemanticsDefinitions.
Require Import Semantics.
Require Import Semantics_Conv.
Require Import AccessRightSets.
Require Import Execution.
Require Import RefSets.
Require Import Basics.
Require Import Attenuation.
Require Import OptionMap2.
Require Import RelationClasses.
Require Import Iff_Equiv.
Require Import AccessEdge.
Require Import AccessGraphs.
Require Import SequentialAccess.
Module MakeAccessExecution (Ref:ReferenceType) (RefS: RefSetType Ref) (Edges: AccessEdgeType Ref) (AccessGraph:AccessGraphType Ref Edges) (Seq:SeqAccType Ref RefS Edges AccessGraph) (Cap:CapabilityType Ref) (Ind:IndexType) (Obj:ObjectType Ref Cap Ind) (Sys:SystemStateType Ref Cap Ind Obj) (SemDefns: SemanticsDefinitionsType Ref Cap Ind Obj Sys) (Sem: SemanticsType Ref RefS Cap Ind Obj Sys SemDefns) (Exe: ExecutionType Ref RefS Cap Ind Obj Sys SemDefns Sem).
Module DT := MakeAttenuation Ref RefS Edges AccessGraph Seq Cap Ind Obj Sys SemDefns Sem.
Import DT.
Export DT.
(* Import Seq.RefSet_Mod. *)
Import RefS.
Theorem ag_objs_spec_subset: forall a b Na Nb, AG.Subset a b ->
Seq.ag_objs_spec a Na -> Seq.ag_objs_spec b Nb -> RefSet.Subset Na Nb.
Proof.
unfold Seq.ag_objs_spec; red. intros a b Na Nb Hsub Hobjs_a Hobjs_b x Hx.
apply Hobjs_a in Hx; destruct Hx as [obj [rgt [Hedge | Hedge]]]; eapply Hsub in Hedge;
apply Hobjs_b; do 2 eapply ex_intro; [left|right];apply Hedge.
Qed.
Theorem dirAcc_dep_compose : forall Fs, Proper (Sys.eq ==> Sys.eq) Fs ->
forall Fsa, dirAcc_approx_dep Fs Fsa -> forall Fs' Fsa', dirAcc_approx_dep Fs' Fsa' ->
dirAcc_approx_dep (compose Fs' Fs) (fun s => (compose (Fsa' (Fs s)) (Fsa s))).
Proof.
unfold dirAcc_approx_dep; unfold compose;
intros Fs HeqF Fsa Hdep Fs' Fsa' Hdep' s s' ag ag' ag2 Hda Hda2 Hsub Heq.
(* apply Hdep' over subset, but instantiate dirAcc first *)
generalize (exists_dirAcc_spec (Fs s)); intros [daF' HdaF'].
eapply Hdep'; [apply HdaF'| apply Hda2| | apply HeqF; apply Heq].
eapply Hdep; [ apply Hda | apply HdaF' | apply Hsub | apply Heq].
Qed.
Implicit Arguments dirAcc_dep_compose [Fs Fsa Fs' Fsa'].
Theorem potAcc_eq_iff: forall i p, Seq.potAcc i p ->
forall i', AG.eq i i' -> forall p', AG.eq p p' -> Seq.potAcc i' p'.
Proof.
intros i p Hpa i' Heq p' Heq'.
destruct Hpa as [Htrans Hmax].
split;
[ eapply Seq.potTransfer_eq; [apply Heq| apply Heq' | auto]
| red; intros a Htrans';
eapply AG.eq_trans; [apply AG.eq_sym; apply Heq' | ]; apply Hmax;
eapply Seq.potTransfer_eq; [apply AG.eq_sym; apply Heq'| apply AG.eq_refl | auto]
].
Qed.
Theorem potAcc_approx_dirAcc_dep_compose: forall Fs, Proper (Sys.eq ==> Sys.eq) Fs ->
forall Fsa, dirAcc_approx_dep Fs Fsa -> Proper (Sys.eq ==> AG.eq ==> AG.eq) Fsa ->
forall Fp, potAcc_approx_dirAcc_dep Fsa Fp ->
forall (Fs':Sys.t->Sys.t) Fsa', Proper (Sys.eq ==> AG.eq ==> AG.eq) Fsa' ->
forall Fp', potAcc_approx_dirAcc_dep Fsa' Fp' ->
potAcc_approx_dirAcc_dep (fun s => (compose (Fsa' (Fs s)) (Fsa s))) (fun s => (compose (Fp' (Fs s)) (Fp s))).
Proof.
intros Fs HeqF Fsa HdaX HeqFsa Fp HpaX Fs' Fsa' HeqFsa' Fp' HpaX'
i i' p p' p2 s s' s'' Heq Heq' Hda Hsub Hpa Hpa' Hsub'.
generalize (exists_dirAcc_spec (Fs s)); intros [i3 Hda3].
generalize (HdaX _ _ _ _ _ Hda Hda3 Hsub (Sys.eq_refl _)); intros HdaXi.
generalize (Seq.exists_potAcc (Fsa s i')); intros [p3 Hpa3].
eapply HpaX';
[ apply Sys.eq_refl
| apply HeqF; eapply Sys.eq_trans; [apply Heq| apply Heq']
| apply Hda3
| apply HdaXi
| apply Hpa3
| eapply potAcc_eq_iff in Hpa'; [ apply Hpa'| | apply AG.eq_refl];
eapply HeqFsa';
[eapply HeqF; auto
| eapply HeqFsa; [auto |apply AG.eq_refl]]
| eapply HpaX;
[ apply Sys.eq_refl
| eapply Sys.eq_trans; [apply Heq | apply Heq']
| apply Hda
| apply Hsub
| apply Hpa
| apply Hpa3
| apply Hsub'
]
].
Qed.
(* This needs to change to capture s in the function *)
(* Perhaps this fixpoint will work better? *)
(* not efficient, but closer to inductive *)
Fixpoint dirAcc_execute op_list s : (AG.t -> AG.t) :=
match op_list with
| nil => id_ag
| cons op tail => compose (dirAcc_op op (Exe.execute s tail)) (dirAcc_execute tail s)
end.
Inductive dirAcc_execute_spec : list Sem.operation -> (Sys.t -> AG.t -> AG.t) -> Prop:=
| dirAcc_execute_spec_nil : dirAcc_execute_spec nil (fun (s:Sys.t) (a:AG.t)=> a)
| dirAcc_execute_spec_cons : forall op op_list Fp, dirAcc_execute_spec op_list Fp ->
dirAcc_execute_spec (cons op op_list) (fun s => compose (dirAcc_op op (Exe.execute s op_list)) (Fp s)).
Theorem dirAcc_execute_spec_dirAcc_execute: forall op_list,
dirAcc_execute_spec op_list (dirAcc_execute op_list).
Proof.
intros.
induction op_list; simpl.
(* base *)
apply dirAcc_execute_spec_nil.
(* step *)
apply dirAcc_execute_spec_cons; auto.
Qed.
Theorem dirAcc_execute_spec_eq_iff: forall opList Fsa,
dirAcc_execute_spec opList Fsa <-> Fsa = (dirAcc_execute opList).
Proof.
intros opList.
induction opList.
intros; split; intros.
inversion H.
simpl in *.
eauto.
rewrite H; eapply dirAcc_execute_spec_dirAcc_execute.
intros; split; intros.
inversion H.
eapply IHopList in H3.
unfold dirAcc_execute in *.
rewrite <- H3. auto.
rewrite H; eapply dirAcc_execute_spec_dirAcc_execute.
Qed.
Fixpoint potAcc_execute op_list s : (AG.t -> AG.t) :=
match op_list with
| nil => id_ag
| cons op tail => compose (potAcc_op op (Exe.execute s tail)) (potAcc_execute tail s)
end.
Inductive potAcc_execute_spec : list Sem.operation -> (Sys.t -> AG.t -> AG.t) -> Prop:=
| potAcc_execute_spec_nil : potAcc_execute_spec nil (fun (s:Sys.t) (a:AG.t)=> a)
| potAcc_execute_spec_cons : forall op op_list Fp, potAcc_execute_spec op_list Fp ->
potAcc_execute_spec (cons op op_list) (fun s => compose (potAcc_op op (Exe.execute s op_list)) (Fp s)).
Theorem potAcc_execute_spec_potAcc_execute: forall op_list,
potAcc_execute_spec op_list (potAcc_execute op_list).
Proof.
intros.
induction op_list; simpl.
(* base *)
apply potAcc_execute_spec_nil.
(* step *)
apply potAcc_execute_spec_cons; auto.
Qed.
Theorem potAcc_execute_spec_eq_iff: forall opList Fsa,
potAcc_execute_spec opList Fsa <-> Fsa = (potAcc_execute opList).
Proof.
intros opList.
induction opList.
intros; split; intros.
inversion H.
simpl in *.
eauto.
rewrite H; eapply potAcc_execute_spec_potAcc_execute.
intros; split; intros.
inversion H.
eapply IHopList in H3.
unfold potAcc_execute in *.
rewrite <- H3. auto.
rewrite H; eapply potAcc_execute_spec_potAcc_execute.
Qed.
(* Inductive potAcc_execute_spec :(list Sem.operation) -> Sys.t -> (AG.t -> AG.t) -> Prop := *)
(* | potAcc_execute_spec_nil : forall s, potAcc_execute_spec nil s id_ag *)
(* | potAcc_execute_spec_cons: forall l s Fp, potAcc_execute_spec l s Fp -> *)
(* forall op, potAcc_execute_spec (cons op l) (Sem.do_op op s) (compose (potAcc_op op s) Fp). *)
(* First, demonstrate that execution is approximated by potAcc_execute_spec *)
(* I didn't write an operation_eq relation, so we will use eq and hope this doesn't hurt us in the long run *)
Theorem execute_proper_1 : Proper (Sys.eq ==> eq ==> Sys.eq) Exe.execute.
Proof.
unfold Proper; unfold respectful; intros.
rewrite H0; clear H0; clear x0.
induction y0; simpl in *; [| apply SemConv.do_op_eq]; auto.
Qed.
Theorem dirAcc_execute_approx :
forall op_list Fsa, dirAcc_execute_spec op_list Fsa ->
dirAcc_approx_dep (fun s => (Exe.execute s op_list)) Fsa.
Proof.
intros; induction H.
(* base *)
unfold dirAcc_approx_dep in *; simpl in *; intros.
eapply AGProps.subset_trans;
[apply AGProps.subset_equal;
eapply dirAcc_spec_eq;
[apply Sys.eq_refl
|apply H0
|apply H
]
|auto
].
(* step *)
eapply dirAcc_dep_compose; auto; try apply dirAcc_approx_dep_op.
(* Execute is proper *)
unfold Proper; unfold respectful; intros; eapply execute_proper_1; auto.
Qed.
Theorem proper_dirAcc_op: forall op,
Proper (Sys.eq ==> AG.eq ==> AG.eq) (dirAcc_op op).
Proof.
unfold dirAcc_op; unfold Proper; unfold respectful; intros.
destruct op; simpl; auto.
(* id_ag cases solved , 4 cases remain*)
(* fetch *)
case (SemDefns.fetch_preReq_dec t t0 x);
case (SemDefns.fetch_preReq_dec t t0 y); intros; eauto;
(* eauto handles the no_op case. Solve portion handles contradiciton cases. *)
try solve [eapply SemDefns.fetch_preReq_eq_iff in f; try apply Ref.eq_refl;
try apply Ind.eq_refl; eauto; contradiction].
eapply ag_add_cap_by_indirect_index_equiv; eauto; try apply Ref.eq_refl.
case ( SemDefns.option_hasRight_dec (SC.getCap t0 t x));
case ( SemDefns.option_hasRight_dec (SC.getCap t0 t y)); intros; auto;
(* auto handles the two easy cases, this handles the contradictory cases *)
eapply SemDefns.option_hasRight_eq in o; solve
[apply n in o; contradiction
| auto
| apply Ref.eq_refl
| apply AccessRight.eq_refl
].
(* store *)
case (SemDefns.store_preReq_dec t t0 x);
case (SemDefns.store_preReq_dec t t0 y); intros; eauto;
(* eauto handles the no_op case. Solve portion handles contradiciton cases. *)
try solve [eapply SemDefns.store_preReq_eq_iff in s; try apply Ref.eq_refl;
try apply Ind.eq_refl; eauto; contradiction].
eapply ag_push_cap_by_indices_equiv; eauto; try apply Ref.eq_refl.
(* send *)
case (SemDefns.send_preReq_dec t t0 x);
case (SemDefns.send_preReq_dec t t0 y); intros; eauto;
(* eauto handles the no_op case. Solve portion handles contradiciton cases. *)
try solve [eapply SemDefns.send_preReq_eq_iff in s; try apply Ref.eq_refl;
try apply Ind.eq_refl; eauto; contradiction].
unfold send_dep_ag.
destruct s as [s_1 s_2]; destruct s0 as [s0_1 s0_2].
unfold SemDefns.option_hasRight in *.
(case (option_sumbool (SC.getCap t0 t x)); intros opt1; [|destruct opt1 as [v1 opt1]]; try rewrite opt1 in *;
(case (option_sumbool (SC.getCap t0 t y)); intros opt2; [|destruct opt2 as [v2 opt2]]; try rewrite opt2 in *);
simpl in *; try contradiction).
generalize H; intros H'.
eapply SC.getCap_eq with (i:=t0) (o:=t) in H'; [ | apply Ind.eq_refl | apply Ref.eq_refl ].
rewrite opt1 in H'; rewrite opt2 in H'; simpl in H'.
eapply Cap.target_eq in H'.
case (option_map1_eq_tgt_dec t0 t x);
case (option_map1_eq_tgt_dec t0 t y); intros; eauto;
try rewrite opt1 in *; try rewrite opt2 in *; simpl in *;
try solve [rewrite H' in *; contradiction
| eapply ag_add_caps_reply_equiv; eauto; try apply Ref.eq_refl
| eapply ag_add_caps_send_equiv; eauto; try apply Ref.eq_refl; try apply CIL_Facts.cil_Equiv
].
(* allocate *)
unfold allocate_dep_ag.
case (SemDefns.allocate_preReq_dec t t0 x);
case (SemDefns.allocate_preReq_dec t t0 y); intros; eauto;
(* eauto handles the no_op case. Solve portion handles contradiciton cases. *)
try solve [eapply SemDefns.allocate_preReq_eq_iff in a; try apply Ref.eq_refl;
try apply Ind.eq_refl; eauto; contradiction].
eapply ag_add_caps_allocate_equiv; eauto; try apply Ref.eq_refl; try apply CIL_Facts.cil_Equiv.
Qed.
Theorem dirAcc_execute_spec_proper : forall op_list Fsa,
dirAcc_execute_spec op_list Fsa -> Proper (Sys.eq ==> AG.eq ==> AG.eq) Fsa.
Proof.
intros op_list Fsa H.
induction H; auto.
(* step *)
unfold Proper; unfold respectful; intros.
eapply proper_dirAcc_op.
eapply execute_proper_1; auto.
eapply IHdirAcc_execute_spec; auto.
Qed.
Hint Resolve proper_dirAcc_op dirAcc_execute_spec_proper.
Theorem potAcc_execute_approx :
forall op_list Fsa, dirAcc_execute_spec op_list Fsa ->
forall Fp, potAcc_execute_spec op_list Fp ->
potAcc_approx_dirAcc_dep Fsa Fp.
Proof.
intros. revert H. revert Fsa.
induction H0.
(* base *)
unfold potAcc_approx_dirAcc_dep. intros.
inversion H. rewrite <- H8 in H5.
eapply AGProps.subset_trans; [ | apply H6].
apply AGProps.subset_equal.
eapply potAcc_equiv; try apply AG.eq_refl; eauto.
(* step *)
intros. inversion H.
eapply potAcc_approx_dirAcc_dep_compose;
try solve
[auto
| (* execute is proper *)
unfold Proper; unfold respectful; intros; eapply execute_proper_1; auto
| (* dirAcc_approx_dep *)
apply dirAcc_execute_approx; auto
| (* potAcc_approx_dirAcc_dep (dirAcc_op op) (potAcc_op op) *)
apply potAcc_approx_dirAcc_dep_op; auto
| eauto
].
Qed.
(* Second, demonstrate that such approximation is reducing over the existing objs *)
Theorem Proper_AG_attenuating :
Proper (RefSet.eq ==> AG.eq ==> AG.eq ==> iff) AG_attenuating.
Proof.
unfold Proper. unfold respectful. unfold AG_attenuating; intros.
split; intros;
(case (Ref.eq_dec src tgt); intros Heq;
[intuition eauto
| right; edestruct H2;
[ eapply H; apply H3
| eapply H; apply H4
| intro Hnot; apply H5; apply H0; apply Hnot
| contradiction
| intro Hnot; apply H6; apply H1; apply Hnot
]
]).
Qed.
Theorem Proper_AG_attenuating_2 :
Proper (RefSet.eq ==> AG.eq ==> AG.Subset --> impl) AG_attenuating.
Proof.
unfold Proper. unfold respectful. unfold impl. unfold flip; unfold AG_attenuating; intros.
case (Ref.eq_dec src tgt); intros Heq; [intuition eauto | ].
right; edestruct H2;
[eapply H; apply H3
| eapply H; apply H4
| intro Hnot; apply H5; apply H0; apply Hnot
| contradiction
| intro Hnot; apply H6; apply H1; apply Hnot].
Qed.
Theorem Proper_AG_attenuating_3:
Proper (RefSet.Subset --> AG.eq ==> AG.Subset --> impl) AG_attenuating.
Proof.
unfold Proper; unfold respectful; unfold impl; unfold flip; intros.
eapply AG_attenuating_subset_objs; [ | apply H].
eapply Proper_AG_attenuating_2; eauto. apply RefSet.eq_refl.
Qed.
Theorem Proper_AG_attenuating_4:
Proper (RefSet.Subset --> AG.Subset ==> AG.Subset --> impl) AG_attenuating.
Proof.
unfold Proper; unfold respectful; unfold impl; unfold flip; intros.
unfold AG_attenuating in *; intros.
case (Ref.eq_dec src tgt); try solve [intuition auto]; right.
edestruct H2;
[ eapply H; apply H3
| eapply H; apply H4
| intro Hnot; apply H5; apply H0; apply Hnot
| contradiction
| intro Hnot; apply H6; apply H1; apply Hnot].
Qed.
(* Helper functions for objs_not_unborn *)
Theorem is_label_id: forall s s', Sys.eq s s' ->
forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).
Proof.
intros s s' Heq o lbl; split; intros Hlbl;
(eapply SC.isLabel_eq;
[eapply Ref.eq_refl
|eapply ObjectLabel.eq_refl
|eauto
|auto]).
Qed.
Theorem is_label_read: forall a t s s', Sys.eq (Sem.do_read a t s) s' ->
forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).
Proof.
intros a t s s' Heq;
eapply Sys.eq_trans in Heq;
[eapply is_label_id; eauto
| eapply Sys.eq_sym; eapply Sem.read_spec].
Qed.
Theorem is_label_write: forall a t s s', Sys.eq (Sem.do_write a t s) s' ->
forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).
Proof.
intros a t s s' Heq;
eapply Sys.eq_trans in Heq;
[eapply is_label_id; eauto
| eapply Sys.eq_sym; eapply Sem.write_spec].
Qed.
Theorem is_label_fetch_invalid: forall a t c i s s', Sys.eq (Sem.do_fetch a t c i s) s' ->
~ SemDefns.fetch_preReq a t s ->
forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).
Proof.
intros a t c i s s' Heq Hprereq.
eapply Sys.eq_trans in Heq;
[ eapply is_label_id; eauto
| eapply Sys.eq_sym; eapply Sem.fetch_invalid; eauto].
Qed.
Theorem is_label_copyCap: forall c t i a s s', Sys.eq (SemDefns.SC.copyCap c t i a s) s' ->
forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).
Proof.
intros c t i a s s' Heq o lbl; split; intros Hlbl; unfold SC.is_label in *;
(* first case *)
(case (option_sumbool (SC.getLabel o s)); intros Hcase; [|destruct Hcase as [tup Hcase]];
try rewrite Hcase in *; simpl in *; try solve [contradiction];
(* second case *)
(case (option_sumbool (SC.getLabel o s')); intros Hcase'; [|destruct Hcase' as [tup' Hcase']];
try rewrite Hcase' in *; simpl in *; try solve [contradiction];
(* getLabel equiv and solv *)
(eapply SC.getLabel_copyCap_map_eq_equiv in Hcase'; [ | eapply Heq | apply Hcase ]; simpl in *;
try solve
[contradiction
| eapply ObjectLabel.eq_trans; solve [eauto | eapply ObjectLabel.eq_sym; eauto]]))).
Qed.
(* move the next two Theorems to systemstate_convimpl *)
Theorem getLabel_weakCopyCap_map_eq: forall s i o i' o' i_src opt_i_lbl opt_i_lbl',
SC.getLabel i_src s = opt_i_lbl ->
SC.getLabel i_src (SC.weakCopyCap i o i' o' s) = opt_i_lbl' ->
option_map_eq ObjectLabel.eq opt_i_lbl opt_i_lbl'.
Proof.
intros s i o i' o' i_src opt_i_lbl opt_i_lbl' Hi_lbl Hi_lbl'.
unfold SC.weakCopyCap in *; unfold SC.getCap in *; unfold SC.getObj in *.
case (option_sumbool (SC.getObjTuple o s)); intros Hopt1;
[| destruct Hopt1 as [o'_tuple Hopt1]]; rewrite Hopt1 in *; simpl in *; auto;
try solve [rewrite <- Hi_lbl; rewrite <- Hi_lbl'; eapply option_map_eq_refl; eauto].
destruct_tuple o'_tuple o'_obj o'_lbl o'_type o'_sched; simpl in *.
case (option_sumbool (OC.getCap i o'_obj)); intros Hopt2;
[| destruct Hopt2 as [copied_cap Hopt2]]; rewrite Hopt2 in *; simpl in *; auto;
try solve [rewrite <- Hi_lbl; rewrite <- Hi_lbl'; eapply option_map_eq_refl; eauto].
unfold SC.addCap in *; unfold SC.getLabel in *;
unfold SC.getObj in *; unfold SC.updateObj in *.
case (option_sumbool (SC.getObjTuple o' s)); intros Hopt3;
[|destruct Hopt3 as [t_tuple Hopt3]; destruct_tuple t_tuple t_obj t_lbl t_type t_sched];
rewrite Hopt3 in *; simpl in *;
try solve [rewrite <- Hi_lbl; rewrite <- Hi_lbl'; eapply option_map_eq_refl; eauto].
unfold SC.addObjTuple in *; unfold SC.getObjTuple in *; unfold OC.addCap in *.
case (Ref.eq_dec o' i_src ); intros Heq1.
(* i_src [=] o' *)
rewrite Sys_Facts.add_eq_o in Hi_lbl'; simpl in *; auto.
unfold SC.tupleGetLabel in *.
rewrite Heq1 in *; rewrite Hopt3 in *; simpl in *;
try solve [rewrite <- Hi_lbl; rewrite <- Hi_lbl'; eapply option_map_eq_refl; eauto].
(* i_src [<>] o' *)
rewrite Sys_Facts.add_neq_o in Hi_lbl'; simpl in *; auto;
try solve [rewrite <- Hi_lbl; rewrite <- Hi_lbl'; eapply option_map_eq_refl; eauto].
Qed.
Theorem getLabel_weakCopyCap_map_eq_equiv: forall s i o i' o' i_src s' opt_i_lbl opt_i_lbl',
Sys.eq (SC.weakCopyCap i o i' o' s) s' ->
SC.getLabel i_src s = opt_i_lbl ->
SC.getLabel i_src s' = opt_i_lbl' ->
option_map_eq ObjectLabel.eq opt_i_lbl opt_i_lbl'.
Proof.
intros.
eapply option_map_eq_transitive;
[eauto
|
|rewrite <- H1; eapply SC.getLabel_eq; [eapply Ref.eq_refl| eapply H]].
rewrite <- H0.
eapply getLabel_weakCopyCap_map_eq; eapply eq_refl.
Qed.
Theorem is_label_weakCopyCap: forall c t i a s s', Sys.eq (SemDefns.SC.weakCopyCap c t i a s) s' ->
forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).
Proof.
intros c t i a s s' Heq o lbl; split; intros Hlbl; unfold SC.is_label in *;
(* first case *)
(case (option_sumbool (SC.getLabel o s)); intros Hcase; [|destruct Hcase as [tup Hcase]];
try rewrite Hcase in *; simpl in *; try solve [contradiction];
(* second case *)
(case (option_sumbool (SC.getLabel o s')); intros Hcase'; [|destruct Hcase' as [tup' Hcase']];
try rewrite Hcase' in *; simpl in *; try solve [contradiction];
(* getLabel equiv and solv *)
(eapply getLabel_weakCopyCap_map_eq_equiv in Hcase'; [ | eapply Heq | apply Hcase ]; simpl in *;
try solve
[contradiction
| eapply ObjectLabel.eq_trans; solve [eauto | eapply ObjectLabel.eq_sym; eauto]]))).
Qed.
Theorem is_label_fetch_valid: forall a t c i s s', Sys.eq (Sem.do_fetch a t c i s) s' ->
SemDefns.fetch_preReq a t s ->
forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).
Proof.
intros a t c i s s' Heq Hfetch_prereq.
case (SemDefns.option_hasRight_dec (SemDefns.SC.getCap t a s) rd); intros Hread'.
generalize Hfetch_prereq; intros [Hprereq Hopt];
eapply Sys.eq_trans in Heq;
[
| eapply Sys.eq_sym; eapply Sem.fetch_read; eauto].
(* has read *)
destruct Hprereq as [[Halive Hactive] Htarget_alive].
unfold SemDefns.target_is_alive in *.
case (option_sumbool (SemDefns.SC.getCap t a s)); intros Hcap; [| destruct Hcap as [cap Hcap]];
rewrite Hcap in *; simpl in *; try contradiction.
eapply is_label_copyCap; eauto.
(* no read *)
generalize Hfetch_prereq; intros [Hprereq [Hread | Hweak]]; try contradiction.
eapply Sys.eq_trans in Heq;
[
| eapply Sys.eq_sym; eapply Sem.fetch_weak; eauto].
destruct Hprereq as [[Halive Hactive] Htarget_alive].
unfold SemDefns.target_is_alive in *.
case (option_sumbool (SemDefns.SC.getCap t a s)); intros Hcap; [| destruct Hcap as [cap Hcap]];
rewrite Hcap in *; simpl in *; try contradiction.
unfold SC.weakCopyCap in *.
eapply is_label_weakCopyCap; eauto.
Qed.
Theorem is_label_store_invalid: forall a t c i s s', Sys.eq (Sem.do_store a t c i s) s' ->
~ SemDefns.store_preReq a t s ->
forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).
Proof.
intros a t c i s s' Heq Hprereq.
eapply Sys.eq_trans in Heq;
[ eapply is_label_id; eauto
| eapply Sys.eq_sym; eapply Sem.store_invalid; eauto].
Qed.
Theorem is_label_store_valid: forall a t c i s s', Sys.eq (Sem.do_store a t c i s) s' ->
SemDefns.store_preReq a t s ->
forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).
Proof.
intros a t c i s s' Heq Hstore_prereq.
generalize Hstore_prereq; intros [Hprereq Hright];
eapply Sys.eq_trans in Heq; [ | eapply Sys.eq_sym; eapply Sem.store_valid; eauto].
destruct Hprereq as [[Halive Hactive] Htarget_alive].
unfold SemDefns.target_is_alive in *.
case (option_sumbool (SemDefns.SC.getCap t a s)); intros Hcap; [| destruct Hcap as [cap Hcap]];
rewrite Hcap in *; simpl in *; try contradiction.
eapply is_label_copyCap; eauto.
Qed.
Theorem is_label_revoke_invalid: forall a t c s s', Sys.eq (Sem.do_revoke a t c s) s' ->
~ SemDefns.revoke_preReq a t s ->
forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).
Proof.
intros a t c s s' Heq Hprereq.
eapply Sys.eq_trans in Heq;
[ eapply is_label_id; eauto
| eapply Sys.eq_sym; eapply Sem.revoke_invalid; eauto].
Qed.
Theorem getLabel_updateObj_equiv: forall n o s s',
Sys.eq (SC.updateObj n o s) s' -> forall a,
SC.getLabel a s = SC.getLabel a s'.
Proof.
unfold SC.updateObj.
unfold SC.getLabel.
unfold SC.getObj.
unfold SC.addObjTuple.
unfold SC.getObjTuple.
intros.
case (option_sumbool (Sys.MapS.find n s)); intros Hcase; [|destruct Hcase as [[[[o' l'] t'] d'] Hcase]];
rewrite Hcase in *; simpl in *; auto.
(* equiv *)
generalize (Sys_MapEquiv.find_eq a _ _ _ (Ref.eq_refl _) H); intros Heq.
case (option_sumbool (Sys.MapS.find a s));intros Hcase1;
[|destruct Hcase1 as [tup1 Hcase1]]; rewrite Hcase1 in *; simpl in *;
(case (option_sumbool (Sys.MapS.find a s'));intros Hcase2;
[|destruct Hcase2 as [tup2 Hcase2]]; rewrite Hcase2 in *; simpl in *);
try contradiction; auto.
unfold SC.tupleGetLabel.
destruct tup1 as [[[obj1 lbl1] sch1] typ1];
destruct tup2 as [[[obj2 lbl2] sch2] typ2];
destruct Heq as [[[Heq1 Heq2] Heq3] Heq4]; simpl in *.
rewrite Heq2 in *; auto.
(* not equiv *)
generalize (Sys_MapEquiv.find_eq a _ _ _ (Ref.eq_refl _) H); intros Heq.
case (Ref.eq_dec a n); intros Heq_r.
rewrite Sys_Facts.add_eq_o in Heq; simpl in *; auto; try contradiction.
unfold Sys.P.t in *.
case (option_sumbool (Sys.MapS.find a s));intros Hcase1;
[|destruct Hcase1 as [tup1 Hcase1]]; rewrite Hcase1 in *; simpl in *;
(case (option_sumbool (Sys.MapS.find a s'));intros Hcase2;
[|destruct Hcase2 as [tup2 Hcase2]]; rewrite Hcase2 in *; simpl in *);
try contradiction; auto; simpl in *;
(try destruct tup1 as [[[obj1 lbl1] sch1] typ1];
destruct tup2 as [[[obj2 lbl2] sch2] typ2];
destruct Heq as [[[Heq1 Heq2] Heq3] Heq4]; simpl in *;
rewrite Heq2 in *; auto;
rewrite Heq_r in *;
rewrite Hcase in *;
try solve [discriminate | injection Hcase1; intros H1 H2 H3 H4; rewrite H3; auto]).
rewrite Sys_Facts.add_neq_o in Heq; simpl in *; auto; try contradiction.
unfold Sys.P.t in *.
case (option_sumbool (Sys.MapS.find a s));intros Hcase1;
[|destruct Hcase1 as [tup1 Hcase1]]; rewrite Hcase1 in *; simpl in *;
(case (option_sumbool (Sys.MapS.find a s'));intros Hcase2;
[|destruct Hcase2 as [tup2 Hcase2]]; rewrite Hcase2 in *; simpl in *);
try contradiction; auto; simpl in *.
try destruct tup1 as [[[obj1 lbl1] sch1] typ1];
destruct tup2 as [[[obj2 lbl2] sch2] typ2];
destruct Heq as [[[Heq1 Heq2] Heq3] Heq4]; simpl in *.
rewrite Heq2; auto.
Qed.
Implicit Arguments getLabel_updateObj_equiv [n o s s'].
Theorem is_label_rmCap: forall c t s s', Sys.eq (SC.rmCap c t s) s' ->
forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).
Proof.
intros c t s s' Heq o lbl; split; intros Hlbl; unfold SC.is_label in *;
unfold SC.rmCap in *;
(case (option_sumbool (SC.getObj t s)); intros Hcase2; [| destruct Hcase2 as [obj Hcase2]];
try rewrite Hcase2 in *; simpl in *; try contradiction);
solve [
(* equiv case *)
case (option_sumbool (SC.getLabel o s')); intros Hcase'; [|destruct Hcase' as [tup' Hcase']];
try rewrite Hcase' in *; simpl in *; try solve [contradiction];
(case (option_sumbool (SC.getLabel o s)); intros Hcase; [|destruct Hcase as [tup Hcase]];
try rewrite Hcase in *; simpl in *; try solve [contradiction];
(eapply SC.getLabel_eq with (r:=o) in Heq; [| eapply Ref.eq_refl];
rewrite Hcase in Heq; rewrite Hcase' in Heq; simpl in *;
solve [contradiction
| eapply ObjectLabel.eq_trans; solve [eapply Sys.eq_sym; eauto | eauto]]))
|
(* second *)
generalize (getLabel_updateObj_equiv Heq); intros Hrw;
rewrite Hrw in *; auto].
Qed.
Theorem is_label_revoke_valid: forall a t c s s', Sys.eq (Sem.do_revoke a t c s) s' ->
SemDefns.revoke_preReq a t s ->
forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).
Proof.
intros a t c s s' Heq Hrevoke_prereq.
generalize Hrevoke_prereq; intros [Hprereq Hright];
eapply Sys.eq_trans in Heq; [ | eapply Sys.eq_sym; eapply Sem.revoke_valid; eauto].
destruct Hprereq as [[Halive Hactive] Htarget_alive].
unfold SemDefns.target_is_alive in *.
case (option_sumbool (SemDefns.SC.getCap t a s)); intros Hcap; [| destruct Hcap as [cap Hcap]];
rewrite Hcap in *; simpl in *; try contradiction.
eapply is_label_rmCap; eauto.
Qed.
Theorem is_label_copyCapList: forall c t ixi_list s s', Sys.eq (SC.copyCapList c t ixi_list s) s' ->
forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).
Proof.
intros c t ixi_list s s' Heq o lbl; split; intros Hlbl; unfold SC.is_label in *;
(* first case *)
(case (option_sumbool (SC.getLabel o s)); intros Hcase; [|destruct Hcase as [tup Hcase]];
try rewrite Hcase in *; simpl in *; try solve [contradiction];
(* second case *)
(case (option_sumbool (SC.getLabel o s')); intros Hcase'; [|destruct Hcase' as [tup' Hcase']];
try rewrite Hcase' in *; simpl in *; try solve [contradiction];
(* getLabel equiv and solv *)
(eapply SC.getLabel_copyCapList_map_eq_equiv in Hcase'; [ | eapply Heq | apply Hcase ]; simpl in *;
try solve
[contradiction
| eapply ObjectLabel.eq_trans; solve [eauto | eapply ObjectLabel.eq_sym; eauto]]))).
Qed.
Theorem is_label_addCap: forall c a cap s s', Sys.eq (SC.addCap c cap a s) s' ->
forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).
Proof.
intros c a cap s s' Heq o lbl; split; intros Hlbl; unfold SC.is_label in *;
unfold SC.addCap in *; unfold SC.getObj in *;
(case (option_sumbool (SC.getObjTuple a s)); intros Htuple; [| destruct Htuple as [[[[obj1 lbl1] typ1] schd1] Htuple]];
rewrite Htuple in *; simpl in *; try contradiction;
(case (option_sumbool (SC.getLabel o s)); intros Hcase; [|destruct Hcase as [tup Hcase]];
try rewrite Hcase in *; simpl in *; try solve [contradiction];
(case (option_sumbool (SC.getLabel o s')); intros Hcase'; [|destruct Hcase' as [tup' Hcase']];
try rewrite Hcase' in *; simpl in *; try solve [contradiction])));
try solve [
(* Solve s [=] s' cases *)
first
[ generalize (getLabel_updateObj_equiv Heq o); intros Hlbl_eq
| generalize (SC.getLabel_eq _ _ _ _ (Ref.eq_refl o) Heq); intros Hlbl_eq
];
try rewrite Hcase' in Hlbl_eq; try rewrite Hcase in Hlbl_eq; try rewrite Hlbl_eq in *; simpl in *;
(* attempt solutions *)
try contradiction; try discriminate; auto;
try solve [injection Hlbl_eq; intros Hlbl_eq'; rewrite Hlbl_eq' in *; auto]].
Qed.
Theorem is_label_send_valid: forall a t c i s s', Sys.eq (Sem.do_send a t c i s) s' ->
SemDefns.send_preReq a t s ->
forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).
Proof.
intros a t c i s s' Heq Hsend_prereq.
generalize Hsend_prereq; intros [Hprereq Hright];
eapply Sys.eq_trans in Heq; [ | eapply Sys.eq_sym; eapply Sem.send_valid; eauto].
destruct Hprereq as [[Halive Hactive] Htarget_alive].
unfold SemDefns.target_is_alive in *.
case (option_sumbool (SemDefns.SC.getCap t a s)); intros Hcap; [| destruct Hcap as [cap Hcap]];
rewrite Hcap in *; simpl in *; try contradiction.
case (option_sumbool i); intros Hi; [|destruct Hi as [i' Hi]]; rewrite Hi in *; simpl in *.
(* no reply *)
eapply is_label_copyCapList; eauto.
(* has reply *)
intros o lbl.
eapply Sys.eq_trans in Heq;
[|eapply SC.copyCapList_eq; [ eapply Ref.eq_refl | apply Ref.eq_refl | eapply CIL_Facts.cil_Equiv| ]].
eapply iff_sym; eapply iff_trans; eapply iff_sym.
eapply is_label_copyCapList; apply Heq.
2:apply Sys.eq_refl.
eapply is_label_addCap; eapply Sys.eq_refl.
Qed.
Theorem is_label_send_invalid: forall a t c i s s', Sys.eq (Sem.do_send a t c i s) s' ->
~ SemDefns.send_preReq a t s ->
forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).
Proof.
intros a t c i s s' Heq Hprereq.
eapply Sys.eq_trans in Heq;
[ eapply is_label_id; eauto
| eapply Sys.eq_sym; eapply Sem.send_invalid; eauto].
Qed.
Theorem is_label_allocate_invalid: forall a t c i s s', Sys.eq (Sem.do_allocate a t c i s) s' ->
~ SemDefns.allocate_preReq a t s ->
forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).
Proof.
intros a t c i s s' Heq Hprereq.
eapply Sys.eq_trans in Heq;
[ eapply is_label_id; eauto
| eapply Sys.eq_sym; eapply Sem.allocate_invalid; eauto].
Qed.
Theorem is_label_allocate_valid: forall a t c i s s', Sys.eq (Sem.do_allocate a t c i s) s' ->
SemDefns.allocate_preReq a t s ->
forall o lbl, (if (Ref.eq_dec o t) then
SC.is_label o s unborn /\ ObjectLabel.eq lbl alive
else SC.is_label o s lbl) <->
SC.is_label o s' lbl.
Proof.
intros a t c i s s' Heq Hallocate_prereq o lbl.
generalize Hallocate_prereq; intros [Halive Hunborn];
eapply Sys.eq_trans in Heq; [ | eapply Sys.eq_sym; eapply Sem.allocate_valid; eauto].
generalize Hunborn; intros Hunborn'; eapply SC.is_label_iff_getLabel in Hunborn.
eapply Sys.eq_trans in Heq.
2:eapply SC.addCap_eq; [ eapply Ind.eq_refl| eapply Cap.eq_refl | eapply Ref.eq_refl| ].
eapply iff_trans.
2:eapply is_label_addCap; apply Heq.
2:apply Sys.eq_refl.
clear Heq.
eapply iff_trans.
2:eapply is_label_copyCapList;eapply Sys.eq_refl.
(* cases of o [=] t *)
case (Ref.eq_dec o t); intros Href_case.
(* o [=] t *)
rewrite Href_case in *.
unfold SC.set_alive.
unfold SC.is_label in *.
unfold SC.is_unborn in *.
rewrite SC.getLabel_set_label_eq_o; simpl; try apply Ref.eq_refl.
rewrite SC.getLabel_updateObj_o.
rewrite SC.getLabel_rmCapsByTarget_o.
rewrite Hunborn in *; simpl.
intuition (eauto; try apply ObjectLabel.eq_sym; auto).
(* o [<>] t *)
unfold SC.set_alive in *.
unfold SC.is_label in *.
unfold SC.is_unborn in *.
rewrite SC.getLabel_set_label_neq_o; auto.
rewrite SC.getLabel_updateObj_o.
rewrite SC.getLabel_rmCapsByTarget_o; auto.
eapply iff_refl.
Qed.
Implicit Arguments is_label_allocate_valid [a t c i s s' o lbl].
Theorem is_label_allocate_valid_unborn: forall a t c i s s', Sys.eq (Sem.do_allocate a t c i s) s' ->
SemDefns.allocate_preReq a t s ->
forall lbl, ObjectLabel.eq lbl unborn ->
forall o, SC.is_label o s' lbl -> SC.is_label o s lbl.
Proof.
intros.
eapply is_label_allocate_valid in H2; try eauto 1.
revert H2; case (Ref.eq_dec o t); intros Hcase H2; intuition.
eapply ObjectLabel.eq_trans in H1; [|apply ObjectLabel.eq_sym; apply H4]; discriminate H1.
Qed.
Require Import OptionMap2.
Theorem is_label_destroy_valid: forall a t s s', Sys.eq (Sem.do_destroy a t s) s' ->
SemDefns.destroy_preReq a t s ->
forall o lbl, (if (option_map_eq_dec Ref.eq_dec (Some o) (SemDefns.option_target (SC.getCap t a s))) then
SC.is_label o s alive /\ ObjectLabel.eq lbl dead
else SC.is_label o s lbl) <->
SC.is_label o s' lbl.
Proof.
intros a t s s' Heq Hdestroy_prereq o lbl.
generalize Hdestroy_prereq; intros [[[Halive Hactive] Htarget_alive] Hwrite];
eapply Sys.eq_trans in Heq; [ | eapply Sys.eq_sym; eapply Sem.destroy_valid; eauto].
unfold SemDefns.target_is_alive in *.
unfold SC.getCap in *.
unfold SC.getObj in *.
case (option_sumbool (SC.getObjTuple a s)) as [Hcase | [[[[obj1 lbl1] typ1] sch1] Hcase]];
rewrite Hcase in *; simpl in *; try contradiction;
(case (option_sumbool (OC.getCap t obj1)) as [Hcase2 | [cap Hcase2]];
rewrite Hcase2 in *; simpl in*; try contradiction).
unfold SC.is_alive in *.
clear Hcase Hcase2 Hwrite.
revert Heq Htarget_alive. generalize (Cap.target cap). intros target Heq Htarget_alive.
clear obj1 lbl1 typ1 sch1. clear cap.
clear Hactive.
unfold SC.set_dead in *.
idtac.
eapply iff_trans; [ clear Heq |
apply SC.is_label_eq_iff; [ apply Ref.eq_refl| apply Heq | apply ObjectLabel.eq_refl]].
case (option_map_eq_dec Ref.eq_dec (Some o) (Some target)) as [Heq_t|Heq_t]; simpl in *.
unfold Ref.eq in Heq_t; rewrite Heq_t in *.
(* target [=] o] *)
rewrite SC.is_label_set_label_eq_o; [| apply Ref.eq_sym; auto].
generalize Htarget_alive; intros Htarget_alive'.
eapply SC.is_label_iff_getLabel in Htarget_alive.
rewrite Htarget_alive.
intuition.
(* target [<>] o *)
rewrite SC.is_label_set_label_neq_o; [apply iff_refl| intro; apply Heq_t; apply Ref.eq_sym; auto].
Qed.
Implicit Arguments is_label_destroy_valid [a t s s' o lbl].
Theorem is_label_destroy_valid_unborn: forall a t s s', Sys.eq (Sem.do_destroy a t s) s' ->
SemDefns.destroy_preReq a t s ->
forall lbl, ObjectLabel.eq lbl unborn ->
forall o, SC.is_label o s' lbl -> SC.is_label o s lbl.
Proof.
intros.
eapply is_label_destroy_valid in H2; try eauto 1.
revert H2; case (option_map_eq_dec Ref.eq_dec (Some o) (SemDefns.option_target (SC.getCap t a s)));
intros Hcase H2; intuition.
eapply ObjectLabel.eq_trans in H1; [|apply ObjectLabel.eq_sym; apply H4]; discriminate H1.
Qed.
Theorem is_label_destroy_invalid: forall a t s s', Sys.eq (Sem.do_destroy a t s) s' ->
~ SemDefns.destroy_preReq a t s ->
forall o lbl, (SC.is_label o s lbl <-> SC.is_label o s' lbl).
Proof.
intros a t s s' Heq Hprereq.
eapply Sys.eq_trans in Heq;
[ eapply is_label_id; eauto
| eapply Sys.eq_sym; eapply Sem.destroy_invalid; eauto].
Qed.
Theorem set_label_eq: forall t t', Ref.eq t t' ->
forall l l', ObjectLabel.eq l l' ->
forall s s', Sys.eq s s' ->
Sys.eq (SC.set_label t s l) (SC.set_label t' s' l').
Proof.
intros.
unfold SC.set_label in *.
generalize (SC.getObjTuple_eq _ _ _ _ H H1); intros Heq_tuple.
case (option_sumbool (SC.getObjTuple t s)) as [Hcase | [[[[obj lbl] sch] typ] Hcase]];
rewrite Hcase in *; simpl in *;
(case (option_sumbool (SC.getObjTuple t' s')) as [Hcase' | [[[[obj' lbl'] sch'] typ'] Hcase']];
rewrite Hcase' in *; simpl in *; try contradiction; eauto).
destruct Heq_tuple as [[[Hobj Hlbl] Hsch] Htyp]; simpl in *.
eapply SC.addObjTuple_eq; eauto; try apply Ref.eq_refl.
unfold ObjectLabel.eq in *. rewrite H0; rewrite Hsch; rewrite Hobj; rewrite Htyp.
eapply Sys.P.eq_refl.
Qed.
(* we need a theorem about objs_not_unborn n s -> Exe.execute_def s list s' -> objs_not_unborn n s' *)
Theorem objs_not_unborn_op: forall n s, objs_not_unborn n s ->
forall op s', Sys.eq (Sem.do_op op s) s' -> objs_not_unborn n s'.
Proof.
intros n s Hobjs op s' H.
unfold objs_not_unborn in *.
intros x Hx Hnot.
eapply Hobjs.
apply Hx.
unfold SC.is_unborn in *.
(* cases *)
destruct op. simpl in *.
(* read *)
eapply is_label_read; eauto.
(* write *)
eapply is_label_write; eauto.
(* fetch *)
case (SemDefns.fetch_preReq_dec t t0 s); intros Hcase;
solve [ eapply is_label_fetch_valid; eauto | eapply is_label_fetch_invalid; eauto].
(* store *)
case (SemDefns.store_preReq_dec t t0 s); intros Hcase;
solve [ eapply is_label_store_valid; eauto | eapply is_label_store_invalid; eauto].
(* revoke *)
case (SemDefns.revoke_preReq_dec t t0 s); intros Hcase;
solve [ eapply is_label_revoke_valid; eauto | eapply is_label_revoke_invalid; eauto].
(* send *)
case (SemDefns.send_preReq_dec t t0 s); intros Hcase;
solve [ eapply is_label_send_valid; eauto | eapply is_label_send_invalid; eauto].
(* allocate *)
case (SemDefns.allocate_preReq_dec t t0 s); intros Hcase;
solve
[ eapply is_label_allocate_valid_unborn; solve [eauto; apply ObjectLabel.eq_refl]
| eapply is_label_allocate_invalid; eauto
].
(* destroy *)
case (SemDefns.destroy_preReq_dec t t0 s); intros Hcase;
solve
[ eapply is_label_destroy_valid_unborn; solve [eauto; apply ObjectLabel.eq_refl]
| eapply is_label_destroy_invalid; eauto
].
Qed.
Theorem objs_not_unborn_oplist : forall n s, objs_not_unborn n s ->
forall opL s', Exe.execute_def s opL s' -> objs_not_unborn n s'.
Proof.
intros n s Hobjs opL s' Hexe.
induction Hexe.
(* base *)
unfold objs_not_unborn in *.
intros x Hx Hnot.
eapply Hobjs.
apply Hx.
unfold SC.is_unborn in *.
eapply SC.isLabel_eq in Hnot.
apply Hnot.
apply Ref.eq_refl.
apply ObjectLabel.eq_refl.
apply Sys.eq_sym; apply H.
(* step *)
eapply objs_not_unborn_op; eauto.
Qed.
Theorem Proper_objs_not_unborn :
Proper (RefSet.Subset --> Sys.eq ==> impl) objs_not_unborn.
Proof.
unfold Proper; unfold respectful; unfold impl; unfold flip; intros.
unfold objs_not_unborn in *.
intros e Hin.
eapply H in Hin.
generalize (H1 e Hin); clear H1; intros H1.
intro Hnot. apply H1.
eapply SC.isLabel_eq;
[ apply Ref.eq_refl | apply ObjectLabel.eq_refl | apply Sys.eq_sym; apply H0 | apply Hnot].
Qed.
Ltac try_solve_potAcc_op_id_case Hp_objs Hp'_objs Hunborn2:=
let Heq := fresh "Heq" in
try solve [ generalize (ag_objs_spec_equiv _ _ _ _ Hp_objs Hp'_objs (AG.eq_refl _)); intros Heq;
eapply Proper_objs_not_unborn; unfold flip;
[ apply RefSetProps.subset_equal; apply RefSet.eq_sym; apply Heq
| apply Sys.eq_refl | apply Hunborn2]].
Theorem ag_objs_spec_insert: forall p p_objs, Seq.ag_objs_spec p p_objs ->
forall a n p'_objs, Seq.ag_objs_spec (insert a n p) p'_objs ->
RefSet.eq p'_objs (RefSet.add a (RefSet.add n p_objs)).
Proof.
intros.
unfold insert in *.
generalize (Seq.ag_objs_spec_ag_objs (ag_add_cap a (Cap.mkCap n all_rights) p)).
generalize (Seq.ag_objs (ag_add_cap a (Cap.mkCap n all_rights) p)).
intros mid_objs Hmid_objs.
rewrite ag_objs_spec_add_cap_equiv_nonempty with (objs':=p'_objs);
[ rewrite CC.mkCap_target
| apply Hmid_objs
| rewrite CC.mkCap_rights; intro Hnot; apply Hnot with tx; eapply in_all_rights
| apply H0
].
rewrite ag_objs_spec_add_cap_equiv_nonempty with (objs':=mid_objs);
[ rewrite CC.mkCap_target
| apply H
| rewrite CC.mkCap_rights; intro Hnot; apply Hnot with tx; eapply in_all_rights
| apply Hmid_objs
].
rewrite RefSetAddEq.double_add;
rewrite RefSetProps.add_add;
rewrite RefSetAddEq.double_add.
eapply RefSet.eq_refl.
Qed.
Theorem ag_objs_spec_endow: forall p p_objs, Seq.ag_objs_spec p p_objs ->
forall a n p'_objs, Seq.ag_objs_spec (endow a n p) p'_objs ->
RefSet.eq p'_objs (RefSet.add a (RefSet.add n p_objs)).
Proof.
intros. unfold endow in *.
generalize (Seq.potAcc_potAcc_fun (insert a n p)); intros Hpa.
destruct Hpa as [Htrans _].
eapply ag_objs_spec_potTransfer in Htrans; eauto.
eapply ag_objs_spec_equiv in H0; [ | apply Htrans | apply AG.eq_refl].
rewrite <- H0 in *.
clear H0 Htrans; clear p'_objs.
eapply ag_objs_spec_insert; eauto.
Qed.
Theorem getLabel_addCap_map_eq_inline: forall r i c o s,
option_map_eq ObjectLabel.eq (SC.getLabel r (SC.addCap i c o s)) (SC.getLabel r s).
Proof.
intros.
generalize (option_map_eq_Equiv _ ObjectLabelEQ); intros [EQ_refl EQ_sym EQ_trans].
eapply EQ_sym.
eapply SC.getLabel_addCap_map_eq; eapply eq_refl.
Qed.
Theorem getLabel_copyCapList_map_eq_inline: forall s o t ixi_list i_src,
option_map_eq ObjectLabel.eq (SC.getLabel i_src (SC.copyCapList o t ixi_list s)) (SC.getLabel i_src s).
Proof.
intros.
generalize (option_map_eq_Equiv _ ObjectLabelEQ); intros [EQ_refl EQ_sym EQ_trans].
eapply EQ_sym; eapply SC.getLabel_copyCapList_map_eq; eapply eq_refl.
Qed.
Theorem is_label_allocate_not_unborn : forall lbl, ~ ObjectLabel.eq lbl unborn ->
forall x s, SC.is_label x s lbl ->
forall a t t' l s', Sys.eq (Sem.do_allocate a t t' l s) s' ->
SC.is_label x s' lbl.
Proof.
intros.
case (SemDefns.allocate_preReq_dec a t s); intros Hcase;
(eapply Sys.eq_trans in H1;
[
| eapply Sys.eq_sym; solve
[eapply Sem.allocate_valid; eauto
| eapply Sem.allocate_invalid; eauto]]);
try solve[ eapply SC.isLabel_eq; [ apply Ref.eq_refl| apply ObjectLabel.eq_refl | apply H1 | apply H0]].
(* allocate occrus*)
generalize Hcase; intros [[Halive Hactive] Hunborn].
eapply SC.is_label_iff_getLabel in Halive.
eapply SC.is_label_iff_getLabel in Hunborn.
eapply SC.is_label_iff_getLabel in H0.
unfold SC.is_label.
generalize (SC.getLabel_eq _ _ _ _ (Ref.eq_refl x) H1); intros Heq; clear H1.
(* this the main theorem what we want, how do we instantiate EQ options, playing with ones I can find*)
generalize (option_map_eq_Equiv _ ObjectLabelEQ); intros [EQ_refl EQ_sym EQ_trans].
unfold Transitive in *.
eapply EQ_trans in Heq;[|eapply EQ_sym; eapply getLabel_addCap_map_eq_inline].
eapply EQ_trans in Heq;[|eapply EQ_sym; eapply getLabel_copyCapList_map_eq_inline].
unfold SC.set_alive in *.
case (Ref.eq_dec x t); intros Hcase2; [unfold Ref.eq in Hcase2; rewrite Hcase2 in *|].
(* x = t *)
rewrite SC.getLabel_set_label_eq_o in Heq; try apply Ref.eq_refl.
rewrite SC.getLabel_updateObj_o in Heq.
rewrite SC.getLabel_rmCapsByTarget_o in Heq.
rewrite H0 in *.
inversion Hunborn as [Hlbl].
rewrite Hlbl in H.
generalize (H (ObjectLabel.eq_refl _)); intros; contradiction.
(* x <> t *)
rewrite SC.getLabel_set_label_neq_o in Heq; auto.
rewrite SC.getLabel_updateObj_o in Heq.
rewrite SC.getLabel_rmCapsByTarget_o in Heq.
(* there should really be a theorem for this *)
rewrite H0 in *.
case (option_sumbool (SC.getLabel x s')) as [Hcase3 | [lbl' Hcase3]];
rewrite Hcase3 in *; simpl in *; auto.
rewrite Heq. apply ObjectLabel.eq_refl.
Qed.
Theorem is_label_allocate_new_label : forall a t s, SemDefns.allocate_preReq a t s ->
forall t2 l s', Sys.eq (Sem.do_allocate a t t2 l s) s' ->
SC.is_label t s' alive.
Proof.
intros a t s Hprereq t2 l s' Heq.
generalize Hprereq; intros [[Halive Hactive] Hunborn].
eapply SC.is_label_iff_getLabel in Halive.
eapply SC.is_label_iff_getLabel in Hunborn.
eapply SC.is_label_iff_getLabel.
eapply Sys.eq_trans in Heq; [|eapply Sys.eq_sym; eapply Sem.allocate_valid; auto].
generalize (SC.getLabel_eq _ _ _ _ (Ref.eq_refl t) Heq); clear Heq; intros Heq.
generalize (option_map_eq_Equiv _ ObjectLabelEQ); intros [EQ_refl EQ_sym EQ_trans].
unfold Transitive in *.
eapply EQ_trans in Heq;[|eapply EQ_sym; eapply getLabel_addCap_map_eq_inline].
eapply EQ_trans in Heq;[|eapply EQ_sym; eapply getLabel_copyCapList_map_eq_inline].
unfold SC.set_alive in *.
rewrite SC.getLabel_set_label_eq_o in Heq; try apply Ref.eq_refl.
rewrite SC.getLabel_updateObj_o in Heq.
rewrite SC.getLabel_rmCapsByTarget_o in Heq.
rewrite Hunborn in *.
case (option_sumbool (SC.getLabel t s')) as [Hcase3 | [lbl' Hcase3]];
rewrite Hcase3 in *; simpl in *; auto; try contradiction.
rewrite Heq. apply eq_refl.
Qed.
Theorem objs_not_unborn_potAcc_op: forall p p_objs, Seq.ag_objs_spec p p_objs ->
forall s, objs_not_unborn p_objs s ->
forall op p'_objs, Seq.ag_objs_spec (potAcc_op op s p) p'_objs ->
forall s', Sys.eq (Sem.do_op op s) s' ->
objs_not_unborn p'_objs s'.
Proof.
intros p p_objs Hp_objs s Hp_objs_unborn op p'_objs Hp'_objs s' Hsys_eq.
generalize (objs_not_unborn_op _ _ Hp_objs_unborn _ _ Hsys_eq); intros Hunborn2.
destruct op; simpl in *; unfold id_ag in *;
try_solve_potAcc_op_id_case Hp_objs Hp'_objs Hunborn2.
unfold endow_dep in *.
revert Hp'_objs; case (SemDefns.allocate_preReq_dec t t0 s); intros Hcase Hp'_objs;
try_solve_potAcc_op_id_case Hp_objs Hp'_objs Hunborn2.
eapply Proper_objs_not_unborn; unfold flip;
[ eapply RefSetProps.subset_equal; eapply ag_objs_spec_endow; [apply Hp_objs | apply Hp'_objs ]
| eapply Sys.eq_refl
|].
clear Hp'_objs Hp_objs_unborn Hp_objs.
unfold objs_not_unborn in *.
intros x Hin.
eapply RefSetProps.Add_add in Hin.
destruct Hin as [Hin | Hin].
(* t = x *)
rewrite Hin in *.
generalize Hcase; intros [[Halive Hactive] Hunborn].
eapply is_label_allocate_not_unborn in Halive; [ | intro Hnot; discriminate Hnot| apply Hsys_eq].
intro Hnot.
unfold SC.is_unborn in *.
eapply SC.is_label_iff_getLabel in Hnot.
eapply SC.is_label_iff_getLabel in Halive.
rewrite Halive in Hnot.
discriminate.
eapply RefSetProps.Add_add in Hin.
destruct Hin as [Hin|Hin].
(* t0 = x *)
rewrite Hin in *.
generalize Hcase; intros [[Halive Hactive] Hunborn].
idtac.
generalize Hcase; intros Halive'.
eapply is_label_allocate_new_label in Halive'; [ | eapply Hsys_eq].
eapply SC.is_label_iff_getLabel in Halive'. unfold SC.is_unborn. intro Hnot.
eapply SC.is_label_iff_getLabel in Hnot.
rewrite Halive' in Hnot.
discriminate Hnot.
(* induction hypothesis *)
eapply Hunborn2; eauto.
Qed.
Theorem objs_not_unborn_potAcc_execute_spec: forall p p_objs, Seq.ag_objs_spec p p_objs ->
forall s, objs_not_unborn p_objs s ->
forall op_list Fp', potAcc_execute_spec op_list Fp' ->
forall Fp'_objs, Seq.ag_objs_spec (Fp' s p) Fp'_objs ->
forall s', Exe.execute_def s op_list s' ->
objs_not_unborn Fp'_objs s'.
Proof.
intros p p_objs Hp_objs s Hp_objs_unborn op_list Fp' Hpax.
induction Hpax; intros Fp'_objs HFp'_objs s' Hexe.
eapply ag_objs_spec_equiv in Hp_objs; [ | apply HFp'_objs | apply AG.eq_refl ].
inversion Hexe.
red; intros. eapply Hp_objs in H0. eapply Hp_objs_unborn in H0.
intros Hnot; apply H0.
eapply SC.isLabel_eq;
[ eapply Ref.eq_refl | eapply ObjectLabel.eq_refl | eapply Sys.eq_sym; eapply H | eapply Hnot].
(* step *)
unfold compose in *.
inversion Hexe.
generalize (Seq.ag_objs_spec_ag_objs (Fp s p)); generalize (Seq.ag_objs (Fp s p)); intros ag_objs' Hag_objs'.
eapply objs_not_unborn_potAcc_op;
[apply Hag_objs'
|
| apply HFp'_objs
|
]; [eapply IHHpax; eauto; eapply Exe.execute_spec; eapply Sys.eq_refl|].
inversion Hexe.
eapply Exe.execute_spec in H6.
eapply Sys.eq_trans; [ | eapply H8].
eapply SemConv.do_op_eq.
eapply H6.
Qed.
Theorem potAcc_execute_spec_potAcc: forall p, Seq.maxTransfer p ->
forall op_list Fp', potAcc_execute_spec op_list Fp' -> forall s, Seq.maxTransfer (Fp' s p).
Proof.
intros p Hmax op_list Fp' Hpax s.
induction Hpax; eauto.
(* step *)
unfold compose.
unfold potAcc_op.
destruct op; unfold id_ag; simpl;
(* eliminate 7 cases of identity transformation *) auto.
unfold endow_dep.
case (SemDefns.allocate_preReq_dec t t0 (Exe.execute s op_list)); intros Hcase;
(* eliminate 1/2 case of id_ag *) auto.
unfold endow.
generalize Seq.potAcc_potAcc_fun; intros Hpa.
edestruct Hpa as [Htrasn Hmax']. eapply Seq.maxTransfer_maxPotTransfer in Hmax'. apply Hmax'.
Qed.
Theorem objs_not_unborn_dirAcc_spec: forall s i, dirAcc_spec s i ->
forall objs, Seq.ag_objs_spec i objs -> objs_not_unborn objs s.
Proof.
intros.
(* introduce contradiciton *)
unfold objs_not_unborn; intros n Hin Hunborn.
(* work through objs_spec *)
eapply H0 in Hin; clear H0; destruct Hin as [obj [rgt [HinE | HinE ]]];
(* cases *)
(* apply dirAcc in HinE and destruct*)
eapply H in HinE;
destruct_dirAcc HinE s'' HeqS src_ref src lbl srcType srcSched HmapS
src' lbl' srcType' srcSched' HeqP Halive ind cap HmapSrc'
cap_obj cap_lbl cap_type cap_sched HmapScap cap_obj' cap_lbl' cap_type' cap_sched'
HeqPcap HaliveCap rgt' HinR HeqEdge;
(* simplify edge equality *)
generalize (Edges.eq_source _ _ HeqEdge); intros HeqEdgeS;
repeat progress rewrite Edges.source_rewrite in HeqEdgeS;
generalize (Edges.eq_target _ _ HeqEdge); intros HeqEdgeT;
repeat progress rewrite Edges.target_rewrite in HeqEdgeT;
generalize (Edges.eq_right _ _ HeqEdge); intros HeqEdgeR;
repeat progress rewrite Edges.right_rewrite in HeqEdgeR;
(* simplify tuple equality *)
destruct_tuple HeqP Hsrc Hlbl HsrcT HsrcS; simpl in *;
destruct_tuple HeqPcap Hsrc_cap Hlbl_cap HsrcT_cap HsrcS_cap; simpl in *;
(* rewrite everything through to show that n is alive in hyp HmapS | HmapScap. *)
rewrite HeqEdgeS in *;
rewrite HeqEdgeT in *;
rewrite Hlbl in *;
rewrite Hlbl_cap in *;
unfold ObjectLabel.eq in *;
rewrite <- Halive in *;
rewrite <- HaliveCap in *.
(* use HmapS to find an equivelent label in s *)
eapply Sys_MapEquiv.exists_mapsTo_eq in HmapS;
[ | apply Sys.eq_sym; apply HeqS | apply Ref.eq_refl].
destruct HmapS as [tuple [Htuple HmapS]].
destruct_tuple tuple t_obj t_lbl t_schd t_typ; simpl in *.
destruct_tuple Htuple Ht_obj Ht_lbl Ht_schd Ht_typ.
rewrite <- Ht_lbl in *.
(* prove contradiciton by discrimination *)
unfold SC.is_unborn in Hunborn.
unfold SC.is_label in Hunborn.
unfold SC.getLabel in Hunborn.
unfold SC.getObjTuple in Hunborn.
eapply Sys.MapS.find_1 in HmapS.
rewrite HmapS in Hunborn.
simpl in Hunborn.
discriminate.
(* other case *)
(* use HmapScap to find an equivelent label in s *)
eapply Sys_MapEquiv.exists_mapsTo_eq in HmapScap;
[ | apply Sys.eq_sym; apply HeqS | apply Ref.eq_refl].
destruct HmapScap as [tuple [Htuple HmapScap]].
destruct_tuple tuple t_obj t_lbl t_schd t_typ; simpl in *.
destruct_tuple Htuple Ht_obj Ht_lbl Ht_schd Ht_typ.
rewrite <- Ht_lbl in *.
(* prove contradiciton by discrimination *)
unfold SC.is_unborn in Hunborn.
unfold SC.is_label in Hunborn.
unfold SC.getLabel in Hunborn.
unfold SC.getObjTuple in Hunborn.
eapply Sys.MapS.find_1 in HmapScap.
rewrite HmapScap in Hunborn.
simpl in Hunborn.
discriminate.
Qed.
(* throw into sequential access *)
Theorem maxTransfer_potAcc_refl : forall p, Seq.maxTransfer p -> Seq.potAcc p p.
Proof.
intros; split.
eapply Seq.potTransfer_base; apply AG.eq_refl.
eapply Seq.maxTransfer_maxPotTransfer; auto.
Qed.
Theorem AG_attenuating_potAcc_op_2: forall objs s, objs_not_unborn objs s ->
forall i p, Seq.potAcc i p ->
forall ag_N, Seq.ag_objs_spec p ag_N -> objs_not_unborn ag_N s ->
forall op, AG_attenuating objs p (potAcc_op op s p).
Proof.
intros objs s Hobjs i p Hpa ag_N Hag_objs Hag_objs_unborn op.
destruct op; simpl; try unfold id_ag; try solve [apply AG_attenuating_eq; apply AG.eq_refl].
unfold endow_dep.
case (SemDefns.allocate_preReq_dec t t0 s); intros H'; try solve [apply AG_attenuating_eq; apply AG.eq_refl].
destruct H'.
eapply AG_attenuating_endow; try solve [ apply Hag_objs | apply Hpa
| intro Hnot; first [apply Hobjs in Hnot|apply Hag_objs_unborn in Hnot]; apply Hnot; auto].
Qed.
Theorem AG_attenuating_compose: forall objs p Fp1, AG_attenuating objs p (Fp1 p) ->
forall Fp2, AG_attenuating objs (Fp1 p) (compose Fp2 Fp1 p) ->
AG_attenuating objs p (compose Fp2 Fp1 p).
Proof.
intros.
eapply AG_attenuating_trans; [ apply H | apply H0].
Qed.
(* This theorem states that the function Fp, which conservatively approximates the execution
of op_list on s, is AG_attenuating-ing on its input provided all objs are unborn. *)
Theorem execute_potAcc_attenuating:
forall op_list Fsa, dirAcc_execute_spec op_list Fsa ->
forall Fp, potAcc_execute_spec op_list Fp ->
forall s i, dirAcc_spec s i -> forall p, Seq.potAcc i p ->
forall objs, objs_not_unborn objs s ->
AG_attenuating objs p (Fp s p).
Proof.
intros op_list Fsa Hdax Fp Hpax s i Hda p Hpa objs Hobjs.
revert Hdax Hpax; revert Fsa Fp.
induction op_list; intros Fsa Fp Hdax Hpax.
(* base *)
inversion Hpax; eauto.
(* step *)
rename a into op.
inversion Hdax. rename Fp0 into Fsa'. clear H H1. clear op0 op_list0.
inversion Hpax. rename Fp0 into Fp'. clear H H3. clear op0 op_list0.
generalize (IHop_list _ _ H2 H4); intros IHreduce; clear IHop_list.
apply AG_attenuating_compose; [apply IHreduce|].
unfold compose.
(* generalize (exists_dirAcc_spec (Exe.execute s op_list)); intros [i' Hda']. *)
(* generalize (Seq.exists_potAcc i'); intros [p' Hpa']. *)
(* generalize (Seq.ag_objs_spec_ag_objs p'); intros Hagobjs. *)
(* generalize (objs_not_unborn_oplist _ _ Hobjs op_list _ (Exe.execute_spec_2 s op_list _ (Sys.eq_refl _))); intros Hobjsunborn. *)
(* okay, aside from the potAcc property, all of these subgoals are about the objs_not_unborn invariants *)
(* first, we need to know that objs not unborn remain not unborn over execution.
second, we need to know that no objs produced by a potAcc_execute_spec funcitons also preserve
objs_obj_unborn *)
eapply AG_attenuating_potAcc_op_2.
(* objs unborn in Exe.execute s op_list *)
eapply objs_not_unborn_oplist; [apply Hobjs| eapply Exe.execute_spec_2; apply Sys.eq_refl].
(* potAcc_execute_spec op_list Fp' -> exists da, Seq.potAcc da (Fp' s p) *)
eapply maxTransfer_potAcc_refl; eapply potAcc_execute_spec_potAcc; [ | eauto];
destruct Hpa as [HpotTrans Hmax]; eapply Seq.maxTransfer_maxPotTransfer in Hmax; auto.
(* ag_objs_spec *)
eapply Seq.ag_objs_spec_ag_objs.
(* potAcc_execute_spec op_list Fp' -> objs_not_unborn (Seq.ag_objs (Fp' s p)) (Exe.execute s op_list) *)
eapply objs_not_unborn_potAcc_execute_spec; eauto; [|apply Exe.execute_spec; eapply Sys.eq_refl].
generalize (Seq.ag_objs_spec_ag_objs p); intros Hp_objs.
eapply ag_objs_spec_potTransfer_2 in Hp_objs; [ | eapply Hpa].
eapply objs_not_unborn_dirAcc_spec; eauto.
Qed.
(* Given execute_potAcc_attenuating, we can now turn to execute_attenuatinge *)
Theorem execute_attenuating : forall s i, dirAcc_spec s i -> forall p, Seq.potAcc i p ->
forall op_list s', Exe.execute_def s op_list s' -> forall i', dirAcc_spec s' i' ->
forall p', Seq.potAcc i' p' -> forall objs, objs_not_unborn objs s ->
AG_attenuating objs p p'.
Proof.
intros s i Hda p Hpa op_list s' Hexe i' Hda' p' Hpa' objs HnAlive.
(* proof sketch *)
(* by dirAcc_execute_spec_dirAcc_execute and potAcc_execute_spec_potAcc_execute, we know that we can
instantiate execute_potAcc_attenuating*)
generalize (execute_potAcc_attenuating
op_list
_ (dirAcc_execute_spec_dirAcc_execute _)
_ (potAcc_execute_spec_potAcc_execute _)
_ _ Hda
_ Hpa
_ HnAlive); intros Hreduce.
eapply Proper_AG_attenuating_4; unfold flip;
[ apply RefSetProps.subset_equal; apply RefSet.eq_refl
| apply AGProps.subset_equal; apply AG.eq_refl
|
| apply Hreduce
].
(* all that remains is to show that potAcc_execute conservatively approximates potAcc *)
generalize (potAcc_execute_approx
op_list
_ (dirAcc_execute_spec_dirAcc_execute _)
_ (potAcc_execute_spec_potAcc_execute _)); intros HPAapprox.
generalize (dirAcc_execute_approx
op_list
_ (dirAcc_execute_spec_dirAcc_execute _)); intros HDAapprox.
unfold dirAcc_approx_dep in *.
unfold potAcc_approx_dirAcc_dep in *.
eapply Exe.execute_spec in Hexe.
eapply dirAcc_spec_iff in Hda'; [ | apply Hexe| apply AG.eq_refl].
generalize (HDAapprox _ _ _ _ _
Hda Hda' (AGProps.subset_equal (AG.eq_refl _)) (Sys.eq_refl _));
clear HDAapprox; intros HDAapprox.
generalize (Seq.exists_potAcc (dirAcc_execute op_list s i)); intros [p2 Hpa2].
generalize (HPAapprox _ _ _ _ _ _ _ _
(Sys.eq_refl _) (Sys.eq_refl _)
Hda (AGProps.subset_equal (AG.eq_refl _))
Hpa Hpa2
(AGProps.subset_equal (AG.eq_refl _)));
clear HPAapprox; intros HPAapprox.
eapply AGProps.subset_trans;[|eapply HPAapprox].
eapply Seq.potAcc_monotonic; [ apply HDAapprox | apply Hpa'| apply Hpa2].
Qed.
End MakeAccessExecution.
|
# ---
# title: this has higher priority than [2]
# description: this has higher priority than [1]
# ---
# This is parsed as a description line --- [1]
# # this is a section title --- [2]
# but won't be recognized as a card title because it's put after the contents
|
[STATEMENT]
theorem "\<exists>(x::int). 0 < x"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<exists>x. 0 < x
[PROOF STEP]
by presburger |
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS_GHC -O0 -freduction-depth=0 #-}
module BlueRipple.Data.CPSVoterPUMS
(
cpsVoterPUMSLoader
, cpsVoterPUMSWithCDLoader
, CPSVoterPUMS
, CPSVoterPUMSWeight
, cpsVoterPUMSRollup
, cpsVoterPUMSRollupWeightedCounts
, cpsVoterPUMSElectoralWeights
, cpsVoterPUMSElectoralWeightsByCD
, cpsVoterPUMSElectoralWeightsByState
, cpsVoterPUMSNationalElectoralWeights
, cpsCountVotersByStateF
-- , cpsKeysToASE
-- , cpsKeysToASR
, cpsKeysToASER
-- , cpsKeysToASER4
, cpsKeysToASER5
, cpsKeysToASER4H
-- , cpsKeysToIdentity
, cpsPossibleVoter
, cpsVoted
) where
import qualified BlueRipple.Data.CPSVoterPUMS.CPSVoterPUMS_Frame as BR
import qualified BlueRipple.Data.DemographicTypes as BR
import qualified BlueRipple.Data.ElectionTypes as BR
import qualified BlueRipple.Data.DataFrames as BR
import qualified BlueRipple.Data.LoadersCore as BR
import qualified BlueRipple.Data.Loaders as BR
import qualified BlueRipple.Data.Keyed as BR
import qualified BlueRipple.Utilities.KnitUtils as BR
import qualified BlueRipple.Data.CountFolds as BRCF
import qualified Control.Foldl as FL
import Control.Lens ((%~))
import qualified Control.Monad.Except as X
import qualified Control.Monad.State as ST
import qualified Data.Array as A
import qualified Data.Serialize as S
import qualified Data.Serialize.Text as S
import qualified Data.List as L
import qualified Data.Map as M
import Data.Maybe ( fromMaybe, catMaybes)
import qualified Data.Text as T
import Data.Text ( Text )
import Text.Read (readMaybe)
import qualified Data.Vinyl as V
import Data.Vinyl.TypeLevel (type (++))
import qualified Data.Vinyl.TypeLevel as V
import qualified Data.Vinyl.Functor as V
import qualified Frames as F
import Data.Vinyl.Lens (type (⊆))
import Frames ( (:.)(..) )
import qualified Frames.CSV as F
import qualified Frames.InCore as FI
import qualified Frames.TH as F
import qualified Frames.Melt as F
import qualified Text.Read as TR
import qualified Frames.Folds as FF
import qualified Frames.MapReduce as FMR
import qualified Frames.ParseableTypes as FP
import qualified Frames.Transform as FT
import qualified Frames.MaybeUtils as FM
import qualified Frames.Utils as FU
import qualified Frames.MapReduce as MR
import qualified Frames.Enumerations as FE
import qualified Frames.Serialize as FS
import qualified Frames.SimpleJoins as FJ
import qualified Frames.Visualization.VegaLite.Data
as FV
--import qualified Graphics.Vega.VegaLite as GV
{-
import qualified Data.IndexedSet as IS
import qualified Numeric.GLM.ProblemTypes as GLM
import qualified Numeric.GLM.ModelTypes as GLM
import qualified Numeric.GLM.Predict as GLM
import qualified Numeric.LinearAlgebra as LA
-}
import Data.Hashable ( Hashable )
import qualified Data.Vector as V
--import qualified Data.Vector.Boxed as VB
import GHC.Generics ( Generic, Rep )
import qualified Knit.Report as K
import qualified Polysemy.Error as P (mapError, Error)
import qualified Polysemy as P (raise)
import GHC.TypeLits (Symbol)
import Data.Kind (Type)
cpsVoterPUMSLoader :: (K.KnitEffects r, BR.CacheEffects r)
=> K.Sem r (K.ActionWithCacheTime r (F.FrameRec CPSVoterPUMS))
cpsVoterPUMSLoader = do
let cpsPUMSDataPath = BR.LocalData $ T.pack BR.cpsVoterPUMSCSV
cachedStateAbbrCrosswalk <- BR.stateAbbrCrosswalkLoader
cachedCPSDataPath <- K.liftKnit $ BR.dataPathWithCacheTime cpsPUMSDataPath
let cachedDeps = (,) <$> cachedStateAbbrCrosswalk <*> cachedCPSDataPath
BR.retrieveOrMakeFrame "data/cpsVoterPUMSWithAbbrs.bin" cachedDeps $ \(stateAbbrCrosswalk, dataPath) -> do
let filter r = (F.rgetField @BR.CPSAGE r >= 18) && (F.rgetField @BR.CPSCITIZEN r /= 5)
withoutAbbr <- K.ignoreCacheTimeM
$ BR.cachedFrameLoader @(F.RecordColumns BR.CPSVoterPUMS_Raw) @CPSVoterPUMS'
dataPath
Nothing
(Just filter)
transformCPSVoterPUMSRow
Nothing
"cpsVoterPUMS.bin"
fmap (fmap F.rcast) (K.knitMaybe "missing state abbreviation in state abbreviation crosswalk"
$ FJ.leftJoinM @'[BR.StateFIPS] withoutAbbr stateAbbrCrosswalk)
-- NB: This should not be used for state-level rollup since some rows will be duplicated if the county is in more than one CD.
cpsVoterPUMSWithCDLoader :: (K.KnitEffects r, BR.CacheEffects r)
=> K.Sem r (K.ActionWithCacheTime r (F.FrameRec (CPSVoterPUMS V.++ [BR.CongressionalDistrict, BR.CountyWeight])))
cpsVoterPUMSWithCDLoader = do
cachedCPSVoterPUMS <- cpsVoterPUMSLoader
cachedCountyToCD <- BR.county2010ToCD116Loader
let cachedDeps = (,) <$> cachedCPSVoterPUMS <*> cachedCountyToCD
BR.retrieveOrMakeFrame "data/cpsVoterPUMSWithAbbrsAndCDs.bin" cachedDeps $ \(cpsVoterPUMS, countyToCD) -> do
K.knitEither . either (Left . show) Right
$ FJ.leftJoinE
@[BR.StateFIPS, BR.CountyFIPS]
(F.filterFrame ((> 0) . F.rgetField @BR.CountyFIPS) cpsVoterPUMS)
(fmap (F.rcast @[BR.CountyFIPS, BR.StateFIPS, BR.CongressionalDistrict, BR.CountyWeight]) countyToCD)
type CPSVoterPUMSWeight = "CPSVoterPUMSWeight" F.:-> Double
type CPSVoterPUMS = '[ BR.Year
, BR.StateFIPS
, BR.StateAbbreviation
, BR.CountyFIPS
, BR.Age4C
, BR.SexC
, BR.RaceAlone4C
, BR.HispC
, BR.IsCitizen
, BR.CollegeGradC
, BR.InCollege
, BR.VoteWhyNotC
, BR.RegWhyNotC
, BR.VoteHowC
, BR.VoteWhenC
, BR.VotedYNC
, BR.RegisteredYNC
, CPSVoterPUMSWeight
]
type CPSVoterPUMS' = V.RDelete BR.StateAbbreviation CPSVoterPUMS
cpsVoterPUMSRollup
:: forall cs rs ks ds.
( cs F.⊆ rs
, ks F.⊆ (ks V.++ cs)
, cs F.⊆ (ks V.++ cs)
, FI.RecVec (ks V.++ ds)
, Ord (F.Record ks)
)
=> (F.Record rs -> F.Record ks)
-> FL.Fold (F.Record cs) (F.Record ds)
-> FL.Fold (F.Record rs) (F.FrameRec (ks V.++ ds))
cpsVoterPUMSRollup getKeys foldData =
FMR.concatFold
$ FMR.mapReduceFold
(FMR.Unpack $ \r -> [getKeys r `V.rappend` F.rcast @cs r])
(FMR.assignKeysAndData @ks @cs)
(FMR.foldAndAddKey foldData)
cpsVoterPUMSRollupWithDefault
:: forall cs rs ls ks ds.
( cs F.⊆ rs
, (ls V.++ ks) F.⊆ (ls V.++ ks V.++ cs)
, cs F.⊆ (ls V.++ ks V.++ cs)
, FI.RecVec (ls V.++ ks V.++ ds)
, Ord (F.Record (ls V.++ ks))
, BR.FiniteSet (F.Record ks)
, (ls V.++ (ks V.++ ds)) ~ ((ls V.++ ks) V.++ ds)
, Ord (F.Record ls)
, ls F.⊆ ((ls V.++ ks) V.++ ds)
, (ks V.++ ds) F.⊆ ((ls V.++ ks) V.++ ds)
, ks F.⊆ (ks V.++ ds)
, ds F.⊆ (ks V.++ ds)
)
=> (F.Record rs -> F.Record ls)
-> (F.Record rs -> F.Record ks)
-> FL.Fold (F.Record cs) (F.Record ds)
-> F.Record ds -- default value if there are no records for a given value of F.Record ks
-> FL.Fold (F.Record rs) (F.FrameRec (ls V.++ ks V.++ ds))
cpsVoterPUMSRollupWithDefault getLoc getKey foldData defD =
let addDefaultF = FMR.concatFold
$ FMR.mapReduceFold
FMR.noUnpack
(FMR.assignKeysAndData @ls @(ks V.++ ds))
(FMR.makeRecsWithKey id
$ FMR.ReduceFold
$ const
$ BR.addDefaultRec @ks defD
)
in FL.fold addDefaultF <$> cpsVoterPUMSRollup (\r -> getLoc r `V.rappend` getKey r) foldData
cpsVoterPUMSRollupWeightedCounts
:: forall cs rs ls ks ds.
( cs F.⊆ rs
, (ls V.++ ks) F.⊆ (ls V.++ ks V.++ cs)
, cs F.⊆ (ls V.++ ks V.++ cs)
, FI.RecVec (ls V.++ ks V.++ ds)
, Ord (F.Record (ls V.++ ks))
, (ls V.++ (ks V.++ ds)) ~ ((ls V.++ ks) V.++ ds)
, BR.FiniteSet (F.Record ks)
, Ord (F.Record ls)
, ls F.⊆ ((ls V.++ ks) V.++ ds)
, (ks V.++ ds) F.⊆ ((ls V.++ ks) V.++ ds)
, ks F.⊆ (ks V.++ ds)
, ds F.⊆ (ks V.++ ds)
)
=> (F.Record rs -> F.Record ls)
-> (F.Record rs -> F.Record ks)
-> (F.Record cs -> Bool) -- which to include
-> (F.Record cs -> Bool) -- which to count
-> (F.Record cs -> Double) -- get weight
-> (Double -> F.Record ds) -- turn the weighted counts into a record
-> F.Record ds -- default
-> FL.Fold (F.Record rs) (F.FrameRec (ls V.++ ks V.++ ds))
cpsVoterPUMSRollupWeightedCounts getLoc getKey filterData countIf wgt countToRec defD =
let countF :: FL.Fold (F.Record cs) (F.Record ds)
countF =
let wgtdAllF = FL.premap wgt FL.sum
wgtdCountF = FL.prefilter countIf $ FL.premap wgt FL.sum
safeDiv n d = if d > 0 then n/d else 0
wF = safeDiv <$> wgtdCountF <*> wgtdAllF -- this is acceptable here since (d == 0) iff (n == 0)
in fmap countToRec wF
ewFold :: FL.Fold (F.Record cs) (F.Record ds)
ewFold = FL.prefilter filterData countF
in cpsVoterPUMSRollupWithDefault getLoc getKey ewFold defD
cpsVoterPUMSElectoralWeights
:: forall cs rs ls ks.
((ls V.++ ks) F.⊆ (ls V.++ ks V.++ cs)
, cs F.⊆ (ls V.++ ks V.++ cs)
, cs F.⊆ rs
, F.ElemOf cs BR.IsCitizen
, F.ElemOf cs BR.VotedYNC
, FI.RecVec (ls V.++ ks V.++ BR.EWCols)
, (ls V.++ (ks V.++ BR.EWCols)) ~ ((ls V.++ ks) V.++ BR.EWCols)
, Ord (F.Record (ls V.++ ks))
, Ord (F.Record ls)
, BR.FiniteSet (F.Record ks)
, ls F.⊆ ((ls V.++ ks) V.++ BR.EWCols)
, (ks V.++ BR.EWCols) F.⊆ ((ls V.++ ks) V.++ BR.EWCols)
, ks F.⊆ (ks V.++ BR.EWCols)
, BR.EWCols F.⊆ (ks V.++ BR.EWCols)
)
=> (F.Record rs -> F.Record ls)
-> (F.Record rs -> F.Record ks)
-> (F.Record cs -> Double)
-> FL.Fold (F.Record rs) (F.FrameRec (ls V.++ ks V.++ BR.EWCols))
cpsVoterPUMSElectoralWeights getLoc getKey getWgt =
let toRec :: Double -> F.Record BR.EWCols
toRec w = BR.EW_Census F.&: BR.EW_Citizen F.&: w F.&: V.RNil
citizen r = F.rgetField @BR.IsCitizen r
possibleVoter r = cpsPossibleVoter $ F.rgetField @BR.VotedYNC r
voted r = cpsVoted $ F.rgetField @BR.VotedYNC r
in cpsVoterPUMSRollupWeightedCounts @cs
getLoc
getKey
(\r -> citizen r && possibleVoter r)
voted
getWgt
toRec
(toRec 0) -- this is a reasonable default to use for inference but not great to use this data directly
cpsVoterPUMSElectoralWeightsByState
:: forall ks.
(F.ElemOf (ks ++ '[BR.IsCitizen, BR.VotedYNC, CPSVoterPUMSWeight]) CPSVoterPUMSWeight
, F.ElemOf (ks ++ '[BR.IsCitizen, BR.VotedYNC, CPSVoterPUMSWeight]) BR.IsCitizen
, F.ElemOf (ks ++ '[BR.IsCitizen, BR.VotedYNC, CPSVoterPUMSWeight]) BR.VotedYNC
, FI.RecVec (ks ++ BR.EWCols)
, Ord (F.Record ks)
, ks F.⊆ ('[BR.Year, BR.StateAbbreviation, BR.StateFIPS] V.++ ks V.++ '[BR.IsCitizen, BR.VotedYNC, CPSVoterPUMSWeight])
, BR.FiniteSet (F.Record ks)
, F.ElemOf (ks V.++ BR.EWCols) BR.ElectoralWeight
, F.ElemOf (ks V.++ BR.EWCols) BR.ElectoralWeightOf
, F.ElemOf (ks V.++ BR.EWCols) BR.ElectoralWeightSource
, (ks V.++ BR.EWCols) F.⊆ ('[BR.Year, BR.StateAbbreviation, BR.StateFIPS] V.++ ks V.++ BR.EWCols)
, ks F.⊆ (ks V.++ BR.EWCols)
)
=> (F.Record CPSVoterPUMS -> F.Record ks)
-> FL.Fold (F.Record CPSVoterPUMS) (F.FrameRec ('[BR.Year, BR.StateAbbreviation, BR.StateFIPS] V.++ ks V.++ BR.EWCols))
cpsVoterPUMSElectoralWeightsByState getCatKey =
cpsVoterPUMSElectoralWeights @[BR.IsCitizen, BR.VotedYNC, CPSVoterPUMSWeight]
(F.rcast @[BR.Year, BR.StateAbbreviation, BR.StateFIPS]) getCatKey (F.rgetField @CPSVoterPUMSWeight)
cpsVoterPUMSNationalElectoralWeights
:: forall ks.
(F.ElemOf (ks ++ '[BR.IsCitizen, BR.VotedYNC, CPSVoterPUMSWeight]) CPSVoterPUMSWeight
, F.ElemOf (ks ++ '[BR.IsCitizen, BR.VotedYNC, CPSVoterPUMSWeight]) BR.IsCitizen
, F.ElemOf (ks ++ '[BR.IsCitizen, BR.VotedYNC, CPSVoterPUMSWeight]) BR.VotedYNC
, FI.RecVec (ks ++ BR.EWCols)
, Ord (F.Record ks)
, ks F.⊆ ('[BR.Year] V.++ ks V.++ '[BR.IsCitizen, BR.VotedYNC, CPSVoterPUMSWeight])
, BR.FiniteSet (F.Record ks)
, F.ElemOf (ks V.++ BR.EWCols) BR.ElectoralWeight
, F.ElemOf (ks V.++ BR.EWCols) BR.ElectoralWeightOf
, F.ElemOf (ks V.++ BR.EWCols) BR.ElectoralWeightSource
, (ks V.++ BR.EWCols) F.⊆ ('[BR.Year] V.++ ks V.++ BR.EWCols)
, ks F.⊆ (ks V.++ BR.EWCols)
)
=> (F.Record CPSVoterPUMS -> F.Record ks)
-> FL.Fold (F.Record CPSVoterPUMS) (F.FrameRec ('[BR.Year] V.++ ks V.++ BR.EWCols))
cpsVoterPUMSNationalElectoralWeights getCatKey =
cpsVoterPUMSElectoralWeights @[BR.IsCitizen, BR.VotedYNC, CPSVoterPUMSWeight] (F.rcast @'[BR.Year]) getCatKey (F.rgetField @CPSVoterPUMSWeight)
cpsVoterPUMSElectoralWeightsByCD
:: forall ks.
(F.ElemOf (ks ++ '[BR.IsCitizen, BR.VotedYNC, CPSVoterPUMSWeight, BR.CountyWeight]) CPSVoterPUMSWeight
, F.ElemOf (ks ++ '[BR.IsCitizen, BR.VotedYNC, CPSVoterPUMSWeight, BR.CountyWeight]) BR.CountyWeight
, F.ElemOf (ks ++ '[BR.IsCitizen, BR.VotedYNC, CPSVoterPUMSWeight, BR.CountyWeight]) BR.IsCitizen
, F.ElemOf (ks ++ '[BR.IsCitizen, BR.VotedYNC, CPSVoterPUMSWeight, BR.CountyWeight]) BR.VotedYNC
, FI.RecVec (ks ++ BR.EWCols)
, Ord (F.Record ks)
, ks F.⊆ ('[BR.Year, BR.StateAbbreviation, BR.StateFIPS, BR.CongressionalDistrict]
V.++ ks
V.++ '[BR.IsCitizen, BR.VotedYNC, CPSVoterPUMSWeight, BR.CountyWeight])
, BR.FiniteSet (F.Record ks)
, F.ElemOf (ks V.++ BR.EWCols) BR.ElectoralWeight
, F.ElemOf (ks V.++ BR.EWCols) BR.ElectoralWeightOf
, F.ElemOf (ks V.++ BR.EWCols) BR.ElectoralWeightSource
, (ks V.++ BR.EWCols) F.⊆ ('[BR.Year, BR.StateAbbreviation, BR.StateFIPS, BR.CongressionalDistrict] V.++ ks V.++ BR.EWCols)
, ks F.⊆ (ks V.++ BR.EWCols)
)
=> (F.Record (CPSVoterPUMS V.++ [BR.CongressionalDistrict, BR.CountyWeight]) -> F.Record ks)
-> FL.Fold (F.Record (CPSVoterPUMS V.++ [BR.CongressionalDistrict, BR.CountyWeight]))
(F.FrameRec ('[BR.Year, BR.StateAbbreviation, BR.StateFIPS, BR.CongressionalDistrict] V.++ ks V.++ BR.EWCols))
cpsVoterPUMSElectoralWeightsByCD getCatKey =
let wgt r = F.rgetField @CPSVoterPUMSWeight r * F.rgetField @BR.CountyWeight r
in cpsVoterPUMSElectoralWeights @[BR.IsCitizen, BR.VotedYNC, CPSVoterPUMSWeight, BR.CountyWeight]
(F.rcast @[BR.Year, BR.StateAbbreviation, BR.StateFIPS, BR.CongressionalDistrict]) getCatKey wgt
-- rollup for MRP
cpsCountVotersByStateF
:: forall ks.
(Ord (F.Record ks)
, FI.RecVec (ks V.++ BRCF.CountCols)
, ks F.⊆ CPSVoterPUMS
)
=> (F.Record CPSVoterPUMS -> F.Record ks)
-> Int -- year
-> FMR.Fold
(F.Record CPSVoterPUMS)
(F.FrameRec ('[BR.StateAbbreviation] V.++ ks V.++ BRCF.CountCols))
cpsCountVotersByStateF getCatKey year =
let isYear y r = F.rgetField @BR.Year r == y
possible r = cpsPossibleVoter $ F.rgetField @BR.VotedYNC r
citizen r = F.rgetField @BR.IsCitizen r
includeRow r = isYear year r && possible r && citizen r
voted r = cpsVoted $ F.rgetField @BR.VotedYNC r
in BRCF.weightedCountFold
(F.rcast @(BR.StateAbbreviation ': ks))
(F.rcast @[BR.VotedYNC, CPSVoterPUMSWeight])
includeRow
voted
(F.rgetField @CPSVoterPUMSWeight)
cpsCountVotersByCDF
:: forall ks.
(Ord (F.Record ks)
, FI.RecVec (ks V.++ BRCF.CountCols)
, ks F.⊆ (CPSVoterPUMS V.++ [BR.CongressionalDistrict, BR.CountyWeight])
)
=> (F.Record (CPSVoterPUMS V.++ [BR.CongressionalDistrict, BR.CountyWeight]) -> F.Record ks)
-> Int -- year
-> FMR.Fold
(F.Record (CPSVoterPUMS V.++ [BR.CongressionalDistrict, BR.CountyWeight]))
(F.FrameRec ('[BR.StateAbbreviation, BR.CongressionalDistrict] V.++ ks V.++ BRCF.CountCols))
cpsCountVotersByCDF getCatKey year =
let isYear y r = F.rgetField @BR.Year r == y
possible r = cpsPossibleVoter $ F.rgetField @BR.VotedYNC r
citizen r = F.rgetField @BR.IsCitizen r
includeRow r = isYear year r && possible r && citizen r
voted r = cpsVoted $ F.rgetField @BR.VotedYNC r
wgt r = F.rgetField @CPSVoterPUMSWeight r * F.rgetField @BR.CountyWeight r
in BRCF.weightedCountFold
(F.rcast @([BR.StateAbbreviation, BR.CongressionalDistrict] V.++ ks))
(F.rcast @[BR.VotedYNC, CPSVoterPUMSWeight, BR.CountyWeight])
includeRow
voted
wgt
-- We give the option of counting "In College" as "College Grad". This is different from what the census summary tables do.
-- NB: This needs to be done consistently with the demographics.
-- We don't have this information for the preferences, at least not from CCES, so doing this amounts to assigning
-- "in college" people to either Grad or NonGrad buckets in terms of voting pref.
cpsKeysToASER5 :: Bool
-> F.Record '[BR.Age4C, BR.SexC, BR.CollegeGradC, BR.InCollege, BR.RaceAlone4C, BR.HispC]
-> F.Record BR.CatColsASER5
cpsKeysToASER5 addInCollegeToGrads r =
let cg = F.rgetField @BR.CollegeGradC r
ic = addInCollegeToGrads && F.rgetField @BR.InCollege r
ra4 = F.rgetField @BR.RaceAlone4C r
h = F.rgetField @BR.HispC r
in (BR.age4ToSimple $ F.rgetField @BR.Age4C r)
F.&: (F.rgetField @BR.SexC r)
F.&: (if cg == BR.Grad || ic then BR.Grad else BR.NonGrad)
F.&: BR.race5FromRaceAlone4AndHisp True ra4 h
F.&: V.RNil
cpsKeysToASER4H :: Bool
-> F.Record [BR.Age4C, BR.SexC, BR.CollegeGradC, BR.InCollege, BR.RaceAlone4C, BR.HispC]
-> F.Record [BR.SimpleAgeC, BR.SexC, BR.CollegeGradC, BR.RaceAlone4C, BR.HispC]
cpsKeysToASER4H addInCollegeToGrads r =
let cg = F.rgetField @BR.CollegeGradC r
ic = addInCollegeToGrads && F.rgetField @BR.InCollege r
in (BR.age4ToSimple $ F.rgetField @BR.Age4C r)
F.&: (F.rgetField @BR.SexC r)
F.&: (if cg == BR.Grad || ic then BR.Grad else BR.NonGrad)
F.&: F.rgetField @BR.RaceAlone4C r
F.&: F.rgetField @BR.HispC r
F.&: V.RNil
cpsKeysToASER :: Bool -> F.Record '[BR.Age4C, BR.SexC, BR.CollegeGradC, BR.InCollege, BR.RaceAlone4C, BR.HispC] -> F.Record BR.CatColsASER
cpsKeysToASER addInCollegeToGrads r =
let cg = F.rgetField @BR.CollegeGradC r
ic = addInCollegeToGrads && F.rgetField @BR.InCollege r
ra4 = F.rgetField @BR.RaceAlone4C r
h = F.rgetField @BR.HispC r
in (BR.age4ToSimple $ F.rgetField @BR.Age4C r)
F.&: (F.rgetField @BR.SexC r)
F.&: (if cg == BR.Grad || ic then BR.Grad else BR.NonGrad)
F.&: (BR.simpleRaceFromRaceAlone4AndHisp True ra4 h)
F.&: V.RNil
{-
cpsKeysToASER4 :: Bool -> F.Record '[BR.Age4C, BR.SexC, BR.CollegeGradC, BR.InCollege, BR.Race5C] -> F.Record BR.CatColsASER4
cpsKeysToASER4 addInCollegeToGrads r =
let cg = F.rgetField @BR.CollegeGradC r
ic = addInCollegeToGrads && F.rgetField @BR.InCollege r
in (BR.age4ToSimple $ F.rgetField @BR.Age4C r)
F.&: (F.rgetField @BR.SexC r)
F.&: (if cg == BR.Grad || ic then BR.Grad else BR.NonGrad)
F.&: (BR.race4FromRace5 $ F.rgetField @BR.Race5C r)
F.&: V.RNil
cpsKeysToASER :: Bool -> F.Record '[BR.Age4C, BR.SexC, BR.CollegeGradC, BR.InCollege, BR.Race5C] -> F.Record BR.CatColsASER
cpsKeysToASER addInCollegeToGrads r =
let cg = F.rgetField @BR.CollegeGradC r
ic = addInCollegeToGrads && F.rgetField @BR.InCollege r
in (BR.age4ToSimple $ F.rgetField @BR.Age4C r)
F.&: (F.rgetField @BR.SexC r)
F.&: (if cg == BR.Grad || ic then BR.Grad else BR.NonGrad)
F.&: (BR.simpleRaceFromRace5 $ F.rgetField @BR.Race5C r)
F.&: V.RNil
cpsKeysToASE :: Bool -> F.Record '[BR.Age4C, BR.SexC, BR.CollegeGradC, BR.InCollege, BR.Race5C] -> F.Record BR.CatColsASE
cpsKeysToASE addInCollegeToGrads r =
let cg = F.rgetField @BR.CollegeGradC r
ic = addInCollegeToGrads && F.rgetField @BR.InCollege r
in (BR.age4ToSimple $ F.rgetField @BR.Age4C r)
F.&: (F.rgetField @BR.SexC r)
F.&: (if cg == BR.Grad || ic then BR.Grad else BR.NonGrad)
F.&: V.RNil
cpsKeysToASR :: F.Record '[BR.Age4C, BR.SexC, BR.CollegeGradC, BR.InCollege, BR.Race5C] -> F.Record BR.CatColsASR
cpsKeysToASR r =
(BR.age4ToSimple $ F.rgetField @BR.Age4C r)
F.&: (F.rgetField @BR.SexC r)
F.&: (BR.simpleRaceFromRace5 $ F.rgetField @BR.Race5C r)
F.&: V.RNil
cpsKeysToIdentity :: F.Record '[BR.Age4C, BR.SexC, BR.CollegeGradC, BR.InCollege, BR.Race5C] -> F.Record '[]
cpsKeysToIdentity = const V.RNil
-}
-- we have to drop all records with age < 18
intToAge4 :: Int -> BR.Age4
intToAge4 n
| n < 18 = error "CPS Voter record with age < 18"
| n < 24 = BR.A4_18To24
| n < 45 = BR.A4_25To44
| n < 65 = BR.A4_45To64
| otherwise = BR.A4_65AndOver
intToCollegeGrad :: Int -> BR.CollegeGrad
intToCollegeGrad n = if n < 111 then BR.NonGrad else BR.Grad
intToInCollege :: Int -> Bool
intToInCollege n = n == 4
intToSex :: Int -> BR.Sex
intToSex n = if n == 1 then BR.Male else BR.Female
intToRaceAlone4 :: Int -> BR.RaceAlone4
intToRaceAlone4 rN
| rN == 100 = BR.RA4_White
| rN == 200 = BR.RA4_Black
| rN == 651 = BR.RA4_Asian
| otherwise = BR.RA4_Other
intToHisp :: Int -> BR.Hisp
intToHisp hN
| (hN >= 100) && (hN <= 901) = BR.Hispanic
| otherwise = BR.NonHispanic
intsToRace5 :: Int -> Int -> BR.Race5
intsToRace5 hN rN
| (hN >= 100) && (hN <= 901) = BR.R5_Hispanic
| rN == 100 = BR.R5_WhiteNonHispanic
| rN == 200 = BR.R5_Black
| rN == 651 = BR.R5_Asian
| otherwise = BR.R5_Other
intToIsCitizen :: Int -> Bool
intToIsCitizen n = n /= 5
intToVoteWhyNot :: Int -> BR.VoteWhyNot
intToVoteWhyNot n
| n == 1 = BR.VWN_PhysicallyUnable
| n == 2 = BR.VWN_Away
| n == 3 = BR.VWN_Forgot
| n == 4 = BR.VWN_NotInterested
| n == 5 = BR.VWN_Busy
| n == 6 = BR.VWN_Transport
| n == 7 = BR.VWN_DislikeChoices
| n == 8 = BR.VWN_RegIssue
| n == 9 = BR.VWN_Weather
| n == 10 = BR.VWN_BadPollingPlace
| otherwise = BR.VWN_Other
intToRegWhyNot :: Int -> BR.RegWhyNot
intToRegWhyNot n
| n == 1 = BR.RWN_MissedDeadline
| n == 2 = BR.RWN_DidntKnowHow
| n == 3 = BR.RWN_Residency
| n == 4 = BR.RWN_PhysicallyUnable
| n == 5 = BR.RWN_Language
| n == 6 = BR.RWN_NotInterested
| n == 7 = BR.RWN_MyVoteIrrelevant
| otherwise = BR.RWN_Other
intToVoteHow :: Int -> BR.VoteHow
intToVoteHow n
| n == 1 = BR.VH_InPerson
| n == 2 = BR.VH_ByMail
| otherwise = BR.VH_Other
intToVoteWhen :: Int -> BR.VoteWhen
intToVoteWhen n
| n == 1 = BR.VW_ElectionDay
| n == 2 = BR.VW_BeforeElectionDay
| otherwise = BR.VW_Other
intToVotedYN :: Int -> BR.VotedYN
intToVotedYN n
| n == 1 = BR.VYN_DidNotVote
| n == 2 = BR.VYN_Voted
| n == 96 = BR.VYN_Refused
| n == 97 = BR.VYN_DontKnow
| n == 98 = BR.VYN_NoResponse
| otherwise = BR.VYN_NotInUniverse
cpsPossibleVoter :: BR.VotedYN -> Bool
cpsPossibleVoter BR.VYN_DidNotVote = True
cpsPossibleVoter BR.VYN_Voted = True
cpsPossibleVoter BR.VYN_Refused = False
cpsPossibleVoter BR.VYN_DontKnow = False
cpsPossibleVoter BR.VYN_NoResponse = False
cpsPossibleVoter BR.VYN_NotInUniverse = False
cpsVoted :: BR.VotedYN -> Bool
cpsVoted BR.VYN_Voted = True
cpsVoted _ = False
intToRegisteredYN :: Int -> BR.RegisteredYN
intToRegisteredYN n
| n == 1 = BR.RYN_NotRegistered
| n == 2 = BR.RYN_Registered
| otherwise = BR.RYN_Other
transformCPSVoterPUMSRow :: BR.CPSVoterPUMS_Raw -> F.Record CPSVoterPUMS'
transformCPSVoterPUMSRow = F.rcast . addCols where
addCols = (FT.addOneFromOne @BR.CPSRACE @BR.RaceAlone4C intToRaceAlone4)
. (FT.addOneFromOne @BR.CPSHISPAN @BR.HispC intToHisp)
. (FT.addName @BR.CPSVOSUPPWT @CPSVoterPUMSWeight)
. (FT.addName @BR.CPSCOUNTY @BR.CountyFIPS)
. (FT.addName @BR.CPSSTATEFIP @BR.StateFIPS)
. (FT.addName @BR.CPSYEAR @BR.Year)
. (FT.addOneFromOne @BR.CPSVOREG @BR.RegisteredYNC intToRegisteredYN)
. (FT.addOneFromOne @BR.CPSVOTED @BR.VotedYNC intToVotedYN)
. (FT.addOneFromOne @BR.CPSVOTEWHEN @BR.VoteWhenC intToVoteWhen)
. (FT.addOneFromOne @BR.CPSVOTEHOW @BR.VoteHowC intToVoteHow)
. (FT.addOneFromOne @BR.CPSVOYNOTREG @BR.RegWhyNotC intToRegWhyNot)
. (FT.addOneFromOne @BR.CPSVOWHYNOT @BR.VoteWhyNotC intToVoteWhyNot)
. (FT.addOneFromOne @BR.CPSSCHLCOLL @BR.InCollege intToInCollege)
. (FT.addOneFromOne @BR.CPSEDUC @BR.CollegeGradC intToCollegeGrad)
. (FT.addOneFromOne @BR.CPSCITIZEN @BR.IsCitizen intToIsCitizen)
. (FT.addOneFromOne @BR.CPSSEX @BR.SexC intToSex)
. (FT.addOneFromOne @BR.CPSAGE @BR.Age4C intToAge4)
{-
transformCPSVoterPUMSRow :: BR.CPSVoterPUMS_Raw -> F.Record CPSVoterPUMS'
transformCPSVoterPUMSRow r = F.rcast @CPSVoterPUMS' (mutate r) where
addAge = FT.recordSingleton @BR.Age4C . intToAge4 . F.rgetField @BR.CPSAGE
addSex = FT.recordSingleton @BR.SexC . intToSex . F.rgetField @BR.CPSSEX
hN = F.rgetField @BR.CPSHISPAN
rN = F.rgetField @BR.CPSRACE
addRace r = FT.recordSingleton @BR.Race5C $ intsToRace5 (hN r) (rN r)
addIsCitizen = FT.recordSingleton @BR.IsCitizen . intToIsCitizen . F.rgetField @BR.CPSCITIZEN
addCollegeGrad = FT.recordSingleton @BR.CollegeGradC . intToCollegeGrad . F.rgetField @BR.CPSEDUC
addInCollege = FT.recordSingleton @BR.InCollege . intToInCollege . F.rgetField @BR.CPSSCHLCOLL
addVoteWhyNot = FT.recordSingleton @BR.VoteWhyNotC . intToVoteWhyNot . F.rgetField @BR.CPSVOWHYNOT
addRegWhyNot = FT.recordSingleton @BR.RegWhyNotC . intToRegWhyNot . F.rgetField @BR.CPSVOYNOTREG
addVoteHow = FT.recordSingleton @BR.VoteHowC . intToVoteHow . F.rgetField @BR.CPSVOTEHOW
addVoteWhen = FT.recordSingleton @BR.VoteWhenC . intToVoteWhen . F.rgetField @BR.CPSVOTEWHEN
addVotedYN = FT.recordSingleton @BR.VotedYNC . intToVotedYN . F.rgetField @BR.CPSVOTED
addRegisteredYN = FT.recordSingleton @BR.RegisteredYNC . intToRegisteredYN . F.rgetField @BR.CPSVOREG
mutate = FT.retypeColumn @BR.CPSYEAR @BR.Year
. FT.retypeColumn @BR.CPSSTATEFIP @BR.StateFIPS
. FT.retypeColumn @BR.CPSCOUNTY @BR.CountyFIPS
. FT.mutate addAge
. FT.mutate addSex
. FT.mutate addRace
. FT.mutate addIsCitizen
. FT.mutate addCollegeGrad
. FT.mutate addInCollege
. FT.mutate addVoteWhyNot
. FT.mutate addRegWhyNot
. FT.mutate addVoteHow
. FT.mutate addVoteWhen
. FT.mutate addVotedYN
. FT.mutate addRegisteredYN
. FT.retypeColumn @BR.CPSVOSUPPWT @CPSVoterPUMSWeight
-}
-- to use in maybeRecsToFrame
-- if SCHG indicates not in school we map to 0 so we will interpret as "Not In College"
{-
fixPUMSRow :: F.Rec (Maybe F.:. F.ElField) PUMS_Raw -> F.Rec (Maybe F.:. F.ElField) PUMS_Raw
fixPUMSRow r = (F.rsubset %~ missingInCollegeTo0)
$ r where
missingInCollegeTo0 :: F.Rec (Maybe :. F.ElField) '[BR.PUMSSCHG] -> F.Rec (Maybe :. F.ElField) '[BR.PUMSSCHG]
missingInCollegeTo0 = FM.fromMaybeMono 0
-}
|
lemmas scaleR_cancel_right = real_vector.scale_cancel_right |
subroutine rel_diff(f1,f2,N,res)
implicit none
integer N
real*8 f1(N)
real*8 f2(N)
real*8 res
integer i
res =0.0D0
do i=1, N, 1
if ( dabs(f1(i)-f2(i))/abs(f1(i)) > res ) then
res = dabs(f1(i)-f2(i))/abs(f1(i))
end if
end do
END
|
Former US president Bill Clinton acknowledged the problems and said Americans should " not be deterred from supporting the relief effort " by upsetting scenes such as those of looting . Lt. Gen. P.K. Keen , deputy commander of US Southern Command , however , announced that despite the stories of looting and violence , there was less violent crime in Port @-@ au @-@ Prince after the earthquake than before .
|
/-
Copyright (c) 2021 Ashvni Narayanan. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Ashvni Narayanan
-/
import zmod.properties
/-!
# Properties of p-adic integers
This file adds some properties of `ℤ_[p]`.
## Tags
p-adic
-/
local attribute [instance] zmod.topological_space
lemma discrete_topology.is_topological_basis {α : Type*} [topological_space α]
[discrete_topology α] [monoid α] :
@topological_space.is_topological_basis α _ (set.range set.singleton_monoid_hom) :=
topological_space.is_topological_basis_of_open_of_nhds (λ u hu, is_open_discrete u)
(λ a u mema openu, ⟨({a} : set α), ⟨a, rfl⟩,
set.mem_singleton a, set.singleton_subset_iff.2 mema⟩)
variables {p : ℕ} [fact p.prime]
namespace padic_int
lemma unit_pow_eq_one (a : units ℤ_[p]) :
(padic_int.to_zmod (a : ℤ_[p]))^(p - 1) = (1 : (zmod p)) :=
begin
-- applying FLT
apply zmod.pow_card_sub_one_eq_one,
rw [← ring_hom.coe_monoid_hom, ← units.coe_map],
apply units.ne_zero _,
apply_instance,
end
/-- The ideal p^n ℤ_[p] is the closed ball B(0, 1/p^n) -/
lemma span_eq_closed_ball (n : ℕ) :
metric.closed_ball 0 (1/p^n) = (@ideal.span ℤ_[p] _ {(p^n : ℤ_[p])} : set ℤ_[p]) :=
begin
ext,
simp only [one_div, dist_zero_right, metric.mem_closed_ball, set_like.mem_coe],
rw ←padic_int.norm_le_pow_iff_mem_span_pow, simp,
end
variable (p)
/-- The ideal p^n ℤ_[p] is closed -/
lemma is_closed_span (n : ℕ) : is_closed (@ideal.span ℤ_[p] _ {(p^n : ℤ_[p])} : set ℤ_[p]) :=
(@span_eq_closed_ball p _ n) ▸ metric.is_closed_ball
variable {p}
/-- The ideal p^n ℤ_[p] is the open ball B(0, 1/p^(1 - n)) -/
lemma span_eq_open_ball (n : ℕ) :
metric.ball 0 ((p : ℝ) ^ (1 - (n : ℤ))) = (@ideal.span ℤ_[p] _ {(p^n : ℤ_[p])} : set ℤ_[p]) :=
begin
ext,
simp only [mem_ball_zero_iff, set_like.mem_coe],
rw [←padic_int.norm_le_pow_iff_mem_span_pow, padic_int.norm_le_pow_iff_norm_lt_pow_add_one,
sub_eq_neg_add 1 (n : ℤ)],
end
variable (p)
/-- The ideal p^n ℤ_[p] is open -/
lemma is_open_span (n : ℕ) : is_open ((ideal.span {p ^ n} : ideal ℤ_[p]) : set ℤ_[p]) :=
(@span_eq_open_ball p _ n) ▸ metric.is_open_ball
/-- The ideal p^n ℤ_[p] is clopen -/
lemma is_clopen_span (n : ℕ) : is_clopen ((ideal.span {p ^ n} : ideal ℤ_[p]) : set ℤ_[p]) :=
⟨is_open_span p n, is_closed_span p n⟩
variable {p}
-- enable set addition for additive groups
open_locale pointwise
open zmod
-- this is more generally a property of profinite groups
lemma preimage_to_zmod_pow {n : ℕ} (x : zmod (p^n)) : (@to_zmod_pow p _ n) ⁻¹' {x} =
{(x : ℤ_[p])} + (((@to_zmod_pow p _ n).ker : ideal ℤ_[p]) : set ℤ_[p]) :=
begin
ext y,
simp only [set.image_add_left, set.mem_preimage, set.singleton_add, set.mem_singleton_iff,
set_like.mem_coe, ring_hom.mem_ker, neg_add_eq_zero, ring_hom.map_add, ring_hom.map_neg,
ring_hom_map_cast],
rw eq_comm,
end
/-- The map `to_zmod_pow` is continuous. -/
lemma continuous_to_zmod_pow (n : ℕ) : continuous (@padic_int.to_zmod_pow p _ n) :=
topological_space.is_topological_basis.continuous discrete_topology.is_topological_basis _
(λ s ⟨x, hx⟩, begin
change {x} = s at hx,
rw [←hx, preimage_to_zmod_pow, ker_to_zmod_pow],
refine is_open.add_left (is_open_span p n), end )
variable (d : ℕ)
/-- The preimage of any singleton under `to_zmod_pow` is clopen. -/
lemma proj_lim_preimage_clopen {n : ℕ} (a : zmod (d*(p^n))) :
is_clopen (set.preimage (padic_int.to_zmod_pow n) {a} : set ℤ_[p]) :=
⟨continuous_def.mp (continuous_to_zmod_pow n) {a} trivial,
continuous_iff_is_closed.mp (continuous_to_zmod_pow n) {a} (is_closed_discrete {a})⟩
/-- The preimage of any singleton under `to_zmod_pow` is clopen. -/
lemma proj_lim_preimage_clopen_one (n : ℕ) (a : zmod (p^n)) :
is_clopen (set.preimage (padic_int.to_zmod_pow n) {a} : set ℤ_[p]) :=
by { have := proj_lim_preimage_clopen 1 a, rw one_mul at this, convert this, simp, }
lemma singleton_add_ball {S : Type*} [normed_group S] (x y : S) (r : ℝ) :
({x} : set S) + metric.ball y r = metric.ball (x + y) r :=
begin
ext z,
have : dist (-x + z) y = dist z (x + y),
{ simp_rw [dist_eq_norm],
refine congr_arg _ _,
rw [← sub_sub, sub_eq_add_neg z x, add_comm z _], },
simp [this, add_comm],
end
/-- The preimage of a singleton x is a ball centered at x. -/
lemma preimage_to_zmod_pow_eq_ball {n : ℕ} (x : zmod (p^n)) :
(padic_int.to_zmod_pow n) ⁻¹' {(x : zmod (p^n))} =
metric.ball (x : ℤ_[p]) ((p : ℝ) ^ (1 - (n : ℤ))) :=
by { rw [preimage_to_zmod_pow, ker_to_zmod_pow, ←span_eq_open_ball, singleton_add_ball, add_zero], }
open nat
lemma cast_to_zmod_pow_eq_appr (a : ℤ_[p]) (n : ℕ) : ((to_zmod_pow n a) : ℤ_[p]) = a.appr n :=
begin
dsimp [to_zmod_pow, to_zmod_hom], rw ←zmod.nat_cast_comp_val ℤ_[p],
{ simp only [nat.cast_inj], apply zmod.val_cast_of_lt (appr_lt _ _), },
exact fact.pow.pos,
end
variable (p)
lemma exists_one_div_pow_lt_of_prime {ε : ℝ} (h : (0 < ε)) : ∃ (n : ℕ), (1 / (p^n) : ℝ) < ε :=
begin
convert exists_pow_lt_of_lt_one h _,
swap, { exact 1/p, },
{ simp only [one_div, inv_pow], },
rw div_lt_iff _,
{ simp only [one_mul, one_lt_cast], apply nat.prime.one_lt (fact.out _), assumption, },
simp only [cast_pos], apply nat.prime.pos (fact.out _), assumption,
end
variable {p}
lemma dist_appr_spec (a : ℤ_[p]) (n : ℕ) : dist a ((a.appr n) : ℤ_[p]) ≤ (p : ℝ)^(-n : ℤ) :=
(dist_eq_norm a (a.appr n)).symm ▸ ((norm_le_pow_iff_mem_span_pow _ _).2 (appr_spec n a))
instance [fact (0 < d)] : compact_space (zmod d) := fintype.compact_space
lemma totally_bounded : totally_bounded (λ (x : ℚ_[p]), ∥x∥ ≤ 1) :=
metric.totally_bounded_of_finite_discretization (λ ε hε, begin
obtain ⟨m, fm⟩ := exists_one_div_pow_lt_of_prime p (half_pos hε),
have f : (2 : ℝ) / (p^m) = (1 / (p^m)) + (1 : ℝ) / (p^m), { rw ← _root_.add_div, refl, },
have fm' : (2 : ℝ)/(p^m) < ε, { rw [f, ← add_halves ε], apply add_lt_add fm fm, },
have f' : ↑p ^ (1 - (m.succ : ℤ)) = (1 : ℝ) / (p^m),
{ symmetry, rw [div_eq_iff _, ←zpow_coe_nat, ← zpow_add₀ _],
norm_num, rw sub_add, rw add_sub_cancel', rw sub_self, rw zpow_zero,
any_goals { apply pow_ne_zero, },
all_goals { norm_cast, apply nat.prime.ne_zero, apply fact.out, }, },
have f'' : ↑p ^ -(m.succ : ℤ) < (1 : ℝ) / (p^m),
{ rw div_eq_inv_mul, rw mul_one, rw zpow_neg, rw inv_lt_inv,
{ rw zpow_coe_nat, apply pow_lt_pow _ (lt_add_one _), norm_cast,
apply nat.prime.one_lt (fact.out _), assumption, },
any_goals { norm_cast, apply pow_pos, apply nat.prime.pos, rw fact_iff at *, assumption, }, },
refine ⟨zmod (p^m.succ), @zmod.fintype _ fact.pow.pos, to_zmod_pow m.succ, λ x y h,
lt_trans (gt_of_gt_of_ge _ (dist_triangle x (appr y m.succ) y)) fm'⟩,
rw [←set.mem_singleton_iff, ←set.mem_preimage, preimage_to_zmod_pow_eq_ball, metric.mem_ball,
cast_to_zmod_pow_eq_appr, f'] at h,
rw [f, dist_comm _ ↑y, add_comm (dist _ _) _],
have := add_lt_add (gt_of_gt_of_ge f'' (ge_iff_le.2 (dist_appr_spec y (m.succ)))) h,
rw [subtype.dist_eq y _, subtype.dist_eq x _, padic_int.coe_coe] at this,
exact this, end)
instance : compact_space ℤ_[p] := is_compact_iff_compact_space.mp
(compact_iff_totally_bounded_complete.mpr ⟨totally_bounded,
complete_space_coe_iff_is_complete.mp (show complete_space ℤ_[p], from infer_instance)⟩)
-- this implies tot disc, hence `ℤ_[p]` is profinite!
instance : totally_separated_space ℤ_[p] :=
{ is_totally_separated_univ := λ x hx y hx ne, begin
obtain ⟨n,hn⟩ : ∃ (n : ℕ), to_zmod_pow n x ≠ to_zmod_pow n y,
{ contrapose ne, push_neg at ne, rw ext_of_to_zmod_pow at ne,
simp only [ne, _root_.ne.def, eq_self_iff_true, not_true, not_false_iff], },
obtain ⟨u, v, hu, hv, memu, memv, univ, disj⟩ :=
(totally_separated_space.is_totally_separated_univ (zmod (p ^ n))) (to_zmod_pow n x)
(set.mem_univ _) (to_zmod_pow n y) (set.mem_univ _) hn,
refine ⟨(to_zmod_pow n)⁻¹' u, (to_zmod_pow n)⁻¹' v,
continuous_def.mp (continuous_to_zmod_pow n) u hu,
continuous_def.mp (continuous_to_zmod_pow n) v hv,
set.mem_preimage.mpr memu, set.mem_preimage.mpr memv, λ z hz, _, _⟩,
{ rw set.mem_union,
have univ' := univ (set.mem_univ (to_zmod_pow n z)),
cases univ',
{ left, apply set.mem_preimage.mpr univ', },
{ right, apply set.mem_preimage.mpr univ', }, },
{ ext z,
rw [←@set.preimage_empty _ _ (to_zmod_pow n), set.mem_preimage],
rw set.ext_iff at disj, specialize disj (to_zmod_pow n z),
simp only [set.mem_inter_eq, set.mem_preimage, set.mem_empty_eq, iff_false, not_and],
simp only [set.mem_inter_eq, set.mem_empty_eq, iff_false, not_and] at disj, assumption, },
end, }
lemma proj_lim_preimage_clopen' {n : ℕ} (a : zmod (p^n)) :
is_clopen (set.preimage (padic_int.to_zmod_pow n) {a} : set ℤ_[p]) :=
⟨continuous_def.mp (continuous_to_zmod_pow n) {a} trivial,
continuous_iff_is_closed.mp (continuous_to_zmod_pow n) {a} (by simp)⟩
variables {p}
lemma ball_mem_unit {x z : ℤ_[p]} (hx : is_unit x) {r : ℝ} (memz : z ∈ metric.ball x r)
(le_one : r ≤ 1) : is_unit z :=
begin
rw [is_unit_iff, ←(is_unit_iff.1 hx), ←norm_neg x],
apply norm_eq_of_norm_add_lt_right,
rw [norm_neg x, ←sub_eq_add_neg, is_unit_iff.1 hx],
refine gt_of_ge_of_gt le_one (dist_eq_norm z x ▸ metric.mem_ball.1 memz),
end
lemma inv_mem_inv_ball {x z : units ℤ_[p]} {r : ℝ} (h : r ≤ 1) (hz : z.val ∈ metric.ball x.val r) :
z.inv ∈ metric.ball x.inv r :=
begin
rw mem_ball_iff_norm,
suffices : ∥z.val * x.val∥ * ∥z.inv - x.inv∥ < r,
{ rw [padic_int.norm_mul, is_unit_iff.1 (ball_mem_unit (units.is_unit _) hz h),
units.val_eq_coe, is_unit_iff.1 (units.is_unit x), one_mul, one_mul] at this,
exact this, },
{ rw [←padic_int.norm_mul, mul_sub, mul_right_comm, mul_assoc _ x.val _, units.val_inv,
units.val_inv, one_mul, mul_one, norm_sub_rev],
exact mem_ball_iff_norm.1 hz, },
end
lemma top_eq_if_cont_inv' {α : Type*} [topological_space α] [monoid α]
(h : @continuous _ _ (topological_space.induced (units.coe_hom α) infer_instance)
infer_instance (@units.inv α _)) :
topological_space.induced (units.coe_hom α) infer_instance ≤ units.topological_space :=
continuous_iff_le_induced.1 begin
-- if I replace this with refine or try to bring it into term mode, I get an incorrect typeclass
-- instance synthesized error
apply continuous.prod_mk continuous_induced_dom (continuous.comp mul_opposite.continuous_op _),
{ convert h, }, end
lemma cont_inv : @continuous _ _ (topological_space.induced (units.coe_hom ℤ_[p]) infer_instance)
infer_instance (@units.inv ℤ_[p] _) :=
begin
-- it is very hard to work in term mode because Lean always infers the incorrect topological
-- structure on the units
rw continuous_def, intros s hs,
rw is_open_iff_forall_mem_open,
rintros x hx,
rw metric.is_open_iff at hs,
obtain ⟨r, r_pos, hs⟩ := hs _ hx,
by_cases r ≤ 1,
{ refine ⟨(units.inv)⁻¹' metric.ball x.inv r, λ z hz, hs hz, is_open_induced_iff.2
⟨metric.ball x.val r, metric.is_open_ball, _⟩, metric.mem_ball_self r_pos⟩,
ext z,
rw [set.mem_preimage, set.mem_preimage],
refine ⟨λ hz, inv_mem_inv_ball h hz, λ hz, _⟩,
repeat { rw [units.inv_eq_coe_inv, ←units.val_eq_coe] at hz },
rw [←inv_inv x, ←inv_inv z],
apply inv_mem_inv_ball h hz, },
{ refine ⟨(units.inv)⁻¹' metric.ball x.inv 1, λ z hz, hs (metric.ball_subset_ball (le_of_lt
(not_le.1 h)) hz), is_open_induced_iff.2 ⟨metric.ball x.val 1, metric.is_open_ball, _⟩,
metric.mem_ball_self (zero_lt_one)⟩,
ext z,
rw [set.mem_preimage, set.mem_preimage],
refine ⟨λ hz, inv_mem_inv_ball rfl.ge hz, λ hz, _⟩,
repeat { rw [units.inv_eq_coe_inv, ←units.val_eq_coe] at hz, },
rw [←inv_inv x, ←inv_inv z],
convert inv_mem_inv_ball (rfl.ge) hz, rw inv_inv, },
end
lemma top_eq_iff_cont_inv {α : Type*} [monoid α] [topological_space α] :
topological_space.induced (units.coe_hom α) infer_instance = units.topological_space ↔
@continuous _ _ (topological_space.induced (units.coe_hom α) infer_instance)
infer_instance (@units.inv α _) :=
begin
refine ⟨λ h, _, λ h,
le_antisymm (top_eq_if_cont_inv' h) (continuous_iff_le_induced.1 units.continuous_coe)⟩,
{ rw h,
have h1 : prod.snd ∘ (units.embed_product α) = mul_opposite.op ∘ units.val ∘ units.has_inv.inv,
{ ext,
rw units.embed_product,
simp only [function.comp_app, units.val_eq_coe, monoid_hom.coe_mk], },
have h2 : continuous (prod.snd ∘ (units.embed_product α)) :=
continuous.comp continuous_snd continuous_induced_dom,
rw h1 at h2,
have h3 := continuous.comp (@mul_opposite.continuous_unop α _) h2,
-- cant substitute h3 as it is, get errors
exact h3, },
end
lemma is_open_coe : is_open_map (coe : units ℤ_[p] → ℤ_[p]) := λ U hU,
begin
rw ←(top_eq_iff_cont_inv.2 cont_inv) at hU, -- need this!
rw is_open_induced_iff at hU,
rcases hU with ⟨t, ht, htU⟩,
refine is_open_iff_forall_mem_open.2 (λ x hx, _),
rcases hx with ⟨y, hy, hyx⟩,
have memt : x ∈ t,
{ rw [←htU, set.mem_preimage, units.coe_hom_apply, hyx] at hy,
apply hy, },
rw metric.is_open_iff at ht,
obtain ⟨r, r_pos, ht⟩ := ht x memt,
have is_unit_x : is_unit x,
{ rw ←hyx, simp only [units.is_unit], },
by_cases r ≤ 1,
{ refine ⟨metric.ball x r, λ z hz, ⟨is_unit.unit (ball_mem_unit is_unit_x hz h), htU ▸ (ht hz),
is_unit.unit_spec (ball_mem_unit is_unit_x hz h)⟩, metric.is_open_ball,
metric.mem_ball_self r_pos⟩, },
{ refine ⟨metric.ball x 1, λ z hz, ⟨is_unit.unit (ball_mem_unit is_unit_x hz le_rfl),
htU ▸ (ht ((metric.ball_subset_ball (le_of_lt (not_le.1 h))) hz)), is_unit.unit_spec
(ball_mem_unit is_unit_x hz le_rfl)⟩, metric.is_open_ball, metric.mem_ball_self zero_lt_one⟩, },
end
lemma is_open_coe' : is_open_map (coe : units (zmod d) → zmod d) :=
inducing.is_open_map { induced := (top_eq_iff_cont_inv.2 begin
convert continuous_of_discrete_topology, apply discrete_topology_induced,
exact units.ext, end).symm } trivial
lemma is_closed_coe : is_closed (set.range (coe : units ℤ_[p] → ℤ_[p])) :=
begin
have : set.range (coe : units ℤ_[p] → ℤ_[p]) = set.preimage norm {1},
{ ext x,
simp only [set.mem_range, set.mem_preimage, set.mem_singleton_iff],
rw ←is_unit_iff,
refine ⟨λ h, h.some_spec ▸ (units.is_unit h.some), λ h, ⟨is_unit.unit h, is_unit.unit_spec _⟩⟩, },
{ refine this.symm ▸ continuous_iff_is_closed.mp continuous_norm {1} (t1_space.t1 1), },
end
lemma emb_coe : embedding (coe : units ℤ_[p] → ℤ_[p]) :=
{ induced := (top_eq_iff_cont_inv.2 cont_inv).symm,
inj := units.ext, }
lemma open_embedding_coe : open_embedding (coe : ℤ_[p]ˣ → ℤ_[p]) :=
⟨emb_coe, (is_open_coe).is_open_range⟩
instance : compact_space ℤ_[p]ˣ :=
{ compact_univ := (embedding.is_compact_iff_is_compact_image emb_coe).2
(compact_of_is_closed_subset compact_univ
((@set.image_univ ℤ_[p]ˣ ℤ_[p] coe).symm ▸ is_closed_coe) (set.subset_univ _)) }
instance : t2_space ℤ_[p]ˣ := embedding.t2_space emb_coe
instance : totally_disconnected_space ℤ_[p]ˣ :=
{ is_totally_disconnected_univ := embedding.is_totally_disconnected emb_coe
(is_totally_disconnected_of_totally_disconnected_space (coe '' set.univ)) }
open_locale pointwise -- needed for has_add (set ℤ_[p])
lemma preimage_to_zmod (x : zmod p) : (@to_zmod p _) ⁻¹' {x} =
{(x : ℤ_[p])} + (((@to_zmod p _).ker : ideal ℤ_[p]) : set ℤ_[p]) :=
begin
ext y,
simp only [set.image_add_left, set.mem_preimage, set.singleton_add,
set.mem_singleton_iff, set_like.mem_coe],
refine ⟨λ h, _, λ h, _⟩,
{ simp only [ring_hom.mem_ker, map_add, map_neg, ring_hom_map_cast, neg_add_eq_zero, h.symm], },
{ simp only [ring_hom.mem_ker, map_add, map_neg, ring_hom_map_cast, neg_add_eq_zero] at h,
exact h.symm, },
end
lemma continuous_to_zmod : continuous (@padic_int.to_zmod p _) :=
topological_space.is_topological_basis.continuous discrete_topology.is_topological_basis _ (λ s hs,
begin
cases hs with x hx,
change {x} = s at hx,
rw [←hx, preimage_to_zmod, ker_to_zmod],
refine is_open.add_left _,
convert is_open_span p 1,
rw [pow_one, maximal_ideal_eq_span_p], end)
lemma is_unit_padic_of_is_unit_zmod {x : ℕ} (h : x.coprime p) :
is_unit (x : ℤ_[p]) :=
begin
rw is_unit_iff,
contrapose h,
have hx' := lt_of_le_of_ne (norm_le_one _) h,
change ∥((x : ℤ) : ℤ_[p])∥ < 1 at hx',
rw norm_int_lt_one_iff_dvd at hx',
norm_cast at hx',
rw [nat.coprime_comm, nat.prime.coprime_iff_not_dvd _, not_not],
{ assumption, },
{ apply fact.out, },
end
lemma nat_is_unit_of_not_dvd {z : ℕ} (h : ¬ p ∣ z) : is_unit (z : ℤ_[p]) :=
begin
contrapose h,
rw [not_not, ←int.coe_nat_dvd, ←padic_int.norm_int_lt_one_iff_dvd],
apply padic_int.mem_nonunits.1 h,
end
lemma cont_units_map {α β : Type*} [topological_space α] [monoid α] [topological_space β] [monoid β]
(ha : @continuous _ _ (topological_space.induced (units.coe_hom α) infer_instance)
infer_instance (@units.inv α _))
(hb : @continuous _ _ (topological_space.induced (units.coe_hom β) infer_instance)
infer_instance (@units.inv β _)) {f : α →* β} (hf : continuous f) :
continuous (units.map f) :=
{ is_open_preimage := λ s hs, begin
rw (top_eq_iff_cont_inv.2 ha).symm,
rw [(top_eq_iff_cont_inv.2 hb).symm, is_open_induced_iff] at hs,
rcases hs with ⟨t, ht, hs⟩,
rw ←hs,
convert_to is_open ((units.coe_hom α)⁻¹' (f⁻¹' t)),
{ rw top_eq_iff_cont_inv.2 ha, },
{ apply continuous.is_open_preimage (continuous.comp hf units.continuous_coe) t ht, }, end, }
lemma continuous_units (n : ℕ) :
continuous (units.map (@padic_int.to_zmod_pow p _ n).to_monoid_hom) :=
cont_units_map cont_inv induced_top_cont_inv (padic_int.continuous_to_zmod_pow n)
lemma proj_lim_preimage_units_clopen {n : ℕ} (a : (zmod (p^n))ˣ) :
is_clopen ((units.map (@padic_int.to_zmod_pow p _ n).to_monoid_hom) ⁻¹' {a}) :=
⟨continuous_def.mp (continuous_units n) {a} (is_open_discrete _),
continuous_iff_is_closed.mp (continuous_units n) {a} (is_closed_discrete {a})⟩
variable (p)
lemma is_unit_to_zmod_pow_of_is_unit {n : ℕ} (hn : 1 < n) (x : ℤ_[p])
(hx : is_unit (to_zmod_pow n x)) : is_unit x :=
begin
rw padic_int.is_unit_iff,
by_contra h,
have hx' := lt_of_le_of_ne (padic_int.norm_le_one _) h,
rw padic_int.norm_lt_one_iff_dvd at hx',
cases hx' with y hy,
rw hy at hx,
rw ring_hom.map_mul at hx,
rw is_unit.mul_iff at hx,
simp only [map_nat_cast] at hx,
have : ¬ is_unit (p : zmod (p^n)),
{ intro h,
set q : (zmod (p^n))ˣ := is_unit.unit h,
have := zmod.val_coe_unit_coprime q,
rw is_unit.unit_spec at this,
rw nat.coprime_pow_right_iff (lt_trans zero_lt_one hn) at this,
rw zmod.val_cast_of_lt _ at this,
simp only [nat.coprime_self] at this,
apply @nat.prime.ne_one p (fact.out _),
rw this,
conv { congr, rw ← pow_one p, },
rw pow_lt_pow_iff _, apply hn,
apply nat.prime.one_lt (fact.out _),
apply_instance, },
apply this, apply hx.1,
end
end padic_int
|
module Postgres.Data.ConnectionStatus
public export
data ConnectionStatus = OK
| BAD
| STARTED
| MADE
| AWAITING_RESPONSE
| AUTH_OK
| SETENV
| SSL_STARTUP
| NEEDED
| OTHER Int
export
Show ConnectionStatus where
show OK = "OK"
show BAD = "BAD"
show STARTED = "STARTED"
show MADE = "MADE"
show AWAITING_RESPONSE = "AWAITING_RESPONSE"
show AUTH_OK = "AUTH_OK"
show SETENV = "SETENV"
show SSL_STARTUP = "SSL_STARTUP"
show NEEDED = "NEEDED"
show (OTHER x) = "OTHER " ++ (show x)
|
# Concatenate arrays
Concatenation([1, 2, 3], [4, 5, 6], [7, 8, 9]);
# [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
# Append to a variable
a := [1, 2, 3];
Append(a, [4, 5, 6);
Append(a, [7, 8, 9]);
a;
# [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
|
import LMT
variable {I} [Nonempty I] {E} [Nonempty E] [Nonempty (A I E)]
example {a1 a2 a3 : A I E} :
(v1) ≠ ((((a1).write i1 (v1)).write i2 (v1)).read i1) → False := by
arr
|
------------------------------------------------------------------------
-- Lemmas related to expansion and CCS
------------------------------------------------------------------------
{-# OPTIONS --sized-types #-}
open import Prelude hiding (module W; step-→)
module Expansion.CCS {ℓ} {Name : Type ℓ} where
open import Equality.Propositional
open import Prelude.Size
open import Function-universe equality-with-J hiding (id; _∘_)
import Bisimilarity.CCS as SL
import Bisimilarity.Equational-reasoning-instances
import Bisimilarity.Weak.Equational-reasoning-instances
open import Equational-reasoning
import Expansion.Equational-reasoning-instances
open import Labelled-transition-system.CCS Name
open import Relation
open import Bisimilarity CCS as S using (_∼_)
open import Bisimilarity.Weak CCS as W using (_≈_; force)
open import Expansion CCS
import Labelled-transition-system.Equational-reasoning-instances CCS
as Dummy
-- Some lemmas used to prove the congruence lemmas below as well as
-- similar results in Bisimilarity.Weak.CCS.
module Cong-lemmas
({R} R′ : Proc ∞ → Proc ∞ → Type ℓ)
⦃ _ : Reflexive R′ ⦄
⦃ _ : Convertible R R′ ⦄
⦃ _ : Convertible R′ R′ ⦄
⦃ _ : Transitive′ R′ _∼_ ⦄
⦃ _ : Transitive _∼_ R′ ⦄
{_[_]↝_ : Proc ∞ → Label → Proc ∞ → Type ℓ}
(right-to-left :
∀ {P Q} → R P Q →
∀ {Q′ μ} → Q [ μ ]⟶ Q′ → ∃ λ P′ → P [ μ ]↝ P′ × R′ P′ Q′)
⦃ _ : ∀ {μ} → Convertible _[ μ ]↝_ _[ μ ]↝_ ⦄
⦃ _ : ∀ {μ} → Convertible _[ μ ]⟶_ _[ μ ]↝_ ⦄
(↝→[]⇒ : ∀ {P Q a} → P [ name a ]↝ Q → P [ name a ]⇒ Q)
([]⇒→↝ : ∀ {P Q} → P [ τ ]⇒ Q → P [ τ ]↝ Q)
(map-↝ :
{F : Proc ∞ → Proc ∞} →
(∀ {P P′ μ} → P [ μ ]⟶ P′ → F P [ μ ]⟶ F P′) →
∀ {P P′ μ} → P [ μ ]↝ P′ → F P [ μ ]↝ F P′)
(map-↝′ :
∀ {μ} {F : Proc ∞ → Proc ∞} →
(∀ {P P′ μ} → Silent μ → P [ μ ]⟶ P′ → F P [ μ ]⟶ F P′) →
(∀ {P P′} → P [ μ ]⟶ P′ → F P [ μ ]⟶ F P′) →
∀ {P P′} → P [ μ ]↝ P′ → F P [ μ ]↝ F P′)
(zip-↝ :
{F : Proc ∞ → Proc ∞ → Proc ∞} →
(∀ {P P′ Q μ} → P [ μ ]⟶ P′ → F P Q [ μ ]⟶ F P′ Q) →
(∀ {P Q Q′ μ} → Q [ μ ]⟶ Q′ → F P Q [ μ ]⟶ F P Q′) →
∀ {μ₁ μ₂ μ₃} →
(Silent μ₁ → Silent μ₂ → Silent μ₃) →
(∀ {P P′ Q} → P [ μ₁ ]⟶ P′ → Silent μ₂ → F P Q [ μ₃ ]⟶ F P′ Q) →
(∀ {P Q Q′} → Silent μ₁ → Q [ μ₂ ]⟶ Q′ → F P Q [ μ₃ ]⟶ F P Q′) →
(∀ {P P′ Q Q′} →
P [ μ₁ ]⟶ P′ → Q [ μ₂ ]⟶ Q′ → F P Q [ μ₃ ]⟶ F P′ Q′) →
∀ {P P′ Q Q′} →
P [ μ₁ ]↝ P′ → Q [ μ₂ ]↝ Q′ → F P Q [ μ₃ ]↝ F P′ Q′)
(!-lemma :
(∀ {P Q μ} → P [ μ ]⇒ Q → ! P [ μ ]⇒ ! P ∣ Q) →
∀ {P Q μ} → P [ μ ]↝ Q →
∃ λ P′ → ((! P) [ μ ]↝ P′) × P′ ∼ ! P ∣ Q)
where
private
infix -3 rl-result-↝
rl-result-↝ : ∀ {P P′ Q′} μ → P [ μ ]↝ P′ → R′ P′ Q′ →
∃ λ P′ → (P [ μ ]↝ P′) × R′ P′ Q′
rl-result-↝ _ P↝P′ P′≳′Q′ = _ , P↝P′ , P′≳′Q′
syntax rl-result-↝ μ P↝P′ P′≳′Q′ = P↝P′ ↝[ μ ] P′≳′Q′
∣-cong :
(∀ {P P′ Q Q′} → R′ P P′ → R′ Q Q′ → R′ (P ∣ Q) (P′ ∣ Q′)) →
∀ {P₁ P₂ Q₁ Q₂ R₂ μ} →
R P₁ P₂ → R Q₁ Q₂ → P₂ ∣ Q₂ [ μ ]⟶ R₂ →
∃ λ R₁ → ((P₁ ∣ Q₁) [ μ ]↝ R₁) × R′ R₁ R₂
∣-cong _∣-cong′_ P₁≳P₂ Q₁≳Q₂ = λ where
(par-left tr) → Σ-map (_∣ _)
(Σ-map (map-↝ par-left)
(_∣-cong′ convert Q₁≳Q₂))
(right-to-left P₁≳P₂ tr)
(par-right tr) → Σ-map (_ ∣_)
(Σ-map (map-↝ par-right)
(convert P₁≳P₂ ∣-cong′_))
(right-to-left Q₁≳Q₂ tr)
(par-τ tr₁ tr₂) → Σ-zip _∣_
(Σ-zip (zip-↝ par-left par-right
(λ ()) (λ _ ()) (λ ())
par-τ)
_∣-cong′_)
(right-to-left P₁≳P₂ tr₁)
(right-to-left Q₁≳Q₂ tr₂)
·-cong :
∀ {P₁ P₂ Q₂ μ μ′} →
R′ (force P₁) (force P₂) → μ · P₂ [ μ′ ]⟶ Q₂ →
∃ λ Q₁ → ((μ · P₁) [ μ′ ]↝ Q₁) × R′ Q₁ Q₂
·-cong P₁≳P₂ action = _ , convert (⟶: action) , P₁≳P₂
⟨ν⟩-cong :
(∀ {a P P′} → R′ P P′ → R′ (⟨ν a ⟩ P) (⟨ν a ⟩ P′)) →
∀ {a μ P P′ Q′} →
R P P′ → ⟨ν a ⟩ P′ [ μ ]⟶ Q′ →
∃ λ Q → (⟨ν a ⟩ P [ μ ]↝ Q) × R′ Q Q′
⟨ν⟩-cong ⟨ν⟩-cong′ {a} {μ} {P} P≳P′
(restriction {P′ = Q′} a∉μ P′⟶Q′) =
case right-to-left P≳P′ P′⟶Q′ of λ where
(Q , P↝Q , Q≳′Q′) →
⟨ν a ⟩ P →⟨ map-↝′ (restriction ∘ ∉τ) (restriction a∉μ) P↝Q ⟩■
↝[ μ ]
⟨ν a ⟩ Q ∼⟨ ⟨ν⟩-cong′ Q≳′Q′ ⟩■
⟨ν a ⟩ Q′
!-cong-lemma₁ : ∀ {P Q μ} → P [ μ ]⇒ Q → ! P [ μ ]⇒ ! P ∣ Q
!-cong-lemma₁ {P} {Q} {μ} = λ where
(steps {q′ = Q′} done P⟶Q′ Q′⇒Q) →
! P [ μ ]⇒⟨ replication (par-right P⟶Q′) ⟩
! P ∣ Q′ →⟨ map-⇒ par-right Q′⇒Q ⟩■
! P ∣ Q
(steps {p′ = P″} {q′ = Q′}
(step {q = P′} {μ = μ′} μ′s P⟶P′ P′⇒P″)
P″⟶Q′ Q′⇒Q) →
! P →⟨ ⟶→⇒ μ′s (replication (par-right P⟶P′)) ⟩
! P ∣ P′ →⟨ map-⇒ par-right P′⇒P″ ⟩
! P ∣ P″ [ μ ]⇒⟨ par-right P″⟶Q′ ⟩
! P ∣ Q′ →⟨ map-⇒ par-right Q′⇒Q ⟩■
! P ∣ Q
!-cong-lemma₂ :
∀ {P Q₁ Q₂ a} →
P [ name a ]⇒ Q₁ → P [ name (co a) ]⇒ Q₂ →
∃ λ R → ! P [ τ ]⇒ R × R ∼ (! P ∣ Q₁) ∣ Q₂
!-cong-lemma₂ {P} {Q₁} {Q₂} {a} = λ where
(steps {q′ = Q₁′} done P⟶Q₁′ Q₁′⇒Q₁)
(steps {q′ = Q₂′} done P⟶Q₂′ Q₂′⇒Q₂) →
_
, (! P [ τ ]⇒⟨ replication (par-τ (replication (par-right P⟶Q₁′)) P⟶Q₂′) ⟩
(! P ∣ Q₁′) ∣ Q₂′ →⟨ zip-⇒ par-left par-right (map-⇒ par-right Q₁′⇒Q₁) Q₂′⇒Q₂ ⟩■
(! P ∣ Q₁) ∣ Q₂)
, reflexive
(steps {q′ = Q₁′} done P⟶Q₁′ Q₁′⇒Q₁)
(steps {p′ = P₂″} {q′ = Q₂′}
(step {q = P₂′} {μ = μ} μs P⟶P₂′ P₂′⇒P₂″)
P₂″⟶Q₂′ Q₂′⇒Q₂) →
_
, (! P →⟨ ⟶→⇒ μs (replication (par-right P⟶P₂′)) ⟩
! P ∣ P₂′ →⟨ map-⇒ par-right P₂′⇒P₂″ ⟩
! P ∣ P₂″ [ τ ]⇒⟨ par-τ (replication (par-right P⟶Q₁′)) P₂″⟶Q₂′ ⟩
(! P ∣ Q₁′) ∣ Q₂′ →⟨ zip-⇒ par-left par-right (map-⇒ par-right Q₁′⇒Q₁) Q₂′⇒Q₂ ⟩■
(! P ∣ Q₁) ∣ Q₂)
, reflexive
(steps {p′ = P₁″} {q′ = Q₁′}
(step {q = P₁′} {μ = μ} μs P⟶P₁′ P₁′⇒P₁″)
P₁″⟶Q₁′ Q₁′⇒Q₁)
(steps {q′ = Q₂′} done P⟶Q₂′ Q₂′⇒Q₂) →
_
, (! P →⟨ ⟶→⇒ μs (replication (par-right P⟶P₁′)) ⟩
! P ∣ P₁′ →⟨ map-⇒ par-right P₁′⇒P₁″ ⟩
! P ∣ P₁″ [ τ ]⇒⟨ par-τ′ (sym $ co-involutive a) (replication (par-right P⟶Q₂′)) P₁″⟶Q₁′ ⟩
(! P ∣ Q₂′) ∣ Q₁′ →⟨ zip-⇒ par-left par-right (map-⇒ par-right Q₂′⇒Q₂) Q₁′⇒Q₁ ⟩■
(! P ∣ Q₂) ∣ Q₁)
, ((! P ∣ Q₂) ∣ Q₁ ∼⟨ SL.swap-rightmost ⟩■
(! P ∣ Q₁) ∣ Q₂)
(steps {p′ = P₁″} {q′ = Q₁′}
(step {q = P₁′} {μ = μ₁} μ₁s P⟶P₁′ P₁′⇒P₁″)
P₁″⟶Q₁′ Q₁′⇒Q₁)
(steps {p′ = P₂″} {q′ = Q₂′}
(step {q = P₂′} {μ = μ₂} μ₂s P⟶P₂′ P₂′⇒P₂″)
P₂″⟶Q₂′ Q₂′⇒Q₂) →
_
, (! P →⟨ ⟶→⇒ μ₂s (replication (par-right P⟶P₂′)) ⟩
! P ∣ P₂′ →⟨ ⟶→⇒ μ₁s (par-left (replication (par-right P⟶P₁′))) ⟩
(! P ∣ P₁′) ∣ P₂′ →⟨ zip-⇒ par-left par-right (map-⇒ par-right P₁′⇒P₁″) P₂′⇒P₂″ ⟩
(! P ∣ P₁″) ∣ P₂″ [ τ ]⇒⟨ par-τ (par-right P₁″⟶Q₁′) P₂″⟶Q₂′ ⟩
(! P ∣ Q₁′) ∣ Q₂′ →⟨ zip-⇒ par-left par-right (map-⇒ par-right Q₁′⇒Q₁) Q₂′⇒Q₂ ⟩■
(! P ∣ Q₁) ∣ Q₂)
, reflexive
!-cong :
(∀ {P P′ Q Q′} → R′ P P′ → R′ Q Q′ → R′ (P ∣ Q) (P′ ∣ Q′)) →
(∀ {P P′} → R′ P P′ → R′ (! P) (! P′)) →
∀ {P P′ Q′ μ} →
R P P′ → ! P′ [ μ ]⟶ Q′ →
∃ λ Q → ((! P) [ μ ]↝ Q) × R′ Q Q′
!-cong _∣-cong′_ !-cong′_ {P} {P′} {Q′} {μ} P≳P′ !P′⟶Q′ =
case SL.6-1-3-2 !P′⟶Q′ of λ where
(inj₁ (P″ , P′⟶P″ , Q′∼!P′∣P″)) →
let Q , P↝Q , Q≳′P″ = right-to-left P≳P′ P′⟶P″
R , !P↝R , R∼!P∣Q = !-lemma !-cong-lemma₁ P↝Q
in
! P →⟨ !P↝R ⟩■
↝[ μ ]
R ∼⟨ R∼!P∣Q ⟩
! P ∣ Q ∼′⟨ (!-cong′ (convert P≳P′)) ∣-cong′ Q≳′P″ ⟩
! P′ ∣ P″ ∼⟨ symmetric Q′∼!P′∣P″ ⟩■
Q′
(inj₂ (refl , P″ , P‴ , a , P′⟶P″ , P′⟶P‴ , Q′∼!P′∣P″∣P‴)) →
let Q₁ , P↝Q₁ , Q₁≳′P″ = right-to-left P≳P′ P′⟶P″
Q₂ , P↝Q₂ , Q₂≳′P‴ = right-to-left P≳P′ P′⟶P‴
R , !P⇒R , R∼[!P∣Q₁]∣Q₂ =
!-cong-lemma₂ (↝→[]⇒ P↝Q₁) (↝→[]⇒ P↝Q₂)
in
! P →⟨ []⇒→↝ !P⇒R ⟩■
↝[ τ ]
R ∼⟨ R∼[!P∣Q₁]∣Q₂ ⟩
(! P ∣ Q₁) ∣ Q₂ ∼′⟨ ((!-cong′ (convert P≳P′)) ∣-cong′ Q₁≳′P″) ∣-cong′ Q₂≳′P‴ ⟩
(! P′ ∣ P″) ∣ P‴ ∼⟨ symmetric Q′∼!P′∣P″∣P‴ ⟩■
Q′
⊕·-cong :
∀ {P Q Q′ S′ μ μ′} →
R′ (force Q) (force Q′) → P ⊕ μ · Q′ [ μ′ ]⟶ S′ →
∃ λ S → ((P ⊕ μ · Q) [ μ′ ]↝ S) × R′ S S′
⊕·-cong {P} {Q} {Q′} {S′} {μ} {μ′} Q≳Q′ = λ where
(sum-left P⟶S′) →
P ⊕ μ · Q →⟨ ⟶: sum-left P⟶S′ ⟩■
↝[ μ′ ]
S′ ■
(sum-right action) →
P ⊕ μ · Q →⟨ ⟶: sum-right action ⟩■
↝[ μ ]
force Q ∼⟨ Q≳Q′ ⟩■
force Q′
·⊕·-cong :
∀ {μ₁ μ₂ P₁ P₁′ P₂ P₂′ S′ μ} →
R′ (force P₁) (force P₁′) → R′ (force P₂) (force P₂′) →
μ₁ · P₁′ ⊕ μ₂ · P₂′ [ μ ]⟶ S′ →
∃ λ S → ((μ₁ · P₁ ⊕ μ₂ · P₂) [ μ ]↝ S) × R′ S S′
·⊕·-cong {μ₁} {μ₂} {P₁} {P₁′} {P₂} {P₂′} P₁≳P₁′ P₂≳P₂′ = λ where
(sum-left action) →
μ₁ · P₁ ⊕ μ₂ · P₂ →⟨ ⟶: sum-left action ⟩■
↝[ μ₁ ]
force P₁ ∼⟨ P₁≳P₁′ ⟩■
force P₁′
(sum-right action) →
μ₁ · P₁ ⊕ μ₂ · P₂ →⟨ ⟶: sum-right action ⟩■
↝[ μ₂ ]
force P₂ ∼⟨ P₂≳P₂′ ⟩■
force P₂′
private
module CL {i} =
Cong-lemmas
[ i ]_≳′_ right-to-left id id
map-[]⇒ map-[]⇒′ (λ f g _ _ _ → zip-[]⇒ f g)
(λ hyp P⇒Q → _ , hyp P⇒Q , reflexive)
mutual
-- _∣_ preserves the expansion relation.
infix 6 _∣-cong_ _∣-cong′_
_∣-cong_ : ∀ {i P P′ Q Q′} →
[ i ] P ≳ P′ → [ i ] Q ≳ Q′ → [ i ] P ∣ Q ≳ P′ ∣ Q′
_∣-cong_ {i} P≳P′ Q≳Q′ =
⟨ lr P≳P′ Q≳Q′
, CL.∣-cong _∣-cong′_ P≳P′ Q≳Q′
⟩
where
lr : ∀ {P P′ Q Q′ R μ} →
[ i ] P ≳ P′ → [ i ] Q ≳ Q′ → P ∣ Q [ μ ]⟶ R →
∃ λ R′ → P′ ∣ Q′ [ μ ]⟶̂ R′ × [ i ] R ≳′ R′
lr P≳P′ Q≳Q′ (par-left tr) = Σ-map (_∣ _)
(Σ-map (map-⟶̂ par-left)
(_∣-cong′ convert {a = ℓ} Q≳Q′))
(left-to-right P≳P′ tr)
lr P≳P′ Q≳Q′ (par-right tr) = Σ-map (_ ∣_)
(Σ-map (map-⟶̂ par-right)
(convert {a = ℓ} P≳P′ ∣-cong′_))
(left-to-right Q≳Q′ tr)
lr P≳P′ Q≳Q′ (par-τ tr₁ tr₂) = Σ-zip _∣_
(Σ-zip (zip-⟶̂ (λ ()) (λ _ ())
(λ ()) par-τ)
_∣-cong′_)
(left-to-right P≳P′ tr₁)
(left-to-right Q≳Q′ tr₂)
_∣-cong′_ : ∀ {i P P′ Q Q′} →
[ i ] P ≳′ P′ → [ i ] Q ≳′ Q′ → [ i ] P ∣ Q ≳′ P′ ∣ Q′
force (P≳P′ ∣-cong′ Q≳Q′) = force P≳P′ ∣-cong force Q≳Q′
-- _·_ preserves the expansion relation.
infix 12 _·-cong_ _·-cong′_
_·-cong_ :
∀ {i μ μ′ P P′} →
μ ≡ μ′ → [ i ] force P ≳′ force P′ → [ i ] μ · P ≳ μ′ · P′
_·-cong_ {i} {μ} {P = P} {P′} refl P≳P′ = ⟨ lr , CL.·-cong P≳P′ ⟩
where
lr : ∀ {Q μ″} →
μ · P [ μ″ ]⟶ Q →
∃ λ Q′ → μ · P′ [ μ″ ]⟶̂ Q′ × [ i ] Q ≳′ Q′
lr action = _ , ⟶→⟶̂ action , P≳P′
_·-cong′_ :
∀ {i μ μ′ P P′} →
μ ≡ μ′ → [ i ] force P ≳′ force P′ → [ i ] μ · P ≳′ μ′ · P′
force (μ≡μ′ ·-cong′ P≳P′) = μ≡μ′ ·-cong P≳P′
-- _∙_ preserves the expansion relation.
infix 12 _∙-cong_ _∙-cong′_
_∙-cong_ : ∀ {i μ μ′ P P′} →
μ ≡ μ′ → [ i ] P ≳ P′ → [ i ] μ ∙ P ≳ μ′ ∙ P′
refl ∙-cong P≳P′ = refl ·-cong convert {a = ℓ} P≳P′
_∙-cong′_ : ∀ {i μ μ′ P P′} →
μ ≡ μ′ → [ i ] P ≳′ P′ → [ i ] μ ∙ P ≳′ μ′ ∙ P′
force (μ≡μ′ ∙-cong′ P≳P′) = μ≡μ′ ∙-cong force P≳P′
-- _∙ turns equal actions into processes related by the expansion
-- relation.
infix 12 _∙-cong _∙-cong′
_∙-cong : ∀ {μ μ′} → μ ≡ μ′ → μ ∙ ≳ μ′ ∙
refl ∙-cong = reflexive
_∙-cong′ : ∀ {μ μ′} → μ ≡ μ′ → μ ∙ ≳′ μ′ ∙
refl ∙-cong′ = reflexive
mutual
-- ⟨ν_⟩ preserves the expansion relation.
⟨ν_⟩-cong : ∀ {i a a′ P P′} →
a ≡ a′ → [ i ] P ≳ P′ → [ i ] ⟨ν a ⟩ P ≳ ⟨ν a′ ⟩ P′
⟨ν_⟩-cong {i} {a} {P = P} {P′} refl P≳P′ =
⟨ lr
, CL.⟨ν⟩-cong ⟨ν refl ⟩-cong′ P≳P′
⟩
where
lr : ∀ {Q μ} →
⟨ν a ⟩ P [ μ ]⟶ Q →
∃ λ Q′ → ⟨ν a ⟩ P′ [ μ ]⟶̂ Q′ × [ i ] Q ≳′ Q′
lr {μ = μ} (restriction {P′ = Q} a∉μ P⟶Q)
with left-to-right P≳P′ P⟶Q
... | Q′ , step P′⟶Q′ , Q≳′Q′ =
⟨ν a ⟩ Q ∼⟨ ⟨ν refl ⟩-cong′ Q≳′Q′ ⟩■
⟨ν a ⟩ Q′
⟵̂[ μ ] ←⟨ ⟶: restriction a∉μ P′⟶Q′ ⟩■
⟨ν a ⟩ P′
... | _ , done μs , Q≳′P′ =
⟨ν a ⟩ Q ∼⟨ ⟨ν refl ⟩-cong′ Q≳′P′ ⟩■
⟨ν a ⟩ P′
⟵̂[ μ ] ←⟨ ⟶̂: done μs ⟩■
⟨ν a ⟩ P′
⟨ν_⟩-cong′ : ∀ {i a a′ P P′} →
a ≡ a′ → [ i ] P ≳′ P′ → [ i ] ⟨ν a ⟩ P ≳′ ⟨ν a′ ⟩ P′
force (⟨ν a≡a′ ⟩-cong′ P≳P′) = ⟨ν a≡a′ ⟩-cong (force P≳P′)
mutual
-- !_ preserves the expansion relation.
infix 10 !-cong_ !-cong′_
!-cong_ : ∀ {i P P′} →
[ i ] P ≳ P′ → [ i ] ! P ≳ ! P′
!-cong_ {i} {P} {P′} P≳P′ =
⟨ lr
, CL.!-cong _∣-cong′_ !-cong′_ P≳P′
⟩
where
lr : ∀ {Q μ} →
! P [ μ ]⟶ Q →
∃ λ Q′ → ! P′ [ μ ]⟶̂ Q′ × [ i ] Q ≳′ Q′
lr {Q} {μ} !P⟶Q = case SL.6-1-3-2 !P⟶Q of λ where
(inj₁ (P″ , P⟶P″ , Q∼!P∣P″)) → case left-to-right P≳P′ P⟶P″ of λ where
(_ , done s , P″≳′P′) → case silent≡τ s of λ where
refl →
_
, (! P′ ■)
, (Q ∼⟨ Q∼!P∣P″ ⟩
! P ∣ P″ ∼′⟨ !-cong′ (convert {a = ℓ} P≳P′) ∣-cong′ P″≳′P′ ⟩ S.∼:
! P′ ∣ P′ ∼⟨ SL.6-1-2 ⟩■
! P′)
(Q′ , step P′⟶Q′ , P″≳′Q′) →
_
, (! P′ ∣ Q′ ←⟨ ⟶: replication (par-right P′⟶Q′) ⟩■
! P′)
, (Q ∼⟨ Q∼!P∣P″ ⟩
! P ∣ P″ ∼⟨ !-cong′ (convert {a = ℓ} P≳P′) ∣-cong′ P″≳′Q′ ⟩■
! P′ ∣ Q′)
(inj₂ (refl , P″ , P‴ , a , P⟶P″ , P⟶P‴ , Q≳!P∣P″∣P‴)) →
case left-to-right P≳P′ P⟶P″ ,′
left-to-right P≳P′ P⟶P‴ of λ where
((Q′ , step P′⟶Q′ , P″≳′Q′) ,
(Q″ , step P′⟶Q″ , P‴≳′Q″)) →
_
, ((! P′ ∣ Q′) ∣ Q″ ←⟨ ⟶: replication (par-τ (replication (par-right P′⟶Q′)) P′⟶Q″) ⟩■
! P′)
, (Q ∼⟨ Q≳!P∣P″∣P‴ ⟩
(! P ∣ P″) ∣ P‴ ∼⟨ (!-cong′ (convert {a = ℓ} P≳P′) ∣-cong′ P″≳′Q′) ∣-cong′ P‴≳′Q″ ⟩■
(! P′ ∣ Q′) ∣ Q″)
((_ , done () , _) , _)
(_ , (_ , done () , _))
!-cong′_ : ∀ {i P P′} → [ i ] P ≳′ P′ → [ i ] ! P ≳′ ! P′
force (!-cong′ P≳P′) = !-cong (force P≳P′)
-- It is not necessarily the case that, if P expands P′, then P ⊕ Q is
-- weakly bisimilar to P′ ⊕ Q (assuming that Name is inhabited).
--
-- I based the counterexample on one in "Enhancements of the
-- bisimulation proof method" by Pous and Sangiorgi.
¬⊕-congˡ-≳≈ : Name → ¬ (∀ {P P′ Q} → P ≳ P′ → P ⊕ Q ≈ P′ ⊕ Q)
¬⊕-congˡ-≳≈ x =
(∀ {P P′ Q} → P ≳ P′ → P ⊕ Q ≈ P′ ⊕ Q) ↝⟨ _$ τa≳a ⟩
τ ∙ (a ∙) ⊕ b ∙ ≈ a ∙ ⊕ b ∙ ↝⟨ τa⊕b≉a⊕b ⟩□
⊥ □
where
a = x , true
b = x , false
τa≳a : ∀ {a} → τ ∙ (a ∙) ≳ a ∙
τa≳a {a} =
⟨ (λ where
action →
a ∙ ■
⟵̂[ τ ]
a ∙ ■)
, (λ where
action →
τ ∙ (a ∙) →⟨ ⟶: action ⟩
a ∙ →⟨ ⟶: action ⟩■
⇒[ name a ]
∅ ■)
⟩
τa⊕b≉a⊕b : ¬ τ ∙ (a ∙) ⊕ b ∙ ≈ a ∙ ⊕ b ∙
τa⊕b≉a⊕b τa⊕b≈a⊕b
with W.left-to-right τa⊕b≈a⊕b (sum-left action)
... | _ , non-silent ¬s _ , _ = ⊥-elim (¬s _)
... | _ , silent _ (step () (sum-left action) _) , _
... | _ , silent _ (step () (sum-right action) _) , _
... | _ , silent _ done , a≈′a⊕b
with W.right-to-left (force a≈′a⊕b) (sum-right action)
... | _ , silent () _ , _
... | _ , non-silent _ (steps done () _) , _
... | _ , non-silent _ (steps (step () action _) _ _) , _
-- It is not necessarily the case that, if Q expands Q′, then P ⊕ Q is
-- weakly bisimilar to P ⊕ Q′ (assuming that Name is inhabited).
¬⊕-congʳ-≳≈ : Name → ¬ (∀ {P Q Q′} → Q ≳ Q′ → P ⊕ Q ≈ P ⊕ Q′)
¬⊕-congʳ-≳≈ x ⊕-congʳ-≳≈ = ¬⊕-congˡ-≳≈ x ⊕-congˡ-≳≈
where
⊕-congˡ-≳≈ : ∀ {P P′ Q} → P ≳ P′ → P ⊕ Q ≈ P′ ⊕ Q
⊕-congˡ-≳≈ {P} {P′} {Q} P≳P′ =
P ⊕ Q ∼⟨ SL.⊕-comm ⟩
Q ⊕ P ∼′⟨ ⊕-congʳ-≳≈ P≳P′ ⟩ S.∼:
Q ⊕ P′ ∼⟨ SL.⊕-comm ⟩■
P′ ⊕ Q
-- _⊕_ does not, in general, preserve the expansion relation in its
-- first argument (assuming that Name is inhabited).
¬⊕-congˡ : Name → ¬ (∀ {P P′ Q} → P ≳ P′ → P ⊕ Q ≳ P′ ⊕ Q)
¬⊕-congˡ x =
(∀ {P P′ Q} → P ≳ P′ → P ⊕ Q ≳ P′ ⊕ Q) ↝⟨ W.≳⇒≈ ∘_ ⟩
(∀ {P P′ Q} → P ≳ P′ → P ⊕ Q ≈ P′ ⊕ Q) ↝⟨ ¬⊕-congˡ-≳≈ x ⟩□
⊥ □
-- _⊕_ does not, in general, preserve the expansion relation in its
-- second argument (assuming that Name is inhabited).
¬⊕-congʳ : Name → ¬ (∀ {P Q Q′} → Q ≳ Q′ → P ⊕ Q ≳ P ⊕ Q′)
¬⊕-congʳ x =
(∀ {P Q Q′} → Q ≳ Q′ → P ⊕ Q ≳ P ⊕ Q′) ↝⟨ W.≳⇒≈ ∘_ ⟩
(∀ {P Q Q′} → Q ≳ Q′ → P ⊕ Q ≈ P ⊕ Q′) ↝⟨ ¬⊕-congʳ-≳≈ x ⟩□
⊥ □
-- Some congruence lemmas for combinations of _⊕_ and _·_.
⊕·-cong : ∀ {i P μ Q Q′} →
[ i ] force Q ≳′ force Q′ → [ i ] P ⊕ μ · Q ≳ P ⊕ μ · Q′
⊕·-cong {i} {P} {μ} {Q} {Q′} Q≳Q′ =
⟨ lr , CL.⊕·-cong Q≳Q′ ⟩
where
lr : ∀ {R μ′} →
P ⊕ μ · Q [ μ′ ]⟶ R →
∃ λ R′ → P ⊕ μ · Q′ [ μ′ ]⟶̂ R′ × [ i ] R ≳′ R′
lr {R} {μ′} = λ where
(sum-left P⟶R) →
R ■
⟵̂[ μ′ ] ←⟨ ⟶: sum-left P⟶R ⟩■
P ⊕ μ · Q′
(sum-right action) →
force Q ∼⟨ Q≳Q′ ⟩■
force Q′
⟵̂[ μ ] ←⟨ ⟶: sum-right action ⟩■
P ⊕ μ · Q′
⊕·-cong′ : ∀ {i P μ Q Q′} →
[ i ] force Q ≳′ force Q′ → [ i ] P ⊕ μ · Q ≳′ P ⊕ μ · Q′
force (⊕·-cong′ Q≳Q′) = ⊕·-cong Q≳Q′
·⊕-cong : ∀ {i P P′ μ Q} →
[ i ] force P ≳′ force P′ → [ i ] μ · P ⊕ Q ≳ μ · P′ ⊕ Q
·⊕-cong {P = P} {P′} {μ} {Q} P≳P′ =
μ · P ⊕ Q ∼⟨ SL.⊕-comm ⟩
Q ⊕ μ · P ∼′⟨ ⊕·-cong P≳P′ ⟩ S.∼:
Q ⊕ μ · P′ ∼⟨ SL.⊕-comm ⟩■
μ · P′ ⊕ Q
·⊕-cong′ : ∀ {i P P′ μ Q} →
[ i ] force P ≳′ force P′ → [ i ] μ · P ⊕ Q ≳′ μ · P′ ⊕ Q
force (·⊕-cong′ P≳P′) = ·⊕-cong P≳P′
infix 8 _·⊕·-cong_ _·⊕·-cong′_
_·⊕·-cong_ :
∀ {i μ₁ μ₂ P₁ P₁′ P₂ P₂′} →
[ i ] force P₁ ≳′ force P₁′ → [ i ] force P₂ ≳′ force P₂′ →
[ i ] μ₁ · P₁ ⊕ μ₂ · P₂ ≳ μ₁ · P₁′ ⊕ μ₂ · P₂′
_·⊕·-cong_ {i} {μ₁} {μ₂} {P₁} {P₁′} {P₂} {P₂′} P₁≳P₁′ P₂≳P₂′ =
⟨ lr , CL.·⊕·-cong P₁≳P₁′ P₂≳P₂′ ⟩
where
lr : ∀ {R μ} → μ₁ · P₁ ⊕ μ₂ · P₂ [ μ ]⟶ R →
∃ λ R′ → μ₁ · P₁′ ⊕ μ₂ · P₂′ [ μ ]⟶̂ R′ × [ i ] R ≳′ R′
lr = λ where
(sum-left action) →
force P₁ ∼⟨ P₁≳P₁′ ⟩■
force P₁′
⟵̂[ μ₁ ] ←⟨ ⟶: sum-left action ⟩■
μ₁ · P₁′ ⊕ μ₂ · P₂′
(sum-right action) →
force P₂ ∼⟨ P₂≳P₂′ ⟩■
force P₂′
⟵̂[ μ₂ ] ←⟨ ⟶: sum-right action ⟩■
μ₁ · P₁′ ⊕ μ₂ · P₂′
_·⊕·-cong′_ :
∀ {i μ₁ μ₂ P₁ P₁′ P₂ P₂′} →
[ i ] force P₁ ≳′ force P₁′ → [ i ] force P₂ ≳′ force P₂′ →
[ i ] μ₁ · P₁ ⊕ μ₂ · P₂ ≳′ μ₁ · P₁′ ⊕ μ₂ · P₂′
force (P₁≳′P₁′ ·⊕·-cong′ P₂≳′P₂′) = P₁≳′P₁′ ·⊕·-cong P₂≳′P₂′
-- _[_] preserves the expansion relation for non-degenerate contexts.
-- (This result is related to Theorem 6.5.25 in "Enhancements of the
-- bisimulation proof method" by Pous and Sangiorgi.)
infix 5 _[_]-cong _[_]-cong′
_[_]-cong :
∀ {i n Ps Qs} {C : Context ∞ n} →
Non-degenerate ∞ C → (∀ x → [ i ] Ps x ≳ Qs x) →
[ i ] C [ Ps ] ≳ C [ Qs ]
hole [ Ps≳Qs ]-cong = Ps≳Qs _
∅ [ Ps≳Qs ]-cong = reflexive
D₁ ∣ D₂ [ Ps≳Qs ]-cong = (D₁ [ Ps≳Qs ]-cong) ∣-cong (D₂ [ Ps≳Qs ]-cong)
action D [ Ps≳Qs ]-cong = refl ·-cong λ { .force → force D [ Ps≳Qs ]-cong }
⟨ν⟩ D [ Ps≳Qs ]-cong = ⟨ν refl ⟩-cong (D [ Ps≳Qs ]-cong)
! D [ Ps≳Qs ]-cong = !-cong (D [ Ps≳Qs ]-cong)
D₁ ⊕ D₂ [ Ps≳Qs ]-cong = ⊕-cong Ps≳Qs D₁ D₂
where
_[_]-cong′ :
∀ {i n Ps Qs} {C : Context ∞ n} →
Non-degenerate′ ∞ C → (∀ x → [ i ] Ps x ≳ Qs x) →
[ i ] C [ Ps ] ≳′ C [ Qs ]
force (D [ Ps≳Qs ]-cong′) = force D [ Ps≳Qs ]-cong
⊕-cong :
∀ {i n Ps Qs} {C₁ C₂ : Context ∞ n} →
(∀ x → [ i ] Ps x ≳ Qs x) →
Non-degenerate-summand ∞ C₁ →
Non-degenerate-summand ∞ C₂ →
[ i ] (C₁ [ Ps ]) ⊕ (C₂ [ Ps ]) ≳ (C₁ [ Qs ]) ⊕ (C₂ [ Qs ])
⊕-cong {Ps = Ps} {Qs} Ps≳Qs = λ where
(process P₁) (process P₂) →
(context P₁ [ Ps ]) ⊕ (context P₂ [ Ps ]) ∼⟨ symmetric (SL.≡→∼ (context-[] P₁) SL.⊕-cong SL.≡→∼ (context-[] P₂)) ⟩
P₁ ⊕ P₂ ∼⟨ SL.≡→∼ (context-[] P₁) SL.⊕-cong SL.≡→∼ (context-[] P₂) ⟩■
(context P₁ [ Qs ]) ⊕ (context P₂ [ Qs ])
(process P₁) (action {μ = μ₂} {C = C₂} D₂) →
(context P₁ [ Ps ]) ⊕ μ₂ · (C₂ [ Ps ]′) ∼⟨ symmetric (SL.≡→∼ (context-[] P₁)) SL.⊕-cong (_ ■) ⟩
P₁ ⊕ μ₂ · (C₂ [ Ps ]′) ∼′⟨ ⊕·-cong (D₂ [ Ps≳Qs ]-cong′) ⟩ S.∼:
P₁ ⊕ μ₂ · (C₂ [ Qs ]′) ∼⟨ SL.≡→∼ (context-[] P₁) SL.⊕-cong (_ ■) ⟩■
(context P₁ [ Qs ]) ⊕ μ₂ · (C₂ [ Qs ]′)
(action {μ = μ₁} {C = C₁} D₁) (process P₂) →
μ₁ · (C₁ [ Ps ]′) ⊕ (context P₂ [ Ps ]) ∼⟨ (_ ■) SL.⊕-cong symmetric (SL.≡→∼ (context-[] P₂)) ⟩
μ₁ · (C₁ [ Ps ]′) ⊕ P₂ ∼′⟨ ·⊕-cong (D₁ [ Ps≳Qs ]-cong′) ⟩ S.∼:
μ₁ · (C₁ [ Qs ]′) ⊕ P₂ ∼⟨ (_ ■) SL.⊕-cong SL.≡→∼ (context-[] P₂) ⟩■
μ₁ · (C₁ [ Qs ]′) ⊕ (context P₂ [ Qs ])
(action {μ = μ₁} {C = C₁} D₁) (action {μ = μ₂} {C = C₂} D₂) →
μ₁ · (C₁ [ Ps ]′) ⊕ μ₂ · (C₂ [ Ps ]′) ∼⟨ (D₁ [ Ps≳Qs ]-cong′) ·⊕·-cong (D₂ [ Ps≳Qs ]-cong′) ⟩■
μ₁ · (C₁ [ Qs ]′) ⊕ μ₂ · (C₂ [ Qs ]′)
_[_]-cong′ :
∀ {i n Ps Qs} {C : Context ∞ n} →
Non-degenerate ∞ C → (∀ x → [ i ] Ps x ≳′ Qs x) →
[ i ] C [ Ps ] ≳′ C [ Qs ]
force (C [ Ps≳Qs ]-cong′) = C [ (λ x → force (Ps≳Qs x)) ]-cong
|
lemmas (in sigma_algebra) sets_Collect = sets_Collect_imp sets_Collect_disj sets_Collect_conj sets_Collect_neg sets_Collect_const sets_Collect_countable_All sets_Collect_countable_Ex sets_Collect_countable_All |
module TextHistogram (
printHistogram,
) where
import Control.Monad (forM_, when)
import Statistics.Test.ApproxRand
import System.IO (hPutStrLn, stderr)
import Text.Printf (printf)
import Histogram
printHistogram :: Int -> TestResult -> IO ()
printHistogram bins result@(TestResult _ score _) =
case histogram bins result of
Left err -> hPutStrLn stderr err
Right hist ->
let bucketSize = (fst $ hist !! 1) - (fst $ head hist)
bucketHalf = bucketSize / 2
charsPerDot = (maximum $ map snd hist) `div` 50 in
forM_ hist $ \(label, freq) -> do
let blocks = freq `div` charsPerDot
when (blocks > 0) $ do
let lower = label - bucketHalf
let barChar = if score >= lower && score < lower + bucketSize then
'✣'
else
'█'
putStr $ printf "%12.3e | " $ lower + bucketHalf
putStrLn $ replicate blocks barChar
|
import .unitary
import .normal
import .eigenvalues
import .algebraically_closed
noncomputable theory
open_locale matrix
open_locale classical
lemma spectral_theorem {n : ℕ} (M : matrix (fin n) (fin n) ℂ) (hn : M.normal) :
∃ U : matrix (fin n) (fin n) ℂ,
∃ D : (fin n) → ℂ,
U.unitary ∧
M = U • (matrix.diagonal D) • U.complex_transpose :=
begin
induction n with n ind, by sorry, -- what is (fin 0)?
rcases exists_eigenvalue M with ⟨c, v, hne0, heigen⟩,
let v' := (vector.complex_norm v)⁻¹ • v,
have : vector.complex_norm v' = 1, by sorry,
rcases unitary_of_unit_vector v' this with ⟨U, hU, hv'⟩,
have hext : ∃ B (c : ℝ), U.conj • M • U = matrix.extension B c ∧ B.normal, by sorry,
rcases hext with ⟨ B, c, key_ext, hB ⟩,
specialize ind B hB,
rcases ind with ⟨U', D', hU', key_B ⟩,
use [U • (U'.extension 1), vector.extension D' c],
split,
sorry,
sorry
end
-- theorem spectral_theorem {M : matrix n n ℂ} (hn : M.normal) :
-- ∃ U : matrix n n ℂ, ∃ D : n → ℂ,
-- U.unitary ∧
-- M = U • (matrix.diagonal D) • U.complex_transpose
-- :=
-- begin
-- rcases (upper_triangular_decomposition M) with ⟨U,L,hU,hLu,key⟩,
-- have hLn : L.normal, by sorry,
-- cases diagonal_of_upper_triangular_normal hLu hLn with D,
-- use [U,D],
-- split,
-- {exact hU},
-- {rwa ←h},
-- end |
-- WARNING: This file was generated automatically by Vehicle
-- and should not be modified manually!
-- Metadata
-- - Agda version: 2.6.2
-- - AISEC version: 0.1.0.1
-- - Time generated: ???
{-# OPTIONS --allow-exec #-}
open import Vehicle
open import Vehicle.Data.Tensor
open import Data.Product
open import Data.Integer as ℤ using (ℤ)
open import Data.Rational as ℚ using (ℚ)
open import Data.List
open import Relation.Binary.PropositionalEquality
module reachability-output where
private
VEHICLE_PROJECT_FILE = "TODO_projectFile"
f : Tensor ℚ (2 ∷ []) → ℚ
f = evaluate record
{ projectFile = VEHICLE_PROJECT_FILE
; networkUUID = "TODO_networkUUID"
}
abstract
reachable : ∃ λ (x : Tensor ℚ (2 ∷ [])) → f x ≡ ℤ.+ 0 ℚ./ 1
reachable = checkProperty record
{ projectFile = VEHICLE_PROJECT_FILE
; propertyUUID = "TODO_propertyUUID"
} |
import syntax.syntax
import logic.basic data.set.basic
local attribute [instance] classical.prop_decidable
open form
/- SEMANTICS -/
/-
We now want to define a *semantics* for our language.#check
-/
---------------------- Semantics ----------------------
/-
In classical modal logic, a frame is a pair F = ⟨W, R⟩
where W is a *non-empty* set of worlds and R is a
binary relation on W (indicating which worlds are related to
which others).
-/
structure frame :=
(W : Type)
(W_inhabited : inhabited W)
(R : W → W → Prop)
/-
Truth at a world
In modal logic, a formula A is true at a world if.
-/
def true_at_world (f : frame) (v : nat → f.W → Prop) : f.W → form → Prop
| w (bot) := false
| w (var n) := v n w
| w (A & B) := (true_at_world w A) ∧ (true_at_world w B)
| w (A ⊃ B) := (true_at_world w A) → (true_at_world w B)
| w (box A) := ∀ y, f.R w y → true_at_world y A
/-
Now we define semantic entailment. Say we have a set of formulas Γ
a formula A. We say that Γ *entails* A iff:
For each model M = ⟨W, R, V⟩ and w ∈ W,
*if* M, w ⊩ B for every B ∈ Γ,
*then* M, w ⊩ A
We'll encode the *if* in its own definition 'ctx_true_in_frame'
-/
/- Given a model (specified by f and v),
all formulas in the context are true at all worlds in the model -/
-- A context is true at a world in a model if each
-- formula of the context is true at that world in that model
def ctx_true_in_model (f : frame) (v : nat → f.W → Prop)
(Γ : ctx) := ∀ A, ∀ w, A ∈ Γ → true_at_world f v w A
-- Global semantic consequence
def entails (Γ : ctx) (A : form) :=
∀ f v, ctx_true_in_model f v Γ → ∀ x, true_at_world f v x A
/-----------------/
/- A formula A is valid in a specific model if true at each world -/
def valid_in_model (A : form) (f : frame)
(v : nat → f.W → Prop) :=
∀ w, true_at_world f v w A
/- A formula A is valid in a specific frame if true at each model in the frame -/
def valid_in_frame (A : form) (f : frame) :=
∀ v w, true_at_world f v w A
/- A formula A is valid in a *class* of frames if true at each frame in the class -/
def valid_in_frame_class (A : form) (F : set (frame)) :=
∀ f ∈ F, ∀ v w, true_at_world f v w A
/- Finally, there are certain formulas that are universally valid -/
def valid_universally (A : form) :=
∀ f v w, true_at_world f v w A
/- Finally, a helpful lemma regarding the moving of negation in/out -/
lemma not_forces_imp : ∀ f v x A,
(¬(true_at_world f v x A)) ↔ (true_at_world f v x (¬A)) :=
begin
intros f v x A, split,
repeat {intros h1 h2, exact h1 h2},
end
|
[STATEMENT]
theorem factor_composition [simp]:
"\<lbrakk> g \<in> G; h \<in> G \<rbrakk> \<Longrightarrow> (g \<cdot>| K) [\<cdot>] (h \<cdot>| K) = g \<cdot> h \<cdot>| K"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>g \<in> G; h \<in> G\<rbrakk> \<Longrightarrow> g \<cdot>| K [\<cdot>] (h \<cdot>| K) = g \<cdot> h \<cdot>| K
[PROOF STEP]
using Class_commutes_with_composition Class_is_Left_Coset
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>?a \<in> G; ?b \<in> G\<rbrakk> \<Longrightarrow> Class ?a [\<cdot>] Class ?b = Class (?a \<cdot> ?b)
?g \<in> G \<Longrightarrow> Class ?g = ?g \<cdot>| K
goal (1 subgoal):
1. \<lbrakk>g \<in> G; h \<in> G\<rbrakk> \<Longrightarrow> g \<cdot>| K [\<cdot>] (h \<cdot>| K) = g \<cdot> h \<cdot>| K
[PROOF STEP]
by auto |
[STATEMENT]
lemma cqt_further_5[PLM]:
"[(\<^bold>\<exists>\<alpha>. \<phi> \<alpha> \<^bold>& \<psi> \<alpha>) \<^bold>\<rightarrow> ((\<^bold>\<exists>\<alpha>. \<phi> \<alpha>) \<^bold>& (\<^bold>\<exists>\<alpha>. \<psi> \<alpha>)) in v]"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. [(\<^bold>\<exists>\<alpha>. \<phi> \<alpha> \<^bold>& \<psi> \<alpha>) \<^bold>\<rightarrow> (\<^bold>\<exists>\<alpha>. \<phi> \<alpha>) \<^bold>& (\<^bold>\<exists>\<alpha>. \<psi> \<alpha>) in v]
[PROOF STEP]
unfolding exists_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. [\<^bold>\<not>(\<^bold>\<forall>x. \<^bold>\<not>(\<phi> x \<^bold>& \<psi> x)) \<^bold>\<rightarrow> \<^bold>\<not>(\<^bold>\<forall>x. \<^bold>\<not>\<phi> x) \<^bold>& \<^bold>\<not>(\<^bold>\<forall>x. \<^bold>\<not>\<psi> x) in v]
[PROOF STEP]
by PLM_solver |
lemma continuous_discrete [simp]: "continuous (at x within A) (f :: 'a :: discrete_topology \<Rightarrow> _)" |
/-
Copyright © 2019, Oracle and/or its affiliates. All rights reserved.
-/
import .setup_definition
import ..lib.util
open set
open measure_theory
open probability_measure
local attribute [instance] classical.prop_decidable
namespace stump
variables (μ: probability_measure ℍ) (target: ℍ)
lemma label_correct:
∀ x, (label target x).snd = tt ↔ x ≤ target :=
begin
intros,
split; intro,
{
unfold label at a,
simp at a,
unfold rle at a,
tidy,
},
{
unfold label,
simp,
unfold rle,
tidy,
}
end
lemma error_interval_1:
∀ h, h ≤ target → error μ target h = μ (Ioc h target) :=
begin
intros,
unfold error,
have SETEQ: error_set h target = Ioc h target,
{
unfold error_set,
unfold Ioc,
unfold label,
unfold rle,
rw ext_iff,
intro,
simp at *,
split; intro,
{
rw not_eq_prop at a_1,
cases a_1; simp at a_1; cases a_1,
{
finish,
},
{
split,
{
exact lt_of_le_of_lt a a_1_right
},
{
transitivity h; assumption,
},
},
},
{
cases a_1,
finish,
},
},
exact congr_arg μ SETEQ,
end
lemma error_interval_2:
∀ h, h > target → error μ target h = μ (Ioc target h) :=
begin
intros,
unfold error,
have SETEQ: error_set h target = Ioc target h,
{
unfold error_set,
unfold Ioc,
unfold label,
unfold rle,
rw ext_iff,
intro,
simp at *,
split; intro,
{
rw not_eq_prop at a_1,
cases a_1; simp at a_1; cases a_1,
{
split,
{
by_contradiction,
have FOO: target < x,
{
transitivity h; try {assumption},
},
contradiction,
},
{
transitivity target; try {assumption},
have FOO: target < h,
{
exact mem_Ioi.mp a,
},
exact le_of_lt a,
},
},
{
split,
{
exact mem_Ioi.mp a_1_right,
},
{
assumption,
},
},
},
{
cases a_1,
finish,
},
},
exact congr_arg μ SETEQ,
end
lemma error_mono:
∀ c₁, ∀ c₂,
c₁ ≤ c₂ →
c₂ ≤ target →
error μ target c₂ ≤ error μ target c₁ :=
begin
intros,
rw error_interval_1,
rw error_interval_1,
apply probability_measure.prob_mono,
exact Ioc_subset_Ioc_left a,
transitivity c₂; assumption,
assumption,
end
lemma error_mono_interval:
∀ c₁, ∀ c₂,
c₁ ≤ c₂ →
c₂ ≤ target →
μ (Ioc c₂ target) ≤ μ (Ioc c₁ target) :=
begin
intros,
rw ← error_interval_1; try {assumption},
rw ← error_interval_1,
apply error_mono; try {assumption},
transitivity c₂; try {assumption},
end
lemma error_max:
error μ target 0 = μ (Ioc 0 target) :=
begin
apply error_interval_1,
tidy,
end
end stump |
(* Title: HOL/Algebra/RingHom.thy
Author: Stephan Hohe, TU Muenchen
*)
theory RingHom
imports Ideal
begin
section \<open>Homomorphisms of Non-Commutative Rings\<close>
text \<open>Lifting existing lemmas in a \<open>ring_hom_ring\<close> locale\<close>
locale ring_hom_ring = R?: ring R + S?: ring S
for R (structure) and S (structure) +
fixes h
assumes homh: "h \<in> ring_hom R S"
notes hom_mult [simp] = ring_hom_mult [OF homh]
and hom_one [simp] = ring_hom_one [OF homh]
sublocale ring_hom_cring \<subseteq> ring: ring_hom_ring
by standard (rule homh)
sublocale ring_hom_ring \<subseteq> abelian_group?: abelian_group_hom R S
apply (rule abelian_group_homI)
apply (rule R.is_abelian_group)
apply (rule S.is_abelian_group)
apply (intro group_hom.intro group_hom_axioms.intro)
apply (rule R.a_group)
apply (rule S.a_group)
apply (insert homh, unfold hom_def ring_hom_def)
apply simp
done
lemma (in ring_hom_ring) is_ring_hom_ring:
"ring_hom_ring R S h"
by (rule ring_hom_ring_axioms)
lemma ring_hom_ringI:
fixes R (structure) and S (structure)
assumes "ring R" "ring S"
assumes (* morphism: "h \<in> carrier R \<rightarrow> carrier S" *)
hom_closed: "!!x. x \<in> carrier R ==> h x \<in> carrier S"
and compatible_mult: "\<And>x y. [| x \<in> carrier R; y \<in> carrier R |] ==> h (x \<otimes> y) = h x \<otimes>\<^bsub>S\<^esub> h y"
and compatible_add: "\<And>x y. [| x \<in> carrier R; y \<in> carrier R |] ==> h (x \<oplus> y) = h x \<oplus>\<^bsub>S\<^esub> h y"
and compatible_one: "h \<one> = \<one>\<^bsub>S\<^esub>"
shows "ring_hom_ring R S h"
proof -
interpret ring R by fact
interpret ring S by fact
show ?thesis apply unfold_locales
apply (unfold ring_hom_def, safe)
apply (simp add: hom_closed Pi_def)
apply (erule (1) compatible_mult)
apply (erule (1) compatible_add)
apply (rule compatible_one)
done
qed
lemma ring_hom_ringI2:
assumes "ring R" "ring S"
assumes h: "h \<in> ring_hom R S"
shows "ring_hom_ring R S h"
proof -
interpret R: ring R by fact
interpret S: ring S by fact
show ?thesis apply (intro ring_hom_ring.intro ring_hom_ring_axioms.intro)
apply (rule R.ring_axioms)
apply (rule S.ring_axioms)
apply (rule h)
done
qed
lemma ring_hom_ringI3:
fixes R (structure) and S (structure)
assumes "abelian_group_hom R S h" "ring R" "ring S"
assumes compatible_mult: "\<And>x y. [| x \<in> carrier R; y \<in> carrier R |] ==> h (x \<otimes> y) = h x \<otimes>\<^bsub>S\<^esub> h y"
and compatible_one: "h \<one> = \<one>\<^bsub>S\<^esub>"
shows "ring_hom_ring R S h"
proof -
interpret abelian_group_hom R S h by fact
interpret R: ring R by fact
interpret S: ring S by fact
show ?thesis apply (intro ring_hom_ring.intro ring_hom_ring_axioms.intro, rule R.ring_axioms, rule S.ring_axioms)
apply (insert group_hom.homh[OF a_group_hom])
apply (unfold hom_def ring_hom_def, simp)
apply safe
apply (erule (1) compatible_mult)
apply (rule compatible_one)
done
qed
lemma ring_hom_cringI:
assumes "ring_hom_ring R S h" "cring R" "cring S"
shows "ring_hom_cring R S h"
proof -
interpret ring_hom_ring R S h by fact
interpret R: cring R by fact
interpret S: cring S by fact
show ?thesis by (intro ring_hom_cring.intro ring_hom_cring_axioms.intro)
(rule R.is_cring, rule S.is_cring, rule homh)
qed
subsection \<open>The Kernel of a Ring Homomorphism\<close>
\<comment> \<open>the kernel of a ring homomorphism is an ideal\<close>
lemma (in ring_hom_ring) kernel_is_ideal:
shows "ideal (a_kernel R S h) R"
apply (rule idealI)
apply (rule R.ring_axioms)
apply (rule additive_subgroup.a_subgroup[OF additive_subgroup_a_kernel])
apply (unfold a_kernel_def', simp+)
done
text \<open>Elements of the kernel are mapped to zero\<close>
lemma (in abelian_group_hom) kernel_zero [simp]:
"i \<in> a_kernel R S h \<Longrightarrow> h i = \<zero>\<^bsub>S\<^esub>"
by (simp add: a_kernel_defs)
subsection \<open>Cosets\<close>
text \<open>Cosets of the kernel correspond to the elements of the image of the homomorphism\<close>
lemma (in ring_hom_ring) rcos_imp_homeq:
assumes acarr: "a \<in> carrier R"
and xrcos: "x \<in> a_kernel R S h +> a"
shows "h x = h a"
proof -
interpret ideal "a_kernel R S h" "R" by (rule kernel_is_ideal)
from xrcos
have "\<exists>i \<in> a_kernel R S h. x = i \<oplus> a" by (simp add: a_r_coset_defs)
from this obtain i
where iker: "i \<in> a_kernel R S h"
and x: "x = i \<oplus> a"
by fast+
note carr = acarr iker[THEN a_Hcarr]
from x
have "h x = h (i \<oplus> a)" by simp
also from carr
have "\<dots> = h i \<oplus>\<^bsub>S\<^esub> h a" by simp
also from iker
have "\<dots> = \<zero>\<^bsub>S\<^esub> \<oplus>\<^bsub>S\<^esub> h a" by simp
also from carr
have "\<dots> = h a" by simp
finally
show "h x = h a" .
qed
lemma (in ring_hom_ring) homeq_imp_rcos:
assumes acarr: "a \<in> carrier R"
and xcarr: "x \<in> carrier R"
and hx: "h x = h a"
shows "x \<in> a_kernel R S h +> a"
proof -
interpret ideal "a_kernel R S h" "R" by (rule kernel_is_ideal)
note carr = acarr xcarr
note hcarr = acarr[THEN hom_closed] xcarr[THEN hom_closed]
from hx and hcarr
have a: "h x \<oplus>\<^bsub>S\<^esub> \<ominus>\<^bsub>S\<^esub>h a = \<zero>\<^bsub>S\<^esub>" by algebra
from carr
have "h x \<oplus>\<^bsub>S\<^esub> \<ominus>\<^bsub>S\<^esub>h a = h (x \<oplus> \<ominus>a)" by simp
from a and this
have b: "h (x \<oplus> \<ominus>a) = \<zero>\<^bsub>S\<^esub>" by simp
from carr have "x \<oplus> \<ominus>a \<in> carrier R" by simp
from this and b
have "x \<oplus> \<ominus>a \<in> a_kernel R S h"
unfolding a_kernel_def'
by fast
from this and carr
show "x \<in> a_kernel R S h +> a" by (simp add: a_rcos_module_rev)
qed
corollary (in ring_hom_ring) rcos_eq_homeq:
assumes acarr: "a \<in> carrier R"
shows "(a_kernel R S h) +> a = {x \<in> carrier R. h x = h a}"
apply rule defer 1
apply clarsimp defer 1
proof
interpret ideal "a_kernel R S h" "R" by (rule kernel_is_ideal)
fix x
assume xrcos: "x \<in> a_kernel R S h +> a"
from acarr and this
have xcarr: "x \<in> carrier R"
by (rule a_elemrcos_carrier)
from xrcos
have "h x = h a" by (rule rcos_imp_homeq[OF acarr])
from xcarr and this
show "x \<in> {x \<in> carrier R. h x = h a}" by fast
next
interpret ideal "a_kernel R S h" "R" by (rule kernel_is_ideal)
fix x
assume xcarr: "x \<in> carrier R"
and hx: "h x = h a"
from acarr xcarr hx
show "x \<in> a_kernel R S h +> a" by (rule homeq_imp_rcos)
qed
(* NEW ========================================================================= *)
lemma (in ring_hom_ring) nat_pow_hom:
"x \<in> carrier R \<Longrightarrow> h (x [^] (n :: nat)) = (h x) [^]\<^bsub>S\<^esub> n"
by (induct n) (auto)
(* ============================================================================= *)
(* REPLACED ==================================================================== *)
lemma (in ring_hom_ring) hom_finsum [simp]:
"f \<in> A \<rightarrow> carrier R \<Longrightarrow>
h (finsum R f A) = finsum S (h \<circ> f) A"
by (induct A rule: infinite_finite_induct, auto simp: Pi_def)
(* ============================================================================= *)
(*contributed by Paulo Emílio de Vilhena*)
lemma (in ring_hom_ring) inj_on_domain:
assumes "inj_on h (carrier R)"
shows "domain S \<Longrightarrow> domain R"
proof -
assume A: "domain S" show "domain R"
proof
have "h \<one> = \<one>\<^bsub>S\<^esub> \<and> h \<zero> = \<zero>\<^bsub>S\<^esub>" by simp
hence "h \<one> \<noteq> h \<zero>"
using domain.one_not_zero[OF A] by simp
thus "\<one> \<noteq> \<zero>"
using assms unfolding inj_on_def by fastforce
next
fix a b
assume a: "a \<in> carrier R"
and b: "b \<in> carrier R"
have "h (a \<otimes> b) = (h a) \<otimes>\<^bsub>S\<^esub> (h b)" by (simp add: a b)
also have " ... = (h b) \<otimes>\<^bsub>S\<^esub> (h a)" using a b A cringE(1)[of S]
by (simp add: cring.cring_simprules(14) domain_def)
also have " ... = h (b \<otimes> a)" by (simp add: a b)
finally have "h (a \<otimes> b) = h (b \<otimes> a)" .
thus "a \<otimes> b = b \<otimes> a"
using assms a b unfolding inj_on_def by simp
assume ab: "a \<otimes> b = \<zero>"
hence "h (a \<otimes> b) = \<zero>\<^bsub>S\<^esub>" by simp
hence "(h a) \<otimes>\<^bsub>S\<^esub> (h b) = \<zero>\<^bsub>S\<^esub>" using a b by simp
hence "h a = \<zero>\<^bsub>S\<^esub> \<or> h b = \<zero>\<^bsub>S\<^esub>" using a b domain.integral[OF A] by simp
thus "a = \<zero> \<or> b = \<zero>"
using a b assms unfolding inj_on_def by force
qed
qed
end
|
lemma has_bochner_integral_restrict_space: fixes f :: "'a \<Rightarrow> 'b::{banach, second_countable_topology}" assumes \<Omega>: "\<Omega> \<inter> space M \<in> sets M" shows "has_bochner_integral (restrict_space M \<Omega>) f i \<longleftrightarrow> has_bochner_integral M (\<lambda>x. indicator \<Omega> x *\<^sub>R f x) i" |
[STATEMENT]
lemma parts_cut_eq [simp]: "X\<in> parts H ==> parts (insert X H) = parts H"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. X \<in> parts H \<Longrightarrow> parts (insert X H) = parts H
[PROOF STEP]
by (metis insert_absorb parts_idem parts_insert) |
Subsets and Splits