text
stringlengths 0
3.34M
|
---|
import analysis.normed_space.int
import polyhedral_lattice.basic
/-!
# The integers are a polyhedral lattice.
The integers, with its usual norm, are a polyhedral lattice.
-/
noncomputable theory
open_locale big_operators
lemma int.sum_units_to_nat_smul (n : ℤ) :
∑ (i : units ℤ), int.to_nat (i * n) • (i : ℤ) = n :=
begin
rw [units_int.univ, finset.sum_insert], swap, dec_trivial,
simp only [neg_mul, mul_one, one_mul, nsmul_eq_mul, units.coe_one, units.coe_neg_one, mul_neg,
finset.sum_singleton, ←sub_eq_add_neg, int.to_nat_sub_to_nat_neg],
end
instance int.polyhedral_lattice : polyhedral_lattice ℤ :=
{ polyhedral' :=
begin
refine ⟨units ℤ, infer_instance, coe, _⟩,
intro n,
refine ⟨λ e, int.to_nat (e * n), (int.sum_units_to_nat_smul _).symm, _⟩,
simp only [int.norm_coe_units, mul_one, nat.cast_one, one_mul, units_int.univ],
show ∥n∥ = ((1 * n).to_nat) + (↑(((-1) * n).to_nat) + 0),
simp only [neg_mul, add_zero, one_mul],
exact (int.to_nat_add_to_nat_neg_eq_norm _).symm,
end }
|
#' Title
#'
#' @param parms
#' @param set
#'
#' @return
#' @export
#'
#' @examples
#'
#' p <- set_parms(livestock$parms, set = list(b = 0.2, f = 0.9))
#'
set_parms <- function(parms, set = list(NA)) {
parms.names <- names(parms)
set.names <- names(set)
m.names <- sort(unique(c(parms.names, set.names)))
parms_new <- sapply(m.names, function(i) {
if (i %in% set.names) set[[i]]
else parms[[i]]
}, simplify = FALSE)
return(parms_new)
}
|
lemma open_UNION_box: fixes M :: "'a::euclidean_space set" assumes "open M" defines "a' \<equiv> \<lambda>f :: 'a \<Rightarrow> real \<times> real. (\<Sum>(i::'a)\<in>Basis. fst (f i) *\<^sub>R i)" defines "b' \<equiv> \<lambda>f :: 'a \<Rightarrow> real \<times> real. (\<Sum>(i::'a)\<in>Basis. snd (f i) *\<^sub>R i)" defines "I \<equiv> {f\<in>Basis \<rightarrow>\<^sub>E \<rat> \<times> \<rat>. box (a' f) (b' f) \<subseteq> M}" shows "M = (\<Union>f\<in>I. box (a' f) (b' f))" |
[GOAL]
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
h : IsAssociatedPrime I M
hf : Function.Injective ↑f
⊢ IsAssociatedPrime I M'
[PROOFSTEP]
obtain ⟨x, rfl⟩ := h.2
[GOAL]
case intro
R : Type u_1
inst✝⁴ : CommRing R
J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
hf : Function.Injective ↑f
x : M
h : IsAssociatedPrime (Submodule.annihilator (Submodule.span R {x})) M
⊢ IsAssociatedPrime (Submodule.annihilator (Submodule.span R {x})) M'
[PROOFSTEP]
refine' ⟨h.1, ⟨f x, _⟩⟩
[GOAL]
case intro
R : Type u_1
inst✝⁴ : CommRing R
J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
hf : Function.Injective ↑f
x : M
h : IsAssociatedPrime (Submodule.annihilator (Submodule.span R {x})) M
⊢ Submodule.annihilator (Submodule.span R {x}) = Submodule.annihilator (Submodule.span R {↑f x})
[PROOFSTEP]
ext r
[GOAL]
case intro.h
R : Type u_1
inst✝⁴ : CommRing R
J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
hf : Function.Injective ↑f
x : M
h : IsAssociatedPrime (Submodule.annihilator (Submodule.span R {x})) M
r : R
⊢ r ∈ Submodule.annihilator (Submodule.span R {x}) ↔ r ∈ Submodule.annihilator (Submodule.span R {↑f x})
[PROOFSTEP]
rw [Submodule.mem_annihilator_span_singleton, Submodule.mem_annihilator_span_singleton, ← map_smul, ← f.map_zero,
hf.eq_iff]
[GOAL]
R : Type u_1
inst✝⁵ : CommRing R
I J : Ideal R
M : Type u_2
inst✝⁴ : AddCommGroup M
inst✝³ : Module R M
M' : Type u_3
inst✝² : AddCommGroup M'
inst✝¹ : Module R M'
f : M →ₗ[R] M'
inst✝ : Subsingleton M
⊢ ¬IsAssociatedPrime I M
[PROOFSTEP]
rintro ⟨hI, x, hx⟩
[GOAL]
case intro.intro
R : Type u_1
inst✝⁵ : CommRing R
I J : Ideal R
M : Type u_2
inst✝⁴ : AddCommGroup M
inst✝³ : Module R M
M' : Type u_3
inst✝² : AddCommGroup M'
inst✝¹ : Module R M'
f : M →ₗ[R] M'
inst✝ : Subsingleton M
hI : Ideal.IsPrime I
x : M
hx : I = Submodule.annihilator (Submodule.span R {x})
⊢ False
[PROOFSTEP]
apply hI.ne_top
[GOAL]
case intro.intro
R : Type u_1
inst✝⁵ : CommRing R
I J : Ideal R
M : Type u_2
inst✝⁴ : AddCommGroup M
inst✝³ : Module R M
M' : Type u_3
inst✝² : AddCommGroup M'
inst✝¹ : Module R M'
f : M →ₗ[R] M'
inst✝ : Subsingleton M
hI : Ideal.IsPrime I
x : M
hx : I = Submodule.annihilator (Submodule.span R {x})
⊢ I = ⊤
[PROOFSTEP]
rwa [Subsingleton.elim x 0, Submodule.span_singleton_eq_bot.mpr rfl, Submodule.annihilator_bot] at hx
[GOAL]
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
H : IsNoetherianRing R
x : M
hx : x ≠ 0
⊢ ∃ P, IsAssociatedPrime P M ∧ Submodule.annihilator (Submodule.span R {x}) ≤ P
[PROOFSTEP]
have : (R ∙ x).annihilator ≠ ⊤ := by
rwa [Ne.def, Ideal.eq_top_iff_one, Submodule.mem_annihilator_span_singleton, one_smul]
[GOAL]
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
H : IsNoetherianRing R
x : M
hx : x ≠ 0
⊢ Submodule.annihilator (Submodule.span R {x}) ≠ ⊤
[PROOFSTEP]
rwa [Ne.def, Ideal.eq_top_iff_one, Submodule.mem_annihilator_span_singleton, one_smul]
[GOAL]
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
H : IsNoetherianRing R
x : M
hx : x ≠ 0
this : Submodule.annihilator (Submodule.span R {x}) ≠ ⊤
⊢ ∃ P, IsAssociatedPrime P M ∧ Submodule.annihilator (Submodule.span R {x}) ≤ P
[PROOFSTEP]
obtain ⟨P, ⟨l, h₁, y, rfl⟩, h₃⟩ :=
set_has_maximal_iff_noetherian.mpr H {P | (R ∙ x).annihilator ≤ P ∧ P ≠ ⊤ ∧ ∃ y : M, P = (R ∙ y).annihilator}
⟨(R ∙ x).annihilator, rfl.le, this, x, rfl⟩
[GOAL]
case intro.intro.intro.intro.intro
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
H : IsNoetherianRing R
x : M
hx : x ≠ 0
this : Submodule.annihilator (Submodule.span R {x}) ≠ ⊤
y : M
h₃ :
∀ (I : Submodule R R),
I ∈
{P |
Submodule.annihilator (Submodule.span R {x}) ≤ P ∧
P ≠ ⊤ ∧ ∃ y, P = Submodule.annihilator (Submodule.span R {y})} →
¬Submodule.annihilator (Submodule.span R {y}) < I
l : Submodule.annihilator (Submodule.span R {x}) ≤ Submodule.annihilator (Submodule.span R {y})
h₁ : Submodule.annihilator (Submodule.span R {y}) ≠ ⊤
⊢ ∃ P, IsAssociatedPrime P M ∧ Submodule.annihilator (Submodule.span R {x}) ≤ P
[PROOFSTEP]
refine' ⟨_, ⟨⟨h₁, _⟩, y, rfl⟩, l⟩
[GOAL]
case intro.intro.intro.intro.intro
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
H : IsNoetherianRing R
x : M
hx : x ≠ 0
this : Submodule.annihilator (Submodule.span R {x}) ≠ ⊤
y : M
h₃ :
∀ (I : Submodule R R),
I ∈
{P |
Submodule.annihilator (Submodule.span R {x}) ≤ P ∧
P ≠ ⊤ ∧ ∃ y, P = Submodule.annihilator (Submodule.span R {y})} →
¬Submodule.annihilator (Submodule.span R {y}) < I
l : Submodule.annihilator (Submodule.span R {x}) ≤ Submodule.annihilator (Submodule.span R {y})
h₁ : Submodule.annihilator (Submodule.span R {y}) ≠ ⊤
⊢ ∀ {x y_1 : R},
x * y_1 ∈ Submodule.annihilator (Submodule.span R {y}) →
x ∈ Submodule.annihilator (Submodule.span R {y}) ∨ y_1 ∈ Submodule.annihilator (Submodule.span R {y})
[PROOFSTEP]
intro a b hab
[GOAL]
case intro.intro.intro.intro.intro
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
H : IsNoetherianRing R
x : M
hx : x ≠ 0
this : Submodule.annihilator (Submodule.span R {x}) ≠ ⊤
y : M
h₃ :
∀ (I : Submodule R R),
I ∈
{P |
Submodule.annihilator (Submodule.span R {x}) ≤ P ∧
P ≠ ⊤ ∧ ∃ y, P = Submodule.annihilator (Submodule.span R {y})} →
¬Submodule.annihilator (Submodule.span R {y}) < I
l : Submodule.annihilator (Submodule.span R {x}) ≤ Submodule.annihilator (Submodule.span R {y})
h₁ : Submodule.annihilator (Submodule.span R {y}) ≠ ⊤
a b : R
hab : a * b ∈ Submodule.annihilator (Submodule.span R {y})
⊢ a ∈ Submodule.annihilator (Submodule.span R {y}) ∨ b ∈ Submodule.annihilator (Submodule.span R {y})
[PROOFSTEP]
rw [or_iff_not_imp_left]
[GOAL]
case intro.intro.intro.intro.intro
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
H : IsNoetherianRing R
x : M
hx : x ≠ 0
this : Submodule.annihilator (Submodule.span R {x}) ≠ ⊤
y : M
h₃ :
∀ (I : Submodule R R),
I ∈
{P |
Submodule.annihilator (Submodule.span R {x}) ≤ P ∧
P ≠ ⊤ ∧ ∃ y, P = Submodule.annihilator (Submodule.span R {y})} →
¬Submodule.annihilator (Submodule.span R {y}) < I
l : Submodule.annihilator (Submodule.span R {x}) ≤ Submodule.annihilator (Submodule.span R {y})
h₁ : Submodule.annihilator (Submodule.span R {y}) ≠ ⊤
a b : R
hab : a * b ∈ Submodule.annihilator (Submodule.span R {y})
⊢ ¬a ∈ Submodule.annihilator (Submodule.span R {y}) → b ∈ Submodule.annihilator (Submodule.span R {y})
[PROOFSTEP]
intro ha
[GOAL]
case intro.intro.intro.intro.intro
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
H : IsNoetherianRing R
x : M
hx : x ≠ 0
this : Submodule.annihilator (Submodule.span R {x}) ≠ ⊤
y : M
h₃ :
∀ (I : Submodule R R),
I ∈
{P |
Submodule.annihilator (Submodule.span R {x}) ≤ P ∧
P ≠ ⊤ ∧ ∃ y, P = Submodule.annihilator (Submodule.span R {y})} →
¬Submodule.annihilator (Submodule.span R {y}) < I
l : Submodule.annihilator (Submodule.span R {x}) ≤ Submodule.annihilator (Submodule.span R {y})
h₁ : Submodule.annihilator (Submodule.span R {y}) ≠ ⊤
a b : R
hab : a * b ∈ Submodule.annihilator (Submodule.span R {y})
ha : ¬a ∈ Submodule.annihilator (Submodule.span R {y})
⊢ b ∈ Submodule.annihilator (Submodule.span R {y})
[PROOFSTEP]
rw [Submodule.mem_annihilator_span_singleton] at ha hab
[GOAL]
case intro.intro.intro.intro.intro
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
H : IsNoetherianRing R
x : M
hx : x ≠ 0
this : Submodule.annihilator (Submodule.span R {x}) ≠ ⊤
y : M
h₃ :
∀ (I : Submodule R R),
I ∈
{P |
Submodule.annihilator (Submodule.span R {x}) ≤ P ∧
P ≠ ⊤ ∧ ∃ y, P = Submodule.annihilator (Submodule.span R {y})} →
¬Submodule.annihilator (Submodule.span R {y}) < I
l : Submodule.annihilator (Submodule.span R {x}) ≤ Submodule.annihilator (Submodule.span R {y})
h₁ : Submodule.annihilator (Submodule.span R {y}) ≠ ⊤
a b : R
hab : (a * b) • y = 0
ha : ¬a • y = 0
⊢ b ∈ Submodule.annihilator (Submodule.span R {y})
[PROOFSTEP]
have H₁ : (R ∙ y).annihilator ≤ (R ∙ a • y).annihilator :=
by
intro c hc
rw [Submodule.mem_annihilator_span_singleton] at hc ⊢
rw [smul_comm, hc, smul_zero]
[GOAL]
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
H : IsNoetherianRing R
x : M
hx : x ≠ 0
this : Submodule.annihilator (Submodule.span R {x}) ≠ ⊤
y : M
h₃ :
∀ (I : Submodule R R),
I ∈
{P |
Submodule.annihilator (Submodule.span R {x}) ≤ P ∧
P ≠ ⊤ ∧ ∃ y, P = Submodule.annihilator (Submodule.span R {y})} →
¬Submodule.annihilator (Submodule.span R {y}) < I
l : Submodule.annihilator (Submodule.span R {x}) ≤ Submodule.annihilator (Submodule.span R {y})
h₁ : Submodule.annihilator (Submodule.span R {y}) ≠ ⊤
a b : R
hab : (a * b) • y = 0
ha : ¬a • y = 0
⊢ Submodule.annihilator (Submodule.span R {y}) ≤ Submodule.annihilator (Submodule.span R {a • y})
[PROOFSTEP]
intro c hc
[GOAL]
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
H : IsNoetherianRing R
x : M
hx : x ≠ 0
this : Submodule.annihilator (Submodule.span R {x}) ≠ ⊤
y : M
h₃ :
∀ (I : Submodule R R),
I ∈
{P |
Submodule.annihilator (Submodule.span R {x}) ≤ P ∧
P ≠ ⊤ ∧ ∃ y, P = Submodule.annihilator (Submodule.span R {y})} →
¬Submodule.annihilator (Submodule.span R {y}) < I
l : Submodule.annihilator (Submodule.span R {x}) ≤ Submodule.annihilator (Submodule.span R {y})
h₁ : Submodule.annihilator (Submodule.span R {y}) ≠ ⊤
a b : R
hab : (a * b) • y = 0
ha : ¬a • y = 0
c : R
hc : c ∈ Submodule.annihilator (Submodule.span R {y})
⊢ c ∈ Submodule.annihilator (Submodule.span R {a • y})
[PROOFSTEP]
rw [Submodule.mem_annihilator_span_singleton] at hc ⊢
[GOAL]
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
H : IsNoetherianRing R
x : M
hx : x ≠ 0
this : Submodule.annihilator (Submodule.span R {x}) ≠ ⊤
y : M
h₃ :
∀ (I : Submodule R R),
I ∈
{P |
Submodule.annihilator (Submodule.span R {x}) ≤ P ∧
P ≠ ⊤ ∧ ∃ y, P = Submodule.annihilator (Submodule.span R {y})} →
¬Submodule.annihilator (Submodule.span R {y}) < I
l : Submodule.annihilator (Submodule.span R {x}) ≤ Submodule.annihilator (Submodule.span R {y})
h₁ : Submodule.annihilator (Submodule.span R {y}) ≠ ⊤
a b : R
hab : (a * b) • y = 0
ha : ¬a • y = 0
c : R
hc : c • y = 0
⊢ c • a • y = 0
[PROOFSTEP]
rw [smul_comm, hc, smul_zero]
[GOAL]
case intro.intro.intro.intro.intro
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
H : IsNoetherianRing R
x : M
hx : x ≠ 0
this : Submodule.annihilator (Submodule.span R {x}) ≠ ⊤
y : M
h₃ :
∀ (I : Submodule R R),
I ∈
{P |
Submodule.annihilator (Submodule.span R {x}) ≤ P ∧
P ≠ ⊤ ∧ ∃ y, P = Submodule.annihilator (Submodule.span R {y})} →
¬Submodule.annihilator (Submodule.span R {y}) < I
l : Submodule.annihilator (Submodule.span R {x}) ≤ Submodule.annihilator (Submodule.span R {y})
h₁ : Submodule.annihilator (Submodule.span R {y}) ≠ ⊤
a b : R
hab : (a * b) • y = 0
ha : ¬a • y = 0
H₁ : Submodule.annihilator (Submodule.span R {y}) ≤ Submodule.annihilator (Submodule.span R {a • y})
⊢ b ∈ Submodule.annihilator (Submodule.span R {y})
[PROOFSTEP]
have H₂ : (Submodule.span R {a • y}).annihilator ≠ ⊤ := by
rwa [Ne.def, Submodule.annihilator_eq_top_iff, Submodule.span_singleton_eq_bot]
[GOAL]
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
H : IsNoetherianRing R
x : M
hx : x ≠ 0
this : Submodule.annihilator (Submodule.span R {x}) ≠ ⊤
y : M
h₃ :
∀ (I : Submodule R R),
I ∈
{P |
Submodule.annihilator (Submodule.span R {x}) ≤ P ∧
P ≠ ⊤ ∧ ∃ y, P = Submodule.annihilator (Submodule.span R {y})} →
¬Submodule.annihilator (Submodule.span R {y}) < I
l : Submodule.annihilator (Submodule.span R {x}) ≤ Submodule.annihilator (Submodule.span R {y})
h₁ : Submodule.annihilator (Submodule.span R {y}) ≠ ⊤
a b : R
hab : (a * b) • y = 0
ha : ¬a • y = 0
H₁ : Submodule.annihilator (Submodule.span R {y}) ≤ Submodule.annihilator (Submodule.span R {a • y})
⊢ Submodule.annihilator (Submodule.span R {a • y}) ≠ ⊤
[PROOFSTEP]
rwa [Ne.def, Submodule.annihilator_eq_top_iff, Submodule.span_singleton_eq_bot]
[GOAL]
case intro.intro.intro.intro.intro
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
H : IsNoetherianRing R
x : M
hx : x ≠ 0
this : Submodule.annihilator (Submodule.span R {x}) ≠ ⊤
y : M
h₃ :
∀ (I : Submodule R R),
I ∈
{P |
Submodule.annihilator (Submodule.span R {x}) ≤ P ∧
P ≠ ⊤ ∧ ∃ y, P = Submodule.annihilator (Submodule.span R {y})} →
¬Submodule.annihilator (Submodule.span R {y}) < I
l : Submodule.annihilator (Submodule.span R {x}) ≤ Submodule.annihilator (Submodule.span R {y})
h₁ : Submodule.annihilator (Submodule.span R {y}) ≠ ⊤
a b : R
hab : (a * b) • y = 0
ha : ¬a • y = 0
H₁ : Submodule.annihilator (Submodule.span R {y}) ≤ Submodule.annihilator (Submodule.span R {a • y})
H₂ : Submodule.annihilator (Submodule.span R {a • y}) ≠ ⊤
⊢ b ∈ Submodule.annihilator (Submodule.span R {y})
[PROOFSTEP]
rwa [H₁.eq_of_not_lt (h₃ (R ∙ a • y).annihilator ⟨l.trans H₁, H₂, _, rfl⟩), Submodule.mem_annihilator_span_singleton,
smul_comm, smul_smul]
[GOAL]
R : Type u_1
inst✝⁵ : CommRing R
I J : Ideal R
M : Type u_2
inst✝⁴ : AddCommGroup M
inst✝³ : Module R M
M' : Type u_3
inst✝² : AddCommGroup M'
inst✝¹ : Module R M'
f : M →ₗ[R] M'
inst✝ : Subsingleton M
⊢ associatedPrimes R M = ∅
[PROOFSTEP]
ext
[GOAL]
case h
R : Type u_1
inst✝⁵ : CommRing R
I J : Ideal R
M : Type u_2
inst✝⁴ : AddCommGroup M
inst✝³ : Module R M
M' : Type u_3
inst✝² : AddCommGroup M'
inst✝¹ : Module R M'
f : M →ₗ[R] M'
inst✝ : Subsingleton M
x✝ : Ideal R
⊢ x✝ ∈ associatedPrimes R M ↔ x✝ ∈ ∅
[PROOFSTEP]
simp only [Set.mem_empty_iff_false, iff_false_iff]
[GOAL]
case h
R : Type u_1
inst✝⁵ : CommRing R
I J : Ideal R
M : Type u_2
inst✝⁴ : AddCommGroup M
inst✝³ : Module R M
M' : Type u_3
inst✝² : AddCommGroup M'
inst✝¹ : Module R M'
f : M →ₗ[R] M'
inst✝ : Subsingleton M
x✝ : Ideal R
⊢ ¬x✝ ∈ associatedPrimes R M
[PROOFSTEP]
apply not_isAssociatedPrime_of_subsingleton
[GOAL]
R : Type u_1
inst✝⁶ : CommRing R
I J : Ideal R
M : Type u_2
inst✝⁵ : AddCommGroup M
inst✝⁴ : Module R M
M' : Type u_3
inst✝³ : AddCommGroup M'
inst✝² : Module R M'
f : M →ₗ[R] M'
inst✝¹ : IsNoetherianRing R
inst✝ : Nontrivial M
⊢ Set.Nonempty (associatedPrimes R M)
[PROOFSTEP]
obtain ⟨x, hx⟩ := exists_ne (0 : M)
[GOAL]
case intro
R : Type u_1
inst✝⁶ : CommRing R
I J : Ideal R
M : Type u_2
inst✝⁵ : AddCommGroup M
inst✝⁴ : Module R M
M' : Type u_3
inst✝³ : AddCommGroup M'
inst✝² : Module R M'
f : M →ₗ[R] M'
inst✝¹ : IsNoetherianRing R
inst✝ : Nontrivial M
x : M
hx : x ≠ 0
⊢ Set.Nonempty (associatedPrimes R M)
[PROOFSTEP]
obtain ⟨P, hP, _⟩ := exists_le_isAssociatedPrime_of_isNoetherianRing R x hx
[GOAL]
case intro.intro.intro
R : Type u_1
inst✝⁶ : CommRing R
I J : Ideal R
M : Type u_2
inst✝⁵ : AddCommGroup M
inst✝⁴ : Module R M
M' : Type u_3
inst✝³ : AddCommGroup M'
inst✝² : Module R M'
f : M →ₗ[R] M'
inst✝¹ : IsNoetherianRing R
inst✝ : Nontrivial M
x : M
hx : x ≠ 0
P : Ideal R
hP : IsAssociatedPrime P M
right✝ : Submodule.annihilator (Submodule.span R {x}) ≤ P
⊢ Set.Nonempty (associatedPrimes R M)
[PROOFSTEP]
exact ⟨P, hP⟩
[GOAL]
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
h : IsAssociatedPrime I M
⊢ Submodule.annihilator ⊤ ≤ I
[PROOFSTEP]
obtain ⟨hI, x, rfl⟩ := h
[GOAL]
case intro.intro
R : Type u_1
inst✝⁴ : CommRing R
J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
x : M
hI : Ideal.IsPrime (Submodule.annihilator (Submodule.span R {x}))
⊢ Submodule.annihilator ⊤ ≤ Submodule.annihilator (Submodule.span R {x})
[PROOFSTEP]
exact Submodule.annihilator_mono le_top
[GOAL]
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
hI : Ideal.IsPrimary I
h : IsAssociatedPrime J (R ⧸ I)
⊢ J = Ideal.radical I
[PROOFSTEP]
obtain ⟨hJ, x, e⟩ := h
[GOAL]
case intro.intro
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
hI : Ideal.IsPrimary I
hJ : Ideal.IsPrime J
x : R ⧸ I
e : J = Submodule.annihilator (Submodule.span R {x})
⊢ J = Ideal.radical I
[PROOFSTEP]
have : x ≠ 0 := by
rintro rfl
apply hJ.1
rwa [Submodule.span_singleton_eq_bot.mpr rfl, Submodule.annihilator_bot] at e
[GOAL]
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
hI : Ideal.IsPrimary I
hJ : Ideal.IsPrime J
x : R ⧸ I
e : J = Submodule.annihilator (Submodule.span R {x})
⊢ x ≠ 0
[PROOFSTEP]
rintro rfl
[GOAL]
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
hI : Ideal.IsPrimary I
hJ : Ideal.IsPrime J
e : J = Submodule.annihilator (Submodule.span R {0})
⊢ False
[PROOFSTEP]
apply hJ.1
[GOAL]
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
hI : Ideal.IsPrimary I
hJ : Ideal.IsPrime J
e : J = Submodule.annihilator (Submodule.span R {0})
⊢ J = ⊤
[PROOFSTEP]
rwa [Submodule.span_singleton_eq_bot.mpr rfl, Submodule.annihilator_bot] at e
[GOAL]
case intro.intro
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
hI : Ideal.IsPrimary I
hJ : Ideal.IsPrime J
x : R ⧸ I
e : J = Submodule.annihilator (Submodule.span R {x})
this : x ≠ 0
⊢ J = Ideal.radical I
[PROOFSTEP]
obtain ⟨x, rfl⟩ := Ideal.Quotient.mkₐ_surjective R _ x
[GOAL]
case intro.intro.intro
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
hI : Ideal.IsPrimary I
hJ : Ideal.IsPrime J
x : R
e : J = Submodule.annihilator (Submodule.span R {↑(Ideal.Quotient.mkₐ R I) x})
this : ↑(Ideal.Quotient.mkₐ R I) x ≠ 0
⊢ J = Ideal.radical I
[PROOFSTEP]
replace e : ∀ {y}, y ∈ J ↔ x * y ∈ I
[GOAL]
case e
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
hI : Ideal.IsPrimary I
hJ : Ideal.IsPrime J
x : R
e : J = Submodule.annihilator (Submodule.span R {↑(Ideal.Quotient.mkₐ R I) x})
this : ↑(Ideal.Quotient.mkₐ R I) x ≠ 0
⊢ ∀ {y : R}, y ∈ J ↔ x * y ∈ I
[PROOFSTEP]
intro y
[GOAL]
case e
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
hI : Ideal.IsPrimary I
hJ : Ideal.IsPrime J
x : R
e : J = Submodule.annihilator (Submodule.span R {↑(Ideal.Quotient.mkₐ R I) x})
this : ↑(Ideal.Quotient.mkₐ R I) x ≠ 0
y : R
⊢ y ∈ J ↔ x * y ∈ I
[PROOFSTEP]
rw [e, Submodule.mem_annihilator_span_singleton, ← map_smul, smul_eq_mul, mul_comm, Ideal.Quotient.mkₐ_eq_mk, ←
Ideal.Quotient.mk_eq_mk, Submodule.Quotient.mk_eq_zero]
[GOAL]
case intro.intro.intro
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
hI : Ideal.IsPrimary I
hJ : Ideal.IsPrime J
x : R
this : ↑(Ideal.Quotient.mkₐ R I) x ≠ 0
e : ∀ {y : R}, y ∈ J ↔ x * y ∈ I
⊢ J = Ideal.radical I
[PROOFSTEP]
apply le_antisymm
[GOAL]
case intro.intro.intro.a
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
hI : Ideal.IsPrimary I
hJ : Ideal.IsPrime J
x : R
this : ↑(Ideal.Quotient.mkₐ R I) x ≠ 0
e : ∀ {y : R}, y ∈ J ↔ x * y ∈ I
⊢ J ≤ Ideal.radical I
[PROOFSTEP]
intro y hy
[GOAL]
case intro.intro.intro.a
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
hI : Ideal.IsPrimary I
hJ : Ideal.IsPrime J
x : R
this : ↑(Ideal.Quotient.mkₐ R I) x ≠ 0
e : ∀ {y : R}, y ∈ J ↔ x * y ∈ I
y : R
hy : y ∈ J
⊢ y ∈ Ideal.radical I
[PROOFSTEP]
exact (hI.2 <| e.mp hy).resolve_left ((Submodule.Quotient.mk_eq_zero I).not.mp this)
[GOAL]
case intro.intro.intro.a
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
hI : Ideal.IsPrimary I
hJ : Ideal.IsPrime J
x : R
this : ↑(Ideal.Quotient.mkₐ R I) x ≠ 0
e : ∀ {y : R}, y ∈ J ↔ x * y ∈ I
⊢ Ideal.radical I ≤ J
[PROOFSTEP]
rw [hJ.radical_le_iff]
[GOAL]
case intro.intro.intro.a
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
hI : Ideal.IsPrimary I
hJ : Ideal.IsPrime J
x : R
this : ↑(Ideal.Quotient.mkₐ R I) x ≠ 0
e : ∀ {y : R}, y ∈ J ↔ x * y ∈ I
⊢ I ≤ J
[PROOFSTEP]
intro y hy
[GOAL]
case intro.intro.intro.a
R : Type u_1
inst✝⁴ : CommRing R
I J : Ideal R
M : Type u_2
inst✝³ : AddCommGroup M
inst✝² : Module R M
M' : Type u_3
inst✝¹ : AddCommGroup M'
inst✝ : Module R M'
f : M →ₗ[R] M'
hI : Ideal.IsPrimary I
hJ : Ideal.IsPrime J
x : R
this : ↑(Ideal.Quotient.mkₐ R I) x ≠ 0
e : ∀ {y : R}, y ∈ J ↔ x * y ∈ I
y : R
hy : y ∈ I
⊢ y ∈ J
[PROOFSTEP]
exact e.mpr (I.mul_mem_left x hy)
[GOAL]
R : Type u_1
inst✝⁵ : CommRing R
I J : Ideal R
M : Type u_2
inst✝⁴ : AddCommGroup M
inst✝³ : Module R M
M' : Type u_3
inst✝² : AddCommGroup M'
inst✝¹ : Module R M'
f : M →ₗ[R] M'
inst✝ : IsNoetherianRing R
hI : Ideal.IsPrimary I
⊢ associatedPrimes R (R ⧸ I) = {Ideal.radical I}
[PROOFSTEP]
ext J
[GOAL]
case h
R : Type u_1
inst✝⁵ : CommRing R
I J✝ : Ideal R
M : Type u_2
inst✝⁴ : AddCommGroup M
inst✝³ : Module R M
M' : Type u_3
inst✝² : AddCommGroup M'
inst✝¹ : Module R M'
f : M →ₗ[R] M'
inst✝ : IsNoetherianRing R
hI : Ideal.IsPrimary I
J : Ideal R
⊢ J ∈ associatedPrimes R (R ⧸ I) ↔ J ∈ {Ideal.radical I}
[PROOFSTEP]
rw [Set.mem_singleton_iff]
[GOAL]
case h
R : Type u_1
inst✝⁵ : CommRing R
I J✝ : Ideal R
M : Type u_2
inst✝⁴ : AddCommGroup M
inst✝³ : Module R M
M' : Type u_3
inst✝² : AddCommGroup M'
inst✝¹ : Module R M'
f : M →ₗ[R] M'
inst✝ : IsNoetherianRing R
hI : Ideal.IsPrimary I
J : Ideal R
⊢ J ∈ associatedPrimes R (R ⧸ I) ↔ J = Ideal.radical I
[PROOFSTEP]
refine' ⟨IsAssociatedPrime.eq_radical hI, _⟩
[GOAL]
case h
R : Type u_1
inst✝⁵ : CommRing R
I J✝ : Ideal R
M : Type u_2
inst✝⁴ : AddCommGroup M
inst✝³ : Module R M
M' : Type u_3
inst✝² : AddCommGroup M'
inst✝¹ : Module R M'
f : M →ₗ[R] M'
inst✝ : IsNoetherianRing R
hI : Ideal.IsPrimary I
J : Ideal R
⊢ J = Ideal.radical I → J ∈ associatedPrimes R (R ⧸ I)
[PROOFSTEP]
rintro rfl
[GOAL]
case h
R : Type u_1
inst✝⁵ : CommRing R
I J : Ideal R
M : Type u_2
inst✝⁴ : AddCommGroup M
inst✝³ : Module R M
M' : Type u_3
inst✝² : AddCommGroup M'
inst✝¹ : Module R M'
f : M →ₗ[R] M'
inst✝ : IsNoetherianRing R
hI : Ideal.IsPrimary I
⊢ Ideal.radical I ∈ associatedPrimes R (R ⧸ I)
[PROOFSTEP]
haveI : Nontrivial (R ⧸ I) :=
by
refine ⟨(Ideal.Quotient.mk I : _) 1, (Ideal.Quotient.mk I : _) 0, ?_⟩
rw [Ne.def, Ideal.Quotient.eq, sub_zero, ← Ideal.eq_top_iff_one]
exact hI.1
[GOAL]
R : Type u_1
inst✝⁵ : CommRing R
I J : Ideal R
M : Type u_2
inst✝⁴ : AddCommGroup M
inst✝³ : Module R M
M' : Type u_3
inst✝² : AddCommGroup M'
inst✝¹ : Module R M'
f : M →ₗ[R] M'
inst✝ : IsNoetherianRing R
hI : Ideal.IsPrimary I
⊢ Nontrivial (R ⧸ I)
[PROOFSTEP]
refine ⟨(Ideal.Quotient.mk I : _) 1, (Ideal.Quotient.mk I : _) 0, ?_⟩
[GOAL]
R : Type u_1
inst✝⁵ : CommRing R
I J : Ideal R
M : Type u_2
inst✝⁴ : AddCommGroup M
inst✝³ : Module R M
M' : Type u_3
inst✝² : AddCommGroup M'
inst✝¹ : Module R M'
f : M →ₗ[R] M'
inst✝ : IsNoetherianRing R
hI : Ideal.IsPrimary I
⊢ ↑(Ideal.Quotient.mk I) 1 ≠ ↑(Ideal.Quotient.mk I) 0
[PROOFSTEP]
rw [Ne.def, Ideal.Quotient.eq, sub_zero, ← Ideal.eq_top_iff_one]
[GOAL]
R : Type u_1
inst✝⁵ : CommRing R
I J : Ideal R
M : Type u_2
inst✝⁴ : AddCommGroup M
inst✝³ : Module R M
M' : Type u_3
inst✝² : AddCommGroup M'
inst✝¹ : Module R M'
f : M →ₗ[R] M'
inst✝ : IsNoetherianRing R
hI : Ideal.IsPrimary I
⊢ ¬I = ⊤
[PROOFSTEP]
exact hI.1
[GOAL]
case h
R : Type u_1
inst✝⁵ : CommRing R
I J : Ideal R
M : Type u_2
inst✝⁴ : AddCommGroup M
inst✝³ : Module R M
M' : Type u_3
inst✝² : AddCommGroup M'
inst✝¹ : Module R M'
f : M →ₗ[R] M'
inst✝ : IsNoetherianRing R
hI : Ideal.IsPrimary I
this : Nontrivial (R ⧸ I)
⊢ Ideal.radical I ∈ associatedPrimes R (R ⧸ I)
[PROOFSTEP]
obtain ⟨a, ha⟩ := associatedPrimes.nonempty R (R ⧸ I)
[GOAL]
case h.intro
R : Type u_1
inst✝⁵ : CommRing R
I J : Ideal R
M : Type u_2
inst✝⁴ : AddCommGroup M
inst✝³ : Module R M
M' : Type u_3
inst✝² : AddCommGroup M'
inst✝¹ : Module R M'
f : M →ₗ[R] M'
inst✝ : IsNoetherianRing R
hI : Ideal.IsPrimary I
this : Nontrivial (R ⧸ I)
a : Ideal R
ha : a ∈ associatedPrimes R (R ⧸ I)
⊢ Ideal.radical I ∈ associatedPrimes R (R ⧸ I)
[PROOFSTEP]
exact ha.eq_radical hI ▸ ha
|
{-# LANGUAGE OverloadedStrings #-}
module VisualizeFunction where
import Control.Monad
import Data.Binary.Put
import Numeric.LinearAlgebra.HMatrix
import System.IO
import qualified Data.ByteString.Lazy as L
import qualified Data.Vector.Storable as V
-- derived from description at https://en.wikipedia.org/wiki/BMP_file_format
putBMPHeader headerLength imageLength = do
putLazyByteString "BM" -- magic identifier
putWord32le (headerLength + imageLength) -- total length of file (bytes)
putLazyByteString "HELO" -- apparently a reserved field which can be filled arbitrarily
putWord32le headerLength -- offset of pixel array in the file (bytes)
putBitmapInfoHeader (width, height) bpp = do
putWord32le 40 -- size of BITMAPINFOHEADER
putWord32le $ fromIntegral width
putWord32le $ fromIntegral (-height) -- negative height -> first row is top of image
putWord16le 1 -- # of color planes
putWord16le bpp -- bits per pixel
putWord32le 0 -- compression method (uncompressed RGB is 0)
putWord32le 0 -- uncompressed size (optional if no compression is used)
replicateM_ 2 $ putWord32le 0 -- dummy values for {x,y}-resolution
putWord32le 0 -- use all 2^bpp colors
putWord32le 0 -- # of "important colors", which is "generally ignored"
addBitmapHeader (w, h) image = do
let headerLength = (2 + 4 + 4 + 4) + 40
let imageLength = fromIntegral $ L.length image
putBMPHeader headerLength imageLength
putBitmapInfoHeader (w, h) 32
putLazyByteString image
putRGB r g b = mapM_ putWord8 [b,g,r,0]
scaleFromTo (a, b) (a', b') x = ((x-a)/(b-a))*(b'-a')+a'
putPixel x y z = putRGB r g b where
minimum = 0
maximum = 2^8 - 1
r = round $ if z < 0 then scaleFromTo (0, -1) (minimum, maximum) z else minimum
g = round $ minimum
b = round $ if z > 0 then scaleFromTo (0, 1) (minimum, maximum) z else minimum
visualizeFunction (xmin, ymin) (xmax, ymax) (w, h) (zmin, zmax) f = runPut image where
xs = linspace w (xmin, xmax)
ys = linspace h (ymin, ymax)
f' = scaleFromTo (zmin, zmax) (-1, 1) . f
image = V.forM_ ys (\y -> V.forM_ xs (\x -> putPixel x y (f' $ vector [x,y])))
visualizeFunctionBMP min max dims range = runPut . addBitmapHeader dims . visualizeFunction min max dims range
saveImage name img = withBinaryFile name WriteMode $ \h -> L.hPutStr h img
emitSample = saveImage "sample.bmp" $ visualizeFunctionBMP (-1,-1) (1,1) (2048, 2048) (-1,1) (tanh . V.sum)
|
theory IICF_Array_List
imports "../Intf/IICF_List" "../../../ds/LLVM_DS_Array_List"
begin
abbreviation (input) "raw_al_assn \<equiv> \<upharpoonleft>arl_assn"
definition "al_assn R \<equiv> hr_comp raw_al_assn (\<langle>the_pure R\<rangle>list_rel)"
abbreviation "al_assn' TYPE('l::len2) R \<equiv> al_assn R :: (_ \<Rightarrow> (_,'l)array_list \<Rightarrow> _)"
lemma arl_assn_free[sepref_frame_free_rules]: "MK_FREE (\<upharpoonleft>arl_assn) arl_free"
apply rule by vcg
lemma al_assn_free[sepref_frame_free_rules]: "MK_FREE (al_assn R) arl_free"
unfolding al_assn_def by (rule sepref_frame_free_rules)+
context
fixes l_dummy :: "'l::len2 itself"
and L AA
defines [simp]: "L \<equiv> (LENGTH ('l))"
defines [simp]: "AA \<equiv> raw_al_assn :: _ \<Rightarrow> (_,'l) array_list \<Rightarrow> _"
begin
private lemma n_unf: "hr_comp AA (\<langle>the_pure A\<rangle>list_rel) = al_assn A" unfolding al_assn_def AA_def ..
private lemma params:
"(max_snat, max_snat) \<in> Id \<rightarrow> Id"
"(L,L)\<in>nat_rel"
by auto
context
notes [fcomp_norm_unfold] = n_unf
notes [param] = params
notes [simp] = refine_pw_simps
begin
thm bool1_rel_def bool.assn_is_rel[symmetric]
private method m_ref =
((unfold snat_rel_def snat.assn_is_rel[symmetric] bool1_rel_def bool.assn_is_rel[symmetric])?,
sepref_to_hoare, vcg_monadify,
vcg')
lemma al_empty_hnr_aux:
"(uncurry0 (arl_new_raw::(_,'l::len2)array_list llM), uncurry0 (RETURN op_list_empty))
\<in> [\<lambda>_. 4 < L]\<^sub>a unit_assn\<^sup>k \<rightarrow> AA"
by m_ref
sepref_decl_impl (no_register) al_empty: al_empty_hnr_aux .
lemma al_nth_hnr_aux: "(uncurry arl_nth, uncurry mop_list_get)
\<in> AA\<^sup>k *\<^sub>a snat_assn\<^sup>k \<rightarrow>\<^sub>a id_assn"
by m_ref
sepref_decl_impl (ismop) al_nth: al_nth_hnr_aux .
lemma al_upd_hnr_aux: "(uncurry2 arl_upd, uncurry2 mop_list_set)
\<in> AA\<^sup>d *\<^sub>a snat_assn\<^sup>k *\<^sub>a id_assn\<^sup>k \<rightarrow>\<^sub>a AA"
by m_ref
sepref_decl_impl (ismop) al_upd: al_upd_hnr_aux .
lemma al_append_hnr_aux: "(uncurry arl_push_back, uncurry mop_list_append)
\<in> [\<lambda>(xs,_). length xs + 1 < max_snat L]\<^sub>a AA\<^sup>d *\<^sub>a id_assn\<^sup>k \<rightarrow> AA"
by m_ref
sepref_decl_impl (ismop) al_append: al_append_hnr_aux .
lemma al_pop_last_hnr_aux: "(arl_pop_back, mop_list_pop_last)
\<in> AA\<^sup>d \<rightarrow>\<^sub>a id_assn \<times>\<^sub>a AA"
by m_ref
sepref_decl_impl (ismop) al_pop_last: al_pop_last_hnr_aux .
lemma al_butlast_hnr_aux: "(\<lambda>l. doM { (_,l) \<leftarrow> arl_pop_back l; return l}, mop_list_butlast) \<in> AA\<^sup>d \<rightarrow>\<^sub>a AA"
by m_ref
sepref_decl_impl (ismop) al_butlast: al_butlast_hnr_aux .
lemma al_len_hnr_aux: "(arl_len, mop_list_length) \<in> AA\<^sup>k \<rightarrow>\<^sub>a snat_assn"
by m_ref
sepref_decl_impl (ismop) al_len: al_len_hnr_aux .
lemma al_is_empty_hnr_aux:
"(\<lambda>al. doM { l\<leftarrow>arl_len al; ll_icmp_eq l (signed_nat 0) }, mop_list_is_empty) \<in> AA\<^sup>k \<rightarrow>\<^sub>a bool1_assn"
by m_ref
sepref_decl_impl (ismop) al_is_empty: al_is_empty_hnr_aux .
end
end
definition [simp]: "op_al_empty TYPE('l::len2) \<equiv> op_list_empty"
sepref_register "op_al_empty TYPE('l::len2)"
lemma al_custom_empty_hnr[sepref_fr_rules]:
"(uncurry0 arl_new_raw, uncurry0 (RETURN (PR_CONST (op_al_empty TYPE('l::len2)))))
\<in> [\<lambda>_. 4<LENGTH('l)]\<^sub>a unit_assn\<^sup>k \<rightarrow> al_assn' TYPE('l) A"
apply simp
apply (rule al_empty_hnr[simplified])
done
lemma al_fold_custom_empty:
"[] = op_al_empty TYPE('l::len2)"
"op_list_empty = op_al_empty TYPE('l::len2)"
"mop_list_empty = RETURN (op_al_empty TYPE('l::len2))"
by auto
subsection \<open>Ad-Hoc Regression Tests\<close>
experiment
begin
sepref_definition example [llvm_code] is "\<lambda>n. do {
let l = op_list_empty;
l \<leftarrow> mop_list_append l 42;
l \<leftarrow> mop_list_append l 43;
l \<leftarrow> mop_list_append l 44;
l \<leftarrow> mop_list_append l 45;
l \<leftarrow> mop_list_append l 46;
let x = l!2;
let l = l[2:=l!3];
l \<leftarrow> mop_list_set l 3 x;
let (_,l) = op_list_pop_last l;
RETURN l
}" :: "(snat_assn' TYPE(32))\<^sup>k \<rightarrow>\<^sub>a al_assn' TYPE(32) (snat_assn' TYPE(32))"
apply (annot_snat_const "TYPE(32)")
supply [simp] = max_snat_def
apply (rewrite al_fold_custom_empty[where 'l=32])
by sepref
export_llvm example
end
end
|
theory Chop_tmap
imports Main "~~/src/HOL/Library/BNF_Corec" "$HIPSTER_HOME/IsaHipster"
begin
setup Tactic_Data.set_coinduct_sledgehammer
codatatype (lset: 'a) Llist =
lnull: LNil
| LCons (lhd: 'a) (ltl: "'a Llist")
where
"ltl LNil = LNil"
codatatype 'a Tree = is_Leaf: Leaf |
Node (left: "'a Tree") (val: 'a) (right: "'a Tree")
where
"left Leaf = Leaf"
| "right Leaf = Leaf"
primcorec chop :: "'a Tree \<Rightarrow> 'a Tree"
where
"is_Leaf t \<or> is_Leaf (left t) \<and> is_Leaf (right t) \<Longrightarrow> is_Leaf (chop t)"
| "val (chop t) = (if is_Leaf (left t) then val (right t) else val (left t))"
| "left (chop t) = (if is_Leaf (left t) then left (right t) else right t)"
| "right (chop t) = (if is_Leaf (left t) then right (right t) else chop (left t))"
primcorec llist_of :: "'a Tree \<Rightarrow> 'a Llist"
where
"is_Leaf t \<Longrightarrow> lnull (llist_of t)"
| "lhd (llist_of t) = val t"
| "ltl (llist_of t) = llist_of (chop t)"
primcorec lmap :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a Llist \<Rightarrow> 'b Llist" where
"lmap f xs = (case xs of LNil \<Rightarrow> LNil | LCons x xs \<Rightarrow> LCons (f x) (lmap f xs))"
primcorec tmap :: "('a \<Rightarrow> 'a) \<Rightarrow> 'a Tree \<Rightarrow> 'a Tree"
where "tmap f t = (case t of Leaf \<Rightarrow> Leaf
| Node l x r \<Rightarrow> Node (tmap f l) (f x) (tmap f r))"
hipster chop tmap
lemma unknown [thy_expl]: "left (left (left y)) = Leaf"
oops
why doesn't this return nicer things?
*)
(*hipster tmap*)
lemma lemma_a [thy_expl]: "tmap y (Node Leaf z Leaf) = Node Leaf (y z) Leaf"
apply (coinduction arbitrary: y z rule: Chop_tmap.Tree.coinduct_strong)
by simp
lemma lemma_aa [thy_expl]: "Node Leaf (y z) (tmap y x2) = tmap y (Node Leaf z x2)"
apply (coinduction arbitrary: x2 y z rule: Chop_tmap.Tree.coinduct_strong)
by (simp_all add: tmap.ctr(1))
lemma lemma_ab [thy_expl]: "Node (tmap y z) (y x2) Leaf = tmap y (Node z x2 Leaf)"
apply (coinduction arbitrary: x2 y z rule: Chop_tmap.Tree.coinduct_strong)
by (simp_all add: tmap.ctr(1))
theorem chop_tmap: "chop (tmap f t) = tmap f (chop t)"
(*by hipster_coinduct_sledgehammer
Failed to apply initial proof method*)
end |
#include <benchmark/benchmark.h>
#include "Tests/ArrowSQLRunner/ArrowSQLRunner.h"
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
extern bool g_enable_heterogeneous_execution;
extern bool g_enable_multifrag_heterogeneous_execution;
boost::filesystem::path g_data_path;
size_t g_fragment_size = 1'000'000;
using namespace TestHelpers::ArrowSQLRunner;
static void createTaxiReducedTable() {
getStorage()->dropTable("trips");
ArrowStorage::TableOptions to{g_fragment_size};
createTable("trips",
{{"pickup_datetime", SQLTypeInfo(kTIMESTAMP, 0, 0)},
{"passenger_count", SQLTypeInfo(kSMALLINT)},
{"trip_distance", SQLTypeInfo(kDECIMAL, 14, 2)},
{"total_amount", SQLTypeInfo(kDECIMAL, 14, 2)},
{"cab_type", SQLTypeInfo(kVARCHAR, true, kENCODING_DICT)}},
to);
}
static void populateTaxiReducedTable() {
namespace fs = boost::filesystem;
ArrowStorage::CsvParseOptions po;
po.header = false;
if (fs::is_directory(g_data_path)) {
for (auto it = fs::directory_iterator{g_data_path}; it != fs::directory_iterator{};
it++) {
getStorage()->appendCsvFile(it->path().string(), "trips", po);
}
} else {
getStorage()->appendCsvFile(g_data_path.string(), "trips", po);
}
}
template <class T>
T v(const TargetValue& r) {
auto scalar_r = boost::get<ScalarTargetValue>(&r);
auto p = boost::get<T>(scalar_r);
return *p;
}
static void warmup() {
auto res =
v<int64_t>(run_simple_agg("select count(*) from trips", ExecutorDeviceType::CPU));
std::cout << "Number of loaded tuples: " << res << std::endl;
}
static void taxi_q1(benchmark::State& state) {
for (auto _ : state) {
run_multiple_agg("select cab_type, count(*) from trips group by cab_type",
ExecutorDeviceType::CPU);
}
}
static void taxi_q2(benchmark::State& state) {
for (auto _ : state) {
run_multiple_agg(
"SELECT passenger_count, avg(total_amount) FROM trips GROUP BY passenger_count",
ExecutorDeviceType::CPU);
}
}
static void taxi_q3(benchmark::State& state) {
for (auto _ : state) {
run_multiple_agg(
"SELECT passenger_count, extract(year from pickup_datetime) AS pickup_year, "
"count(*) FROM trips GROUP BY passenger_count, pickup_year",
ExecutorDeviceType::CPU);
}
}
static void taxi_q4(benchmark::State& state) {
for (auto _ : state) {
run_multiple_agg(
"SELECT passenger_count, extract(year from pickup_datetime) AS pickup_year, "
"cast(trip_distance as int) AS distance, count(*) AS the_count FROM trips GROUP "
"BY passenger_count, pickup_year, distance ORDER BY pickup_year, the_count "
"desc",
ExecutorDeviceType::CPU);
}
}
BENCHMARK(taxi_q1);
BENCHMARK(taxi_q2);
BENCHMARK(taxi_q3);
BENCHMARK(taxi_q4);
int main(int argc, char* argv[]) {
::benchmark::Initialize(&argc, argv);
namespace po = boost::program_options;
namespace fs = boost::filesystem;
po::options_description desc("Options");
desc.add_options()("enable-heterogeneous",
po::value<bool>(&g_enable_heterogeneous_execution)
->default_value(g_enable_heterogeneous_execution)
->implicit_value(true),
"Allow heterogeneous execution.");
desc.add_options()("enable-multifrag",
po::value<bool>(&g_enable_multifrag_heterogeneous_execution)
->default_value(g_enable_multifrag_heterogeneous_execution)
->implicit_value(true),
"Allow multifrag heterogeneous execution.");
desc.add_options()("data", po::value<fs::path>(&g_data_path), "Path to taxi dataset.");
desc.add_options()("fragment-size",
po::value<size_t>(&g_fragment_size)->default_value(g_fragment_size),
"Table fragment size.");
logger::LogOptions log_options(argv[0]);
log_options.severity_ = logger::Severity::FATAL;
log_options.set_options(); // update default values
desc.add(log_options.get_options());
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(desc).run(), vm);
po::notify(vm);
if (vm.count("help")) {
std::cout << "Usage:" << std::endl << desc << std::endl;
}
logger::init(log_options);
init();
try {
createTaxiReducedTable();
populateTaxiReducedTable();
warmup();
::benchmark::RunSpecifiedBenchmarks();
} catch (const std::exception& e) {
LOG(ERROR) << e.what();
return -1;
}
reset();
}
|
! TODO: adapt this to neo2 magfie
function kappa2()
real(8) :: kappa2
kappa2 = (1d0 - eta*B0mn(fsind,1)*(1-eps(fsind)))/(2d0*eta*(B0mn(fsind,1)*eps(fsind)))
!kappa2 = sqrt((mi*v**2/2d0-J_perp()*om_c(0d0))/(2*J_perp()*&
! om_c(pi/2)*eps(fsind)))
!print *, mi*v**2/2d0, E() - qi*Phi_E(fsind)
end function kappa2
! Shaing2009-035009 - (8) for bounce averaged toroidal drift
function Omph_shaing()
real(8) :: Omph_shaing, kappa, Eell, Kell
! Elliptic integrals for Shaing formula
!kappa = sqrt((E()-qi*Phi_E(fsind)-J_perp()*om_c(0.0d0))/(2*J_perp()*&
! om_c(pi/2)*eps(fsind)))
kappa = sqrt((mi*v**2/2d0-J_perp()*om_c(0d0))/(2*J_perp()*&
om_c(pi/2)*eps))
!kappa = sqrt(0.83) ! test case so that 2*E/K = 1
Kell = ellf(pi/2d0, kappa)
Eell = elle(pi/2d0, kappa)
! Shaing2009-035009 - (8) for bounce averaged toroidal drift
Omph_shaing = Om_tE +&
J_perp()*B0mn(fsind,1)/mi*depsdr(fsind)*(2*Eell/Kell-1)
end function Omph_shaing
|
/-
Copyright (c) 2018 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Mario Carneiro, Simon Hudon, Alex Keizer
-/
import Qpf.MathlibPort.Fin2
import Qpf.Util.HEq
-- import Mathlib
universe u v w
abbrev DVec {n : Nat} (αs : Fin2 n → Type u) : Type _
:= (i : Fin2 n) → αs i
abbrev Vec (α : Type _) (n : Nat)
:= @DVec n fun _ => α
namespace Vec
def append1 {α : Type u} {n} (tl : Vec α n) (hd : α) : Vec α (.succ n)
| .fs i => tl i
| .fz => hd
-- infixl:67 " ::: " => append1
/-- Drop the last element from a `Vec` -/
def drop (v : Vec α (n+1)) : Vec α n
:= fun i => v <| .fs i
def constVec {α : Type _} (a : α) (n : Nat) : Vec α n
:= fun _ => a
end Vec
unif_hint (n : Nat) where |- Fin2 n → Type u =?= Vec.{u+1} (Type u) n
unif_hint {α : Type _} (n : Nat) where |- DVec.{u+1} (Vec.constVec α n) =?= Vec.{u+1} α n
namespace DVec
/-- Return the last element from a `DVec` -/
abbrev last (v : @DVec (n+1) αs ) : αs 0
:= v 0
/-- Drop the last element from a `DVec` -/
def drop (v : DVec αs) : DVec (Vec.drop αs)
:= fun i => v <| .fs i
@[reducible]
def nil : @DVec 0 αs
:= fun emp => by contradiction
@[reducible]
def append1 {α : Type u} {αs : Vec (Type u) n} (tl : DVec αs) (hd : α) : DVec (Vec.append1 αs α)
| .fs i => tl i
| .fz => hd
-- infixl:67 " ::: " => append1
end DVec
namespace Vec
variable {α : Type _} {n : Nat}
abbrev nil : Vec α 0 := DVec.nil
abbrev last : Vec α n.succ → α := DVec.last
end Vec
/-
# Notation macros
-/
syntax "!![" term,* "]" : term
macro_rules
| `(!![]) => `(Vec.nil)
| `(!![$x]) => `(Vec.append1 !![] $x)
| `(!![ $xs,* , $x]) => `(Vec.append1 !![$xs,*] $x)
namespace Vec
theorem drop_append1 {v : Vec α n} {a : α} {i : PFin2 n} :
drop (append1 v a) i = v i :=
rfl
theorem drop_append1' {v : Vec α n} {a : α} :
drop (append1 v a) = v :=
by funext x; rfl
theorem last_append1 {v : Vec α n} {a : α} :
last (append1 v a) = a
:= rfl
@[simp]
theorem append1_drop_last (v : Vec α (n+1)) : append1 (drop v) (last v) = v :=
funext $ fun i => by cases i; rfl; rfl
def reverse (v : Vec α n) : Vec α n :=
fun i => v i.inv
@[simp]
theorem reverse_involution {v : Vec α n} :
v.reverse.reverse = v :=
by
funext i;
dsimp only [reverse]
apply congrArg;
simp only [Fin2.inv, PFin2.toFin2_ofFin2_iso, PFin2.inv_involution, PFin2.ofFin2_toFin2_iso]
end Vec
namespace Vec
/-- Create a `Vec` from a `List`. Note that this conceptually reverses the list, since in a `Vec`
the 0th index points to the right-most element
-/
def ofList : (as : List α) → Vec α (as.length)
| List.nil => Vec.nil
| List.cons a as => Vec.append1 (ofList as) a
/-- Create a `List` from a `Vec`. Note that this conceptually reverses the vector, since in a `Vec`
the 0th index points to the right-most element
-/
def toList : {n : Nat} → Vec α n → List α
| 0, _ => List.nil
| _+1, v => List.cons v.last (toList v.drop)
@[simp]
theorem toList_length_eq_n {v : Vec α n} :
v.toList.length = n :=
by
induction n
case zero => rfl
case succ n ih =>
dsimp only [toList, List.length]
dsimp only [HAdd.hAdd, Add.add, Nat.add]
apply congrArg
apply ih
@[simp]
theorem ofList_toList_iso {v : Vec α n} :
HEq (ofList (toList v)) v :=
by
apply HEq.trans (b := cast (β:=Vec α (List.length (toList v))) ?hc v);
case hc =>
simp only [toList_length_eq_n]
case h₂ =>
apply cast_heq
case h₁ =>
apply heq_of_eq;
funext i;
apply eq_of_heq;
rw[cast_arg] <;> try (solve | simp);
simp_heq
induction n <;> cases i;
case succ.fz n ih => {
dsimp[ofList, toList, append1, last, DVec.last]
apply hcongr <;> (try solve | intros; rfl)
simp_heq;
simp only [OfNat.ofNat]
apply hcongr <;> (try solve | intros; rfl)
simp
}
case succ.fs n ih i => {
dsimp[ofList, toList, append1, drop]
apply HEq.trans (@ih (fun i => v (.fs i)) i);
apply hcongr <;> (try solve | intros; rfl)
simp_heq
apply hcongr;
case H₂ => apply cast_heq
case H₃ => apply congrArg; simp
case H₄ => intro _; apply congrArg; simp
apply hcongr <;> (try solve | intros; rfl);
simp
}
theorem ofList_toList_iso' {v : Vec α n} :
HEq (fun (j : PFin2.{u} (toList v).length) => ofList (toList v) j.toFin2)
(fun (j : PFin2.{u} (toList v).length) => v <| PFin2.toFin2 <| cast (by rw[toList_length_eq_n]) j) :=
by
apply HEq.funext
. rfl
intro j
have n_eq : (toList v).length = n := toList_length_eq_n;
apply hcongr
. apply ofList_toList_iso
. intros
apply hcongr <;> intros <;> (try rw[n_eq])
. simp_heq
. intros; simp
. rw[n_eq]
@[simp]
theorem toList_ofList_iso {as : List α} :
toList (ofList as) = as :=
by
induction as;
case nil => rfl
case cons a as ih => simp only [toList, ofList, append1, last, DVec.last, drop, ih]
instance : Coe (Vec (Type u) n) (TypeVec.{u} n) where
coe v i := v i
instance : Coe (TypeVec.{u} n) (Vec (Type u) n) where
coe v i := v i
instance : Coe (Fin n → α) (Vec α n) where
coe f i := f (Fin2.inv i)
end Vec
|
```python
from sympy import *
```
```python
s=10
```
```python
x = Symbol("x")
```
```python
y = x
#y = (2*x-1)
```
```python
legpols = []
```
```python
for k in range(0,s+1):
legpol = 0
for j in range(0, k//2+1):
legpol += (-1)**j * factorial(2*k - 2*j) / factorial(k-j) / factorial(k-2*j) / factorial(j) / 2**k * y**(k-2*j)
legpols.append(expand(legpol))
```
```python
legpols
```
[1,
x,
3*x**2/2 - 1/2,
5*x**3/2 - 3*x/2,
35*x**4/8 - 15*x**2/4 + 3/8,
63*x**5/8 - 35*x**3/4 + 15*x/8,
231*x**6/16 - 315*x**4/16 + 105*x**2/16 - 5/16,
429*x**7/16 - 693*x**5/16 + 315*x**3/16 - 35*x/16,
6435*x**8/128 - 3003*x**6/32 + 3465*x**4/64 - 315*x**2/32 + 35/128,
12155*x**9/128 - 6435*x**7/32 + 9009*x**5/64 - 1155*x**3/32 + 315*x/128,
46189*x**10/256 - 109395*x**8/256 + 45045*x**6/128 - 15015*x**4/128 + 3465*x**2/256 - 63/256]
```python
```
|
theory Funpow
imports
"HOL-Library.FuncSet"
"HOL-Library.Permutations"
begin
section \<open>Auxiliary Lemmas about @{term "op ^^"}\<close>
lemma funpow_simp_l: "f ((f ^^ n) x) = (f ^^ Suc n) x"
by (metis comp_apply funpow.simps(2))
lemma funpow_add_app: "(f ^^ n) ((f ^^ m) x) = (f ^^ (n + m)) x"
by (metis comp_apply funpow_add)
lemma funpow_mod_eq:
assumes "(f ^^ n) x = x" "0 < n" shows "(f ^^ (m mod n)) x = (f ^^ m) x"
proof (induct m rule: less_induct)
case (less m)
{ assume "m < n" then have ?case by simp }
moreover
{ assume "m = n" then have ?case by (simp add: \<open>_ = x\<close>)}
moreover
{ assume "n < m"
then have "m - n < m" "0 < m - n" using \<open>0 < n\<close> by arith+
have "(f ^^ (m mod n)) x = (f ^^ ((m - n) mod n)) x"
using \<open>0 < m - n\<close> by (simp add: mod_geq)
also have "\<dots> = (f ^^ (m - n)) x"
using \<open>m - n < m\<close> by (rule less)
also have "\<dots> = (f ^^ (m - n)) ((f ^^ n) x)"
by (simp add: assms)
also have "\<dots> = (f ^^ m) x"
using \<open>0 < m - n\<close> by (simp add: funpow_add_app)
finally have ?case . }
ultimately show ?case by (metis linorder_neqE_nat)
qed
lemma id_funpow_id:
assumes "f x = x" shows "(f ^^ n) x = x"
using assms by (induct n) auto
lemma inv_id_abs[simp]: "inv (\<lambda>a. a) = id" unfolding id_def[symmetric] by simp
lemma inj_funpow:
fixes f :: "'a \<Rightarrow> 'a"
assumes "inj f" shows "inj (f ^^ n)"
proof (induct n)
case 0 then show ?case by (auto simp: id_def[symmetric])
next
case (Suc n) with assms show ?case unfolding funpow.simps by (rule inj_comp)
qed
lemma funpow_inj_finite:
assumes "inj p" "finite {(p ^^ n) x |n. True}"
shows "\<exists>n>0. (p ^^ n) x = x"
proof -
have "\<not>finite {0::nat..}" by simp
moreover
have "{(p ^^ n) x |n. True} = (\<lambda>n. (p ^^ n) x) ` {0..}" by auto
with assms have "finite \<dots>" by simp
ultimately have "\<exists>n\<in>{0..}. \<not> finite {m \<in> {0..}. (p ^^ m) x = (p ^^ n) x}"
by (rule pigeonhole_infinite)
then obtain n where "\<not>finite {m. (p ^^ m) x = (p ^^ n) x}" by auto
then have "\<not>finite ({m. (p ^^ m) x = (p ^^ n) x} - {n})" by auto
then have "({m. (p ^^ m) x = (p ^^ n) x} - {n}) \<noteq> {}"
by (metis finite.emptyI)
then obtain m where m: "(p ^^ m) x = (p ^^ n) x" "m \<noteq> n" by auto
{ fix m n assume "(p ^^ n) x = (p ^^ m) x" "m < n"
have "(p ^^ (n - m)) x = inv (p ^^ m) ((p ^^ m) ((p ^^ (n - m)) x))"
using \<open>inj p\<close> by (simp add: inv_f_f inj_funpow)
also have "((p ^^ m) ((p ^^ (n - m)) x)) = (p ^^ n) x"
using `m < n` by (simp add: funpow_add_app)
also have "inv (p ^^ m) \<dots> = x"
using \<open>inj p\<close> by (simp add: \<open>(p ^^ n) x = _\<close> inj_funpow)
finally have "(p ^^ (n - m)) x = x" "0 < n - m"
using \<open>m < n\<close> by auto }
note general = this
show ?thesis
proof (cases m n rule: linorder_cases)
case less
then show ?thesis using general m by metis
next
case equal
then show ?thesis using m by metis
next
case greater
then show ?thesis using general m by metis
qed
qed
lemma permutes_in_funpow_image:
assumes "f permutes S" "x \<in> S"
shows "(f ^^ n) x \<in> S"
using assms by (induct n) (auto simp: permutes_in_image)
(* XXX move*)
lemma permutation_self:
assumes "permutation p" shows "\<exists>n>0. (p ^^ n) x = x"
proof cases
assume "p x = x" then show ?thesis by auto
next
assume "p x \<noteq> x"
from assms have "inj p" by (intro permutation_bijective bij_is_inj)
{ fix n
from \<open>p x \<noteq> x\<close> have "(p ^^ Suc n) x \<noteq> (p ^^ n) x"
proof (induct n arbitrary: x)
case 0 then show ?case by simp
next
case (Suc n)
have "p (p x) \<noteq> p x"
proof (rule notI)
assume "p (p x) = p x"
then show False using \<open>p x \<noteq> x\<close> \<open>inj p\<close> by (simp add: inj_eq)
qed
have "(p ^^ Suc (Suc n)) x = (p ^^ Suc n) (p x)"
by (metis funpow_simp_l funpow_swap1)
also have "\<dots> \<noteq> (p ^^ n) (p x)"
by (rule Suc) fact
also have "(p ^^ n) (p x) = (p ^^ Suc n) x"
by (metis funpow_simp_l funpow_swap1)
finally show ?case by simp
qed }
then have "{(p ^^ n) x | n. True} \<subseteq> {x. p x \<noteq> x}"
by auto
then have "finite {(p ^^ n) x | n. True}"
using permutation_finite_support[OF assms] by (rule finite_subset)
with \<open>inj p\<close> show ?thesis by (rule funpow_inj_finite)
qed
(* XXX move *)
lemma (in -) funpow_invs:
assumes "m \<le> n" and inv: "\<And>x. f (g x) = x"
shows "(f ^^ m) ((g ^^ n) x) = (g ^^ (n - m)) x"
using \<open>m \<le> n\<close>
proof (induction m)
case (Suc m)
moreover then have "n - m = Suc (n - Suc m)" by auto
ultimately show ?case by (auto simp: inv)
qed simp
section \<open>Function-power distance between values\<close>
(* xxx move *)
definition funpow_dist :: "('a \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> nat" where
"funpow_dist f x y \<equiv> LEAST n. (f ^^ n) x = y"
abbreviation funpow_dist1 :: "('a \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> nat" where
"funpow_dist1 f x y \<equiv> Suc (funpow_dist f (f x) y)"
lemma funpow_dist_0:
assumes "x = y" shows "funpow_dist f x y = 0"
using assms unfolding funpow_dist_def by (intro Least_eq_0) simp
lemma funpow_dist_least:
assumes "n < funpow_dist f x y" shows "(f ^^ n) x \<noteq> y"
proof (rule notI)
assume "(f ^^ n) x = y"
then have "funpow_dist f x y \<le> n" unfolding funpow_dist_def by (rule Least_le)
with assms show False by linarith
qed
lemma funpow_dist1_least:
assumes "0 < n" "n < funpow_dist1 f x y" shows "(f ^^ n) x \<noteq> y"
proof (rule notI)
assume "(f ^^ n) x = y"
then have "(f ^^ (n - 1)) (f x) = y"
using \<open>0 < n\<close> by (cases n) (simp_all add: funpow_swap1)
then have "funpow_dist f (f x) y \<le> n - 1" unfolding funpow_dist_def by (rule Least_le)
with assms show False by simp
qed
section \<open>Cyclic Permutations\<close>
inductive_set orbit :: "('a \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> 'a set" for f x where
base: "f x \<in> orbit f x" |
step: "y \<in> orbit f x \<Longrightarrow> f y \<in> orbit f x"
definition cyclic_on :: "('a \<Rightarrow> 'a) \<Rightarrow> 'a set \<Rightarrow> bool" where
"cyclic_on f S \<longleftrightarrow> (\<exists>s\<in>S. S = orbit f s)"
lemma orbit_altdef: "orbit f x = {(f ^^ n) x | n. 0 < n}" (is "?L = ?R")
proof (intro set_eqI iffI)
fix y assume "y \<in> ?L" then show "y \<in> ?R"
by (induct rule: orbit.induct) (auto simp: exI[where x=1] exI[where x="Suc n" for n])
next
fix y assume "y \<in> ?R"
then obtain n where "y = (f ^^ n) x" "0 < n" by blast
then show "y \<in> ?L"
proof (induction n arbitrary: y)
case (Suc n) then show ?case by (cases "n = 0") (auto intro: orbit.intros)
qed simp
qed
lemma orbit_trans:
assumes "s \<in> orbit f t" "t \<in> orbit f u" shows "s \<in> orbit f u"
using assms by induct (auto intro: orbit.intros)
lemma orbit_subset:
assumes "s \<in> orbit f (f t)" shows "s \<in> orbit f t"
using assms by (induct) (auto intro: orbit.intros)
lemma orbit_sim_step:
assumes "s \<in> orbit f t" shows "f s \<in> orbit f (f t)"
using assms by induct (auto intro: orbit.intros)
lemma orbit_step:
assumes "y \<in> orbit f x" "f x \<noteq> y" shows "y \<in> orbit f (f x)"
using assms
proof induction
case (step y) then show ?case by (cases "x = y") (auto intro: orbit.intros)
qed simp
lemma self_in_orbit_trans:
assumes "s \<in> orbit f s" "t \<in> orbit f s" shows "t \<in> orbit f t"
using assms(2,1) by induct (auto intro: orbit_sim_step)
lemma orbit_swap:
assumes "s \<in> orbit f s" "t \<in> orbit f s" shows "s \<in> orbit f t"
using assms(2,1)
proof induction
case base then show ?case by (cases "f s = s") (auto intro: orbit_step)
next
case (step x) then show ?case by (cases "f x = s") (auto intro: orbit_step)
qed
lemma permutation_self_in_orbit:
assumes "permutation f" shows "s \<in> orbit f s"
unfolding orbit_altdef using permutation_self[OF assms, of s] by simp metis
lemma orbit_altdef_self_in:
assumes "s \<in> orbit f s" shows "orbit f s = {(f ^^ n) s | n. True}"
proof (intro set_eqI iffI)
fix x assume "x \<in> {(f ^^ n) s | n. True}"
then obtain n where "x = (f ^^ n) s" by auto
then show "x \<in> orbit f s" using assms by (cases "n = 0") (auto simp: orbit_altdef)
qed (auto simp: orbit_altdef)
lemma orbit_altdef_permutation:
assumes "permutation f" shows "orbit f s = {(f ^^ n) s | n. True}"
using assms by (intro orbit_altdef_self_in permutation_self_in_orbit)
lemma orbit_altdef_bounded:
assumes "(f ^^ n) s = s" "0 < n" shows "orbit f s = {(f ^^ m) s| m. m < n}"
proof -
from assms have "s \<in> orbit f s" unfolding orbit_altdef by auto metis
then have "orbit f s = {(f ^^ m) s|m. True}" by (rule orbit_altdef_self_in)
also have "\<dots> = {(f ^^ m) s| m. m < n}"
using assms by (auto simp: funpow_mod_eq intro: exI[where x="m mod n" for m])
finally show ?thesis .
qed
lemma funpow_in_orbit:
assumes "s \<in> orbit f t" shows "(f ^^ n) s \<in> orbit f t"
using assms by (induct n) (auto intro: orbit.intros)
lemma finite_orbit:
assumes "s \<in> orbit f s" shows "finite (orbit f s)"
proof -
from assms obtain n where n: "0 < n" "(f ^^n) s = s" by (auto simp: orbit_altdef)
then show ?thesis by (auto simp: orbit_altdef_bounded)
qed
lemma self_in_orbit_step:
assumes "s \<in> orbit f s" shows "orbit f (f s) = orbit f s"
proof (intro set_eqI iffI)
fix t assume "t \<in> orbit f s" then show "t \<in> orbit f (f s)"
using assms by (auto intro: orbit_step orbit_sim_step)
qed (auto intro: orbit_subset)
lemma permutation_orbit_step:
assumes "permutation f" shows "orbit f (f s) = orbit f s"
using assms by (intro self_in_orbit_step permutation_self_in_orbit)
lemma orbit_nonempty:
"orbit f s \<noteq> {}"
using orbit.base by fastforce
lemma orbit_inv_eq:
assumes "permutation f"
shows "orbit (inv f) x = orbit f x" (is "?L = ?R")
proof -
{ fix g y assume A: "permutation g" "y \<in> orbit (inv g) x"
have "y \<in> orbit g x"
proof -
have inv_g: "\<And>y. x = g y \<Longrightarrow> inv g x = y" "\<And>y. inv g (g y) = y"
by (metis A(1) bij_inv_eq_iff permutation_bijective)+
{ fix y assume "y \<in> orbit g x"
then have "inv g y \<in> orbit g x"
by (cases) (simp_all add: inv_g A(1) permutation_self_in_orbit)
} note inv_g_in_orb = this
from A(2) show ?thesis
by induct (simp_all add: inv_g_in_orb A permutation_self_in_orbit)
qed
} note orb_inv_ss = this
have "inv (inv f) = f"
by (simp add: assms inv_inv_eq permutation_bijective)
then show ?thesis
using orb_inv_ss[OF assms] orb_inv_ss[OF permutation_inverse[OF assms]] by auto
qed
lemma cyclic_on_alldef:
"cyclic_on f S \<longleftrightarrow> S \<noteq> {} \<and> (\<forall>s\<in>S. S = orbit f s)"
unfolding cyclic_on_def by (auto intro: orbit.step orbit_swap orbit_trans)
lemma cyclic_on_funpow_in:
assumes "cyclic_on f S" "s \<in> S" shows "(f^^n) s \<in> S"
using assms unfolding cyclic_on_def by (auto intro: funpow_in_orbit)
lemma finite_cyclic_on:
assumes "cyclic_on f S" shows "finite S"
using assms by (auto simp: cyclic_on_def finite_orbit)
lemma cyclic_on_singleI:
assumes "s \<in> S" "S = orbit f s" shows "cyclic_on f S"
using assms unfolding cyclic_on_def by blast
lemma inj_on_funpow_least:
assumes "(f ^^ n) s = s" "\<And>m. \<lbrakk>m < n; 0 < m\<rbrakk> \<Longrightarrow> (f ^^ m) s \<noteq> s"
shows "inj_on (\<lambda>k. (f^^k) s) {0..<n}"
proof -
{ fix k l assume A: "k < n" "l < n" "k \<noteq> l" "(f ^^ k) s = (f ^^ l) s"
def k' \<equiv> "min k l" and l' \<equiv> "max k l"
with A have A': "k' < l'" "(f ^^ k') s = (f ^^ l') s" "l' < n"
by (auto simp: min_def max_def)
have "s = (f ^^ ((n - l') + l')) s" using assms \<open>l' < n\<close> by simp
also have "\<dots> = (f ^^ (n - l')) ((f ^^ l') s)" by (simp add: funpow_add)
also have "(f ^^ l') s = (f ^^ k') s" by (simp add: A')
also have "(f ^^ (n - l')) \<dots> = (f ^^ (n - l' + k')) s" by (simp add: funpow_add)
finally have "(f ^^ (n - l' + k')) s = s" by simp
moreover have "n - l' + k' < n" "0 < n - l' + k'"using A' by linarith+
ultimately have False using assms(2) by auto
}
then show ?thesis by (intro inj_onI) auto
qed
lemma cyclic_on_inI:
assumes "cyclic_on f S" "s \<in> S" shows "f s \<in> S"
using assms by (auto simp: cyclic_on_def intro: orbit.intros)
lemma bij_betw_funpow:
assumes "bij_betw f S S" shows "bij_betw (f ^^ n) S S"
proof (induct n)
case 0 then show ?case by (auto simp: id_def[symmetric])
next
case (Suc n)
then show ?case unfolding funpow.simps using assms by (rule bij_betw_trans)
qed
(*XXX rename move*)
lemma orbit_FOO:
assumes self:"a \<in> orbit g a"
and eq: "\<And>x. x \<in> orbit g a \<Longrightarrow> g' (f x) = f (g x)"
shows "f ` orbit g a = orbit g' (f a)" (is "?L = ?R")
proof (intro set_eqI iffI)
fix x assume "x \<in> ?L"
then obtain x0 where "x0 \<in> orbit g a" "x = f x0" by auto
then show "x \<in> ?R"
proof (induct arbitrary: x)
case base then show ?case by (auto simp: self orbit.base eq[symmetric])
next
case step then show ?case by cases (auto simp: eq[symmetric] orbit.intros)
qed
next
fix x assume "x \<in> ?R"
then show "x \<in> ?L"
proof (induct arbitrary: )
case base then show ?case by (auto simp: self orbit.base eq)
next
case step then show ?case by cases (auto simp: eq orbit.intros)
qed
qed
lemma cyclic_on_FOO:
assumes "cyclic_on f S"
assumes "\<And>x. x \<in> S \<Longrightarrow> g (h x) = h (f x)"
shows "cyclic_on g (h ` S)"
using assms by (auto simp: cyclic_on_def) (meson orbit_FOO)
lemma cyclic_on_f_in:
assumes "f permutes S" "cyclic_on f A" "f x \<in> A"
shows "x \<in> A"
proof -
from assms have fx_in_orb: "f x \<in> orbit f (f x)" by (auto simp: cyclic_on_alldef)
from assms have "A = orbit f (f x)" by (auto simp: cyclic_on_alldef)
moreover
then have "\<dots> = orbit f x" using \<open>f x \<in> A\<close> by (auto intro: orbit_step orbit_subset)
ultimately
show ?thesis by (metis (no_types) orbit.simps permutes_inverses(2)[OF assms(1)])
qed
lemma permutes_not_in:
assumes "f permutes S" "x \<notin> S" shows "f x = x"
using assms by (auto simp: permutes_def)
lemma orbit_cong0:
assumes "x \<in> A" "f \<in> A \<rightarrow> A" "\<And>y. y \<in> A \<Longrightarrow> f y = g y" shows "orbit f x = orbit g x"
proof -
{ fix n have "(f ^^ n) x = (g ^^ n) x \<and> (f ^^ n) x \<in> A"
by (induct n rule: nat.induct) (insert assms, auto)
} then show ?thesis by (auto simp: orbit_altdef)
qed
lemma orbit_cong:
assumes self_in: "t \<in> orbit f t" and eq: "\<And>s. s \<in> orbit f t \<Longrightarrow> g s = f s"
shows "orbit g t = orbit f t"
using assms(1) _ assms(2) by (rule orbit_cong0) (auto simp: orbit.step eq)
lemma cyclic_cong:
assumes "\<And>s. s \<in> S \<Longrightarrow> f s = g s" shows "cyclic_on f S = cyclic_on g S"
proof -
have "(\<exists>s\<in>S. orbit f s = orbit g s) \<Longrightarrow> cyclic_on f S = cyclic_on g S"
by (metis cyclic_on_alldef cyclic_on_def)
then show ?thesis by (metis assms orbit_cong cyclic_on_def)
qed
lemma permutes_comp_preserves_cyclic1:
assumes "g permutes B" "cyclic_on f C"
assumes "A \<inter> B = {}" "C \<subseteq> A"
shows "cyclic_on (f o g) C"
proof -
have *: "\<And>c. c \<in> C \<Longrightarrow> f (g c) = f c"
using assms by (subst permutes_not_in[where f=g]) auto
with assms(2) show ?thesis by (simp cong: cyclic_cong)
qed
lemma permutes_comp_preserves_cyclic2:
assumes "f permutes A" "cyclic_on g C"
assumes "A \<inter> B = {}" "C \<subseteq> B"
shows "cyclic_on (f o g) C"
proof -
obtain c where c: "c \<in> C" "C = orbit g c" "c \<in> orbit g c"
using \<open>cyclic_on g C\<close> by (auto simp: cyclic_on_def)
then have "\<And>c. c \<in> C \<Longrightarrow> f (g c) = g c"
using assms c by (subst permutes_not_in[where f=f]) (auto intro: orbit.intros)
with assms(2) show ?thesis by (simp cong: cyclic_cong)
qed
(*XXX merge with previous section?*)
subsection \<open>Orbits\<close>
lemma permutes_orbit_subset:
assumes "f permutes S" "x \<in> S" shows "orbit f x \<subseteq> S"
proof
fix y assume "y \<in> orbit f x"
then show "y \<in> S" by induct (auto simp: permutes_in_image assms)
qed
lemma cyclic_on_orbit':
assumes "permutation f" shows "cyclic_on f (orbit f x)"
unfolding cyclic_on_alldef using orbit_nonempty[of f x]
by (auto intro: assms orbit_swap orbit_trans permutation_self_in_orbit)
(* XXX remove? *)
lemma cyclic_on_orbit:
assumes "f permutes S" "finite S" shows "cyclic_on f (orbit f x)"
using assms by (intro cyclic_on_orbit') (auto simp: permutation_permutes)
lemma orbit_cyclic_eq3:
assumes "cyclic_on f S" "y \<in> S" shows "orbit f y = S"
using assms unfolding cyclic_on_alldef by simp
(*XXX move*)
lemma orbit_eq_singleton_iff: "orbit f x = {x} \<longleftrightarrow> f x = x" (is "?L \<longleftrightarrow> ?R")
proof
assume A: ?R
{ fix y assume "y \<in> orbit f x" then have "y = x"
by induct (auto simp: A)
} then show ?L by (metis orbit_nonempty singletonI subsetI subset_singletonD)
next
assume A: ?L
then have "\<And>y. y \<in> orbit f x \<Longrightarrow> f x = y"
by - (erule orbit.cases, simp_all)
then show ?R using A by blast
qed
(* XXX move *)
lemma eq_on_cyclic_on_iff1:
assumes "cyclic_on f S" "x \<in> S"
obtains "f x \<in> S" "f x = x \<longleftrightarrow> card S = 1"
proof
from assms show "f x \<in> S" by (auto simp: cyclic_on_def intro: orbit.intros)
from assms have "S = orbit f x" by (auto simp: cyclic_on_alldef)
then have "f x = x \<longleftrightarrow> S = {x}" by (metis orbit_eq_singleton_iff)
then show "f x = x \<longleftrightarrow> card S = 1" using \<open>x \<in> S\<close> by (auto simp: card_Suc_eq)
qed
subsection \<open>Decomposition of Arbitrary Permutations\<close>
definition perm_restrict :: "('a \<Rightarrow> 'a) \<Rightarrow> 'a set \<Rightarrow> ('a \<Rightarrow> 'a)" where
"perm_restrict f S x \<equiv> if x \<in> S then f x else x"
lemma perm_restrict_comp:
assumes "A \<inter> B = {}" "cyclic_on f B"
shows "perm_restrict f A o perm_restrict f B = perm_restrict f (A \<union> B)"
proof -
have "\<And>x. x \<in> B \<Longrightarrow> f x \<in> B" using \<open>cyclic_on f B\<close> by (rule cyclic_on_inI)
with assms show ?thesis by (auto simp: perm_restrict_def fun_eq_iff)
qed
lemma perm_restrict_simps:
"x \<in> S \<Longrightarrow> perm_restrict f S x = f x"
"x \<notin> S \<Longrightarrow> perm_restrict f S x = x"
by (auto simp: perm_restrict_def)
lemma perm_restrict_perm_restrict:
"perm_restrict (perm_restrict f A) B = perm_restrict f (A \<inter> B)"
by (auto simp: perm_restrict_def)
lemma perm_restrict_union:
assumes "perm_restrict f A permutes A" "perm_restrict f B permutes B" "A \<inter> B = {}"
shows "perm_restrict f A o perm_restrict f B = perm_restrict f (A \<union> B)"
using assms by (auto simp: fun_eq_iff perm_restrict_def permutes_def) (metis Diff_iff Diff_triv)
lemma perm_restrict_id[simp]:
assumes "f permutes S" shows "perm_restrict f S = f"
using assms by (auto simp: permutes_def perm_restrict_def)
lemma cyclic_on_perm_restrict:
"cyclic_on (perm_restrict f S) S \<longleftrightarrow> cyclic_on f S"
by (simp add: perm_restrict_def cong: cyclic_cong)
lemma perm_restrict_diff_cyclic:
assumes "f permutes S" "cyclic_on f A"
shows "perm_restrict f (S - A) permutes (S - A)"
proof -
{ fix y
have "\<exists>x. perm_restrict f (S - A) x = y"
proof cases
assume A: "y \<in> S - A"
with \<open>f permutes S\<close> obtain x where "f x = y" "x \<in> S"
unfolding permutes_def by auto metis
moreover
with A have "x \<notin> A" by (metis Diff_iff assms(2) cyclic_on_inI)
ultimately
have "perm_restrict f (S - A) x = y" by (simp add: perm_restrict_simps)
then show ?thesis ..
next
assume "y \<notin> S - A"
then have "perm_restrict f (S - A) y = y" by (simp add: perm_restrict_simps)
then show ?thesis ..
qed
} note X = this
{ fix x y assume "perm_restrict f (S - A) x = perm_restrict f (S - A) y"
with assms have "x = y"
by (auto simp: perm_restrict_def permutes_def split: if_splits intro: cyclic_on_f_in)
} note Y = this
show ?thesis by (auto simp: permutes_def perm_restrict_simps X intro: Y)
qed
lemma orbit_eqI:
"y = f x \<Longrightarrow> y \<in> orbit f x"
"z = f y \<Longrightarrow>y \<in> orbit f x \<Longrightarrow>z \<in> orbit f x"
by (metis orbit.base) (metis orbit.step)
lemma permutes_decompose:
assumes "f permutes S" "finite S"
shows "\<exists>C. (\<forall>c \<in> C. cyclic_on f c) \<and> \<Union>C = S \<and> (\<forall>c1 \<in> C. \<forall>c2 \<in> C. c1 \<noteq> c2 \<longrightarrow> c1 \<inter> c2 = {})"
using assms(2,1)
proof (induction arbitrary: f rule: finite_psubset_induct)
case (psubset S)
show ?case
proof (cases "S = {}")
case True then show ?thesis by (intro exI[where x="{}"]) auto
next
case False
then obtain s where "s \<in> S" by auto
with `f permutes S` have "orbit f s \<subseteq> S"
by (rule permutes_orbit_subset)
have cyclic_orbit: "cyclic_on f (orbit f s)"
using \<open>f permutes S\<close> \<open>finite S\<close> by (rule cyclic_on_orbit)
let ?f' = "perm_restrict f (S - orbit f s)"
have "f s \<in> S" using \<open>f permutes S\<close> \<open>s \<in> S\<close> by (auto simp: permutes_in_image)
then have "S - orbit f s \<subset> S" using orbit.base[of f s] \<open>s \<in> S\<close> by blast
moreover
have "?f' permutes (S - orbit f s)"
using \<open>f permutes S\<close> cyclic_orbit by (rule perm_restrict_diff_cyclic)
ultimately
obtain C where C: "\<And>c. c \<in> C \<Longrightarrow> cyclic_on ?f' c" "\<Union>C = S - orbit f s"
"\<forall>c1 \<in> C. \<forall>c2 \<in> C. c1 \<noteq> c2 \<longrightarrow> c1 \<inter> c2 = {}"
using psubset.IH by metis
{ fix c assume "c \<in> C"
then have *: "\<And>x. x \<in> c \<Longrightarrow> perm_restrict f (S - orbit f s) x = f x"
using C(2) \<open>f permutes S\<close> by (auto simp add: perm_restrict_def)
then have "cyclic_on f c" using C(1)[OF \<open>c \<in> C\<close>] by (simp cong: cyclic_cong add: *)
} note in_C_cyclic = this
have Un_ins: "\<Union>insert (orbit f s) C = S"
using \<open>\<Union>C = _\<close> \<open>orbit f s \<subseteq> S\<close> by blast
have Disj_ins: "(\<forall>c1 \<in> insert (orbit f s) C. \<forall>c2 \<in> insert (orbit f s) C. c1 \<noteq> c2 \<longrightarrow> c1 \<inter> c2 = {})"
using C by auto
show ?thesis
by (intro conjI Un_ins Disj_ins exI[where x="insert (orbit f s) C"])
(auto simp: cyclic_orbit in_C_cyclic)
qed
qed
subsection \<open>Funpow + Orbit\<close>
lemma funpow_dist_prop:
"y \<in> orbit f x \<Longrightarrow> (f ^^ funpow_dist f x y) x = y"
unfolding funpow_dist_def by (rule LeastI_ex) (auto simp: orbit_altdef)
lemma funpow_dist_0_eq:
assumes "y \<in> orbit f x" shows "funpow_dist f x y = 0 \<longleftrightarrow> x = y"
using assms by (auto simp: funpow_dist_0 dest: funpow_dist_prop)
lemma funpow_dist_step:
assumes "x \<noteq> y" "y \<in> orbit f x" shows "funpow_dist f x y = Suc (funpow_dist f (f x) y)"
proof -
from \<open>y \<in> _\<close> obtain n where "(f ^^ n) x = y" by (auto simp: orbit_altdef)
with \<open>x \<noteq> y\<close> obtain n' where [simp]: "n = Suc n'" by (cases n) auto
show ?thesis
unfolding funpow_dist_def
proof (rule Least_Suc2)
show "(f ^^ n) x = y" by fact
then show "(f ^^ n') (f x) = y" by (simp add: funpow_swap1)
show "(f ^^ 0) x \<noteq> y" using \<open>x \<noteq> y\<close> by simp
show "\<forall>k. ((f ^^ Suc k) x = y) = ((f ^^ k) (f x) = y)"
by (simp add: funpow_swap1)
qed
qed
lemma funpow_dist1_prop:
assumes "y \<in> orbit f x" shows "(f ^^ funpow_dist1 f x y) x = y"
by (metis assms funpow.simps(1) funpow_dist_0 funpow_dist_prop funpow_simp_l funpow_swap1 id_apply orbit_step)
(*XXX simplify? *)
lemma funpow_neq_less_funpow_dist:
assumes "y \<in> orbit f x" "m \<le> funpow_dist f x y" "n \<le> funpow_dist f x y" "m \<noteq> n"
shows "(f ^^ m) x \<noteq> (f ^^ n) x"
proof (rule notI)
assume A: "(f ^^ m) x = (f ^^ n) x"
def m' \<equiv> "min m n" and n' \<equiv> "max m n"
with A assms have A': "m' < n'" "(f ^^ m') x = (f ^^ n') x" "n' \<le> funpow_dist f x y"
by (auto simp: min_def max_def)
have "y = (f ^^ funpow_dist f x y) x"
using \<open>y \<in> _\<close> by (simp only: funpow_dist_prop)
also have "\<dots> = (f ^^ ((funpow_dist f x y - n') + n')) x"
using \<open>n' \<le> _\<close> by simp
also have "\<dots> = (f ^^ ((funpow_dist f x y - n') + m')) x"
by (simp add: funpow_add \<open>(f ^^ m') x = _\<close>)
also have "(f ^^ ((funpow_dist f x y - n') + m')) x \<noteq> y"
using A' by (intro funpow_dist_least) linarith
finally show "False" by simp
qed
(* XXX reduce to funpow_neq_less_funpow_dist? *)
lemma funpow_neq_less_funpow_dist1:
assumes "y \<in> orbit f x" "m < funpow_dist1 f x y" "n < funpow_dist1 f x y" "m \<noteq> n"
shows "(f ^^ m) x \<noteq> (f ^^ n) x"
proof (rule notI)
assume A: "(f ^^ m) x = (f ^^ n) x"
def m' \<equiv> "min m n" and n' \<equiv> "max m n"
with A assms have A': "m' < n'" "(f ^^ m') x = (f ^^ n') x" "n' < funpow_dist1 f x y"
by (auto simp: min_def max_def)
have "y = (f ^^ funpow_dist1 f x y) x"
using \<open>y \<in> _\<close> by (simp only: funpow_dist1_prop)
also have "\<dots> = (f ^^ ((funpow_dist1 f x y - n') + n')) x"
using \<open>n' < _\<close> by simp
also have "\<dots> = (f ^^ ((funpow_dist1 f x y - n') + m')) x"
by (simp add: funpow_add \<open>(f ^^ m') x = _\<close>)
also have "(f ^^ ((funpow_dist1 f x y - n') + m')) x \<noteq> y"
using A' by (intro funpow_dist1_least) linarith+
finally show "False" by simp
qed
lemma inj_on_funpow_dist:
assumes "y \<in> orbit f x" shows "inj_on (\<lambda>n. (f ^^ n) x) {0..funpow_dist f x y}"
using funpow_neq_less_funpow_dist[OF assms] by (intro inj_onI) auto
lemma orbit_conv_funpow_dist1:
assumes "x \<in> orbit f x"
shows "orbit f x = (\<lambda>n. (f ^^ n) x) ` {0..<funpow_dist1 f x x}" (is "?L = ?R")
using funpow_dist1_prop[OF assms]
by (auto simp: orbit_altdef_bounded[where n="funpow_dist1 f x x"])
lemma funpow_dist1_prop1:
assumes "(f ^^ n) x = y" "0 < n" shows "(f ^^ funpow_dist1 f x y) x = y"
proof -
from assms have "y \<in> orbit f x" by (auto simp: orbit_altdef)
then show ?thesis by (rule funpow_dist1_prop)
qed
lemma funpow_dist1_dist:
assumes "funpow_dist1 f x y < funpow_dist1 f x z"
assumes "{y,z} \<subseteq> orbit f x"
shows "funpow_dist1 f x z = funpow_dist1 f x y + funpow_dist1 f y z" (is "?L = ?R")
proof -
have x_z: "(f ^^ funpow_dist1 f x z) x = z" using assms by (blast intro: funpow_dist1_prop)
have x_y: "(f ^^ funpow_dist1 f x y) x = y" using assms by (blast intro: funpow_dist1_prop)
have "(f ^^ (funpow_dist1 f x z - funpow_dist1 f x y)) y
= (f ^^ (funpow_dist1 f x z - funpow_dist1 f x y)) ((f ^^ funpow_dist1 f x y) x)"
using x_y by simp
also have "\<dots> = z"
using assms x_z by (simp del: funpow.simps add: funpow_add_app)
finally have y_z_diff: "(f ^^ (funpow_dist1 f x z - funpow_dist1 f x y)) y = z" .
then have "(f ^^ funpow_dist1 f y z) y = z"
using assms by (intro funpow_dist1_prop1) auto
then have "(f ^^ funpow_dist1 f y z) ((f ^^ funpow_dist1 f x y) x) = z"
using x_y by simp
then have "(f ^^ (funpow_dist1 f y z + funpow_dist1 f x y)) x = z"
by (simp del: funpow.simps add: funpow_add_app)
show ?thesis
proof (rule antisym)
from y_z_diff have "(f ^^ funpow_dist1 f y z) y = z"
using assms by (intro funpow_dist1_prop1) auto
then have "(f ^^ funpow_dist1 f y z) ((f ^^ funpow_dist1 f x y) x) = z"
using x_y by simp
then have "(f ^^ (funpow_dist1 f y z + funpow_dist1 f x y)) x = z"
by (simp del: funpow.simps add: funpow_add_app)
then have "funpow_dist1 f x z \<le> funpow_dist1 f y z + funpow_dist1 f x y"
using funpow_dist1_least not_less by fastforce
then show "?L \<le> ?R" by presburger
next
have "funpow_dist1 f y z \<le> funpow_dist1 f x z - funpow_dist1 f x y"
using y_z_diff assms(1) by (metis not_less zero_less_diff funpow_dist1_least)
then show "?R \<le> ?L" by linarith
qed
qed
lemma funpow_dist1_le_self:
assumes "(f ^^ m) x = x" "0 < m" "y \<in> orbit f x"
shows "funpow_dist1 f x y \<le> m"
proof (cases "x = y")
case True with assms show ?thesis by (auto dest!: funpow_dist1_least)
next
case False
have "(f ^^ funpow_dist1 f x y) x = (f ^^ (funpow_dist1 f x y mod m)) x"
using assms by (simp add: funpow_mod_eq)
then have "\<not>(funpow_dist1 f x y mod m < funpow_dist1 f x y)"
by (metis False assms(3) funpow_dist_least funpow_dist_prop funpow_dist_step)
then show ?thesis
by (metis (poly_guards_query) Divides.mod_less_eq_dividend assms(2) le_less mod_less_divisor)
qed
subsection \<open>Permutation Domains\<close>
definition has_dom :: "('a \<Rightarrow> 'a) \<Rightarrow> 'a set \<Rightarrow> bool" where
"has_dom f S \<equiv> \<forall>s. s \<notin> S \<longrightarrow> f s = s"
lemma permutes_conv_has_dom:
"f permutes S \<longleftrightarrow> bij f \<and> has_dom f S"
by (auto simp: permutes_def has_dom_def bij_iff)
section \<open>Segments\<close>
inductive_set segment :: "('a \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> 'a set" for f a b where
base: "f a \<noteq> b \<Longrightarrow> f a \<in> segment f a b" |
step: "x \<in> segment f a b \<Longrightarrow> f x \<noteq> b \<Longrightarrow> f x \<in> segment f a b"
lemma segment_step_2D:
assumes "x \<in> segment f a (f b)" shows "x \<in> segment f a b \<or> x = b"
using assms by induct (auto intro: segment.intros)
lemma not_in_segment2D:
assumes "x \<in> segment f a b" shows "x \<noteq> b"
using assms by induct auto
lemma segment_altdef:
assumes "b \<in> orbit f a"
shows "segment f a b = (\<lambda>n. (f ^^ n) a) ` {1..<funpow_dist1 f a b}" (is "?L = ?R")
proof (intro set_eqI iffI)
fix x assume "x \<in> ?L"
have "f a \<noteq>b \<Longrightarrow> b \<in> orbit f (f a)"
using assms by (simp add: orbit_step)
then have *: "f a \<noteq> b \<Longrightarrow> 0 < funpow_dist f (f a) b"
using assms using gr0I funpow_dist_0_eq[OF \<open>_ \<Longrightarrow> b \<in> orbit f (f a)\<close>] by (simp add: orbit.intros)
from \<open>x \<in> ?L\<close> show "x \<in> ?R"
proof induct
case base then show ?case by (intro image_eqI[where x=1]) (auto simp: *)
next
case step then show ?case using assms funpow_dist1_prop less_antisym
by (fastforce intro!: image_eqI[where x="Suc n" for n])
qed
next
fix x assume "x \<in> ?R"
then obtain n where "(f ^^ n ) a = x" "0 < n" "n < funpow_dist1 f a b" by auto
then show "x \<in> ?L"
proof (induct n arbitrary: x)
case 0 then show ?case by simp
next
case (Suc n)
have "(f ^^ Suc n) a \<noteq> b" using Suc by (meson funpow_dist1_least)
with Suc show ?case by (cases "n = 0") (auto intro: segment.intros)
qed
qed
(*XXX move up*)
lemma segmentD_orbit:
assumes "x \<in> segment f y z" shows "x \<in> orbit f y"
using assms by induct (auto intro: orbit.intros)
lemma segment1_empty: "segment f x (f x) = {}"
by (auto simp: segment_altdef orbit.base funpow_dist_0)
lemma segment_subset:
assumes "y \<in> segment f x z"
assumes "w \<in> segment f x y"
shows "w \<in> segment f x z"
using assms by (induct arbitrary: w) (auto simp: segment1_empty intro: segment.intros dest: segment_step_2D elim: segment.cases)
(* XXX move up*)
lemma not_in_segment1:
assumes "y \<in> orbit f x" shows "x \<notin> segment f x y"
proof
assume "x \<in> segment f x y"
then obtain n where n: "0 < n" "n < funpow_dist1 f x y" "(f ^^ n) x = x"
using assms by (auto simp: segment_altdef Suc_le_eq)
then have neq_y: "(f ^^ (funpow_dist1 f x y - n)) x \<noteq> y" by (simp add: funpow_dist1_least)
have "(f ^^ (funpow_dist1 f x y - n)) x = (f ^^ (funpow_dist1 f x y - n)) ((f ^^ n) x)"
using n by (simp add: funpow_add_app)
also have "\<dots> = (f ^^ funpow_dist1 f x y) x"
using \<open>n < _\<close> by (simp add: funpow_add_app)
also have "\<dots> = y" using assms by (rule funpow_dist1_prop)
finally show False using neq_y by contradiction
qed
lemma not_in_segment2: "y \<notin> segment f x y"
using not_in_segment2D by metis
(*XXX move*)
lemma in_segmentE:
assumes "y \<in> segment f x z" "z \<in> orbit f x"
obtains "(f ^^ funpow_dist1 f x y) x = y" "funpow_dist1 f x y < funpow_dist1 f x z"
proof
from assms show "(f ^^ funpow_dist1 f x y) x = y"
by (intro segmentD_orbit funpow_dist1_prop)
moreover
obtain n where "(f ^^ n) x = y" "0 < n" "n < funpow_dist1 f x z"
using assms by (auto simp: segment_altdef)
moreover then have "funpow_dist1 f x y \<le> n" by (meson funpow_dist1_least not_less)
ultimately show "funpow_dist1 f x y < funpow_dist1 f x z" by linarith
qed
(*XXX move*)
lemma cyclic_split_segment:
assumes S: "cyclic_on f S" "a \<in> S" "b \<in> S" and "a \<noteq> b"
shows "S = {a,b} \<union> segment f a b \<union> segment f b a" (is "?L = ?R")
proof (intro set_eqI iffI)
fix c assume "c \<in> ?L"
with S have "c \<in> orbit f a" unfolding cyclic_on_alldef by auto
then show "c \<in> ?R" by induct (auto intro: segment.intros)
next
fix c assume "c \<in> ?R"
moreover have "segment f a b \<subseteq> orbit f a" "segment f b a \<subseteq> orbit f b"
by (auto dest: segmentD_orbit)
ultimately show "c \<in> ?L" using S by (auto simp: cyclic_on_alldef)
qed
(*XXX move*)
lemma segment_split:
assumes y_in_seg: "y \<in> segment f x z"
shows "segment f x z = segment f x y \<union> {y} \<union> segment f y z" (is "?L = ?R")
proof (intro set_eqI iffI)
fix w assume "w \<in> ?L" then show "w \<in> ?R" by induct (auto intro: segment.intros)
next
fix w assume "w \<in> ?R"
moreover
{ assume "w \<in> segment f x y" then have "w \<in> segment f x z"
using segment_subset[OF y_in_seg] by auto }
moreover
{ assume "w \<in> segment f y z" then have "w \<in> segment f x z"
using y_in_seg by induct (auto intro: segment.intros) }
ultimately
show "w \<in> ?L" using y_in_seg by (auto intro: segment.intros)
qed
lemma in_segmentD_inv:
assumes "x \<in> segment f a b" "x \<noteq> f a"
assumes "inj f"
shows "inv f x \<in> segment f a b"
using assms by (auto elim: segment.cases)
lemma in_orbit_invI:
assumes "b \<in> orbit f a"
assumes "inj f"
shows "a \<in> orbit (inv f) b"
using assms(1)
apply induct
apply (simp add: assms(2) orbit_eqI(1))
by (metis assms(2) inv_f_f orbit.base orbit_trans)
lemma segment_step_2:
assumes A: "x \<in> segment f a b" "b \<noteq> a" and "inj f"
shows "x \<in> segment f a (f b)"
using A by induct (auto intro: segment.intros dest: not_in_segment2D injD[OF \<open>inj f\<close>])
lemma inv_end_in_segment:
assumes "b \<in> orbit f a" "f a \<noteq> b" "bij f"
shows "inv f b \<in> segment f a b"
using assms(1,2)
proof induct
case base then show ?case by simp
next
case (step x)
moreover
from \<open>bij f\<close> have "inj f" by (rule bij_is_inj)
moreover
then have "x \<noteq> f x \<Longrightarrow> f a = x \<Longrightarrow> x \<in> segment f a (f x)" by (meson segment.simps)
moreover
have "x \<noteq> f x"
using step \<open>inj f\<close> by (metis in_orbit_invI inv_f_eq not_in_segment1 segment.base)
then have "inv f x \<in> segment f a (f x) \<Longrightarrow> x \<in> segment f a (f x)"
using \<open>bij f\<close> \<open>inj f\<close> by (auto dest: segment.step simp: surj_f_inv_f bij_is_surj)
then have "inv f x \<in> segment f a x \<Longrightarrow> x \<in> segment f a (f x)"
using \<open>f a \<noteq> f x\<close> \<open>inj f\<close> by (auto dest: segment_step_2 injD)
ultimately show ?case by (cases "f a = x") simp_all
qed
lemma segment_overlapping:
assumes "x \<in> orbit f a" "x \<in> orbit f b" "bij f"
shows "segment f a x \<subseteq> segment f b x \<or> segment f b x \<subseteq> segment f a x"
using assms(1,2)
proof induction
case base then show ?case by (simp add: segment1_empty)
next
case (step x)
from \<open>bij f\<close> have "inj f" by (simp add: bij_is_inj)
have *: "\<And>f x y. y \<in> segment f x (f x) \<Longrightarrow> False" by (simp add: segment1_empty)
{ fix y z
assume A: "y \<in> segment f b (f x)" "y \<notin> segment f a (f x)" "z \<in> segment f a (f x)"
from \<open>x \<in> orbit f a\<close> \<open>f x \<in> orbit f b\<close> \<open>y \<in> segment f b (f x)\<close>
have "x \<in> orbit f b"
by (metis * inv_end_in_segment[OF _ _ \<open>bij f\<close>] inv_f_eq[OF \<open>inj f\<close>] segmentD_orbit)
moreover
with \<open>x \<in> orbit f a\<close> step.IH
have "segment f a (f x) \<subseteq> segment f b (f x) \<or> segment f b (f x) \<subseteq> segment f a (f x)"
apply auto
apply (metis * inv_end_in_segment[OF _ _ \<open>bij f\<close>] inv_f_eq[OF \<open>inj f\<close>] segment_step_2D segment_subset step.prems subsetCE)
by (metis (no_types, lifting) `inj f` * inv_end_in_segment[OF _ _ \<open>bij f\<close>] inv_f_eq orbit_eqI(2) segment_step_2D segment_subset subsetCE)
ultimately
have "segment f a (f x) \<subseteq> segment f b (f x)" using A by auto
} note C = this
then show ?case by auto
qed
lemma segment_disj:
assumes "a \<noteq> b" "bij f"
shows "segment f a b \<inter> segment f b a = {}"
proof (rule ccontr)
assume "\<not>?thesis"
then obtain x where x: "x \<in> segment f a b" "x \<in> segment f b a" by blast
then have "segment f a b = segment f a x \<union> {x} \<union> segment f x b"
"segment f b a = segment f b x \<union> {x} \<union> segment f x a"
by (auto dest: segment_split)
then have o: "x \<in> orbit f a" "x \<in> orbit f b" by (auto dest: segmentD_orbit)
note * = segment_overlapping[OF o \<open>bij f\<close>]
have "inj f" using \<open>bij f\<close> by (simp add: bij_is_inj)
have "segment f a x = segment f b x"
proof (intro set_eqI iffI)
fix y assume A: "y \<in> segment f b x"
then have "y \<in> segment f a x \<or> f a \<in> segment f b a"
using * x(2) by (auto intro: segment.base segment_subset)
then show "y \<in> segment f a x"
using \<open>inj f\<close> A by (metis (no_types) not_in_segment2 segment_step_2)
next
fix y assume A: "y \<in> segment f a x "
then have "y \<in> segment f b x \<or> f b \<in> segment f a b"
using * x(1) by (auto intro: segment.base segment_subset)
then show "y \<in> segment f b x"
using \<open>inj f\<close> A by (metis (no_types) not_in_segment2 segment_step_2)
qed
moreover
have "segment f a x \<noteq> segment f b x"
by (metis assms bij_is_inj not_in_segment2 segment.base segment_step_2 segment_subset x(1))
ultimately show False by contradiction
qed
lemma segment_x_x_eq:
assumes "permutation f"
shows "segment f x x = orbit f x - {x}" (is "?L = ?R")
proof (intro set_eqI iffI)
fix y assume "y \<in> ?L" then show "y \<in> ?R" by (auto dest: segmentD_orbit simp: not_in_segment2)
next
fix y assume "y \<in> ?R"
then have "y \<in> orbit f x" "y \<noteq> x" by auto
then show "y \<in> ?L" by induct (auto intro: segment.intros)
qed
section \<open>Lists of Powers\<close>
definition iterate :: "nat \<Rightarrow> nat \<Rightarrow> ('a \<Rightarrow> 'a ) \<Rightarrow> 'a \<Rightarrow> 'a list" where
"iterate m n f x = map (\<lambda>n. (f^^n) x) [m..<n]"
lemma set_iterate:
"set (iterate m n f x) = (\<lambda>k. (f ^^ k) x) ` {m..<n} "
by (auto simp: iterate_def)
lemma iterate_empty[simp]: "iterate n m f x = [] \<longleftrightarrow> m \<le> n"
by (auto simp: iterate_def)
lemma iterate_nth[simp]:
assumes "k < n - m" shows "iterate m n f x ! k = (f^^(m+k)) x"
using assms
by (induct k arbitrary: m) (auto simp: iterate_def)
lemma iterate_applied:
"iterate n m f (f x) = iterate (Suc n) (Suc m) f x"
by (induct m arbitrary: n) (auto simp: iterate_def funpow_swap1)
end
|
# basic test that parsing works correctly
testdir = dirname(@__FILE__)
@test_throws Gumbo.InvalidHTMLException parsehtml("", strict=true)
let
page = open("$testdir/example.html") do example
example |> readall |> parsehtml
end
@test page.doctype == "html"
root = page.root
@test tag(root[1][1]) == :meta
@test root[2][1][1].text == "A simple test page."
@test is(root[2][1][1].parent, root[2][1])
end
|
The Marilyn Denis Show has brought you Marilyn’s 10 Days of Giveaways from which you could get a chance to win exciting prizes every day. To enter Marilyn.ca 10 Days of Giveaways, Visit Sweepstakes entry page and follow the on-screen steps to enter the Sweepstakes. You can enter daily now through December 17th, 2018. So hurry up!
Giveaway Period: This sweepstakes runs until December 17th, 2018! |
{- |
Module : $Header$
Description : This is the abstract file for the Scheme compiler.
Copyright : (c) Michael Buchel
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : portable
This is the abstract module, where all the abstract concepts are kept.
| -}
module Abstract where
import Data.Array
import Data.Complex
import Data.Ratio
-- | Data structure for holding Lisp values.
data LispVal = Atom String
| List [LispVal]
| DottedList [LispVal] LispVal
| Number Integer
| String String
| Bool Bool
| Character Char
| Float Double
| Ratio Rational
| Complex (Complex Double)
| Vector (Array Int LispVal)
-- | Instance of show for LispVal.
instance Show LispVal where
show = showVal
-- | Seperates the list into words.
unwordsList :: [LispVal] -- ^ List to unword.
-> String
unwordsList = unwords . map showVal
-- | Lisp value to string.
showVal :: LispVal -- ^ Expression we got.
-> String
showVal (Atom name) = name
showVal (List x) = "(" ++ unwordsList x ++ ")"
showVal (DottedList x y) = "(" ++ unwordsList x ++ " . " ++ showVal y ++ ")"
showVal (String contents) = "\"" ++ contents ++ "\""
showVal (Bool True) = "#t"
showVal (Bool False) = "#f"
showVal (Number x) = show x
showVal (Character x) = show x
showVal (Float x) = show x
showVal (Ratio x) = show x
showVal (Complex x) = show x
showVal (Vector x) = show x
|
# The references to special cases are to Table of Integrals, Series, and Products, § 9.121, followed by NIST's DLMF.
"""
Compute the Gauss hypergeometric function `₂F₁(a,b;c;z)`.
"""
function _₂F₁(a::Number,b::Number,c::Number,z::Number)
if real(a) > real(b)
return _₂F₁(b,a,c,z) # ensure a ≤ b
elseif isequal(a,c) # 1. 15.4.6
return exp(-b*log1p(-z))
elseif isequal(b,c) # 1. 15.4.6
return exp(-a*log1p(-z))
elseif isequal(c,0.5)
if isequal(a+b,0) # 31. 15.4.11 & 15.4.12
return cosnasinsqrt(2b,z)
elseif isequal(a+b,1) # 32. 15.4.13 & 15.4.14
return cosnasinsqrt(1-2b,z)*exp(-0.5log1p(-z))
elseif isequal(b-a,0.5) # 15.4.7 & 15.4.8
return expnlog1pcoshatanhsqrt(-2a,z)
end
elseif isequal(c,1.5)
if abeqcd(a,b,0.5) # 13. 15.4.4 & 15.4.5
return sqrtasinsqrt(z)
elseif abeqcd(a,b,1) # 14.
return sqrtasinsqrt(z)*exp(-0.5log1p(-z))
elseif abeqcd(a,b,0.5,1) # 15. 15.4.2 & 15.4.3
return sqrtatanhsqrt(z)
elseif isequal(a+b,1) # 29. 15.4.15 & 15.4.16
return sinnasinsqrt(1-2b,z)
elseif isequal(a+b,2) # 30.
return sinnasinsqrt(2-2b,z)*exp(-0.5log1p(-z))
elseif isequal(b-a,0.5) # 4. 15.4.9 & 15.4.10
return expnlog1psinhatanhsqrt(1-2a,z)
end
elseif isequal(c,2)
if abeqcd(a,b,1) # 6. 15.4.1
return (s = -z; log1p(s)/s)
elseif a ∈ ℤ && b == 1 # 5.
return expm1nlog1p(1-a,-z)
elseif a == 1 && b ∈ ℤ # 5.
return expm1nlog1p(1-b,-z)
end
elseif isequal(c,2.5) && abeqcd(a,b,1,1.5)
return speciallog(z)
end
_₂F₁general(a,b,c,z) # catch-all
end
_₂F₁(a::Number,b::Number,c::Number,z::AbstractArray) = reshape(promote_type(typeof(a),typeof(b),typeof(c),eltype(z))[ _₂F₁(a,b,c,z[i]) for i in eachindex(z) ], size(z))
"""
Compute the Gauss hypergeometric function `₂F₁(a,b;c;z)` with general parameters a,b, and c.
This polyalgorithm is designed based on the paper
N. Michel and M. V. Stoitsov, Fast computation of the Gauss hypergeometric function with all its parameters complex with application to the Pöschl–Teller–Ginocchio potential wave functions, Comp. Phys. Commun., 178:535–551, 2008.
"""
function _₂F₁general(a::Number,b::Number,c::Number,z::Number)
T = promote_type(typeof(a),typeof(b),typeof(c),typeof(z))
real(b) < real(a) && (return _₂F₁general(b,a,c,z))
real(c) < real(a)+real(b) && (return exp((c-a-b)*log1p(-z))*_₂F₁general(c-a,c-b,c,z))
if abs(z) ≤ ρ || -a ∈ ℕ₀ || -b ∈ ℕ₀
_₂F₁maclaurin(a,b,c,z)
elseif abs(z/(z-1)) ≤ ρ && absarg(1-z) < convert(real(T),π)
exp(-a*log1p(-z))_₂F₁maclaurin(a,c-b,c,z/(z-1))
elseif abs(inv(z)) ≤ ρ && absarg(-z) < convert(real(T),π)
_₂F₁Inf(a,b,c,z)
elseif abs(1-inv(z)) ≤ ρ && absarg(z) < convert(real(T),π) && absarg(1-z) < convert(real(T),π)
exp(-a*log1p(-z))*_₂F₁Inf(a,c-b,c,z/(z-1))
elseif abs(1-z) ≤ ρ && absarg(z) < convert(real(T),π) && absarg(1-z) < convert(real(T),π)
_₂F₁one(a,b,c,z)
elseif abs(inv(1-z)) ≤ ρ && absarg(-z) < convert(real(T),π)
exp(-a*log1p(-z))*_₂F₁one(a,c-b,c,z/(z-1))
elseif absarg(1-z) < convert(real(T),π)
_₂F₁taylor(a,b,c,z)
else
zero(T)#throw(DomainError())
end
end
"""
Compute the Gauss hypergeometric function `₂F₁(a,b;c;z)` with general parameters a,b, and c.
This polyalgorithm is designed based on the review
J. W. Pearson, S. Olver and M. A. Porter, Numerical methos for the computation of the confluent and Gauss hypergeometric functions, arXiv:1407.7786, 2014.
"""
function _₂F₁general2(a::Number,b::Number,c::Number,z::Number)
T = promote_type(typeof(a),typeof(b),typeof(c),typeof(z))
if abs(z) ≤ ρ || -a ∈ ℕ₀ || -b ∈ ℕ₀
_₂F₁maclaurin(a,b,c,z)
elseif abs(z/(z-1)) ≤ ρ && absarg(1-z) < convert(real(T),π) # 15.8.1
w = z/(z-1)
_₂F₁maclaurin(a,c-b,c,w)*exp(-a*log1p(-z))
elseif abs(inv(z)) ≤ ρ && absarg(-z) < convert(real(T),π)
w = inv(z)
if isapprox(a,b) # 15.8.8
gamma(c)/gamma(a)/gamma(c-a)*(-w)^a*_₂F₁logsumalt(a,c-a,z,w)
elseif a-b ∉ ℤ # 15.8.2
gamma(c)*((-w)^a*gamma(b-a)/gamma(b)/gamma(c-a)*_₂F₁maclaurin(a,a-c+1,a-b+1,w)+(-w)^b*gamma(a-b)/gamma(a)/gamma(c-b)*_₂F₁maclaurin(b,b-c+1,b-a+1,w))
else
zero(T) # TODO: full 15.8.8
end
elseif abs(inv(1-z)) ≤ ρ && absarg(-z) < convert(real(T),π)
w = inv(1-z)
if isapprox(a,b) # 15.8.9
gamma(c)*exp(-a*log1p(-z))/gamma(a)/gamma(c-b)*_₂F₁logsum(a,c-a,z,w,1)
elseif a-b ∉ ℤ # 15.8.3
gamma(c)*(exp(-a*log1p(-z))*gamma(b-a)/gamma(b)/gamma(c-a)*_₂F₁maclaurin(a,c-b,a-b+1,w)+exp(-b*log1p(-z))*gamma(a-b)/gamma(a)/gamma(c-b)*_₂F₁maclaurin(b,c-a,b-a+1,w))
else
zero(T) # TODO: full 15.8.9
end
elseif abs(1-z) ≤ ρ && absarg(z) < convert(real(T),π) && absarg(1-z) < convert(real(T),π)
w = 1-z
if isapprox(c,a+b) # 15.8.10
gamma(c)/gamma(a)/gamma(b)*_₂F₁logsum(a,b,z,w,-1)
elseif c-a-b ∉ ℤ # 15.8.4
gamma(c)*(gamma(c-a-b)/gamma(c-a)/gamma(c-b)*_₂F₁maclaurin(a,b,a+b-c+1,w)+exp((c-a-b)*log1p(-z))*gamma(a+b-c)/gamma(a)/gamma(b)*_₂F₁maclaurin(c-a,c-b,c-a-b+1,w))
else
zero(T) # TODO: full 15.8.10
end
elseif abs(1-inv(z)) ≤ ρ && absarg(z) < convert(real(T),π) && absarg(1-z) < convert(real(T),π)
w = 1-inv(z)
if isapprox(c,a+b) # 15.8.11
gamma(c)*z^(-a)/gamma(a)*_₂F₁logsumalt(a,b,z,w)
elseif c-a-b ∉ ℤ # 15.8.5
gamma(c)*(z^(-a)*gamma(c-a-b)/gamma(c-a)/gamma(c-b)*_₂F₁maclaurin(a,a-c+1,a+b-c+1,w)+z^(a-c)*(1-z)^(c-a-b)*gamma(a+b-c)/gamma(a)/gamma(b)*_₂F₁maclaurin(c-a,1-a,c-a-b+1,w))
else
zero(T) # TODO: full 15.8.11
end
elseif abs(z-0.5) > 0.5
if isapprox(a,b) && !isapprox(c,a+0.5)
gamma(c)/gamma(a)/gamma(c-a)*(0.5-z)^(-a)*_₂F₁continuationalt(a,c,0.5,z)
elseif a-b ∉ ℤ
gamma(c)*(gamma(b-a)/gamma(b)/gamma(c-a)*(0.5-z)^(-a)*_₂F₁continuation(a,a+b,c,0.5,z) + gamma(a-b)/gamma(a)/gamma(c-b)*(0.5-z)^(-b)*_₂F₁continuation(b,a+b,c,0.5,z))
else
zero(T)
end
else
zero(T)#throw(DomainError())
end
end
"""
Compute the generalized hypergeometric function `₃F₂(a₁,a₂,a₃;b₁,b₂;z)` with the Maclaurin series.
"""
function _₃F₂(a₁::Number,a₂::Number,a₃::Number,b₁::Number,b₂::Number,z::Number)
if abs(z) ≤ ρ
_₃F₂maclaurin(a₁,a₂,a₃,b₁,b₂,z)
else
zero(z)
end
end
_₃F₂(a₁::Number,a₂::Number,a₃::Number,b₁::Number,b₂::Number,z::AbstractArray) = reshape(promote_type(typeof(a₁),typeof(a₂),typeof(a₃),typeof(b₁),typeof(b₂),eltype(z))[ _₃F₂(a₁,a₂,a₃,b₁,b₂,z[i]) for i in eachindex(z) ], size(z))
_₃F₂(a₁::Number,b₁::Number,z) = _₃F₂(1,1,a₁,2,b₁,z)
"""
Compute the generalized hypergeometric function `mFn(a;b;z)` with the Maclaurin series.
"""
function mFn{S<:Number,V<:Number}(a::AbstractVector{S},b::AbstractVector{V},z::Number)
if abs(z) ≤ ρ || length(a) ≤ length(b)
mFnmaclaurin(a,b,z)
else
zero(promote_type(S,V,typeof(z)))
end
end
mFn{S<:Number,V<:Number}(a::AbstractVector{S},b::AbstractVector{V},z::AbstractArray) = reshape(promote_type(S,V,eltype(z))[ mFn(a,b,z[i]) for i in eachindex(z) ], size(z))
|
-- ---------------------------------------------------------------------
-- Ejercicio. Demostrar eue si
-- |x + 3| < 5
-- entonces
-- -8 < x < 2
-- ----------------------------------------------------------------------
import data.real.basic
-- 1ª demostración
-- ===============
example
(x y : ℝ)
: abs (x + 3) < 5 → -8 < x ∧ x < 2 :=
begin
rw abs_lt,
intro h,
split,
linarith,
linarith,
end
-- Prueba
-- ======
/-
x y : ℝ
⊢ abs (x + 3) < 5 → -8 < x ∧ x < 2
>> rw abs_lt,
⊢ -5 < x + 3 ∧ x + 3 < 5 → -8 < x ∧ x < 2
>> intro h,
h : -5 < x + 3 ∧ x + 3 < 5
⊢ -8 < x ∧ x < 2
>> split,
| ⊢ -8 < x
>> linarith,
⊢ x < 2
>> linarith,
no goals
-/
-- Comentario: El lema usado es
-- + abs_lt: abs a < b ↔ -b < a ∧ a < b
-- 2ª demostración
-- ===============
example
(x y : ℝ)
: abs (x + 3) < 5 → -8 < x ∧ x < 2 :=
begin
rw abs_lt,
intro h,
split; linarith,
end
-- Comentario: La composición (split; linarith) aplica split y a
-- continuación le aplica linarith a cada subojetivo.
|
If $X$ is a countable set and $A$ is a function from $X$ to $M$, then $\bigcup_{x \in X} A(x)$ is in $M$. |
! ###############################################################################################################################
! Begin MIT license text.
! _______________________________________________________________________________________________________
! Copyright 2019 Dr William R Case, Jr ([email protected])
! Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
! associated documentation files (the "Software"), to deal in the Software without restriction, including
! without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
! copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to
! the following conditions:
! The above copyright notice and this permission notice shall be included in all copies or substantial
! portions of the Software and documentation.
! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
! OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
! THE SOFTWARE.
! _______________________________________________________________________________________________________
! End MIT license text.
MODULE TRANSFORM_NODE_FORCES_Interface
INTERFACE
SUBROUTINE TRANSFORM_NODE_FORCES ( COORD_SYS )
USE PENTIUM_II_KIND, ONLY : BYTE, LONG, DOUBLE
USE IOUNT1, ONLY : WRT_ERR, WRT_LOG, ERR, F04, F06
USE SCONTR, ONLY : BLNK_SUB_NAM, MELGP, NCORD
USE TIMDAT, ONLY : TSEC
USE SUBR_BEGEND_LEVELS, ONLY : TRANSFORM_NODE_FORCES_BEGEND
USE CONSTANTS_1, ONLY : ZERO
USE MODEL_STUF, ONLY : CAN_ELEM_TYPE_OFFSET, GRID, CORD, BGRID, ELDOF, ELGP, OFFDIS, OFFSET, PEB, PEG, PEL, TE, &
TYPE
IMPLICIT NONE
CHARACTER(LEN=*), INTENT(IN) :: COORD_SYS ! 'B" for basic, 'G' for global
INTEGER(LONG), PARAMETER :: NCOLA = 3 ! An input to subr MATMULT_FFF called herein
INTEGER(LONG), PARAMETER :: NCOLB = 1 ! An input to subr MATMULT_FFF called herein
INTEGER(LONG), PARAMETER :: NROWA = 3 ! An input to subr MATMULT_FFF called herein
INTEGER(LONG), PARAMETER :: NROW = 3 ! An input to subr MATPUT, MATGET called herein
INTEGER(LONG), PARAMETER :: NCOL = 1 ! An input to subr MATPUT, MATGET called herein
INTEGER(LONG), PARAMETER :: PCOL = 1 ! An input to subr MATPUT, MATGET called herein
INTEGER(LONG), PARAMETER :: SUBR_BEGEND = TRANSFORM_NODE_FORCES_BEGEND
REAL(DOUBLE) :: THETAD,PHID ! Returns from subr GEN_T0L (not used here)
END SUBROUTINE TRANSFORM_NODE_FORCES
END INTERFACE
END MODULE TRANSFORM_NODE_FORCES_Interface
|
!
! (c) 2019 Guide Star Engineering, LLC
! This Software was developed for the US Nuclear Regulatory Commission (US NRC)
! under contract "Multi-Dimensional Physics Implementation into Fuel Analysis under
! Steady-state and Transients (FAST)", contract # NRC-HQ-60-17-C-0007
!
!
! NEMO - Numerical Engine (for) Multiphysics Operators
! Copyright (c) 2007, Stefano Toninel
! Gian Marco Bianchi University of Bologna
! David P. Schmidt University of Massachusetts - Amherst
! Salvatore Filippone University of Rome Tor Vergata
! All rights reserved.
!
! Redistribution and use in source and binary forms, with or without modification,
! are permitted provided that the following conditions are met:
!
! 1. Redistributions of source code must retain the above copyright notice,
! this list of conditions and the following disclaimer.
! 2. Redistributions in binary form must reproduce the above copyright notice,
! this list of conditions and the following disclaimer in the documentation
! and/or other materials provided with the distribution.
! 3. Neither the name of the NEMO project nor the names of its contributors
! may be used to endorse or promote products derived from this software
! without specific prior written permission.
!
! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
! ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
! WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
! DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
! ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
! (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
! LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
! ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
! (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
! SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
!
!---------------------------------------------------------------------------------
!
! $Id: part_random.f90 8157 2014-10-09 13:02:44Z sfilippo $
!
! Description:
! Random partitioning
!
SUBMODULE(part_random) part_random_procedures
USE class_psblas
IMPLICIT NONE
CONTAINS
MODULE PROCEDURE bld_part_random
!
INTEGER :: ic, icontxt, info, mypnum, n
REAL(psb_dpk_) :: alpha
REAL(psb_dpk_) :: load(0:(nprocs-1))
icontxt = icontxt_()
mypnum = mypnum_()
!!$
!!$ if(associated(part) .and. size(part) /= ncells) then
!!$ deallocate(part)
!!$ part => null()
!!$ end if
!!$
!!$ if(.not.associated(part)) then
ALLOCATE(part(ncells),stat=info)
IF(info /= 0) THEN
WRITE(*,100)
CALL abort_psblas
END IF
!!$ end if
IF(mypnum == 0) THEN
WRITE(*,200)
WRITE(*,300,advance='no') 'RANDOM'
END IF
! RANDOM partitioning
n = nprocs - 1
DO ic = 1, ncells
CALL random_NUMBER(alpha)
part(ic) = NINT(alpha * n)
END DO
! Computes load of single processes
load = 0.d0
DO ic=0,n
load(ic) = COUNT(part==ic)
load(ic) = REAL(load(ic)) / REAL(ncells) * 100
ENDDO
WRITE(*,400) load
100 FORMAT(' ERROR! Memory allocation failure in BLD_PART_RANDOM')
200 FORMAT(' Domain Partitioning',5x,'Load')
300 FORMAT(1x,a)
400 FORMAT(15x,16(3x,f5.1,'%'))
END PROCEDURE bld_part_random
END SUBMODULE part_random_procedures
|
[STATEMENT]
lemma sgn_integer_code [code]:
"sgn k = (if k = 0 then 0 else if (k::integer) < 0 then - 1 else 1)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. sgn k = (if k = 0 then 0 else if k < 0 then - 1 else 1)
[PROOF STEP]
by simp |
associate(x => y)
endassociate
associate(x => (y))
end associate
associate(x => y+z)
end associate
associate(x => -y)
end associate
call some_subroutine(x, (x))
x = f((x))
|
/-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Deniz Aydin, Floris van Doorn, Mario Carneiro
-/
import Std.Classes.Cast
import Std.Data.Nat.Lemmas
import Std.Data.Int.Basic
import Std.Data.Option.Basic
import Std.Tactic.NormCast.Lemmas
import Std.Tactic.RCases
open Nat
namespace Int
@[simp] theorem ofNat_eq_coe : ofNat n = Nat.cast n := rfl
@[simp] theorem ofNat_zero : ((0 : Nat) : Int) = 0 := rfl
@[simp] theorem ofNat_one : ((1 : Nat) : Int) = 1 := rfl
@[simp] theorem default_eq_zero : default = (0 : Int) := rfl
/- ## Definitions of basic functions -/
theorem subNatNat_of_sub_eq_zero {m n : Nat} (h : n - m = 0) : subNatNat m n = ↑(m - n) := by
rw [subNatNat, h, ofNat_eq_coe]
theorem subNatNat_of_sub_eq_succ {m n k : Nat} (h : n - m = succ k) : subNatNat m n = -[k+1] := by
rw [subNatNat, h]
@[local simp] protected theorem neg_zero : -(0:Int) = 0 := rfl
theorem ofNat_add (n m : Nat) : (↑(n + m) : Int) = n + m := rfl
theorem ofNat_mul (n m : Nat) : (↑(n * m) : Int) = n * m := rfl
theorem ofNat_succ (n : Nat) : (succ n : Int) = n + 1 := rfl
@[local simp] theorem neg_ofNat_zero : -((0 : Nat) : Int) = 0 := rfl
@[local simp] theorem neg_ofNat_succ (n : Nat) : -(succ n : Int) = -[n+1] := rfl
@[local simp] theorem neg_negSucc (n : Nat) : -(-[n+1]) = succ n := rfl
theorem negSucc_coe (n : Nat) : -[n+1] = -↑(n + 1) := rfl
theorem negOfNat_eq : negOfNat n = -ofNat n := rfl
/- ## These are only for internal use -/
@[simp] theorem add_def {a b : Int} : Int.add a b = a + b := rfl
@[simp] theorem ofNat_add_ofNat (m n : Nat) : (↑m + ↑n : Int) = ↑(m + n) := rfl
@[simp] theorem ofNat_add_negSucc (m n : Nat) : ↑m + -[n+1] = subNatNat m (succ n) := rfl
@[simp] theorem negSucc_add_ofNat (m n : Nat) : -[m+1] + ↑n = subNatNat n (succ m) := rfl
@[simp] theorem negSucc_add_negSucc (m n : Nat) : -[m+1] + -[n+1] = -[succ (m + n) +1] := rfl
@[simp] theorem mul_def {a b : Int} : Int.mul a b = a * b := rfl
@[local simp] theorem ofNat_mul_ofNat (m n : Nat) : (↑m * ↑n : Int) = ↑(m * n) := rfl
@[local simp] theorem ofNat_mul_negSucc' (m n : Nat) : ↑m * -[n+1] = negOfNat (m * succ n) := rfl
@[local simp] theorem negSucc_mul_ofNat' (m n : Nat) : -[m+1] * ↑n = negOfNat (succ m * n) := rfl
@[local simp] theorem negSucc_mul_negSucc' (m n : Nat) :
-[m+1] * -[n+1] = ofNat (succ m * succ n) := rfl
/- ## some basic functions and properties -/
theorem ofNat_inj : ((m : Nat) : Int) = (n : Nat) ↔ m = n := ⟨ofNat.inj, congrArg _⟩
theorem ofNat_eq_zero : ((n : Nat) : Int) = 0 ↔ n = 0 := ofNat_inj
theorem ofNat_ne_zero : ((n : Nat) : Int) ≠ 0 ↔ n ≠ 0 := not_congr ofNat_eq_zero
theorem negSucc_inj : negSucc m = negSucc n ↔ m = n := ⟨negSucc.inj, fun H => by simp [H]⟩
theorem negSucc_eq (n : Nat) : -[n+1] = -((n : Int) + 1) := rfl
@[simp] theorem negSucc_ne_zero (n : Nat) : -[n+1] ≠ 0 := fun.
@[simp] theorem zero_ne_negSucc (n : Nat) : 0 ≠ -[n+1] := fun.
/- ## neg -/
@[simp] protected theorem neg_neg : ∀ a : Int, -(-a) = a
| 0 => rfl
| succ _ => rfl
| -[_+1] => rfl
protected theorem neg_inj {a b : Int} : -a = -b ↔ a = b :=
⟨fun h => by rw [← Int.neg_neg a, ← Int.neg_neg b, h], congrArg _⟩
protected theorem neg_eq_zero : -a = 0 ↔ a = 0 := Int.neg_inj (b := 0)
protected theorem neg_ne_zero : -a ≠ 0 ↔ a ≠ 0 := not_congr Int.neg_eq_zero
protected theorem sub_eq_add_neg {a b : Int} : a - b = a + -b := rfl
theorem add_neg_one (i : Int) : i + -1 = i - 1 := rfl
/- ## basic properties of subNatNat -/
-- @[elabAsElim] -- TODO(Mario): unexpected eliminator resulting type
theorem subNatNat_elim (m n : Nat) (motive : Nat → Nat → Int → Prop)
(hp : ∀ i n, motive (n + i) n i)
(hn : ∀ i m, motive m (m + i + 1) -[i+1]) :
motive m n (subNatNat m n) := by
unfold subNatNat
match h : n - m with
| 0 =>
have ⟨k, h⟩ := Nat.le.dest (Nat.le_of_sub_eq_zero h)
rw [h.symm, Nat.add_sub_cancel_left]; apply hp
| succ k =>
rw [Nat.sub_eq_iff_eq_add (Nat.le_of_lt (Nat.lt_of_sub_eq_succ h))] at h
rw [h, Nat.add_comm]; apply hn
theorem subNatNat_add_left : subNatNat (m + n) m = n := by
unfold subNatNat
rw [Nat.sub_eq_zero_of_le (Nat.le_add_right ..), Nat.add_sub_cancel_left, ofNat_eq_coe]
theorem subNatNat_add_right : subNatNat m (m + n + 1) = negSucc n := by
simp [subNatNat, Nat.add_assoc, Nat.add_sub_cancel_left]
theorem subNatNat_add_add (m n k : Nat) : subNatNat (m + k) (n + k) = subNatNat m n := by
apply subNatNat_elim m n (fun m n i => subNatNat (m + k) (n + k) = i)
· intro i j
rw [Nat.add_assoc, Nat.add_comm i k, ← Nat.add_assoc]
exact subNatNat_add_left
· intro i j
rw [Nat.add_assoc j i 1, Nat.add_comm j (i+1), Nat.add_assoc, Nat.add_comm (i+1) (j+k)]
exact subNatNat_add_right
theorem subNatNat_of_le {m n : Nat} (h : n ≤ m) : subNatNat m n = ↑(m - n) :=
subNatNat_of_sub_eq_zero (Nat.sub_eq_zero_of_le h)
theorem subNatNat_of_lt {m n : Nat} (h : m < n) : subNatNat m n = -[pred (n - m) +1] :=
subNatNat_of_sub_eq_succ <| (Nat.succ_pred_eq_of_pos (Nat.sub_pos_of_lt h)).symm
/- ## natAbs -/
@[simp] theorem natAbs_ofNat (n : Nat) : natAbs ↑n = n := rfl
@[simp] theorem natAbs_negSucc (n : Nat) : natAbs -[n+1] = n.succ := rfl
@[simp] theorem natAbs_zero : natAbs (0 : Int) = (0 : Nat) := rfl
@[simp] theorem natAbs_one : natAbs (1 : Int) = (1 : Nat) := rfl
@[simp] theorem natAbs_eq_zero : natAbs a = 0 ↔ a = 0 :=
⟨fun H => match a with
| ofNat _ => congrArg ofNat H
| -[_+1] => absurd H (succ_ne_zero _),
fun e => e ▸ rfl⟩
theorem natAbs_ne_zero {a : Int} : a.natAbs ≠ 0 ↔ a ≠ 0 := not_congr Int.natAbs_eq_zero
theorem natAbs_pos : 0 < natAbs a ↔ a ≠ 0 := by rw [Nat.pos_iff_ne_zero, Ne, natAbs_eq_zero]
theorem natAbs_mul_self : ∀ {a : Int}, ↑(natAbs a * natAbs a) = a * a
| ofNat _ => rfl
| -[_+1] => rfl
@[simp] theorem natAbs_neg : ∀ (a : Int), natAbs (-a) = natAbs a
| 0 => rfl
| succ _ => rfl
| -[_+1] => rfl
theorem natAbs_eq : ∀ (a : Int), a = natAbs a ∨ a = -↑(natAbs a)
| ofNat _ => Or.inl rfl
| -[_+1] => Or.inr rfl
theorem eq_nat_or_neg (a : Int) : ∃ n : Nat, a = n ∨ a = -↑n := ⟨_, natAbs_eq a⟩
theorem natAbs_negOfNat (n : Nat) : natAbs (negOfNat n) = n := by
cases n <;> rfl
theorem natAbs_mul (a b : Int) : natAbs (a * b) = natAbs a * natAbs b := by
cases a <;> cases b <;>
simp only [← Int.mul_def, Int.mul, natAbs_negOfNat] <;> simp only [natAbs]
theorem natAbs_mul_natAbs_eq {a b : Int} {c : Nat}
(h : a * b = (c : Int)) : a.natAbs * b.natAbs = c := by rw [← natAbs_mul, h, natAbs]
@[simp] theorem natAbs_mul_self' (a : Int) : (natAbs a * natAbs a : Int) = a * a := by
rw [← Int.ofNat_mul, natAbs_mul_self]
theorem natAbs_eq_natAbs_iff {a b : Int} : a.natAbs = b.natAbs ↔ a = b ∨ a = -b := by
constructor <;> intro h
· cases Int.natAbs_eq a with
| inl h₁ | inr h₁ =>
cases Int.natAbs_eq b with
| inl h₂ | inr h₂ => rw [h₁, h₂]; simp [h]
· cases h with (subst a; try rfl)
| inr h => rw [Int.natAbs_neg]
theorem natAbs_eq_iff {a : Int} {n : Nat} : a.natAbs = n ↔ a = n ∨ a = -↑n := by
rw [← Int.natAbs_eq_natAbs_iff, Int.natAbs_ofNat]
/- ## sign -/
@[simp] theorem sign_zero : sign 0 = 0 := rfl
@[simp] theorem sign_one : sign 1 = 1 := rfl
theorem sign_neg_one : sign (-1) = -1 := rfl
theorem sign_of_succ (n : Nat) : sign (Nat.succ n) = 1 := rfl
theorem natAbs_sign (z : Int) : z.sign.natAbs = if z = 0 then 0 else 1 :=
match z with | 0 | succ _ | -[_+1] => rfl
theorem natAbs_sign_of_nonzero {z : Int} (hz : z ≠ 0) : z.sign.natAbs = 1 := by
rw [Int.natAbs_sign, if_neg hz]
theorem sign_ofNat_of_nonzero {n : Nat} (hn : n ≠ 0) : Int.sign n = 1 :=
match n, Nat.exists_eq_succ_of_ne_zero hn with
| _, ⟨n, rfl⟩ => Int.sign_of_succ n
@[simp] theorem sign_neg (z : Int) : Int.sign (-z) = -Int.sign z := by
match z with | 0 | succ _ | -[_+1] => rfl
/- # ring properties -/
/- addition -/
protected theorem add_comm : ∀ a b : Int, a + b = b + a
| ofNat n, ofNat m => by simp [Nat.add_comm]
| ofNat _, -[_+1] => rfl
| -[_+1], ofNat _ => rfl
| -[_+1], -[_+1] => by simp [Nat.add_comm]
@[local simp] protected theorem add_zero : ∀ a : Int, a + 0 = a
| ofNat _ => rfl
| -[_+1] => rfl
@[local simp] protected theorem zero_add (a : Int) : 0 + a = a := Int.add_comm .. ▸ a.add_zero
theorem ofNat_add_negSucc_of_lt (h : m < n.succ) : ofNat m + -[n+1] = -[n - m+1] :=
show subNatNat .. = _ by simp [succ_sub (le_of_lt_succ h), subNatNat]
theorem subNatNat_sub (h : n ≤ m) (k : Nat) : subNatNat (m - n) k = subNatNat m (k + n) := by
rwa [← subNatNat_add_add _ _ n, Nat.sub_add_cancel]
theorem subNatNat_add (m n k : Nat) : subNatNat (m + n) k = m + subNatNat n k := by
cases n.lt_or_ge k with
| inl h' =>
simp [subNatNat_of_lt h', succ_pred_eq_of_pos (Nat.sub_pos_of_lt h')]
conv => lhs; rw [← Nat.sub_add_cancel (Nat.le_of_lt h')]
apply subNatNat_add_add
| inr h' => simp [subNatNat_of_le h',
subNatNat_of_le (Nat.le_trans h' (le_add_left ..)), Nat.add_sub_assoc h']
theorem subNatNat_add_negSucc (m n k : Nat) :
subNatNat m n + -[k+1] = subNatNat m (n + succ k) := by
have h := Nat.lt_or_ge m n
cases h with
| inr h' =>
rw [subNatNat_of_le h']
simp
rw [subNatNat_sub h', Nat.add_comm]
| inl h' =>
have h₂ : m < n + succ k := Nat.lt_of_lt_of_le h' (le_add_right _ _)
have h₃ : m ≤ n + k := le_of_succ_le_succ h₂
rw [subNatNat_of_lt h', subNatNat_of_lt h₂]
simp [Nat.add_comm]
rw [← add_succ, succ_pred_eq_of_pos (Nat.sub_pos_of_lt h'), add_succ, succ_sub h₃, Nat.pred_succ]
rw [Nat.add_comm n, Nat.add_sub_assoc (Nat.le_of_lt h')]
protected theorem add_assoc : ∀ a b c : Int, a + b + c = a + (b + c)
| (m:Nat), (n:Nat), c => aux1 ..
| Nat.cast m, b, Nat.cast k => by
rw [Int.add_comm, ← aux1, Int.add_comm k, aux1, Int.add_comm b]
| a, (n:Nat), (k:Nat) => by
rw [Int.add_comm, Int.add_comm a, ← aux1, Int.add_comm a, Int.add_comm k]
| -[m+1], -[n+1], (k:Nat) => aux2 ..
| -[m+1], (n:Nat), -[k+1] => by
rw [Int.add_comm, ← aux2, Int.add_comm n, ← aux2, Int.add_comm -[m+1]]
| (m:Nat), -[n+1], -[k+1] => by
rw [Int.add_comm, Int.add_comm m, Int.add_comm m, ← aux2, Int.add_comm -[k+1]]
| -[m+1], -[n+1], -[k+1] => by
simp [add_succ, Nat.add_comm, Nat.add_left_comm, neg_ofNat_succ]
where
aux1 (m n : Nat) : ∀ c : Int, m + n + c = m + (n + c)
| (k:Nat) => by simp [Nat.add_assoc]
| -[k+1] => by simp [subNatNat_add]
aux2 (m n k : Nat) : -[m+1] + -[n+1] + k = -[m+1] + (-[n+1] + k) := by
simp [add_succ]
rw [Int.add_comm, subNatNat_add_negSucc]
simp [add_succ, succ_add, Nat.add_comm]
protected theorem add_left_comm (a b c : Int) : a + (b + c) = b + (a + c) := by
rw [← Int.add_assoc, Int.add_comm a, Int.add_assoc]
protected theorem add_right_comm (a b c : Int) : a + b + c = a + c + b := by
rw [Int.add_assoc, Int.add_comm b, ← Int.add_assoc]
/- ## negation -/
theorem subNatNat_self : ∀ n, subNatNat n n = 0
| 0 => rfl
| succ m => by rw [subNatNat_of_sub_eq_zero (Nat.sub_self ..), Nat.sub_self, ofNat_zero]
attribute [local simp] subNatNat_self
@[local simp] protected theorem add_left_neg : ∀ a : Int, -a + a = 0
| 0 => rfl
| succ m => by simp
| -[m+1] => by simp
@[local simp] protected theorem add_right_neg (a : Int) : a + -a = 0 := by
rw [Int.add_comm, Int.add_left_neg]
@[simp] protected theorem neg_eq_of_add_eq_zero {a b : Int} (h : a + b = 0) : -a = b := by
rw [← Int.add_zero (-a), ← h, ← Int.add_assoc, Int.add_left_neg, Int.zero_add]
protected theorem eq_neg_of_eq_neg {a b : Int} (h : a = -b) : b = -a := by
rw [h, Int.neg_neg]
protected theorem eq_neg_comm {a b : Int} : a = -b ↔ b = -a :=
⟨Int.eq_neg_of_eq_neg, Int.eq_neg_of_eq_neg⟩
protected theorem neg_eq_comm {a b : Int} : -a = b ↔ -b = a := by
rw [eq_comm, Int.eq_neg_comm, eq_comm]
protected theorem neg_add_cancel_left (a b : Int) : -a + (a + b) = b := by
rw [← Int.add_assoc, Int.add_left_neg, Int.zero_add]
protected theorem add_neg_cancel_left (a b : Int) : a + (-a + b) = b := by
rw [← Int.add_assoc, Int.add_right_neg, Int.zero_add]
protected theorem add_neg_cancel_right (a b : Int) : a + b + -b = a := by
rw [Int.add_assoc, Int.add_right_neg, Int.add_zero]
protected theorem neg_add_cancel_right (a b : Int) : a + -b + b = a := by
rw [Int.add_assoc, Int.add_left_neg, Int.add_zero]
protected theorem add_left_cancel {a b c : Int} (h : a + b = a + c) : b = c := by
have h₁ : -a + (a + b) = -a + (a + c) := by rw [h]
simp [← Int.add_assoc, Int.add_left_neg, Int.zero_add] at h₁; exact h₁
@[local simp] protected theorem neg_add {a b : Int} : -(a + b) = -a + -b := by
apply Int.add_left_cancel (a := a + b)
rw [Int.add_right_neg, Int.add_comm a, ← Int.add_assoc, Int.add_assoc b,
Int.add_right_neg, Int.add_zero, Int.add_right_neg]
/- ## subtraction -/
@[simp] theorem negSucc_sub_one (n : Nat) : -[n+1] - 1 = -[n + 1 +1] := rfl
protected theorem sub_self (a : Int) : a - a = 0 := by
rw [Int.sub_eq_add_neg, Int.add_right_neg]
protected theorem sub_zero (a : Int) : a - 0 = a := by simp [Int.sub_eq_add_neg]
protected theorem zero_sub (a : Int) : 0 - a = -a := by simp [Int.sub_eq_add_neg]
protected theorem sub_eq_zero_of_eq {a b : Int} (h : a = b) : a - b = 0 := by
rw [h, Int.sub_self]
protected theorem eq_of_sub_eq_zero {a b : Int} (h : a - b = 0) : a = b := by
have : 0 + b = b := by rw [Int.zero_add]
have : a - b + b = b := by rwa [h]
rwa [Int.sub_eq_add_neg, Int.neg_add_cancel_right] at this
protected theorem sub_eq_zero {a b : Int} : a - b = 0 ↔ a = b :=
⟨Int.eq_of_sub_eq_zero, Int.sub_eq_zero_of_eq⟩
protected theorem sub_sub (a b c : Int) : a - b - c = a - (b + c) := by
simp [Int.sub_eq_add_neg, Int.add_assoc]
protected theorem neg_sub (a b : Int) : -(a - b) = b - a := by
simp [Int.sub_eq_add_neg, Int.add_comm]
protected theorem sub_sub_self (a b : Int) : a - (a - b) = b := by
simp [Int.sub_eq_add_neg, ← Int.add_assoc]
protected theorem sub_neg (a b : Int) : a - -b = a + b := by simp [Int.sub_eq_add_neg]
/- ## multiplication -/
@[simp] theorem ofNat_mul_negSucc (m n : Nat) : (m : Int) * -[n+1] = -↑(m * succ n) := rfl
@[simp] theorem negSucc_mul_ofNat (m n : Nat) : -[m+1] * n = -↑(succ m * n) := rfl
@[simp] theorem negSucc_mul_negSucc (m n : Nat) : -[m+1] * -[n+1] = succ m * succ n := rfl
protected theorem mul_comm (a b : Int) : a * b = b * a := by
cases a <;> cases b <;> simp [Nat.mul_comm]
theorem ofNat_mul_negOfNat (m n : Nat) : (m : Nat) * negOfNat n = negOfNat (m * n) := by
cases n <;> rfl
theorem negOfNat_mul_ofNat (m n : Nat) : negOfNat m * (n : Nat) = negOfNat (m * n) := by
rw [Int.mul_comm]; simp [ofNat_mul_negOfNat, Nat.mul_comm]
theorem negSucc_mul_negOfNat (m n : Nat) : -[m+1] * negOfNat n = ofNat (succ m * n) := by
cases n <;> rfl
theorem negOfNat_mul_negSucc (m n : Nat) : negOfNat n * -[m+1] = ofNat (n * succ m) := by
rw [Int.mul_comm, negSucc_mul_negOfNat, Nat.mul_comm]
attribute [local simp] ofNat_mul_negOfNat negOfNat_mul_ofNat
negSucc_mul_negOfNat negOfNat_mul_negSucc
protected theorem mul_assoc (a b c : Int) : a * b * c = a * (b * c) := by
cases a <;> cases b <;> cases c <;> simp [Nat.mul_assoc]
protected theorem mul_left_comm (a b c : Int) : a * (b * c) = b * (a * c) := by
rw [← Int.mul_assoc, ← Int.mul_assoc, Int.mul_comm a]
protected theorem mul_right_comm (a b c : Int) : a * b * c = a * c * b := by
rw [Int.mul_assoc, Int.mul_assoc, Int.mul_comm b]
@[simp] protected theorem mul_zero (a : Int) : a * 0 = 0 := by cases a <;> rfl
@[simp] protected theorem zero_mul (a : Int) : 0 * a = 0 := Int.mul_comm .. ▸ a.mul_zero
theorem negOfNat_eq_subNatNat_zero (n) : negOfNat n = subNatNat 0 n := by cases n <;> rfl
theorem ofNat_mul_subNatNat (m n k : Nat) :
m * subNatNat n k = subNatNat (m * n) (m * k) := by
cases m with
| zero => simp [ofNat_zero, Int.zero_mul, Nat.zero_mul]
| succ m => cases n.lt_or_ge k with
| inl h =>
have h' : succ m * n < succ m * k := Nat.mul_lt_mul_of_pos_left h (Nat.succ_pos m)
simp [subNatNat_of_lt h, subNatNat_of_lt h']
rw [succ_pred_eq_of_pos (Nat.sub_pos_of_lt h), ← neg_ofNat_succ, Nat.mul_sub_left_distrib,
← succ_pred_eq_of_pos (Nat.sub_pos_of_lt h')]; rfl
| inr h =>
have h' : succ m * k ≤ succ m * n := Nat.mul_le_mul_left _ h
simp [subNatNat_of_le h, subNatNat_of_le h', Nat.mul_sub_left_distrib]
theorem negOfNat_add (m n : Nat) : negOfNat m + negOfNat n = negOfNat (m + n) := by
cases m <;> cases n <;> simp [Nat.succ_add] <;> rfl
theorem negSucc_mul_subNatNat (m n k : Nat) :
-[m+1] * subNatNat n k = subNatNat (succ m * k) (succ m * n) := by
cases n.lt_or_ge k with
| inl h =>
have h' : succ m * n < succ m * k := Nat.mul_lt_mul_of_pos_left h (Nat.succ_pos m)
rw [subNatNat_of_lt h, subNatNat_of_le (Nat.le_of_lt h')]
simp [succ_pred_eq_of_pos (Nat.sub_pos_of_lt h), Nat.mul_sub_left_distrib]
| inr h => cases Nat.lt_or_ge k n with
| inl h' =>
have h₁ : succ m * n > succ m * k := Nat.mul_lt_mul_of_pos_left h' (Nat.succ_pos m)
rw [subNatNat_of_le h, subNatNat_of_lt h₁, negSucc_mul_ofNat,
Nat.mul_sub_left_distrib, ← succ_pred_eq_of_pos (Nat.sub_pos_of_lt h₁)]; rfl
| inr h' => rw [Nat.le_antisymm h h', subNatNat_self, subNatNat_self, Int.mul_zero]
attribute [local simp] ofNat_mul_subNatNat negOfNat_add negSucc_mul_subNatNat
protected theorem mul_add : ∀ a b c : Int, a * (b + c) = a * b + a * c
| (m:Nat), (n:Nat), (k:Nat) => by simp [Nat.left_distrib]
| (m:Nat), (n:Nat), -[k+1] => by
simp [negOfNat_eq_subNatNat_zero]; rw [← subNatNat_add]; rfl
| (m:Nat), -[n+1], (k:Nat) => by
simp [negOfNat_eq_subNatNat_zero]; rw [Int.add_comm, ← subNatNat_add]; rfl
| (m:Nat), -[n+1], -[k+1] => by simp; rw [← Nat.left_distrib, succ_add]; rfl
| -[m+1], (n:Nat), (k:Nat) => by simp [Nat.mul_comm]; rw [← Nat.right_distrib, Nat.mul_comm]
| -[m+1], (n:Nat), -[k+1] => by
simp [negOfNat_eq_subNatNat_zero]; rw [Int.add_comm, ← subNatNat_add]; rfl
| -[m+1], -[n+1], (k:Nat) => by simp [negOfNat_eq_subNatNat_zero]; rw [← subNatNat_add]; rfl
| -[m+1], -[n+1], -[k+1] => by simp; rw [← Nat.left_distrib, succ_add]; rfl
protected theorem add_mul (a b c : Int) : (a + b) * c = a * c + b * c := by
simp [Int.mul_comm, Int.mul_add]
protected theorem neg_mul_eq_neg_mul (a b : Int) : -(a * b) = -a * b :=
Int.neg_eq_of_add_eq_zero <| by rw [← Int.add_mul, Int.add_right_neg, Int.zero_mul]
protected theorem neg_mul_eq_mul_neg (a b : Int) : -(a * b) = a * -b :=
Int.neg_eq_of_add_eq_zero <| by rw [← Int.mul_add, Int.add_right_neg, Int.mul_zero]
@[local simp] protected theorem neg_mul (a b : Int) : -a * b = -(a * b) :=
(Int.neg_mul_eq_neg_mul a b).symm
@[local simp] protected theorem mul_neg (a b : Int) : a * -b = -(a * b) :=
(Int.neg_mul_eq_mul_neg a b).symm
protected theorem neg_mul_neg (a b : Int) : -a * -b = a * b := by simp
protected theorem neg_mul_comm (a b : Int) : -a * b = a * -b := by simp
protected theorem mul_sub (a b c : Int) : a * (b - c) = a * b - a * c := by
simp [Int.sub_eq_add_neg, Int.mul_add]
protected theorem sub_mul (a b c : Int) : (a - b) * c = a * c - b * c := by
simp [Int.sub_eq_add_neg, Int.add_mul]
protected theorem zero_ne_one : (0 : Int) ≠ 1 := fun.
@[simp] protected theorem sub_add_cancel (a b : Int) : a - b + b = a :=
Int.neg_add_cancel_right a b
@[simp] protected theorem add_sub_cancel (a b : Int) : a + b - b = a :=
Int.add_neg_cancel_right a b
protected theorem add_sub_assoc (a b c : Int) : a + b - c = a + (b - c) := by
rw [Int.sub_eq_add_neg, Int.add_assoc, ← Int.sub_eq_add_neg]
theorem ofNat_sub (h : m ≤ n) : ((n - m : Nat) : Int) = n - m := by
match m with
| 0 => rfl
| succ m =>
show ofNat (n - succ m) = subNatNat n (succ m)
rw [subNatNat, Nat.sub_eq_zero_of_le h]
theorem negSucc_coe' (n : Nat) : -[n+1] = -↑n - 1 := by
rw [Int.sub_eq_add_neg, ← Int.neg_add]; rfl
protected theorem subNatNat_eq_coe {m n : Nat} : subNatNat m n = ↑m - ↑n := by
apply subNatNat_elim m n fun m n i => i = m - n
· intros i n
rw [Int.ofNat_add, Int.sub_eq_add_neg, Int.add_assoc, Int.add_left_comm,
Int.add_right_neg, Int.add_zero]
· intros i n
simp only [negSucc_coe, ofNat_add, Int.sub_eq_add_neg, Int.neg_add, ← Int.add_assoc]
rw [← @Int.sub_eq_add_neg n, ← ofNat_sub, Nat.sub_self, ofNat_zero, Int.zero_add]
apply Nat.le_refl
theorem toNat_sub (m n : Nat) : toNat (m - n) = m - n := by
rw [← Int.subNatNat_eq_coe]
refine subNatNat_elim m n (fun m n i => toNat i = m - n) (fun i n => ?_) (fun i n => ?_)
· exact (Nat.add_sub_cancel_left ..).symm
· dsimp; rw [Nat.add_assoc, Nat.sub_eq_zero_of_le (Nat.le_add_right ..)]; rfl
@[simp] protected theorem one_mul : ∀ a : Int, 1 * a = a
| ofNat n => show ofNat (1 * n) = ofNat n by rw [Nat.one_mul]
| -[n+1] => show -[1 * n +1] = -[n+1] by rw [Nat.one_mul]
@[simp] protected theorem mul_one (a : Int) : a * 1 = a := by rw [Int.mul_comm, Int.one_mul]
protected theorem mul_neg_one (a : Int) : a * -1 = -a := by rw [Int.mul_neg, Int.mul_one]
protected theorem neg_eq_neg_one_mul : ∀ a : Int, -a = -1 * a
| 0 => rfl
| succ n => show _ = -[1 * n +1] by rw [Nat.one_mul]; rfl
| -[n+1] => show _ = ofNat _ by rw [Nat.one_mul]; rfl
theorem sign_mul_natAbs : ∀ a : Int, sign a * natAbs a = a
| 0 => rfl
| succ _ => Int.one_mul _
| -[_+1] => (Int.neg_eq_neg_one_mul _).symm
@[simp] theorem sign_mul : ∀ a b, sign (a * b) = sign a * sign b
| a, 0 | 0, b => by simp [Int.mul_zero, Int.zero_mul]
| succ _, succ _ | succ _, -[_+1] | -[_+1], succ _ | -[_+1], -[_+1] => rfl
/-! ## Order properties of the integers -/
theorem nonneg_def {a : Int} : NonNeg a ↔ ∃ n : Nat, a = n :=
⟨fun ⟨n⟩ => ⟨n, rfl⟩, fun h => match a, h with | _, ⟨n, rfl⟩ => ⟨n⟩⟩
theorem NonNeg.elim {a : Int} : NonNeg a → ∃ n : Nat, a = n := nonneg_def.1
theorem nonneg_or_nonneg_neg : ∀ (a : Int), NonNeg a ∨ NonNeg (-a)
| (_:Nat) => .inl ⟨_⟩
| -[_+1] => .inr ⟨_⟩
theorem le_def (a b : Int) : a ≤ b ↔ NonNeg (b - a) := .rfl
theorem lt_iff_add_one_le (a b : Int) : a < b ↔ a + 1 ≤ b := .rfl
theorem le.intro_sub {a b : Int} (n : Nat) (h : b - a = n) : a ≤ b := by
simp [le_def, h]; constructor
theorem le.intro {a b : Int} (n : Nat) (h : a + n = b) : a ≤ b :=
le.intro_sub n <| by rw [← h, Int.add_comm]; simp [Int.sub_eq_add_neg, Int.add_assoc]
theorem le.dest_sub {a b : Int} (h : a ≤ b) : ∃ n : Nat, b - a = n := nonneg_def.1 h
theorem le.dest {a b : Int} (h : a ≤ b) : ∃ n : Nat, a + n = b :=
let ⟨n, h₁⟩ := le.dest_sub h
⟨n, by rw [← h₁, Int.add_comm]; simp [Int.sub_eq_add_neg, Int.add_assoc]⟩
protected theorem le_total (a b : Int) : a ≤ b ∨ b ≤ a :=
(nonneg_or_nonneg_neg (b - a)).imp_right fun H => by
rwa [show -(b - a) = a - b by simp [Int.add_comm, Int.sub_eq_add_neg]] at H
@[simp, norm_cast] theorem ofNat_le {m n : Nat} : (↑m : Int) ≤ ↑n ↔ m ≤ n :=
⟨fun h =>
let ⟨k, hk⟩ := le.dest h
Nat.le.intro <| Int.ofNat.inj <| (Int.ofNat_add m k).trans hk,
fun h =>
let ⟨k, (hk : m + k = n)⟩ := Nat.le.dest h
le.intro k (by rw [← hk]; rfl)⟩
theorem ofNat_zero_le (n : Nat) : 0 ≤ (↑n : Int) := ofNat_le.2 n.zero_le
theorem eq_ofNat_of_zero_le {a : Int} (h : 0 ≤ a) : ∃ n : Nat, a = n := by
have t := le.dest_sub h; simp [Int.sub_eq_add_neg] at t; exact t
theorem eq_succ_of_zero_lt {a : Int} (h : 0 < a) : ∃ n : Nat, a = n.succ :=
let ⟨n, (h : ↑(1 + n) = a)⟩ := le.dest h
⟨n, by rw [Nat.add_comm] at h; exact h.symm⟩
theorem lt_add_succ (a : Int) (n : Nat) : a < a + Nat.succ n :=
le.intro n <| by rw [Int.add_comm, Int.add_left_comm]; rfl
theorem lt.intro {a b : Int} {n : Nat} (h : a + Nat.succ n = b) : a < b :=
h ▸ lt_add_succ a n
theorem lt.dest {a b : Int} (h : a < b) : ∃ n : Nat, a + Nat.succ n = b :=
let ⟨n, h⟩ := le.dest h; ⟨n, by rwa [Int.add_comm, Int.add_left_comm] at h⟩
@[simp, norm_cast] theorem ofNat_lt {n m : Nat} : (↑n : Int) < ↑m ↔ n < m := by
rw [lt_iff_add_one_le, ← ofNat_succ, ofNat_le]; rfl
@[simp, norm_cast] theorem ofNat_pos {n : Nat} : 0 < (↑n : Int) ↔ 0 < n := ofNat_lt
theorem ofNat_nonneg (n : Nat) : 0 ≤ (n : Int) := ⟨_⟩
theorem ofNat_succ_pos (n : Nat) : 0 < (succ n : Int) := ofNat_lt.2 <| Nat.succ_pos _
@[simp] protected theorem le_refl (a : Int) : a ≤ a :=
le.intro _ (Int.add_zero a)
protected theorem le_trans {a b c : Int} (h₁ : a ≤ b) (h₂ : b ≤ c) : a ≤ c :=
let ⟨n, hn⟩ := le.dest h₁; let ⟨m, hm⟩ := le.dest h₂
le.intro (n + m) <| by rw [← hm, ← hn, Int.add_assoc, ofNat_add]
protected theorem le_antisymm {a b : Int} (h₁ : a ≤ b) (h₂ : b ≤ a) : a = b := by
let ⟨n, hn⟩ := le.dest h₁; let ⟨m, hm⟩ := le.dest h₂
have := hn; rw [← hm, Int.add_assoc, ← ofNat_add] at this
have := Int.ofNat.inj <| Int.add_left_cancel <| this.trans (Int.add_zero _).symm
rw [← hn, Nat.eq_zero_of_add_eq_zero_left this, ofNat_zero, Int.add_zero a]
protected
protected theorem ne_of_lt {a b : Int} (h : a < b) : a ≠ b := fun e => by
cases e; exact Int.lt_irrefl _ h
protected theorem ne_of_gt {a b : Int} (h : b < a) : a ≠ b := (Int.ne_of_lt h).symm
protected theorem le_of_lt {a b : Int} (h : a < b) : a ≤ b :=
let ⟨_, hn⟩ := lt.dest h; le.intro _ hn
protected theorem lt_iff_le_and_ne {a b : Int} : a < b ↔ a ≤ b ∧ a ≠ b := by
refine ⟨fun h => ⟨Int.le_of_lt h, Int.ne_of_lt h⟩, fun ⟨aleb, aneb⟩ => ?_⟩
let ⟨n, hn⟩ := le.dest aleb
have : n ≠ 0 := aneb.imp fun eq => by rw [← hn, eq, ofNat_zero, Int.add_zero]
apply lt.intro; rwa [← Nat.succ_pred_eq_of_pos (Nat.pos_of_ne_zero this)] at hn
theorem lt_succ (a : Int) : a < a + 1 := Int.le_refl _
protected theorem mul_nonneg {a b : Int} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b := by
let ⟨n, hn⟩ := eq_ofNat_of_zero_le ha
let ⟨m, hm⟩ := eq_ofNat_of_zero_le hb
rw [hn, hm, ← ofNat_mul]; apply ofNat_nonneg
protected theorem mul_pos {a b : Int} (ha : 0 < a) (hb : 0 < b) : 0 < a * b := by
let ⟨n, hn⟩ := eq_succ_of_zero_lt ha
let ⟨m, hm⟩ := eq_succ_of_zero_lt hb
rw [hn, hm, ← ofNat_mul]; apply ofNat_succ_pos
protected theorem zero_lt_one : (0 : Int) < 1 := ⟨_⟩
protected theorem lt_iff_le_not_le {a b : Int} : a < b ↔ a ≤ b ∧ ¬b ≤ a := by
rw [Int.lt_iff_le_and_ne]
constructor <;> refine fun ⟨h, h'⟩ => ⟨h, h'.imp fun h' => ?_⟩
· exact Int.le_antisymm h h'
· subst h'; apply Int.le_refl
protected theorem not_le {a b : Int} : ¬a ≤ b ↔ b < a :=
⟨fun h => Int.lt_iff_le_not_le.2 ⟨(Int.le_total ..).resolve_right h, h⟩,
fun h => (Int.lt_iff_le_not_le.1 h).2⟩
protected theorem not_lt {a b : Int} : ¬a < b ↔ b ≤ a :=
by rw [← Int.not_le, Decidable.not_not]
protected theorem lt_trichotomy (a b : Int) : a < b ∨ a = b ∨ b < a :=
if eq : a = b then .inr <| .inl eq else
if le : a ≤ b then .inl <| Int.lt_iff_le_and_ne.2 ⟨le, eq⟩ else
.inr <| .inr <| Int.not_le.1 le
protected theorem lt_of_le_of_lt {a b c : Int} (h₁ : a ≤ b) (h₂ : b < c) : a < c :=
Int.not_le.1 fun h => Int.not_le.2 h₂ (Int.le_trans h h₁)
protected theorem lt_of_lt_of_le {a b c : Int} (h₁ : a < b) (h₂ : b ≤ c) : a < c :=
Int.not_le.1 fun h => Int.not_le.2 h₁ (Int.le_trans h₂ h)
protected theorem lt_trans {a b c : Int} (h₁ : a < b) (h₂ : b < c) : a < c :=
Int.lt_of_le_of_lt (Int.le_of_lt h₁) h₂
protected theorem le_of_not_le {a b : Int} : ¬ a ≤ b → b ≤ a := (Int.le_total a b).resolve_left
protected theorem min_def (n m : Int) : min n m = if n ≤ m then n else m := rfl
protected theorem max_def (n m : Int) : max n m = if n ≤ m then m else n := rfl
protected theorem min_comm (a b : Int) : min a b = min b a := by
simp [Int.min_def]
by_cases h₁ : a ≤ b <;> by_cases h₂ : b ≤ a <;> simp [h₁, h₂]
· exact Int.le_antisymm h₁ h₂
· cases not_or_intro h₁ h₂ <| Int.le_total ..
protected theorem min_le_right (a b : Int) : min a b ≤ b := by rw [Int.min_def]; split <;> simp [*]
protected theorem min_le_left (a b : Int) : min a b ≤ a := Int.min_comm .. ▸ Int.min_le_right ..
protected theorem le_min {a b c : Int} : a ≤ min b c ↔ a ≤ b ∧ a ≤ c :=
⟨fun h => ⟨Int.le_trans h (Int.min_le_left ..), Int.le_trans h (Int.min_le_right ..)⟩,
fun ⟨h₁, h₂⟩ => by rw [Int.min_def]; split <;> assumption⟩
protected theorem min_eq_left {a b : Int} (h : a ≤ b) : min a b = a := by simp [Int.min_def, h]
protected theorem min_eq_right {a b : Int} (h : b ≤ a) : min a b = b := by
rw [Int.min_comm a b]; exact Int.min_eq_left h
protected theorem max_comm (a b : Int) : max a b = max b a := by
simp only [Int.max_def]
by_cases h₁ : a ≤ b <;> by_cases h₂ : b ≤ a <;> simp [h₁, h₂]
· exact Int.le_antisymm h₂ h₁
· cases not_or_intro h₁ h₂ <| Int.le_total ..
protected theorem le_max_left (a b : Int) : a ≤ max a b := by rw [Int.max_def]; split <;> simp [*]
protected theorem le_max_right (a b : Int) : b ≤ max a b := Int.max_comm .. ▸ Int.le_max_left ..
protected theorem max_le {a b c : Int} : max a b ≤ c ↔ a ≤ c ∧ b ≤ c :=
⟨fun h => ⟨Int.le_trans (Int.le_max_left ..) h, Int.le_trans (Int.le_max_right ..) h⟩,
fun ⟨h₁, h₂⟩ => by rw [Int.max_def]; split <;> assumption⟩
protected theorem max_eq_right {a b : Int} (h : a ≤ b) : max a b = b := by
simp [Int.max_def, h, Int.not_lt.2 h]
protected theorem max_eq_left {a b : Int} (h : b ≤ a) : max a b = a := by
rw [← Int.max_comm b a]; exact Int.max_eq_right h
theorem eq_natAbs_of_zero_le {a : Int} (h : 0 ≤ a) : a = natAbs a := by
let ⟨n, e⟩ := eq_ofNat_of_zero_le h
rw [e]; rfl
theorem le_natAbs {a : Int} : a ≤ natAbs a :=
match Int.le_total 0 a with
| .inl h => by rw [eq_natAbs_of_zero_le h]; apply Int.le_refl
| .inr h => Int.le_trans h (ofNat_zero_le _)
theorem negSucc_lt_zero (n : Nat) : -[n+1] < 0 :=
Int.not_le.1 fun h => let ⟨_, h⟩ := eq_ofNat_of_zero_le h; nomatch h
@[simp] theorem negSucc_not_nonneg (n : Nat) : 0 ≤ -[n+1] ↔ False := by
simp only [Int.not_le, iff_false]; exact Int.negSucc_lt_zero n
@[simp] theorem negSucc_not_pos (n : Nat) : 0 < -[n+1] ↔ False := by
simp only [Int.not_lt, iff_false]; constructor
theorem eq_negSucc_of_lt_zero : ∀ {a : Int}, a < 0 → ∃ n : Nat, a = -[n+1]
| ofNat _, h => absurd h (Int.not_lt.2 (ofNat_zero_le _))
| -[n+1], _ => ⟨n, rfl⟩
protected theorem add_le_add_left {a b : Int} (h : a ≤ b) (c : Int) : c + a ≤ c + b :=
let ⟨n, hn⟩ := le.dest h; le.intro n <| by rw [Int.add_assoc, hn]
protected theorem add_lt_add_left {a b : Int} (h : a < b) (c : Int) : c + a < c + b :=
Int.lt_iff_le_and_ne.2 ⟨Int.add_le_add_left (Int.le_of_lt h) _, fun heq =>
b.lt_irrefl <| by rwa [Int.add_left_cancel heq] at h⟩
protected theorem add_le_add_right {a b : Int} (h : a ≤ b) (c : Int) : a + c ≤ b + c :=
Int.add_comm c a ▸ Int.add_comm c b ▸ Int.add_le_add_left h c
protected theorem add_lt_add_right {a b : Int} (h : a < b) (c : Int) : a + c < b + c :=
Int.add_comm c a ▸ Int.add_comm c b ▸ Int.add_lt_add_left h c
protected theorem le_of_add_le_add_left {a b c : Int} (h : a + b ≤ a + c) : b ≤ c := by
have : -a + (a + b) ≤ -a + (a + c) := Int.add_le_add_left h _
simp [Int.neg_add_cancel_left] at this
assumption
protected theorem lt_of_add_lt_add_left {a b c : Int} (h : a + b < a + c) : b < c := by
have : -a + (a + b) < -a + (a + c) := Int.add_lt_add_left h _
simp [Int.neg_add_cancel_left] at this
assumption
protected theorem le_of_add_le_add_right {a b c : Int} (h : a + b ≤ c + b) : a ≤ c :=
Int.le_of_add_le_add_left (a := b) <| by rwa [Int.add_comm b a, Int.add_comm b c]
protected theorem lt_of_add_lt_add_right {a b c : Int} (h : a + b < c + b) : a < c :=
Int.lt_of_add_lt_add_left (a := b) <| by rwa [Int.add_comm b a, Int.add_comm b c]
protected theorem add_le_add_iff_left (a : Int) : a + b ≤ a + c ↔ b ≤ c :=
⟨Int.le_of_add_le_add_left, (Int.add_le_add_left · _)⟩
protected theorem add_lt_add_iff_left (a : Int) : a + b < a + c ↔ b < c :=
⟨Int.lt_of_add_lt_add_left, (Int.add_lt_add_left · _)⟩
protected theorem add_le_add_iff_right (c : Int) : a + c ≤ b + c ↔ a ≤ b :=
⟨Int.le_of_add_le_add_right, (Int.add_le_add_right · _)⟩
protected theorem add_lt_add_iff_right (c : Int) : a + c < b + c ↔ a < b :=
⟨Int.lt_of_add_lt_add_right, (Int.add_lt_add_right · _)⟩
protected theorem add_le_add {a b c d : Int} (h₁ : a ≤ b) (h₂ : c ≤ d) : a + c ≤ b + d :=
Int.le_trans (Int.add_le_add_right h₁ c) (Int.add_le_add_left h₂ b)
protected theorem le_add_of_nonneg_right {a b : Int} (h : 0 ≤ b) : a ≤ a + b := by
have : a + b ≥ a + 0 := Int.add_le_add_left h a
rwa [Int.add_zero] at this
protected theorem le_add_of_nonneg_left {a b : Int} (h : 0 ≤ b) : a ≤ b + a := by
have : 0 + a ≤ b + a := Int.add_le_add_right h a
rwa [Int.zero_add] at this
protected theorem add_lt_add {a b c d : Int} (h₁ : a < b) (h₂ : c < d) : a + c < b + d :=
Int.lt_trans (Int.add_lt_add_right h₁ c) (Int.add_lt_add_left h₂ b)
protected theorem add_lt_add_of_le_of_lt {a b c d : Int} (h₁ : a ≤ b) (h₂ : c < d) : a + c < b + d :=
Int.lt_of_le_of_lt (Int.add_le_add_right h₁ c) (Int.add_lt_add_left h₂ b)
protected theorem add_lt_add_of_lt_of_le {a b c d : Int} (h₁ : a < b) (h₂ : c ≤ d) : a + c < b + d :=
Int.lt_of_lt_of_le (Int.add_lt_add_right h₁ c) (Int.add_le_add_left h₂ b)
protected theorem lt_add_of_pos_right (a : Int) {b : Int} (h : 0 < b) : a < a + b := by
have : a + 0 < a + b := Int.add_lt_add_left h a
rwa [Int.add_zero] at this
protected theorem lt_add_of_pos_left (a : Int) {b : Int} (h : 0 < b) : a < b + a := by
have : 0 + a < b + a := Int.add_lt_add_right h a
rwa [Int.zero_add] at this
protected theorem add_nonneg {a b : Int} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a + b :=
Int.zero_add 0 ▸ Int.add_le_add ha hb
protected theorem add_pos {a b : Int} (ha : 0 < a) (hb : 0 < b) : 0 < a + b :=
Int.zero_add 0 ▸ Int.add_lt_add ha hb
protected theorem add_pos_of_pos_of_nonneg {a b : Int} (ha : 0 < a) (hb : 0 ≤ b) : 0 < a + b :=
Int.zero_add 0 ▸ Int.add_lt_add_of_lt_of_le ha hb
protected theorem add_pos_of_nonneg_of_pos {a b : Int} (ha : 0 ≤ a) (hb : 0 < b) : 0 < a + b :=
Int.zero_add 0 ▸ Int.add_lt_add_of_le_of_lt ha hb
protected theorem add_nonpos {a b : Int} (ha : a ≤ 0) (hb : b ≤ 0) : a + b ≤ 0 :=
Int.zero_add 0 ▸ Int.add_le_add ha hb
protected theorem add_neg {a b : Int} (ha : a < 0) (hb : b < 0) : a + b < 0 :=
Int.zero_add 0 ▸ Int.add_lt_add ha hb
protected theorem add_neg_of_neg_of_nonpos {a b : Int} (ha : a < 0) (hb : b ≤ 0) : a + b < 0 :=
Int.zero_add 0 ▸ Int.add_lt_add_of_lt_of_le ha hb
protected theorem add_neg_of_nonpos_of_neg {a b : Int} (ha : a ≤ 0) (hb : b < 0) : a + b < 0 :=
Int.zero_add 0 ▸ Int.add_lt_add_of_le_of_lt ha hb
protected theorem lt_add_of_le_of_pos {a b c : Int} (hbc : b ≤ c) (ha : 0 < a) : b < c + a :=
Int.add_zero b ▸ Int.add_lt_add_of_le_of_lt hbc ha
theorem add_one_le_iff {a b : Int} : a + 1 ≤ b ↔ a < b := .rfl
theorem lt_add_one_iff {a b : Int} : a < b + 1 ↔ a ≤ b := Int.add_le_add_iff_right _
@[simp] theorem succ_ofNat_pos (n : Nat) : 0 < (n : Int) + 1 :=
lt_add_one_iff.2 (ofNat_zero_le _)
theorem le_add_one {a b : Int} (h : a ≤ b) : a ≤ b + 1 :=
Int.le_of_lt (Int.lt_add_one_iff.2 h)
protected theorem neg_le_neg {a b : Int} (h : a ≤ b) : -b ≤ -a := by
have : 0 ≤ -a + b := Int.add_left_neg a ▸ Int.add_le_add_left h (-a)
have : 0 + -b ≤ -a + b + -b := Int.add_le_add_right this (-b)
rwa [Int.add_neg_cancel_right, Int.zero_add] at this
protected theorem le_of_neg_le_neg {a b : Int} (h : -b ≤ -a) : a ≤ b :=
suffices - -a ≤ - -b by simp [Int.neg_neg] at this; assumption
Int.neg_le_neg h
protected theorem nonneg_of_neg_nonpos {a : Int} (h : -a ≤ 0) : 0 ≤ a :=
Int.le_of_neg_le_neg <| by rwa [Int.neg_zero]
protected theorem neg_nonpos_of_nonneg {a : Int} (h : 0 ≤ a) : -a ≤ 0 := by
have : -a ≤ -0 := Int.neg_le_neg h
rwa [Int.neg_zero] at this
protected theorem nonpos_of_neg_nonneg {a : Int} (h : 0 ≤ -a) : a ≤ 0 :=
Int.le_of_neg_le_neg <| by rwa [Int.neg_zero]
protected theorem neg_nonneg_of_nonpos {a : Int} (h : a ≤ 0) : 0 ≤ -a := by
have : -0 ≤ -a := Int.neg_le_neg h
rwa [Int.neg_zero] at this
protected theorem neg_lt_neg {a b : Int} (h : a < b) : -b < -a := by
have : 0 < -a + b := Int.add_left_neg a ▸ Int.add_lt_add_left h (-a)
have : 0 + -b < -a + b + -b := Int.add_lt_add_right this (-b)
rwa [Int.add_neg_cancel_right, Int.zero_add] at this
protected theorem lt_of_neg_lt_neg {a b : Int} (h : -b < -a) : a < b :=
Int.neg_neg a ▸ Int.neg_neg b ▸ Int.neg_lt_neg h
protected theorem pos_of_neg_neg {a : Int} (h : -a < 0) : 0 < a :=
Int.lt_of_neg_lt_neg <| by rwa [Int.neg_zero]
protected theorem neg_neg_of_pos {a : Int} (h : 0 < a) : -a < 0 := by
have : -a < -0 := Int.neg_lt_neg h
rwa [Int.neg_zero] at this
protected theorem neg_of_neg_pos {a : Int} (h : 0 < -a) : a < 0 :=
have : -0 < -a := by rwa [Int.neg_zero]
Int.lt_of_neg_lt_neg this
protected theorem neg_pos_of_neg {a : Int} (h : a < 0) : 0 < -a := by
have : -0 < -a := Int.neg_lt_neg h
rwa [Int.neg_zero] at this
protected theorem le_neg_of_le_neg {a b : Int} (h : a ≤ -b) : b ≤ -a := by
have h := Int.neg_le_neg h
rwa [Int.neg_neg] at h
protected theorem neg_le_of_neg_le {a b : Int} (h : -a ≤ b) : -b ≤ a := by
have h := Int.neg_le_neg h
rwa [Int.neg_neg] at h
protected theorem lt_neg_of_lt_neg {a b : Int} (h : a < -b) : b < -a := by
have h := Int.neg_lt_neg h
rwa [Int.neg_neg] at h
protected theorem neg_lt_of_neg_lt {a b : Int} (h : -a < b) : -b < a := by
have h := Int.neg_lt_neg h
rwa [Int.neg_neg] at h
protected theorem sub_nonneg_of_le {a b : Int} (h : b ≤ a) : 0 ≤ a - b := by
have h := Int.add_le_add_right h (-b)
rwa [Int.add_right_neg] at h
protected theorem le_of_sub_nonneg {a b : Int} (h : 0 ≤ a - b) : b ≤ a := by
have h := Int.add_le_add_right h b
rwa [Int.sub_add_cancel, Int.zero_add] at h
protected theorem sub_nonpos_of_le {a b : Int} (h : a ≤ b) : a - b ≤ 0 := by
have h := Int.add_le_add_right h (-b)
rwa [Int.add_right_neg] at h
protected theorem le_of_sub_nonpos {a b : Int} (h : a - b ≤ 0) : a ≤ b := by
have h := Int.add_le_add_right h b
rwa [Int.sub_add_cancel, Int.zero_add] at h
protected theorem sub_pos_of_lt {a b : Int} (h : b < a) : 0 < a - b := by
have h := Int.add_lt_add_right h (-b)
rwa [Int.add_right_neg] at h
protected theorem lt_of_sub_pos {a b : Int} (h : 0 < a - b) : b < a := by
have h := Int.add_lt_add_right h b
rwa [Int.sub_add_cancel, Int.zero_add] at h
protected theorem sub_neg_of_lt {a b : Int} (h : a < b) : a - b < 0 := by
have h := Int.add_lt_add_right h (-b)
rwa [Int.add_right_neg] at h
protected theorem lt_of_sub_neg {a b : Int} (h : a - b < 0) : a < b := by
have h := Int.add_lt_add_right h b
rwa [Int.sub_add_cancel, Int.zero_add] at h
protected theorem add_le_of_le_neg_add {a b c : Int} (h : b ≤ -a + c) : a + b ≤ c := by
have h := Int.add_le_add_left h a
rwa [Int.add_neg_cancel_left] at h
protected theorem le_neg_add_of_add_le {a b c : Int} (h : a + b ≤ c) : b ≤ -a + c := by
have h := Int.add_le_add_left h (-a)
rwa [Int.neg_add_cancel_left] at h
protected theorem add_le_of_le_sub_left {a b c : Int} (h : b ≤ c - a) : a + b ≤ c := by
have h := Int.add_le_add_left h a
rwa [← Int.add_sub_assoc, Int.add_comm a c, Int.add_sub_cancel] at h
protected theorem le_sub_left_of_add_le {a b c : Int} (h : a + b ≤ c) : b ≤ c - a := by
have h := Int.add_le_add_right h (-a)
rwa [Int.add_comm a b, Int.add_neg_cancel_right] at h
protected theorem add_le_of_le_sub_right {a b c : Int} (h : a ≤ c - b) : a + b ≤ c := by
have h := Int.add_le_add_right h b
rwa [Int.sub_add_cancel] at h
protected theorem le_sub_right_of_add_le {a b c : Int} (h : a + b ≤ c) : a ≤ c - b := by
have h := Int.add_le_add_right h (-b)
rwa [Int.add_neg_cancel_right] at h
protected theorem le_add_of_neg_add_le {a b c : Int} (h : -b + a ≤ c) : a ≤ b + c := by
have h := Int.add_le_add_left h b
rwa [Int.add_neg_cancel_left] at h
protected theorem neg_add_le_of_le_add {a b c : Int} (h : a ≤ b + c) : -b + a ≤ c := by
have h := Int.add_le_add_left h (-b)
rwa [Int.neg_add_cancel_left] at h
protected theorem le_add_of_sub_left_le {a b c : Int} (h : a - b ≤ c) : a ≤ b + c := by
have h := Int.add_le_add_right h b
rwa [Int.sub_add_cancel, Int.add_comm] at h
protected theorem sub_left_le_of_le_add {a b c : Int} (h : a ≤ b + c) : a - b ≤ c := by
have h := Int.add_le_add_right h (-b)
rwa [Int.add_comm b c, Int.add_neg_cancel_right] at h
protected theorem le_add_of_sub_right_le {a b c : Int} (h : a - c ≤ b) : a ≤ b + c := by
have h := Int.add_le_add_right h c
rwa [Int.sub_add_cancel] at h
protected theorem sub_right_le_of_le_add {a b c : Int} (h : a ≤ b + c) : a - c ≤ b := by
have h := Int.add_le_add_right h (-c)
rwa [Int.add_neg_cancel_right] at h
protected theorem le_add_of_neg_add_le_left {a b c : Int} (h : -b + a ≤ c) : a ≤ b + c := by
rw [Int.add_comm] at h
exact Int.le_add_of_sub_left_le h
protected theorem neg_add_le_left_of_le_add {a b c : Int} (h : a ≤ b + c) : -b + a ≤ c := by
rw [Int.add_comm]
exact Int.sub_left_le_of_le_add h
protected theorem le_add_of_neg_add_le_right {a b c : Int} (h : -c + a ≤ b) : a ≤ b + c := by
rw [Int.add_comm] at h
exact Int.le_add_of_sub_right_le h
protected theorem neg_add_le_right_of_le_add {a b c : Int} (h : a ≤ b + c) : -c + a ≤ b := by
rw [Int.add_comm] at h
exact Int.neg_add_le_left_of_le_add h
protected theorem le_add_of_neg_le_sub_left {a b c : Int} (h : -a ≤ b - c) : c ≤ a + b :=
Int.le_add_of_neg_add_le_left (Int.add_le_of_le_sub_right h)
protected theorem neg_le_sub_left_of_le_add {a b c : Int} (h : c ≤ a + b) : -a ≤ b - c := by
have h := Int.le_neg_add_of_add_le (Int.sub_left_le_of_le_add h)
rwa [Int.add_comm] at h
protected theorem le_add_of_neg_le_sub_right {a b c : Int} (h : -b ≤ a - c) : c ≤ a + b :=
Int.le_add_of_sub_right_le (Int.add_le_of_le_sub_left h)
protected theorem neg_le_sub_right_of_le_add {a b c : Int} (h : c ≤ a + b) : -b ≤ a - c :=
Int.le_sub_left_of_add_le (Int.sub_right_le_of_le_add h)
protected theorem sub_le_of_sub_le {a b c : Int} (h : a - b ≤ c) : a - c ≤ b :=
Int.sub_left_le_of_le_add (Int.le_add_of_sub_right_le h)
protected theorem sub_le_sub_left {a b : Int} (h : a ≤ b) (c : Int) : c - b ≤ c - a :=
Int.add_le_add_left (Int.neg_le_neg h) c
protected theorem sub_le_sub_right {a b : Int} (h : a ≤ b) (c : Int) : a - c ≤ b - c :=
Int.add_le_add_right h (-c)
protected theorem sub_le_sub {a b c d : Int} (hab : a ≤ b) (hcd : c ≤ d) : a - d ≤ b - c :=
Int.add_le_add hab (Int.neg_le_neg hcd)
protected theorem add_lt_of_lt_neg_add {a b c : Int} (h : b < -a + c) : a + b < c := by
have h := Int.add_lt_add_left h a
rwa [Int.add_neg_cancel_left] at h
protected theorem lt_neg_add_of_add_lt {a b c : Int} (h : a + b < c) : b < -a + c := by
have h := Int.add_lt_add_left h (-a)
rwa [Int.neg_add_cancel_left] at h
protected theorem add_lt_of_lt_sub_left {a b c : Int} (h : b < c - a) : a + b < c := by
have h := Int.add_lt_add_left h a
rwa [← Int.add_sub_assoc, Int.add_comm a c, Int.add_sub_cancel] at h
protected theorem lt_sub_left_of_add_lt {a b c : Int} (h : a + b < c) : b < c - a := by
have h := Int.add_lt_add_right h (-a)
rwa [Int.add_comm a b, Int.add_neg_cancel_right] at h
protected theorem add_lt_of_lt_sub_right {a b c : Int} (h : a < c - b) : a + b < c := by
have h := Int.add_lt_add_right h b
rwa [Int.sub_add_cancel] at h
protected theorem lt_sub_right_of_add_lt {a b c : Int} (h : a + b < c) : a < c - b := by
have h := Int.add_lt_add_right h (-b)
rwa [Int.add_neg_cancel_right] at h
protected theorem lt_add_of_neg_add_lt {a b c : Int} (h : -b + a < c) : a < b + c := by
have h := Int.add_lt_add_left h b
rwa [Int.add_neg_cancel_left] at h
protected theorem neg_add_lt_of_lt_add {a b c : Int} (h : a < b + c) : -b + a < c := by
have h := Int.add_lt_add_left h (-b)
rwa [Int.neg_add_cancel_left] at h
protected theorem lt_add_of_sub_left_lt {a b c : Int} (h : a - b < c) : a < b + c := by
have h := Int.add_lt_add_right h b
rwa [Int.sub_add_cancel, Int.add_comm] at h
protected theorem sub_left_lt_of_lt_add {a b c : Int} (h : a < b + c) : a - b < c := by
have h := Int.add_lt_add_right h (-b)
rwa [Int.add_comm b c, Int.add_neg_cancel_right] at h
protected theorem lt_add_of_sub_right_lt {a b c : Int} (h : a - c < b) : a < b + c := by
have h := Int.add_lt_add_right h c
rwa [Int.sub_add_cancel] at h
protected theorem sub_right_lt_of_lt_add {a b c : Int} (h : a < b + c) : a - c < b := by
have h := Int.add_lt_add_right h (-c)
rwa [Int.add_neg_cancel_right] at h
protected theorem lt_add_of_neg_add_lt_left {a b c : Int} (h : -b + a < c) : a < b + c := by
rw [Int.add_comm] at h
exact Int.lt_add_of_sub_left_lt h
protected theorem neg_add_lt_left_of_lt_add {a b c : Int} (h : a < b + c) : -b + a < c := by
rw [Int.add_comm]
exact Int.sub_left_lt_of_lt_add h
protected theorem lt_add_of_neg_add_lt_right {a b c : Int} (h : -c + a < b) : a < b + c := by
rw [Int.add_comm] at h
exact Int.lt_add_of_sub_right_lt h
protected theorem neg_add_lt_right_of_lt_add {a b c : Int} (h : a < b + c) : -c + a < b := by
rw [Int.add_comm] at h
exact Int.neg_add_lt_left_of_lt_add h
protected theorem lt_add_of_neg_lt_sub_left {a b c : Int} (h : -a < b - c) : c < a + b :=
Int.lt_add_of_neg_add_lt_left (Int.add_lt_of_lt_sub_right h)
protected theorem neg_lt_sub_left_of_lt_add {a b c : Int} (h : c < a + b) : -a < b - c := by
have h := Int.lt_neg_add_of_add_lt (Int.sub_left_lt_of_lt_add h)
rwa [Int.add_comm] at h
protected theorem lt_add_of_neg_lt_sub_right {a b c : Int} (h : -b < a - c) : c < a + b :=
Int.lt_add_of_sub_right_lt (Int.add_lt_of_lt_sub_left h)
protected theorem neg_lt_sub_right_of_lt_add {a b c : Int} (h : c < a + b) : -b < a - c :=
Int.lt_sub_left_of_add_lt (Int.sub_right_lt_of_lt_add h)
protected theorem sub_lt_of_sub_lt {a b c : Int} (h : a - b < c) : a - c < b :=
Int.sub_left_lt_of_lt_add (Int.lt_add_of_sub_right_lt h)
protected theorem sub_lt_sub_left {a b : Int} (h : a < b) (c : Int) : c - b < c - a :=
Int.add_lt_add_left (Int.neg_lt_neg h) c
protected theorem sub_lt_sub_right {a b : Int} (h : a < b) (c : Int) : a - c < b - c :=
Int.add_lt_add_right h (-c)
protected theorem sub_lt_sub {a b c d : Int} (hab : a < b) (hcd : c < d) : a - d < b - c :=
Int.add_lt_add hab (Int.neg_lt_neg hcd)
protected theorem sub_lt_sub_of_le_of_lt {a b c d : Int}
(hab : a ≤ b) (hcd : c < d) : a - d < b - c :=
Int.add_lt_add_of_le_of_lt hab (Int.neg_lt_neg hcd)
protected theorem sub_lt_sub_of_lt_of_le {a b c d : Int}
(hab : a < b) (hcd : c ≤ d) : a - d < b - c :=
Int.add_lt_add_of_lt_of_le hab (Int.neg_le_neg hcd)
protected theorem sub_le_self (a : Int) {b : Int} (h : 0 ≤ b) : a - b ≤ a :=
calc a + -b
_ ≤ a + 0 := Int.add_le_add_left (Int.neg_nonpos_of_nonneg h) _
_ = a := by rw [Int.add_zero]
protected theorem sub_lt_self (a : Int) {b : Int} (h : 0 < b) : a - b < a :=
calc a + -b
_ < a + 0 := Int.add_lt_add_left (Int.neg_neg_of_pos h) _
_ = a := by rw [Int.add_zero]
protected theorem add_le_add_three {a b c d e f : Int}
(h₁ : a ≤ d) (h₂ : b ≤ e) (h₃ : c ≤ f) : a + b + c ≤ d + e + f :=
Int.add_le_add (Int.add_le_add h₁ h₂) h₃
protected theorem mul_lt_mul_of_pos_left {a b c : Int}
(h₁ : a < b) (h₂ : 0 < c) : c * a < c * b := by
have : 0 < c * (b - a) := Int.mul_pos h₂ (Int.sub_pos_of_lt h₁)
rw [Int.mul_sub] at this
exact Int.lt_of_sub_pos this
protected theorem mul_lt_mul_of_pos_right {a b c : Int}
(h₁ : a < b) (h₂ : 0 < c) : a * c < b * c := by
have : 0 < b - a := Int.sub_pos_of_lt h₁
have : 0 < (b - a) * c := Int.mul_pos this h₂
rw [Int.sub_mul] at this
exact Int.lt_of_sub_pos this
protected theorem mul_le_mul_of_nonneg_left {a b c : Int}
(h₁ : a ≤ b) (h₂ : 0 ≤ c) : c * a ≤ c * b := by
if hba : b ≤ a then rw [Int.le_antisymm hba h₁]; apply Int.le_refl else
if hc0 : c ≤ 0 then simp [Int.le_antisymm hc0 h₂, Int.zero_mul] else
exact Int.le_of_lt <| Int.mul_lt_mul_of_pos_left
(Int.lt_iff_le_not_le.2 ⟨h₁, hba⟩) (Int.lt_iff_le_not_le.2 ⟨h₂, hc0⟩)
protected theorem mul_le_mul_of_nonneg_right {a b c : Int}
(h₁ : a ≤ b) (h₂ : 0 ≤ c) : a * c ≤ b * c := by
rw [Int.mul_comm, Int.mul_comm b]; exact Int.mul_le_mul_of_nonneg_left h₁ h₂
protected theorem mul_le_mul {a b c d : Int}
(hac : a ≤ c) (hbd : b ≤ d) (nn_b : 0 ≤ b) (nn_c : 0 ≤ c) : a * b ≤ c * d :=
Int.le_trans (Int.mul_le_mul_of_nonneg_right hac nn_b) (Int.mul_le_mul_of_nonneg_left hbd nn_c)
protected theorem mul_nonpos_of_nonneg_of_nonpos {a b : Int}
(ha : 0 ≤ a) (hb : b ≤ 0) : a * b ≤ 0 := by
have h : a * b ≤ a * 0 := Int.mul_le_mul_of_nonneg_left hb ha
rwa [Int.mul_zero] at h
protected theorem mul_nonpos_of_nonpos_of_nonneg {a b : Int}
(ha : a ≤ 0) (hb : 0 ≤ b) : a * b ≤ 0 := by
have h : a * b ≤ 0 * b := Int.mul_le_mul_of_nonneg_right ha hb
rwa [Int.zero_mul] at h
protected theorem mul_lt_mul {a b c d : Int}
(h₁ : a < c) (h₂ : b ≤ d) (h₃ : 0 < b) (h₄ : 0 ≤ c) : a * b < c * d :=
Int.lt_of_lt_of_le (Int.mul_lt_mul_of_pos_right h₁ h₃) (Int.mul_le_mul_of_nonneg_left h₂ h₄)
protected theorem mul_lt_mul' {a b c d : Int}
(h₁ : a ≤ c) (h₂ : b < d) (h₃ : 0 ≤ b) (h₄ : 0 < c) : a * b < c * d :=
Int.lt_of_le_of_lt (Int.mul_le_mul_of_nonneg_right h₁ h₃) (Int.mul_lt_mul_of_pos_left h₂ h₄)
protected theorem mul_neg_of_pos_of_neg {a b : Int} (ha : 0 < a) (hb : b < 0) : a * b < 0 := by
have h : a * b < a * 0 := Int.mul_lt_mul_of_pos_left hb ha
rwa [Int.mul_zero] at h
protected theorem mul_neg_of_neg_of_pos {a b : Int} (ha : a < 0) (hb : 0 < b) : a * b < 0 := by
have h : a * b < 0 * b := Int.mul_lt_mul_of_pos_right ha hb
rwa [Int.zero_mul] at h
protected theorem mul_le_mul_of_nonpos_right {a b c : Int}
(h : b ≤ a) (hc : c ≤ 0) : a * c ≤ b * c :=
have : -c ≥ 0 := Int.neg_nonneg_of_nonpos hc
have : b * -c ≤ a * -c := Int.mul_le_mul_of_nonneg_right h this
Int.le_of_neg_le_neg <| by rwa [← Int.neg_mul_eq_mul_neg, ← Int.neg_mul_eq_mul_neg] at this
protected theorem mul_nonneg_of_nonpos_of_nonpos {a b : Int}
(ha : a ≤ 0) (hb : b ≤ 0) : 0 ≤ a * b := by
have : 0 * b ≤ a * b := Int.mul_le_mul_of_nonpos_right ha hb
rwa [Int.zero_mul] at this
protected theorem mul_lt_mul_of_neg_left {a b c : Int} (h : b < a) (hc : c < 0) : c * a < c * b :=
have : -c > 0 := Int.neg_pos_of_neg hc
have : -c * b < -c * a := Int.mul_lt_mul_of_pos_left h this
have : -(c * b) < -(c * a) := by
rwa [← Int.neg_mul_eq_neg_mul, ← Int.neg_mul_eq_neg_mul] at this
Int.lt_of_neg_lt_neg this
protected theorem mul_lt_mul_of_neg_right {a b c : Int} (h : b < a) (hc : c < 0) : a * c < b * c :=
have : -c > 0 := Int.neg_pos_of_neg hc
have : b * -c < a * -c := Int.mul_lt_mul_of_pos_right h this
have : -(b * c) < -(a * c) := by
rwa [← Int.neg_mul_eq_mul_neg, ← Int.neg_mul_eq_mul_neg] at this
Int.lt_of_neg_lt_neg this
protected theorem mul_pos_of_neg_of_neg {a b : Int} (ha : a < 0) (hb : b < 0) : 0 < a * b := by
have : 0 * b < a * b := Int.mul_lt_mul_of_neg_right ha hb
rwa [Int.zero_mul] at this
protected theorem mul_self_le_mul_self {a b : Int} (h1 : 0 ≤ a) (h2 : a ≤ b) : a * a ≤ b * b :=
Int.mul_le_mul h2 h2 h1 (Int.le_trans h1 h2)
protected theorem mul_self_lt_mul_self {a b : Int} (h1 : 0 ≤ a) (h2 : a < b) : a * a < b * b :=
Int.mul_lt_mul' (Int.le_of_lt h2) h2 h1 (Int.lt_of_le_of_lt h1 h2)
theorem exists_eq_neg_ofNat {a : Int} (H : a ≤ 0) : ∃ n : Nat, a = -(n : Int) :=
let ⟨n, h⟩ := eq_ofNat_of_zero_le (Int.neg_nonneg_of_nonpos H)
⟨n, Int.eq_neg_of_eq_neg h.symm⟩
theorem natAbs_of_nonneg {a : Int} (H : 0 ≤ a) : (natAbs a : Int) = a :=
match a, eq_ofNat_of_zero_le H with
| _, ⟨_, rfl⟩ => rfl
theorem ofNat_natAbs_of_nonpos {a : Int} (H : a ≤ 0) : (natAbs a : Int) = -a := by
rw [← natAbs_neg, natAbs_of_nonneg (Int.neg_nonneg_of_nonpos H)]
theorem lt_of_add_one_le {a b : Int} (H : a + 1 ≤ b) : a < b := H
theorem add_one_le_of_lt {a b : Int} (H : a < b) : a + 1 ≤ b := H
theorem lt_add_one_of_le {a b : Int} (H : a ≤ b) : a < b + 1 := Int.add_le_add_right H 1
theorem le_of_lt_add_one {a b : Int} (H : a < b + 1) : a ≤ b := Int.le_of_add_le_add_right H
theorem sub_one_lt_of_le {a b : Int} (H : a ≤ b) : a - 1 < b :=
Int.sub_right_lt_of_lt_add <| lt_add_one_of_le H
theorem le_of_sub_one_lt {a b : Int} (H : a - 1 < b) : a ≤ b :=
le_of_lt_add_one <| Int.lt_add_of_sub_right_lt H
theorem le_sub_one_of_lt {a b : Int} (H : a < b) : a ≤ b - 1 := Int.le_sub_right_of_add_le H
theorem lt_of_le_sub_one {a b : Int} (H : a ≤ b - 1) : a < b := Int.add_le_of_le_sub_right H
theorem sign_eq_one_of_pos {a : Int} (h : 0 < a) : sign a = 1 :=
match a, eq_succ_of_zero_lt h with
| _, ⟨_, rfl⟩ => rfl
theorem sign_eq_neg_one_of_neg {a : Int} (h : a < 0) : sign a = -1 :=
match a, eq_negSucc_of_lt_zero h with
| _, ⟨_, rfl⟩ => rfl
theorem eq_zero_of_sign_eq_zero : ∀ {a : Int}, sign a = 0 → a = 0
| 0, _ => rfl
theorem pos_of_sign_eq_one : ∀ {a : Int}, sign a = 1 → 0 < a
| (_ + 1 : Nat), _ => ofNat_lt.2 (Nat.succ_pos _)
theorem neg_of_sign_eq_neg_one : ∀ {a : Int}, sign a = -1 → a < 0
| (_ + 1 : Nat), h => nomatch h
| 0, h => nomatch h
| -[_+1], _ => negSucc_lt_zero _
theorem sign_eq_one_iff_pos (a : Int) : sign a = 1 ↔ 0 < a :=
⟨pos_of_sign_eq_one, sign_eq_one_of_pos⟩
theorem sign_eq_neg_one_iff_neg (a : Int) : sign a = -1 ↔ a < 0 :=
⟨neg_of_sign_eq_neg_one, sign_eq_neg_one_of_neg⟩
theorem sign_eq_zero_iff_zero (a : Int) : sign a = 0 ↔ a = 0 :=
⟨eq_zero_of_sign_eq_zero, fun h => by rw [h, sign_zero]⟩
protected theorem mul_eq_zero {a b : Int} : a * b = 0 ↔ a = 0 ∨ b = 0 := by
refine ⟨fun h => ?_, fun h => h.elim (by simp [·, Int.zero_mul]) (by simp [·, Int.mul_zero])⟩
exact match Int.lt_trichotomy a 0, Int.lt_trichotomy b 0 with
| .inr (.inl heq₁), _ => .inl heq₁
| _, .inr (.inl heq₂) => .inr heq₂
| .inl hlt₁, .inl hlt₂ => absurd h <| Int.ne_of_gt <| Int.mul_pos_of_neg_of_neg hlt₁ hlt₂
| .inl hlt₁, .inr (.inr hgt₂) => absurd h <| Int.ne_of_lt <| Int.mul_neg_of_neg_of_pos hlt₁ hgt₂
| .inr (.inr hgt₁), .inl hlt₂ => absurd h <| Int.ne_of_lt <| Int.mul_neg_of_pos_of_neg hgt₁ hlt₂
| .inr (.inr hgt₁), .inr (.inr hgt₂) => absurd h <| Int.ne_of_gt <| Int.mul_pos hgt₁ hgt₂
protected theorem mul_ne_zero {a b : Int} (a0 : a ≠ 0) (b0 : b ≠ 0) : a * b ≠ 0 :=
mt Int.mul_eq_zero.1 <| not_or.2 ⟨a0, b0⟩
protected theorem eq_of_mul_eq_mul_right {a b c : Int} (ha : a ≠ 0) (h : b * a = c * a) : b = c :=
have : (b - c) * a = 0 := by rwa [Int.sub_mul, Int.sub_eq_zero]
Int.sub_eq_zero.1 <| (Int.mul_eq_zero.1 this).resolve_right ha
protected theorem eq_of_mul_eq_mul_left {a b c : Int} (ha : a ≠ 0) (h : a * b = a * c) : b = c :=
have : a * b - a * c = 0 := Int.sub_eq_zero_of_eq h
have : a * (b - c) = 0 := by rw [Int.mul_sub, this]
have : b - c = 0 := (Int.mul_eq_zero.1 this).resolve_left ha
Int.eq_of_sub_eq_zero this
theorem eq_one_of_mul_eq_self_left {a b : Int} (Hpos : a ≠ 0) (H : b * a = a) : b = 1 :=
Int.eq_of_mul_eq_mul_right Hpos <| by rw [Int.one_mul, H]
theorem eq_one_of_mul_eq_self_right {a b : Int} (Hpos : b ≠ 0) (H : b * a = b) : a = 1 :=
Int.eq_of_mul_eq_mul_left Hpos <| by rw [Int.mul_one, H]
/-! ### nat abs -/
theorem ofNat_natAbs_eq_of_nonneg : ∀ a : Int, 0 ≤ a → Int.natAbs a = a
| (_:Nat), _ => rfl
| -[n+1], h => absurd (negSucc_lt_zero n) (Int.not_lt.2 h)
theorem eq_natAbs_iff_mul_eq_zero : natAbs a = n ↔ (a - n) * (a + n) = 0 := by
rw [natAbs_eq_iff, Int.mul_eq_zero, ← Int.sub_neg, Int.sub_eq_zero, Int.sub_eq_zero]
theorem natAbs_add_le (a b : Int) : natAbs (a + b) ≤ natAbs a + natAbs b := by
suffices ∀ a b : Nat, natAbs (subNatNat a b.succ) ≤ (a + b).succ by
match a, b with
| (a:Nat), (b:Nat) => simp
| (a:Nat), -[b+1] => simp; apply this
| -[a+1], (b:Nat) => simp [Nat.succ_add, Nat.add_comm a b]; apply this
| -[a+1], -[b+1] => simp [Nat.succ_add]; apply Nat.le_refl
refine fun a b => subNatNat_elim a b.succ
(fun m n i => n = b.succ → natAbs i ≤ (m + b).succ) ?_
(fun i n (e : (n + i).succ = _) => ?_) rfl
· rintro i n rfl
rw [Nat.add_comm _ i, Nat.add_assoc]
exact Nat.le_add_right i (b.succ + b).succ
· apply succ_le_succ
rw [← succ.inj e, ← Nat.add_assoc, Nat.add_comm]
apply Nat.le_add_right
theorem natAbs_sub_le (a b : Int) : natAbs (a - b) ≤ natAbs a + natAbs b := by
rw [← Int.natAbs_neg b]; apply natAbs_add_le
theorem negSucc_eq' (m : Nat) : -[m+1] = -m - 1 := by simp only [negSucc_eq, Int.neg_add]; rfl
theorem natAbs_lt_natAbs_of_nonneg_of_lt {a b : Int}
(w₁ : 0 ≤ a) (w₂ : a < b) : a.natAbs < b.natAbs :=
match a, b, eq_ofNat_of_zero_le w₁, eq_ofNat_of_zero_le (Int.le_trans w₁ (Int.le_of_lt w₂)) with
| _, _, ⟨_, rfl⟩, ⟨_, rfl⟩ => ofNat_lt.1 w₂
/-! ### toNat -/
theorem toNat_eq_max : ∀ a : Int, (toNat a : Int) = max a 0
| (n : Nat) => (Int.max_eq_left (ofNat_zero_le n)).symm
| -[n+1] => (Int.max_eq_right (Int.le_of_lt (negSucc_lt_zero n))).symm
@[simp] theorem toNat_zero : (0 : Int).toNat = 0 := rfl
@[simp] theorem toNat_one : (1 : Int).toNat = 1 := rfl
@[simp] theorem toNat_of_nonneg {a : Int} (h : 0 ≤ a) : (toNat a : Int) = a := by
rw [toNat_eq_max, Int.max_eq_left h]
@[simp] theorem toNat_ofNat (n : Nat) : toNat ↑n = n := rfl
@[simp] theorem toNat_ofNat_add_one {n : Nat} : ((n : Int) + 1).toNat = n + 1 := rfl
theorem self_le_toNat (a : Int) : a ≤ toNat a := by rw [toNat_eq_max]; apply Int.le_max_left
@[simp] theorem le_toNat {n : Nat} {z : Int} (h : 0 ≤ z) : n ≤ z.toNat ↔ (n : Int) ≤ z := by
rw [← Int.ofNat_le, Int.toNat_of_nonneg h]
@[simp] theorem toNat_lt {n : Nat} {z : Int} (h : 0 ≤ z) : z.toNat < n ↔ z < (n : Int) := by
rw [← Int.not_le, ← Nat.not_le, Int.le_toNat h]
theorem toNat_add {a b : Int} (ha : 0 ≤ a) (hb : 0 ≤ b) : (a + b).toNat = a.toNat + b.toNat :=
match a, b, eq_ofNat_of_zero_le ha, eq_ofNat_of_zero_le hb with
| _, _, ⟨_, rfl⟩, ⟨_, rfl⟩ => rfl
theorem toNat_add_nat {a : Int} (ha : 0 ≤ a) (n : Nat) : (a + n).toNat = a.toNat + n :=
match a, eq_ofNat_of_zero_le ha with | _, ⟨_, rfl⟩ => rfl
@[simp] theorem pred_toNat : ∀ i : Int, (i - 1).toNat = i.toNat - 1
| 0 => rfl
| (n+1:Nat) => by simp [ofNat_add]
| -[n+1] => rfl
@[simp] theorem toNat_sub_toNat_neg : ∀ n : Int, ↑n.toNat - ↑(-n).toNat = n
| 0 => rfl
| (_+1:Nat) => Int.sub_zero _
| -[_+1] => Int.zero_sub _
@[simp] theorem toNat_add_toNat_neg_eq_natAbs : ∀ n : Int, n.toNat + (-n).toNat = n.natAbs
| 0 => rfl
| (_+1:Nat) => Nat.add_zero _
| -[_+1] => Nat.zero_add _
theorem mem_toNat' : ∀ (a : Int) (n : Nat), toNat' a = some n ↔ a = n
| (m : Nat), n => Option.some_inj.trans ofNat_inj.symm
| -[m+1], n => by constructor <;> intro.
@[simp] theorem toNat_neg_nat : ∀ n : Nat, (-(n : Int)).toNat = 0
| 0 => rfl
| _+1 => rfl
|
module LightClick.IR.Channel.Normalise
import Data.List
import Data.Vect
import Toolkit.Data.DList
import Toolkit.Data.DVect
import LightClick.Types
import LightClick.Terms
import LightClick.IR.ModuleCentric
import LightClick.IR.ChannelCentric
import public LightClick.IR.Channel.Normalise.Error
import LightClick.IR.Channel.Normalise.LetFloat
import LightClick.IR.Channel.Normalise.Merge
import LightClick.IR.Channel.Normalise.FreshBinders
%default total
export
covering -- comes from Merge runMerge not being total.
normalise : ChannelIR UNIT -> Either Normalise.Error (ChannelIR UNIT)
normalise expr =
do e' <- runLetFloat expr
em' <- runMerge e'
emb' <- freshBinders em'
pure emb'
-- --------------------------------------------------------------------- [ EOF ]
|
module Language.LSP.Message.Progress
import Language.JSON
import Language.LSP.Message.Derive
import Language.LSP.Message.Utils
import Language.Reflection
%language ElabReflection
%default total
||| Refer to https://microsoft.github.io/language-server-protocol/specification.html#progress
public export
ProgressToken : Type
ProgressToken = OneOf [Int, String]
||| Refer to https://microsoft.github.io/language-server-protocol/specification.html#clientInitiatedProgress
public export
record WorkDoneProgressOptions where
constructor MkWorkDoneProgressOptions
workDoneProgress : Maybe Bool
%runElab deriveJSON defaultOpts `{{WorkDoneProgressOptions}}
||| Refer to https://microsoft.github.io/language-server-protocol/specification.html#clientInitiatedProgress
public export
record WorkDoneProgressParams where
constructor MkWorkDoneProgressParams
workDoneToken : Maybe ProgressToken
%runElab deriveJSON defaultOpts `{{WorkDoneProgressParams}}
||| Refer to https://microsoft.github.io/language-server-protocol/specification.html#partialResultParams
public export
record PartialResultParams where
constructor MkPartialResultParams
partialResultToken : Maybe ProgressToken
%runElab deriveJSON defaultOpts `{{PartialResultParams}}
||| Refer to https://microsoft.github.io/language-server-protocol/specification.html#workDoneProgressBegin
public export
record WorkDoneProgressBegin where
constructor MkWorkDoneProgressBegin
title : String
cancellable : Maybe Bool
message : Maybe String
percentage : Maybe Int
%runElab deriveJSON (record {staticFields = [("kind", JString "begin")]} defaultOpts) `{{WorkDoneProgressBegin}}
||| Refer to https://microsoft.github.io/language-server-protocol/specification.html#workDoneProgressReport
public export
record WorkDoneProgressReport where
constructor MkWorkDoneProgressReport
cancellable : Maybe Bool
message : Maybe String
percentage : Maybe Int
%runElab deriveJSON (record {staticFields = [("kind", JString "report")]} defaultOpts) `{{WorkDoneProgressReport}}
||| Refer to https://microsoft.github.io/language-server-protocol/specification.html#workDoneProgressEnd
public export
record WorkDoneProgressEnd where
constructor MkWorkDoneProgressEnd
message : Maybe String
%runElab deriveJSON (record {staticFields = [("kind", JString "end")]} defaultOpts) `{{WorkDoneProgressEnd}}
|
context("check_response")
test_that("check_response returns an error", {
skip_on_cran()
skip_on_travis()
skip_on_appveyor()
skip_if_government_down()
# Sys.sleep(time = 0.5)
expect_warning(ncdc_locs_cats(startdate='2100-01-01'), "no data found")
# Sys.sleep(time = 0.5)
expect_warning(ncdc_locs_cats(startdate='1990-01-0'), "An error occured")
# Sys.sleep(time = 0.5)
expect_warning(
ncdc(datasetid='GHCNDS', locationid='FIPS:BR', datatypeid='PRCP',
startdate = '2010-05-01', enddate = '2010-05-10')
, "Error:.+")
# Sys.sleep(time = 0.5)
expect_warning(
ncdc(datasetid='GHCND')
, "Required parameter 'startdate' is missing")
})
test_that("check_response returns the correct error messages", {
skip_on_cran()
skip_on_travis()
skip_on_appveyor()
skip_if_government_down()
# no data found
# Sys.sleep(time = 0.5)
expect_warning(ncdc_locs_cats(startdate='2100-01-01'), "no data found")
# wrong date input
# Sys.sleep(time = 0.5)
expect_warning(ncdc_locs_cats(startdate='1990-01-0'), "error occured while servicing your request")
# missing startdate parameter
# Sys.sleep(time = 0.5)
expect_warning(ncdc(datasetid='GHCND'), "Required parameter 'startdate' is missing")
# internal server error
# Sys.sleep(time = 0.5)
expect_warning(
ncdc(datasetid='GHCNDS', locationid='FIPS:BR', datatypeid='PRCP',
startdate = '2010-05-01', enddate = '2010-05-10'),
"Error:.+"
)
# no data found
# Sys.sleep(time = 0.5)
expect_warning(ncdc_datacats(startdate = '2013-10-01', locationid = "234234234"), "no data found")
# bad key
# Sys.sleep(time = 0.5)
expect_warning(ncdc_datacats(datacategoryid="ANNAGR", token = "asdfs"), "400")
# Sys.sleep(time = 0.5)
# invalid longitude value - no useful server error message, gives 200 status, but empty JSON array
expect_warning(ncdc_stations(extent=c(47.5204,-122.2047,47.6139,-192.1065)), "no data found")
})
|
\documentclass[11pt]{article}
\usepackage{amsfonts}
\usepackage{url}
\setlength{\oddsidemargin}{0in}
\setlength{\evensidemargin}{0in}
\setlength{\textwidth}{6.5in}
\setlength{\topmargin}{0in}
\setlength{\headsep}{0.5in}
\setlength{\textheight}{8.5in}
\setcounter{page}{1}
%\pagestyle{empty}
%\hbadness=10000
\begin{document}
\huge
\noindent
{Discrete Optimization Assignment:}
\vspace{0.25cm}
\noindent
{\bf Any Integer}
\normalsize
\section{Problem Statement}
This assignment is designed to familiarize you with the programming assignment infrastructure. All of the assignments in this class involve writing an optimization algorithm (i.e. a program) and submitting your results with the provided submission script. In this assignment, you will write a very simple program to submit a {\em positive integer} of your choice to the course. Your grade on this assignment will be determined by the size of the integer you submit to the grader.
\section{Assignment}
Write an algorithm to submit a positive integer to the course. Try submitting different integers in the range from -10 to 10 to see how the grader feedback changes based on the number you submit.
\section{Data Format Specification}
The output is one line containing your integer, $i$.
%
\begin{verbatim}[Output Format]
i
\end{verbatim}
%
\paragraph{Examples}
\begin{verbatim}[Output Example]
-3
\end{verbatim}
\begin{verbatim}[Output Example]
1
\end{verbatim}
\begin{verbatim}[Output Example]
3
\end{verbatim}
\section{Instructions}
Edit \texttt{solver.py} and modify the \texttt{solve\_it()} function to return your integer. Your \texttt{solve\_it} implementation can be tested with the command \texttt{python ./solver.py}
\paragraph{Handin}
Run \texttt{submit.py} with the command,
\texttt{python ./submit.py}\\
Follow the instructions to submit your integer and return to the Coursera website to view your results. There is no penalty for multiple submissions. However, it may take several minutes for your grade to appear on the website.
\input{techReqs.tex}
\end{document}
|
--
#print "---- h1"
def h1 (b : Bool) : Nat :=
match b with
| true => 0
| false => 10
#eval h1 false
#print "---- h2"
def h2 (x : List Nat) : Nat :=
match x with
| [x1, x2] => x1 + x2
| x::xs => x
| _ => 0
#eval h2 [1, 2]
#eval h2 [10, 4, 5]
#eval h2 []
#print "---- h3"
def h3 (x : Array Nat) : Nat :=
match x with
| #[x] => x
| #[x, y] => x + y
| xs => xs.size
#eval h3 #[10]
#eval h3 #[10, 20]
#eval h3 #[10, 20, 30, 40]
#print "---- inv"
inductive Image {α β : Type} (f : α → β) : β → Type
| mk (a : α) : Image f (f a)
def mkImage {α β : Type} (f : α → β) (a : α) : Image f (f a) :=
Image.mk a
def inv {α β : Type} {f : α → β} {b : β} (t : Image f b) : α :=
match b, t with
| _, Image.mk a => a
#eval inv (mkImage Nat.succ 10)
theorem foo {p q} (h : p ∨ q) : q ∨ p :=
match h with
| Or.inl h => Or.inr h
| Or.inr h => Or.inl h
def f (x : Nat × Nat) : Bool × Bool × Bool → Nat :=
match x with
| (a, b) => fun _ => a
structure S :=
(x y z : Nat := 0)
def f1 : S → S :=
fun { x := x, ..} => { y := x }
theorem ex2 : f1 { x := 10 } = { y := 10 } :=
rfl
universes u
inductive Vec (α : Type u) : Nat → Type u
| nil : Vec α 0
| cons {n} (head : α) (tail : Vec α n) : Vec α (n+1)
inductive VecPred {α : Type u} (P : α → Prop) : {n : Nat} → Vec α n → Prop
| nil : VecPred P Vec.nil
| cons {n : Nat} {head : α} {tail : Vec α n} : P head → VecPred P tail → VecPred P (Vec.cons head tail)
theorem ex3 {α : Type u} (P : α → Prop) : {n : Nat} → (v : Vec α (n+1)) → VecPred P v → Exists P
| _, Vec.cons head _, VecPred.cons h _ => ⟨head, h⟩
theorem ex4 {α : Type u} (P : α → Prop) : {n : Nat} → (v : Vec α (n+1)) → VecPred P v → Exists P
| _, Vec.cons head _, VecPred.cons h (w : VecPred P Vec.nil) => ⟨head, h⟩ -- ERROR
axiom someNat : Nat
noncomputable def f2 (x : Nat) := -- must mark as noncomputable since it uses axiom `someNat`
x + someNat
inductive Parity : Nat -> Type
| even (n) : Parity (n + n)
| odd (n) : Parity (Nat.succ (n + n))
axiom nDiv2 (n : Nat) : n % 2 = 0 → n = n/2 + n/2
axiom nDiv2Succ (n : Nat) : n % 2 ≠ 0 → n = Nat.succ (n/2 + n/2)
def parity (n : Nat) : Parity n :=
if h : n % 2 = 0 then
Eq.ndrec (Parity.even (n/2)) (nDiv2 n h).symm
else
Eq.ndrec (Parity.odd (n/2)) (nDiv2Succ n h).symm
partial def natToBin : (n : Nat) → List Bool
| 0 => []
| n => match n, parity n with
| _, Parity.even j => false :: natToBin j
| _, Parity.odd j => true :: natToBin j
#eval natToBin 6
partial def natToBin' : (n : Nat) → List Bool
| 0 => []
| n => match parity n with
| Parity.even j => false :: natToBin j
| Parity.odd j => true :: natToBin j
partial def natToBinBad (n : Nat) : List Bool :=
match n, parity n with
| 0, _ => []
| _, Parity.even j => false :: natToBin j
| _, Parity.odd j => true :: natToBin j
partial def natToBin2 (n : Nat) : List Bool :=
match n, parity n with
| _, Parity.even 0 => []
| _, Parity.even j => false :: natToBin j
| _, Parity.odd j => true :: natToBin j
#eval natToBin2 6
partial def natToBin2' (n : Nat) : List Bool :=
match parity n with
| Parity.even 0 => []
| Parity.even j => false :: natToBin j
| Parity.odd j => true :: natToBin j
#check fun (a, b) => a -- Error type of pattern variable contains metavariables
#check fun (a, b) => (a:Nat) + b
#check fun (a, b) => a && b
#check fun ((a : Nat), (b : Nat)) => a + b
#check fun
| some a, some b => some (a + b : Nat)
| _, _ => none
-- overapplied matcher
#check fun x => (match x with | 0 => id | x+1 => id) x
#check fun
| #[1, 2] => 2
| #[] => 0
| #[3, 4, 5] => 3
| _ => 4
-- underapplied matcher
def g {α} : List α → Nat
| [a] => 1
| _ => 0
#check g.match_1
#check fun (e : Empty) => (nomatch e : False)
|
[STATEMENT]
lemma asprod_distrib1:"m \<noteq> 0 \<Longrightarrow> m *\<^sub>a (x + y) = (m *\<^sub>a x) + (m *\<^sub>a y)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. m \<noteq> 0 \<Longrightarrow> m *\<^sub>a (x + y) = m *\<^sub>a x + m *\<^sub>a y
[PROOF STEP]
apply (cut_tac mem_ant[of "x"], cut_tac mem_ant[of "y"])
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>m \<noteq> 0; x = - \<infinity> \<or> (\<exists>z. x = ant z) \<or> x = \<infinity>; y = - \<infinity> \<or> (\<exists>z. y = ant z) \<or> y = \<infinity>\<rbrakk> \<Longrightarrow> m *\<^sub>a (x + y) = m *\<^sub>a x + m *\<^sub>a y
[PROOF STEP]
apply (cut_tac less_linear[of "m" "0"],
erule disjE,
erule disjE, erule disjE, simp,
erule disjE, simp add:asprod_def add_ant_def, simp,
simp, (erule disjE)+, erule exE, simp add:asprod_mult,
simp add:Zero_ant_def asprod_mult)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<lbrakk>m \<noteq> 0; x = - \<infinity>; (\<exists>z. y = ant z) \<or> y = \<infinity>; 0 < m\<rbrakk> \<Longrightarrow> m *\<^sub>a (- \<infinity> + y) = m *\<^sub>a (- \<infinity>) + m *\<^sub>a y
2. \<lbrakk>m \<noteq> 0; y = - \<infinity> \<or> (\<exists>z. y = ant z) \<or> y = \<infinity>; m < 0 \<or> m = 0 \<or> 0 < m; (\<exists>z. x = ant z) \<or> x = \<infinity>\<rbrakk> \<Longrightarrow> m *\<^sub>a (x + y) = m *\<^sub>a x + m *\<^sub>a y
[PROOF STEP]
apply (erule disjE, erule exE, simp add:asprod_mult,
simp add: Zero_ant_def asprod_mult,
erule disjE, erule disjE, erule disjE, erule exE,
simp add:asprod_mult,
simp add:Zero_ant_def asprod_mult,
erule disjE, erule exE, simp add:asprod_mult,
simp add:Zero_ant_def asprod_mult)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>m \<noteq> 0; m < 0 \<or> m = 0 \<or> 0 < m; (\<exists>z. x = ant z) \<or> x = \<infinity>; (\<exists>z. y = ant z) \<or> y = \<infinity>\<rbrakk> \<Longrightarrow> m *\<^sub>a (x + y) = m *\<^sub>a x + m *\<^sub>a y
[PROOF STEP]
apply (simp, erule disjE, erule exE, simp,
(erule disjE)+, erule exE, simp add:asprod_mult,
simp add:a_zpz, simp add:asprod_mult distrib_left,
simp add:asprod_mult)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>z. \<lbrakk>m \<noteq> 0; (\<exists>z. y = ant z) \<or> y = \<infinity>; x = ant z; 0 < m\<rbrakk> \<Longrightarrow> m *\<^sub>a (ant z + y) = m *\<^sub>a ant z + m *\<^sub>a y
2. \<lbrakk>m \<noteq> 0; m < 0 \<or> 0 < m; (\<exists>z. y = ant z) \<or> y = \<infinity>; x = \<infinity>\<rbrakk> \<Longrightarrow> m *\<^sub>a (x + y) = m *\<^sub>a x + m *\<^sub>a y
[PROOF STEP]
apply (erule disjE, erule exE, simp add:a_zpz asprod_mult,
simp add: distrib_left, simp add:asprod_mult,
(erule disjE)+, erule exE, simp add:asprod_mult, simp,
erule disjE, erule exE, simp add:asprod_mult, simp)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done |
Formal statement is: lemma coeff_map_poly: assumes "f 0 = 0" shows "coeff (map_poly f p) n = f (coeff p n)" Informal statement is: If $f(0) = 0$, then the coefficient of $x^n$ in $f(p(x))$ is $f(a_n)$, where $a_n$ is the coefficient of $x^n$ in $p(x)$. |
The Civilian Public Service ( CPS ) was a program of the United States government that provided conscientious objectors with an alternative to military service during World War II . From 1941 to 1947 , nearly 12 @,@ 000 draftees , willing to serve their country in some capacity but unwilling to perform any type of military service , accepted assignments in work of national importance in 152 CPS camps throughout the United States and Puerto Rico . Draftees from the historic peace churches and other faiths worked in areas such as soil conservation , forestry , fire fighting , agriculture , under the supervision of such agencies as the U.S. Forest Service , the Soil Conservation Service , and the National Park Service . Others helped provide social services and mental health services .
|
module QuasiDefinite
# package code goes here
# imports
import Base.blasfunc
import Base.LinAlg: BlasReal, BlasComplex, BlasFloat, BlasChar, BlasInt,
blas_int, DimensionMismatch, chkstride1, chksquare
# load the libQuasiDefinite
include("../deps/deps.jl")
#Generic LAPACK error handlers, copied from https://github.com/JuliaLang/julia/blob/master/base/linalg/lapack.jl
macro assertargsok() #Handle only negative info codes - use only if positive info code is useful!
:(info[1]<0 && throw(ArgumentError("invalid argument #$(-info[1]) to LAPACK call")))
end
#Check that upper/lower (for special matrices) is correctly specified
macro chkuplo()
:((uplo=='U' || uplo=='L') ||
throw(ArgumentError(string("uplo argument must be 'U' (upper) or 'L' (lower), got ", repr(uplo)))))
end
# from SCS.jl
function __init__()
# default binaries need access to Julia's lapack symbols
@unix_only dlopen(Base.liblapack_name, RTLD_LAZY|RTLD_DEEPBIND|RTLD_GLOBAL)
end
# see: https://github.com/JuliaLang/julia/blob/master/base/linalg/lapack.jl#L1735
@eval begin
function qdtrf!(uplo::BlasChar, A::StridedMatrix{Float64})
chkstride1(A)
chksquare(A)
@chkuplo
lda = max(1,stride(A,2))
lda==0 && return A, 0
info = Array(BlasInt, 1)
ccall(($(blasfunc(:dqdtrf_)), libQuasiDefinite), Void,
(Ptr{BlasChar}, Ptr{BlasInt}, Ptr{Float64}, Ptr{BlasInt}, Ptr{BlasInt}),
&uplo, &size(A,1), A, &lda, info)
@assertargsok
return A, info[1]
end
end
@eval begin
function qdtf2!(uplo::BlasChar, A::StridedMatrix{Float64})
chkstride1(A)
chksquare(A)
@chkuplo
lda = max(1,stride(A,2))
lda==0 && return A, 0
info = Array(BlasInt, 1)
ccall(($(blasfunc(:dqdtf2_)), libQuasiDefinite), Void,
(Ptr{BlasChar}, Ptr{BlasInt}, Ptr{Float64}, Ptr{BlasInt}, Ptr{BlasInt}),
&uplo, &size(A,1), A, &lda, info)
@assertargsok
return A, info[1]
end
end
@eval begin
function nptf2!(A::StridedMatrix{Float64})
chkstride1(A)
lda = max(1,stride(A,2))
lda==0 && return A, 0
info = Array(BlasInt, 1)
ccall(($(blasfunc(:dnptf2_)), libQuasiDefinite), Void,
(Ptr{BlasInt}, Ptr{BlasInt}, Ptr{Float64}, Ptr{BlasInt}, Ptr{BlasInt}),
&size(A,1), &size(A,2), A, &lda, info)
@assertargsok
return A, info[1]
end
end
function run()
A = Float64[2 -1; -1 2]
B, info = qdtrf!('U',A)
println(B)
println(info)
end
end # module
|
module ML.Unsupervised.Clustering.KMeans (
fit,
predict,
KMeans(..)
) where
import Numeric.LinearAlgebra
import Numeric.LinearAlgebra.Data
import Data.Ratio ((%))
import Data.List (minimumBy)
import qualified Data.Vector.Storable as V
import Debug.Trace
data KMeans a l = KMeans {
centroids :: [(l, V.Vector a)]
} deriving (Show, Eq)
fit :: (Fractional a, Ord a, Eq l, Show l, Show a, V.Storable a) => [l] -> [V.Vector a] -> KMeans a l
fit labels points = fit' (KMeans initialCentroids)
where
fit' kmeans = let
ass = assignment kmeans
updatedKmeans = update kmeans ass in
if (trace ("updated assignment: " ++ show (assignment updatedKmeans)) assignment updatedKmeans) == ass
then updatedKmeans
else fit' updatedKmeans
update kmeans ass = KMeans $ zip labels $ fmap (\l -> centerOfMass $ snd <$> filter (\x -> fst x == l) ass) labels
assignment kmeans = fmap (\x -> (assign kmeans x, x)) points
assign kmeans point = fst $ minimumBy (\x1 x2 -> snd x1 `compare` snd x2) $ (fmap (\(l, cent) -> (l, distance cent point))) $ centroids kmeans
distance v1 v2 = V.sum $ V.zipWith (\x1 x2 -> (x2 - x1) * (x2 - x1)) v1 v2
initialCentroids = zip labels points
centerOfMass :: (Fractional a, V.Storable a) => [V.Vector a] -> V.Vector a
centerOfMass (p:pts) = V.map (/ (fromRational $ (toInteger $ length pts + 1) % 1)) $ foldr sumVectors p pts
dim = V.length $ head points
sumVectors :: (Num a, V.Storable a) => V.Vector a -> V.Vector a -> V.Vector a
sumVectors = V.zipWith (+)
predict :: (Ord a, Num a, V.Storable a) => KMeans a l -> V.Vector a -> l
predict kmeans point = fst $ minimumBy (\x1 x2 -> snd x1 `compare` snd x2) $ (fmap (\(l, cent) -> (l, distance cent point))) $ centroids kmeans
where
distance v1 v2 = V.sum $ V.zipWith (\x1 x2 -> (x2 - x1) * (x2 - x1)) v1 v2
fitMatrix :: (Element a) => [l] -> Matrix a -> KMeans a l
fitMatrix = undefined
|
% EX_LAPLACE_ISO_PLATE: solve the Poisson problem in one quarter of a plate with a hole, discretized with NURBS (isoparametric approach).
% 1) PHYSICAL DATA OF THE PROBLEM
clear problem_data
% Physical domain, defined as NURBS map given in a text file
problem_data.geo_name = 'geo_plate_with_hole.txt';
% Type of boundary conditions for each side of the domain
problem_data.nmnn_sides = [3 4];
problem_data.drchlt_sides = [1 2];
% Physical parameters
problem_data.c_diff = @(x, y) ones(size(x));
% Source and boundary terms
problem_data.f = @(x, y) zeros(size(x));
problem_data.g = @test_plate_mixed_bc_g_nmnn;
problem_data.h = @(x, y, ind) exp(x).*sin(y);
% Exact solution (optional)
problem_data.uex = @(x, y) exp(x).*sin (y);
problem_data.graduex = @(x, y) cat (1, ...
reshape (exp(x).*sin(y), [1, size(x)]), ...
reshape (exp(x).*cos(y), [1, size(x)]));
% 2) CHOICE OF THE DISCRETIZATION PARAMETERS
clear method_data
method_data.degree = [3 3]; % Degree of the splines
method_data.regularity = [2 2]; % Regularity of the splines
method_data.nsub = [8 8]; % Number of subdivisions
method_data.nquad = [4 4]; % Points for the Gaussian quadrature rule
% 3) CALL TO THE SOLVER
[geometry, msh, space, u] = solve_laplace_iso (problem_data, method_data);
% 4) POST-PROCESSING
% 4.1) EXPORT TO PARAVIEW
output_file = 'Plate_NRB_Deg3_Reg2_Sub8';
vtk_pts = {linspace(0, 1, 21), linspace(0, 1, 21)};
fprintf ('The result is saved in the file %s \n \n', output_file);
sp_to_vtk (u, space, geometry, vtk_pts, output_file, 'u')
% 4.2) PLOT IN MATLAB. COMPARISON WITH THE EXACT SOLUTION
[eu, F] = sp_eval (u, space, geometry, vtk_pts);
[X, Y] = deal (squeeze(F(1,:,:)), squeeze(F(2,:,:)));
subplot (1,2,1)
surf (X, Y, eu)
title ('Numerical solution'), axis tight
subplot (1,2,2)
surf (X, Y, problem_data.uex (X,Y))
title ('Exact solution'), axis tight
% Display errors of the computed solution in the L2 and H1 norm
[error_h1, error_l2] = ...
sp_h1_error (space, msh, u, problem_data.uex, problem_data.graduex)
%!demo
%! ex_laplace_iso_plate
%!test
%! problem_data.geo_name = 'geo_plate_with_hole.txt';
%! problem_data.nmnn_sides = [3 4];
%! problem_data.drchlt_sides = [1 2];
%! problem_data.c_diff = @(x, y) ones(size(x));
%! problem_data.f = @(x, y) zeros(size(x));
%! problem_data.g = @test_plate_mixed_bc_g_nmnn;
%! problem_data.h = @(x, y, ind) exp(x).*sin(y);
%! problem_data.uex = @(x, y) exp(x).*sin (y);
%! problem_data.graduex = @(x, y) cat (1, ...
%! reshape (exp(x).*sin(y), [1, size(x)]), ...
%! reshape (exp(x).*cos(y), [1, size(x)]));
%! method_data.degree = [3 3]; % Degree of the splines
%! method_data.regularity = [2 2]; % Regularity of the splines
%! method_data.nsub = [8 8]; % Number of subdivisions
%! method_data.nquad = [4 4]; % Points for the Gaussian quadrature rule
%! [geometry, msh, space, u] = solve_laplace_iso (problem_data, method_data);
%! [error_h1, error_l2] = sp_h1_error (space, msh, u, problem_data.uex, problem_data.graduex);
%! assert (msh.nel, 128)
%! assert (space.ndof, 231)
%! assert (error_h1, 6.16178098362953e-04, 1e-16)
%! assert (error_l2, 4.44336164898602e-05, 1e-16) |
using SimpleGraphs, ProgressMeter, SemiIsomorphism
struct Trees
n::Int
end
function Base.iterate(T::Trees, state = 0)
N = T.n
NN = Int128(N)^(N - 2)
if state == NN
return nothing
end
code = Int.(digits(state, base = N, pad = N - 2) .+ 1)
G = prufer_restore(code)
name(G, "Tree")
return (G, state + 1)
end
Base.length(T::Trees) = Int128(T.n)^(T.n - 2)
"""
distinct_trees(n)
Returns a list of all trees on `n` vertices that are pairwise non-isomorphic.
**WARNINGS**
+ This can be used up to `n = 9`. Beyond that it's very slows.
+ Filtering out isomorphic duplicates is done by a heuristic. Tested up to `n = 9` and it works.
See https://oeis.org/A000055
"""
function distinct_trees(n::Int)
result = Set{SimpleGraph{Int}}()
seen = Set{UInt64}()
P = Progress(length(Trees(n)))
for T ∈ Trees(n)
next!(P)
uh = uhash(T)
if uh ∈ seen
continue
end
push!(seen, uh)
push!(result, T)
end
return collect(result)
end
function find_semi_iso_pair(list::Vector{SimpleGraph{T}}) where {T}
nG = length(list)
for j = 1:nG-1
for k = j+1:nG
if is_semi_iso(TT[j], TT[k])
return TT[j], TT[k]
end
end
end
println("No pair found")
nothing
end
function find_frac_iso_pair(list::Vector{SimpleGraph{T}}) where {T}
nG = length(list)
for j = 1:nG-1
for k = j+1:nG
if is_fiso(TT[j], TT[k])
return TT[j], TT[k]
end
end
end
println("No pair found")
nothing
end
|
module ShowNat where
open import IO
open import Data.Unit
open import Data.Nat.Show
main = run (putStrLn (Data.Nat.Show.show 10))
|
(*
* Copyright (c) 2020, CleanQ Project - Systems Group, ETH Zurich
* All rights reserved.
*
* This software may be distributed and modified according to the terms of
* the BSD 2-Clause license. Note that NO WARRANTY is provided.
*
* See "LICENSE" for details.
*
* SPDX-License-Identifier: BSD-2-Clause
*)
section \<open>Set Model Simpl proofs\<close>
text \<open>
Due to problems importing both SIMPL and COMPLX we split the files and have all the proofs
using SIMPL in this file
\<close>
theory CleanQ_SetModel_Simpl
(*<*)
imports
Main
CleanQ_SetModel
"../Simpl/Simpl"
begin
(*>*)
(*<*)
(* Define some global variables to make Simpl/Complex proofs work *)
record 'g CleanQ_Set_State_vars =
SetRB_' :: "nat CleanQ_Set_State"
(*>*)
(* ==================================================================================== *)
subsection \<open>Integration in SIMPL\<close>
(* ==================================================================================== *)
text \<open>
We now integrate the the CleanQ Set Model into SIMPL. For each of the two operations,
enqueue and dequeue, we specify a Hoare-triple with pre and post conditions, and
the operation.
\<close>
(* ------------------------------------------------------------------------------------ *)
subsubsection \<open>Enqueue Operation\<close>
(* ------------------------------------------------------------------------------------ *)
text \<open>
We first show, that we can define a Hoare triple for the enqueue operations from both
agents X and Y, and that in both cases the invariant is preserved.
\<close>
lemma CleanQ_Set_enq_x_preserves_invariants :
"\<Gamma>\<turnstile> \<lbrace> rb' = \<acute>SetRB \<and> CleanQ_Set_Invariants K \<acute>SetRB \<and> b \<in> SX \<acute>SetRB \<rbrace>
\<acute>SetRB :== (CleanQ_Set_enq_x b \<acute>SetRB)
\<lbrace> CleanQ_Set_Invariants K \<acute>SetRB \<rbrace>"
by(vcg, simp only: CleanQ_Set_enq_x_Invariants)
lemma CleanQ_Set_enq_y_preserves_invariants :
"\<Gamma>\<turnstile> \<lbrace> rb' = \<acute>SetRB \<and> CleanQ_Set_Invariants K \<acute>SetRB \<and> b \<in> SY \<acute>SetRB \<rbrace>
\<acute>SetRB :== (CleanQ_Set_enq_y b \<acute>SetRB)
\<lbrace> CleanQ_Set_Invariants K \<acute>SetRB \<rbrace>"
by(vcg, simp only: CleanQ_Set_enq_y_Invariants)
text \<open>
The same applies for the multi-step \verb+eneuque_n+ operation.
\<close>
lemma CleanQ_Set_enq_n_x_preserves_invariants :
"\<Gamma>\<turnstile> \<lbrace> rb' = \<acute>SetRB \<and> CleanQ_Set_Invariants K \<acute>SetRB \<and> (\<forall>b \<in> B. b \<in> (SX \<acute>SetRB)) \<rbrace>
\<acute>SetRB :== (CleanQ_Set_enq_n_x B \<acute>SetRB)
\<lbrace> CleanQ_Set_Invariants K \<acute>SetRB \<rbrace>"
apply(vcg) using CleanQ_Set_enq_n_x_Invariants by blast
lemma CleanQ_Set_enq_n_y_preserves_invariants :
"\<Gamma>\<turnstile> \<lbrace> rb' = \<acute>SetRB \<and> CleanQ_Set_Invariants K \<acute>SetRB \<and> (\<forall>b \<in> B. b \<in> (SY \<acute>SetRB)) \<rbrace>
\<acute>SetRB :== (CleanQ_Set_enq_n_y B \<acute>SetRB)
\<lbrace> CleanQ_Set_Invariants K \<acute>SetRB \<rbrace>"
apply(vcg) using CleanQ_Set_enq_n_y_Invariants by blast
text \<open>
The enqueue operation happens in two steps. The buffer element is removed
from one set and added to a new set. We can express this as two sequential operations
in the next lemma, where we show that the invariant is still preserved and that
the outcome is the same, as with the definition above.
\<close>
lemma CleanQ_Set_enq_x_two_step:
"\<Gamma>\<turnstile> \<lbrace> rb' = \<acute>SetRB \<and> CleanQ_Set_Invariants K \<acute>SetRB \<and> b \<in> SX \<acute>SetRB \<rbrace>
\<acute>SetRB :== \<acute>SetRB \<lparr> SX := (SX \<acute>SetRB) - {b} \<rparr> ;;
\<acute>SetRB :== \<acute>SetRB \<lparr> TXY := (TXY \<acute>SetRB) \<union> {b} \<rparr>
\<lbrace> \<acute>SetRB = CleanQ_Set_enq_x b rb' \<and> CleanQ_Set_Invariants K \<acute>SetRB \<rbrace>"
by(vcg, auto simp:CleanQ_Set_Invariants_simp CleanQ_Set_enq_x_def)
lemma CleanQ_Set_enq_y_two_step:
"\<Gamma>\<turnstile> \<lbrace> rb' = \<acute>SetRB \<and> CleanQ_Set_Invariants K \<acute>SetRB \<and> b \<in> SY \<acute>SetRB \<rbrace>
\<acute>SetRB :== \<acute>SetRB \<lparr> SY := (SY \<acute>SetRB) - {b} \<rparr> ;;
\<acute>SetRB :== \<acute>SetRB \<lparr> TYX := (TYX \<acute>SetRB) \<union> {b} \<rparr>
\<lbrace> \<acute>SetRB = CleanQ_Set_enq_y b rb' \<and> CleanQ_Set_Invariants K \<acute>SetRB \<rbrace>"
by(vcg, auto simp:CleanQ_Set_Invariants_simp CleanQ_Set_enq_y_def)
text \<open>
Next we can define this conditionally, where we only execute the enqueue operation,
when we are owning the buffer.
\<close>
lemma CleanQ_Set_enq_x_conditional :
"\<Gamma>\<turnstile> \<lbrace> CleanQ_Set_Invariants K \<acute>SetRB \<rbrace>
IF b \<in> SX \<acute>SetRB THEN
\<acute>SetRB :== (CleanQ_Set_enq_x b \<acute>SetRB)
FI
\<lbrace> CleanQ_Set_Invariants K \<acute>SetRB \<and> b \<notin> (SX \<acute>SetRB) \<rbrace>"
by(vcg, auto simp:CleanQ_Set_enq_x_Invariants CleanQ_Set_enq_x_def
CleanQ_Set_Invariants_simp)
lemma CleanQ_Set_enq_y_conditional :
"\<Gamma>\<turnstile> \<lbrace> CleanQ_Set_Invariants K \<acute>SetRB \<rbrace>
IF b \<in> SY \<acute>SetRB THEN
\<acute>SetRB :== (CleanQ_Set_enq_y b \<acute>SetRB)
FI
\<lbrace> CleanQ_Set_Invariants K \<acute>SetRB \<and> b \<notin> (SY \<acute>SetRB) \<rbrace>"
by(vcg, auto simp:CleanQ_Set_enq_y_Invariants CleanQ_Set_enq_y_def
CleanQ_Set_Invariants_simp)
(* ------------------------------------------------------------------------------------ *)
subsubsection \<open>Dequeue Operation\<close>
(* ------------------------------------------------------------------------------------ *)
text \<open>
We first show, that we can define a Hoare triple for the dequeue operations from both
agents X and Y, and that in both cases the invariant is preserved.
\<close>
lemma CleanQ_Set_deq_x_preserves_invariants:
"\<Gamma>\<turnstile> \<lbrace> rb' = \<acute>SetRB \<and> CleanQ_Set_Invariants K \<acute>SetRB \<and> b \<in> TYX \<acute>SetRB \<rbrace>
\<acute>SetRB :== (CleanQ_Set_deq_x b \<acute>SetRB)
\<lbrace> CleanQ_Set_Invariants K \<acute>SetRB \<rbrace>"
by(vcg, simp only: CleanQ_Set_deq_x_Invariants)
lemma CleanQ_Set_deq_y_preserves_invariants:
"\<Gamma>\<turnstile> \<lbrace> rb' = \<acute>SetRB \<and> CleanQ_Set_Invariants K \<acute>SetRB \<and> b \<in> TXY \<acute>SetRB \<rbrace>
\<acute>SetRB :== (CleanQ_Set_deq_y b \<acute>SetRB)
\<lbrace> CleanQ_Set_Invariants K \<acute>SetRB \<rbrace>"
by(vcg, simp only: CleanQ_Set_deq_y_Invariants)
text \<open>
The same applies for the multi-step \verb+eneuque_n+ operation.
\<close>
lemma CleanQ_Set_deq_n_x_preserves_invariants:
"\<Gamma>\<turnstile> \<lbrace> rb' = \<acute>SetRB \<and> CleanQ_Set_Invariants K \<acute>SetRB \<and> (\<forall> b \<in> B. b \<in> TYX \<acute>SetRB) \<rbrace>
\<acute>SetRB :== (CleanQ_Set_deq_n_x B \<acute>SetRB)
\<lbrace> CleanQ_Set_Invariants K \<acute>SetRB \<rbrace>"
apply(vcg) using CleanQ_Set_deq_n_x_Invariants by blast
lemma CleanQ_Set_deq_n_y_preserves_invariants:
"\<Gamma>\<turnstile> \<lbrace> rb' = \<acute>SetRB \<and> CleanQ_Set_Invariants K \<acute>SetRB \<and> (\<forall> b \<in> B. b \<in> TXY \<acute>SetRB) \<rbrace>
\<acute>SetRB :== (CleanQ_Set_deq_n_y B \<acute>SetRB)
\<lbrace> CleanQ_Set_Invariants K \<acute>SetRB \<rbrace>"
apply(vcg) using CleanQ_Set_deq_n_y_Invariants by blast
text \<open>
The dequeue operation effectively happens in two steps. The buffer element is removed
from one set and added to a new set. We can express this as two sequential operations
in the next lemma, where we show that the invariant is still preserved and that
the outcome is the same, as with the definition above.
\<close>
lemma CleanQ_Set_deq_x_two_step:
"\<Gamma>\<turnstile> \<lbrace> rb' = \<acute>SetRB \<and> CleanQ_Set_Invariants K \<acute>SetRB \<and> b \<in> TYX \<acute>SetRB \<rbrace>
\<acute>SetRB :== \<acute>SetRB \<lparr> TYX := (TYX \<acute>SetRB) - {b} \<rparr> ;;
\<acute>SetRB :== \<acute>SetRB \<lparr> SX := (SX \<acute>SetRB) \<union> {b} \<rparr>
\<lbrace> \<acute>SetRB = CleanQ_Set_deq_x b rb' \<and> CleanQ_Set_Invariants K \<acute>SetRB \<rbrace>"
by(vcg, simp add: CleanQ_Set_deq_x_def CleanQ_Set_Invariants_simp, auto)
lemma CleanQ_Set_deq_y_two_step:
"\<Gamma>\<turnstile> \<lbrace> rb' = \<acute>SetRB \<and> CleanQ_Set_Invariants K \<acute>SetRB \<and> b \<in> TXY \<acute>SetRB \<rbrace>
\<acute>SetRB :== \<acute>SetRB \<lparr> TXY := (TXY \<acute>SetRB) - {b} \<rparr> ;;
\<acute>SetRB :== \<acute>SetRB \<lparr> SY := (SY \<acute>SetRB) \<union> {b} \<rparr>
\<lbrace> \<acute>SetRB = CleanQ_Set_deq_y b rb' \<and> CleanQ_Set_Invariants K \<acute>SetRB \<rbrace>"
by(vcg, simp add: CleanQ_Set_deq_y_def CleanQ_Set_Invariants_simp, auto)
text \<open>
Next we can define this conditionally, where we only execute the enqueue operation,
when we are owning the buffer
\<close>
lemma CleanQ_Set_deq_x_conditional:
"\<Gamma>\<turnstile> \<lbrace> CleanQ_Set_Invariants K \<acute>SetRB \<rbrace>
IF b \<in> TYX \<acute>SetRB THEN
\<acute>SetRB :== (CleanQ_Set_deq_x b \<acute>SetRB)
FI
\<lbrace> CleanQ_Set_Invariants K \<acute>SetRB \<rbrace>"
by (vcg, meson CleanQ_Set_deq_x_Invariants)
lemma CleanQ_Set_deq_y_conditional:
"\<Gamma>\<turnstile> \<lbrace> CleanQ_Set_Invariants K \<acute>SetRB \<rbrace>
IF b \<in> TXY \<acute>SetRB THEN
\<acute>SetRB :== (CleanQ_Set_deq_y b \<acute>SetRB)
FI
\<lbrace> CleanQ_Set_Invariants K \<acute>SetRB \<rbrace>"
by (vcg, meson CleanQ_Set_deq_y_Invariants)
(* ------------------------------------------------------------------------------------ *)
subsubsection \<open>Combining Enqueue and Dequeue\<close>
(* ------------------------------------------------------------------------------------ *)
text \<open>
We can now combine the enqeueue and dequeue operations and pass a buffer around the
queue and back to the originator. We prove this by showing the state is the same.
\<close>
lemma CleanQ_Set_ops_combine :
"\<Gamma>\<turnstile> \<lbrace> CleanQ_Set_Invariants K \<acute>SetRB \<and> rb = \<acute>SetRB \<and> b \<in> SX \<acute>SetRB \<rbrace>
\<acute>SetRB :== (CleanQ_Set_enq_x b \<acute>SetRB) ;;
\<acute>SetRB :== (CleanQ_Set_deq_y b \<acute>SetRB) ;;
\<acute>SetRB :== (CleanQ_Set_enq_y b \<acute>SetRB) ;;
\<acute>SetRB :== (CleanQ_Set_deq_x b \<acute>SetRB)
\<lbrace> CleanQ_Set_Invariants K \<acute>SetRB \<and> rb = \<acute>SetRB \<and> b \<in> SX \<acute>SetRB \<rbrace>"
apply(vcg, auto simp:CleanQ_Set_ops CleanQ_Set_Invariants_simp)
using insert_absorb by fastforce
(*<*)
end
(*>*) |
lemma tendsto_diff_smallo: shows "(f1 \<longlongrightarrow> a) F \<Longrightarrow> f2 \<in> o[F](f1) \<Longrightarrow> ((\<lambda>x. f1 x - f2 x) \<longlongrightarrow> a) F" |
Artificial Boredom: toward human-like self-directed learning. Poster at Biologically Inspired Cognitive Architectures conference, Washington, DC. Herd, S.A., Mingus, B. & O'Reilly, R.C. (2010).
2009 - Present. Moderator of the Connectionists mailing list.
This page was last modified on 9 October 2018, at 11:48. |
#include <stdio.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_min.h>
double fn1 (double x, void * params)
{
return cos(x) + 1.0;
}
int
main (void)
{
int status;
int iter = 0, max_iter = 100;
const gsl_min_fminimizer_type *T;
gsl_min_fminimizer *s;
double m = 2.0, m_expected = M_PI;
double a = 0.0, b = 6.0;
gsl_function F;
F.function = &fn1;
F.params = 0;
T = gsl_min_fminimizer_brent;
s = gsl_min_fminimizer_alloc (T);
gsl_min_fminimizer_set (s, &F, m, a, b);
printf ("using %s method\n",
gsl_min_fminimizer_name (s));
printf ("%5s [%9s, %9s] %9s %10s %9s\n",
"iter", "lower", "upper", "min",
"err", "err(est)");
printf ("%5d [%.7f, %.7f] %.7f %+.7f %.7f\n",
iter, a, b,
m, m - m_expected, b - a);
do
{
iter++;
status = gsl_min_fminimizer_iterate (s);
m = gsl_min_fminimizer_x_minimum (s);
a = gsl_min_fminimizer_x_lower (s);
b = gsl_min_fminimizer_x_upper (s);
status
= gsl_min_test_interval (a, b, 0.001, 0.0);
if (status == GSL_SUCCESS)
printf ("Converged:\n");
printf ("%5d [%.7f, %.7f] "
"%.7f %+.7f %.7f\n",
iter, a, b,
m, m - m_expected, b - a);
}
while (status == GSL_CONTINUE && iter < max_iter);
gsl_min_fminimizer_free (s);
return status;
}
|
\documentclass[10pt]{beamer}
\usetheme[
%%% option passed to the outer theme
% progressstyle=fixedCircCnt, % fixedCircCnt, movingCircCnt (moving is deault)
]{DNA}
\usepackage{natbib}
\usepackage{float}
\usepackage{graphicx}
\usepackage[labelformat=empty,font=scriptsize,skip=0pt,justification=justified,singlelinecheck=false]{caption}
\usepackage[caption=false]{subfig}
\usepackage{amsmath}
\usepackage{mathtools}
\usepackage[percent]{overpic}
\usepackage{tikz}
\usetikzlibrary{arrows}
\usepackage{ulem}
\usepackage{multimedia}
\usepackage{siunitx}
\DeclareSIUnit\basepair{bp}
%remove the icon
\setbeamertemplate{bibliography item}{}
%remove line breaks
\setbeamertemplate{bibliography entry title}{}
\setbeamertemplate{bibliography entry location}{}
\setbeamertemplate{bibliography entry note}{}
%\setbeameroption{hide notes} % Only slides
%\setbeameroption{show only notes} % Only notes
% \setbeameroption{show notes on second screen=right} % Both
% Give a slight yellow tint to the notes page
\setbeamertemplate{note page}{\pagecolor{yellow!5}\insertnote}\usepackage{palatino}
% If you want to change the colors of the various elements in the theme, edit and uncomment the following lines
% Change the bar colors:
%\setbeamercolor{DNA}{fg=red!20,bg=red}
% Change the color of the structural elements:
%\setbeamercolor{structure}{fg=red}
% Change the frame title text color:
%\setbeamercolor{frametitle}{fg=blue}
% Change the normal text color background:
%\setbeamercolor{normal text}{fg=black,bg=gray!10}
% % beamer: How to place images behind text (z-order)
% % (http://tex.stackexchange.com/a/134311)
% \makeatletter
% \newbox\@backgroundblock
% \newenvironment{backgroundblock}[2]{%
% \global\setbox\@backgroundblock=\vbox\bgroup%
% \unvbox\@backgroundblock%
% \vbox to0pt\bgroup\vskip#2\hbox to0pt\bgroup\hskip#1\relax%
% }{\egroup\egroup\egroup}
% \addtobeamertemplate{background}{\box\@backgroundblock}{}
% \makeatother
%-------------------------------------------------------
% INCLUDE PACKAGES
%-------------------------------------------------------
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage[T1]{fontenc}
\usepackage{helvet}
%-------------------------------------------------------
% DEFFINING AND REDEFINING COMMANDS
%-------------------------------------------------------
% colored hyperlinks
\newcommand{\chref}[2]{%
\href{#1}{{\usebeamercolor[bg]{DNA}#2}}
}
%-------------------------------------------------------
% INFORMATION IN THE TITLE PAGE
%-------------------------------------------------------
\title[] % [] is optional - is placed on the bottom of the sidebar on every slide
{% is placed on the title page
\textbf{Nucleosome Heterogeneity Governs Chromatin Organization}
}
\subtitle[Nucleosome Heterogeneity]
{%
\textbf{2018--12--04}
}
% \author[Bruno Beltran]{Trent Newman$^{1}$, \textbf{Bruno Beltran$^{2}$}, James McGehee$^{1}$,
% Cori Cahoon$^{1}$, Dan Elnatan$^{1}$, Dan Chu$^{1}$, Andrew Spakowitz$^{2}$,
% Sean Burgess$^{1}$ \\
% \ttfamily [email protected]}
% \institute[UC Davis Mol \& Cell Bio and Stanford Biophysics]{$^{1}$Department of
% Molecular and Cellular Biology, UC Davis \\ $^{2}$Department of Biophysics,
% Stanford University}
\author[Bruno Beltran]
{Bruno Beltran \\
{\ttfamily [email protected]}
}
\institute[]
{%
Graduate Student, Spakowitz Lab\\
Biophysics PhD Program, Stanford University
%there must be an empty line above this line - otherwise some unwanted space is added between the university and the country (I do not know why:( )
}
% \date{February 18, 2018}
%-------------------------------------------------------
% THE BODY OF THE PRESENTATION
%-------------------------------------------------------
\begin{document}
%-------------------------------------------------------
% THE TITLEPAGE
%-------------------------------------------------------
{\1% % this is the name of the PDF file for the background
\begin{frame}[plain,noframenumbering] % the plain option removes the header from the title page, noframenumbering removes the numbering of this frame only
\titlepage{} % call the title page information from above
\end{frame}}
% \begin{frame}{Content}{}
% \tableofcontents
% \end{frame}
\begin{frame}{Big Picture}
\includegraphics[width=0.21\linewidth]{./2018-12-04-090226_878x1113_scrot.png}
\includegraphics[width=0.21\linewidth]{./2018-12-04-090240_876x1102_scrot.png}
\includegraphics[width=0.21\linewidth]{./2018-12-04-090256_875x1122_scrot.png}
\includegraphics[width=0.21\linewidth]{./2018-12-04-090316_874x1120_scrot.png}
\includegraphics[width=0.21\linewidth]{./2018-12-04-090355_874x1119_scrot.png}
\end{frame}
%-------------------------------------------------------
\section{Introduction}
%-------------------------------------------------------
\begin{frame}{Chromatin}
\begin{center}
\includegraphics[height=0.60\textheight]{./qual-figures/chromemt-zoom.jpg}
\tiny{Ou, H.D. et al.\@ \textit{ChromEMT:\@ Visualizing 3D chromatin
structure and compaction in interphase and mitotic cells}. Science 357 (2017).}
\note[item]{Define chromatin.}
\end{center}
\end{frame}
\begin{frame}{Modeling Chromatin}
\begin{center}
\only<1>{\includegraphics[height=0.60\textheight]{./qual-figures/model-detail-slide-1.png}}
\only<2>{\includegraphics[height=0.60\textheight]{./qual-figures/model-detail-slide-2.png}}
\only<3>{\includegraphics[height=0.60\textheight]{./qual-figures/model-detail-slide-3.png}}
\only<4>{\includegraphics[height=0.60\textheight]{./qual-figures/model-detail-slide-4.png}}
\end{center}
\only<2->{\tiny{Ou, H.D. et al.\@ \textit{ChromEMT:\@ Visualizing 3D chromatin
structure and compaction in interphase and mitotic cells}. Science 357
(2017).}}
\only<3->{\tiny{Quinn MacPherson (unpublished data)}}
\end{frame}
%-------------------------------------------------------
\section{Results}
%-------------------------------------------------------
\begin{frame}{Figure 1}
\begin{figure}[t]
\centering
\subfloat[]{\label{fig:entry-exit}
\begin{overpic}[width=100pt]{./paper-figures/fig-1a-nucleosome-geometry.png}
\put(16,-3){\large$\displaystyle\theta$}
\put(10,59){\large$\displaystyle\Omega_\text{entry}$}
\put(62,17.5){\large$\displaystyle\Omega_\text{exit}$}
\end{overpic}%
}\hspace{2em}
\subfloat[]{\label{fig:linker-effect}
\begin{overpic}[width=130pt]{./paper-figures/fig-1b-helicity-effect.png}
\put(17,11){\parbox{1.5cm}{\centering DNA Helicity}}
\put(-2,47){\large$\displaystyle\phi$}
\put(-6,63){$\displaystyle\SI{33}{\basepair}$}
\put(11,77){$\displaystyle-\SI{2}{\basepair}$}
\put(40,81){$\displaystyle\SI{35}{\basepair}$}
\put(61,72){$\displaystyle+\SI{2}{\basepair}$}
\put(76,46.5){$\displaystyle\SI{37}{\basepair}$}
\end{overpic}
}%
\end{figure}
\end{frame}
\begin{frame}{Figure 2}
\begin{figure}
\centering
\mbox{\includegraphics[scale=1.4]{../../deepti/nuc_chain_tmp/plots/PRL/fig2a_r2_homogenous_vs_wlc-scaled.pdf}
\includegraphics[scale=1.4]{../../deepti/nuc_chain_tmp/plots/PRL/fig2b_kuhn_length_in_nm_31to51links_0unwraps-with-renderings.pdf}}
\end{figure}
\end{frame}
\begin{frame}{Figure 3}
\centering
\includegraphics[height=0.75\textheight]{../../deepti/nuc_chain_tmp/plots/PRL/fig-3-kuhn_length_vs_window_size_41_sigma0to40-v4.pdf}
\end{frame}
\begin{frame}{Figure 4}
\begin{figure}
\centering
\mbox{\includegraphics[scale=1.4]{../../deepti/nuc_chain_tmp/plots/PRL/fig4a_r2_exp_vs_wlc-scaled.pdf}
\includegraphics[scale=1.4]{../../deepti/nuc_chain_tmp/plots/PRL/fig4b_kuhn_exponential-with-images.pdf}}
\end{figure}
\end{frame}
\begin{frame}{Figure 5}
\begin{center}
\includegraphics{./paper-figures/fig5_looping_hetero31to52bp_bold3curves.pdf}
\end{center}
\end{frame}
%-------------------------------------------------------
\section{Conclusion}
%-------------------------------------------------------
\begin{frame}{Summary}
\begin{itemize}[<+->]
\item On time scales longer than nucleosome turnover, chromatin is an
effective WLC.\@
\begin{itemize}[<+->]
\item Nucleosome heterogeneity $\to$ structural universality
\item Small amounts of heterogeneity are required to justify ``maximally
entropic'' approximation.
\item Maximum entropy picture is well approximated by an effective
WLC.\@
\end{itemize}
\item On time scales shorter than nucleosome turnover, nucleosome
spacing drastically affects chromatin organization.
\end{itemize}
\end{frame}
% \begin{frame}[allowframebreaks]
% \frametitle{References}
% \bibliographystyle{amsalpha}
% \bibliography{./multilocus.bib}
% \end{frame}
{\1
\begin{frame}[plain,noframenumbering]
\finalpage{Thank you!}
\end{frame}}
\end{document}
|
function result = part_sf_majorize ( n, nparta, a, npartb, b )
%*****************************************************************************80
%
%% PART_SF_MAJORIZE determines if partition A majorizes partition B.
%
% Discussion:
%
% The partitions must be in standard form.
%
% If A, with NPARTA parts, and B, with NPARTB parts, are both partitions
% of the same positive integer N, then we say that A majorizes B if,
% for every index K from 1 to N, it is true that
%
% sum ( 1 <= I <= K ) B(I) <= sum ( 1 <= I <= K ) A(I)
%
% where entries of A beyond index NPARTA, and of B beyond BPARTB
% are assumed to be 0. We say that A strictly majorizes B if
% A majorizes B, and for at least one index K the inequality is strict.
%
% For any two partitions of N, it is possible that A majorizes B,
% B majorizes A, both partitions majorize each other (in which case
% they are equal), or that neither majorizes the other.
%
% Licensing:
%
% This code is distributed under the GNU LGPL license.
%
% Modified:
%
% 27 July 2011
%
% Author:
%
% John Burkardt
%
% Reference:
%
% Jack vanLint, Richard Wilson,
% A Course in Combinatorics,
% Cambridge, 1992,
% ISBN: 0-521-42260-4,
% LC: QA164.L56.
%
% Parameters:
%
% Input, integer N, the integer to be partitioned.
% N must be positive.
%
% Input, integer NPARTA, the number of parts in partition A.
% 1 <= NPARTA <= N.
%
% Input, integer A(NPARTA), contains partition A in standard
% form. A(1) through A(NPARTA) contain nonzero integers which sum to N.
%
% Input, integer NPARTB, the number of parts in partition B.
% 1 <= NPARTB <= N.
%
% Input, integer B(NPARTB), contains partition B in standard
% form. B(1) through B(NPARTB) contain nonzero integers which sum to N.
%
% Output, integer RESULT, the result of the comparison.
% -2, A and B are incomparable, would have been -1.
% -1, A < B, (A is strictly majorized by B),
% 0, A = B, (A and B are identical),
% +1, A > B, (A strictly majorizes B),
% +2, A and B are incomparable, would have been +1.
%
%
% Check.
%
ierror = part_sf_check ( n, nparta, a );
if ( ierror ~= 0 )
fprintf ( 1, '\n' );
fprintf ( 1, 'PART_SF_MAJORIZE - Fatal error!\n' );
fprintf ( 1, ' The input array A is illegal.\n' );
error ( 'PART_SF_MAJORIZE - Fatal error!' );
end
ierror = part_sf_check ( n, npartb, b );
if ( ierror ~= 0 )
fprintf ( 1, '\n' );
fprintf ( 1, 'PART_SF_MAJORIZE - Fatal error!\n' );
fprintf ( 1, ' The input array B is illegal.\n' );
error ( 'PART_SF_MAJORIZE - Fatal error!' );
end
result = 0;
suma = 0;
sumb = 0;
for i = 1 : min ( nparta, npartb )
if ( i <= nparta )
suma = suma + a(i);
end
if ( i <= npartb )
sumb = sumb + b(i);
end
if ( result == -1 )
if ( sumb < suma )
result = -2;
return
end
elseif ( result == 0 )
if ( suma < sumb )
result = -1;
elseif ( sumb < suma )
result = +1;
end
elseif ( result == + 1 )
if ( suma < sumb )
result = +2;
return
end
end
end
return
end
|
import face_recognition
import cv2
import tqdm
from scipy.io import loadmat
import matplotlib.pyplot as plt
if __name__ == '__main__':
f_video = '../data/sample.mat'
data = loadmat(f_video)
images = data['image_record'].T
for image in tqdm.tqdm(images):
# Resize frame of video to 1/4 size for faster face detection processing
frame = image[0]
# small_frame = cv2.resize(frame, (0, 0), fx=0.5, fy=0.5)
# Find all the faces and face encodings in the current frame of video
face_locations = face_recognition.face_locations(frame,
model="cnn")
# Display the results
for top, right, bottom, left in face_locations:
# Scale back up face locations since the frame we detected in was scaled to 1/4 size
# top *= 4
# right *= 4
# bottom *= 4
# left *= 4
# Extract the region of the image that contains the face
face_image = frame[top:bottom, left:right]
# Blur the face image
face_image = cv2.GaussianBlur(face_image, (99, 99), 30)
# Put the blurred face region back into the frame image
frame[top:bottom, left:right] = face_image
plt.imshow(frame) plt.show()
|
(* Title: Irrational_Series_Erdos_Straus.thy
Author: Angeliki Koutsoukou-Argyraki and Wenda Li, University of Cambridge, UK.
We formalise certain irrationality criteria for infinite series by P. Erdos and E.G. Straus.
In particular, we formalise Theorem 2.1, Corollary 2.10 and Theorem 3.1 in [1]. The latter is an
application of Theorem 2.1 involving the prime numbers.
References:
[1] P. Erdos and E.G. Straus, On the irrationality of certain series, Pacific Journal of
Mathematics, Vol. 55, No 1, 1974 https://projecteuclid.org/euclid.pjm/1102911140
*)
theory "Irrational_Series_Erdos_Straus" imports
Prime_Number_Theorem.Prime_Number_Theorem
Prime_Distribution_Elementary.PNT_Consequences
begin
section \<open>Miscellaneous\<close>
lemma suminf_comparison:
assumes "summable f" and "\<forall>n. norm (g n) \<le> f n"
shows "suminf g \<le> suminf f"
proof (rule suminf_le)
show "\<forall>n. g n \<le> f n"
apply rule
subgoal for n using assms(2)[rule_format,of n] by auto
done
show "summable g"
apply (rule summable_comparison_test'[OF \<open>summable f\<close>, of 0])
using assms(2) by auto
show "summable f" using assms(1) .
qed
lemma tendsto_of_int_diff_0:
assumes "(\<lambda>n. f n - of_int(g n)) \<longlonglongrightarrow> (0::real)" "\<forall>\<^sub>F n in sequentially. f n > 0"
shows "\<forall>\<^sub>F n in sequentially. 0 \<le> g n"
proof -
have "\<forall>\<^sub>F n in sequentially. \<bar>f n - of_int(g n)\<bar> < 1 / 2"
using assms(1)[unfolded tendsto_iff,rule_format,of "1/2"] by auto
then show ?thesis using assms(2)
apply eventually_elim
by linarith
qed
lemma eventually_mono_sequentially:
assumes "eventually P sequentially"
assumes "\<And>x. P (x+k) \<Longrightarrow> Q (x+k)"
shows "eventually Q sequentially"
using sequentially_offset[OF assms(1),of k]
apply (subst eventually_sequentially_seg[symmetric,of _ k])
apply (elim eventually_mono)
by fact
lemma frequently_eventually_at_top:
fixes P Q::"'a::linorder \<Rightarrow> bool"
assumes "frequently P at_top" "eventually Q at_top"
shows "frequently (\<lambda>x. P x \<and> (\<forall>y\<ge>x. Q y) ) at_top"
using assms
unfolding frequently_def eventually_at_top_linorder
by (metis (mono_tags, hide_lams) le_cases order_trans)
lemma eventually_at_top_mono:
fixes P Q::"'a::linorder \<Rightarrow> bool"
assumes event_P:"eventually P at_top"
assumes PQ_imp:"\<And>x. x\<ge>z \<Longrightarrow> \<forall>y\<ge>x. P y \<Longrightarrow> Q x"
shows "eventually Q at_top"
proof -
obtain N where N_P:"\<forall>n\<ge>N. P n"
using event_P[unfolded eventually_at_top_linorder] by auto
define N' where "N' = max N z"
have "Q x" when "x\<ge>N'" for x
apply (rule PQ_imp)
using N_P that unfolding N'_def by auto
then show ?thesis unfolding eventually_at_top_linorder
by auto
qed
lemma frequently_at_top_elim:
fixes P Q::"'a::linorder \<Rightarrow> bool"
assumes "\<exists>\<^sub>Fx in at_top. P x"
assumes "\<And>i. P i \<Longrightarrow> \<exists>j>i. Q j"
shows "\<exists>\<^sub>Fx in at_top. Q x"
using assms unfolding frequently_def eventually_at_top_linorder
by (meson leD le_cases less_le_trans)
lemma less_Liminf_iff:
fixes X :: "_ \<Rightarrow> _ :: complete_linorder"
shows "Liminf F X < C \<longleftrightarrow> (\<exists>y<C. frequently (\<lambda>x. y \<ge> X x) F)"
apply (subst Not_eq_iff[symmetric])
apply (simp add:not_less not_frequently not_le le_Liminf_iff)
by force
lemma sequentially_even_odd_imp:
assumes "\<forall>\<^sub>F N in sequentially. P (2*N)" "\<forall>\<^sub>F N in sequentially. P (2*N+1)"
shows "\<forall>\<^sub>F n in sequentially. P n"
proof -
obtain N where N_P:"\<forall>x\<ge>N. P (2 * x) \<and> P (2 * x + 1)"
using eventually_conj[OF assms]
unfolding eventually_at_top_linorder by auto
define N' where "N'=2*N "
have "P n" when "n\<ge>2*N" for n
proof -
define n' where "n'= n div 2"
then have "n'\<ge>N" using that by auto
then have "P (2 * n') \<and> P (2 * n' + 1)"
using N_P by auto
then show ?thesis unfolding n'_def
apply (cases "even n")
by auto
qed
then show ?thesis unfolding eventually_at_top_linorder by auto
qed
section \<open>Theorem 2.1 and Corollary 2.10\<close>
context
fixes a b ::"nat\<Rightarrow>int "
assumes a_pos:"\<forall> n. a n >0 " and a_large:"\<forall>\<^sub>F n in sequentially. a n > 1"
and ab_tendsto: "(\<lambda>n. \<bar>b n\<bar> / (a (n-1)*a n)) \<longlonglongrightarrow> 0"
begin
private lemma aux_series_summable: "summable (\<lambda>n. b n / (\<Prod>k\<le>n. a k))"
proof -
have "\<forall>e>0. \<forall>\<^sub>F x in sequentially. \<bar>b x\<bar> / (a (x-1) * a x) < e"
using ab_tendsto[unfolded tendsto_iff]
apply (simp add:of_int_abs[symmetric] abs_mult del:of_int_abs)
by (subst (asm) (2) abs_of_pos,use \<open>\<forall> n. a n > 0\<close> in auto)+
from this[rule_format,of 1]
have "\<forall>\<^sub>F x in sequentially. \<bar>real_of_int(b x)\<bar> < (a (x-1) * a x)"
using \<open>\<forall> n. a n >0\<close> by auto
moreover have "\<forall>n. (\<Prod>k\<le>n. real_of_int (a k)) > 0"
using a_pos by (auto intro!:linordered_semidom_class.prod_pos)
ultimately have "\<forall>\<^sub>F n in sequentially. \<bar>b n\<bar> / (\<Prod>k\<le>n. a k)
< (a (n-1) * a n) / (\<Prod>k\<le>n. a k)"
apply (elim eventually_mono)
by (auto simp add:field_simps)
moreover have "\<bar>b n\<bar> / (\<Prod>k\<le>n. a k) = norm (b n / (\<Prod>k\<le>n. a k))" for n
using \<open>\<forall>n. (\<Prod>k\<le>n. real_of_int (a k)) > 0\<close>[rule_format,of n] by auto
ultimately have "\<forall>\<^sub>F n in sequentially. norm (b n / (\<Prod>k\<le>n. a k))
< (a (n-1) * a n) / (\<Prod>k\<le>n. a k)"
by algebra
moreover have "summable (\<lambda>n. (a (n-1) * a n) / (\<Prod>k\<le>n. a k))"
proof -
obtain s where a_gt_1:"\<forall> n\<ge>s. a n >1"
using a_large[unfolded eventually_at_top_linorder] by auto
define cc where "cc= (\<Prod>k<s. a k)"
have "cc>0"
unfolding cc_def
apply (rule linordered_semidom_class.prod_pos)
using a_pos by auto
have "(\<Prod>k\<le>n+s. a k) \<ge> cc * 2^n" for n
proof -
have "prod a {s..<Suc (s + n)} \<ge> 2^n"
proof (induct n)
case 0
then show ?case using a_gt_1 by auto
next
case (Suc n)
moreover have "a (s + Suc n) \<ge> 2"
using a_gt_1 by (smt le_add1)
ultimately show ?case
apply (subst prod.atLeastLessThan_Suc,simp)
using mult_mono'[of 2 "a (Suc (s + n))" " 2 ^ n" "prod a {s..<Suc (s + n)}",simplified]
by (simp add: mult.commute)
qed
moreover have "prod a {0..(n + s)} =
prod a {..<s} * prod a {s..<Suc (s + n)} "
using prod.atLeastLessThan_concat[of 0 s "s+n+1" a,simplified]
apply (simp add: atLeastLessThanSuc_atLeastAtMost algebra_simps
atLeast0LessThan)
by (smt a_gt_1 le_add2 lessThan_atLeast0 mult.left_commute prod.last_plus zero_le)
ultimately show ?thesis
using \<open>cc>0\<close> unfolding cc_def by (simp add: atLeast0AtMost)
qed
then have "1/(\<Prod>k\<le>n+s. a k) \<le> 1/(cc * 2^n)" for n
proof -
assume asm:"\<And>n. cc * 2 ^ n \<le> prod a {..n + s}"
then have "real_of_int (cc * 2 ^ n) \<le> prod a {..n + s}" using of_int_le_iff by blast
moreover have "prod a {..n + s} >0" using \<open>cc>0\<close> by (simp add: a_pos prod_pos)
ultimately show ?thesis using \<open>cc>0\<close>
by (auto simp:field_simps simp del:of_int_prod)
qed
moreover have "summable (\<lambda>n. 1/(cc * 2^n))"
proof -
have "summable (\<lambda>n. 1/(2::int)^n)"
using summable_geometric[of "1/(2::int)"] by (simp add:power_one_over)
from summable_mult[OF this,of "1/cc"] show ?thesis by auto
qed
ultimately have "summable (\<lambda>n. 1 / (\<Prod>k\<le>n+s. a k))"
apply (elim summable_comparison_test'[where N=0])
apply (unfold real_norm_def, subst abs_of_pos)
by (auto simp add: \<open>\<forall>n. 0 < (\<Prod>k\<le>n. real_of_int (a k))\<close>)
then have "summable (\<lambda>n. 1 / (\<Prod>k\<le>n. a k))"
apply (subst summable_iff_shift[where k=s,symmetric])
by simp
then have "summable (\<lambda>n. (a (n+1) * a (n+2)) / (\<Prod>k\<le>n+2. a k))"
proof -
assume asm:"summable (\<lambda>n. 1 / real_of_int (prod a {..n}))"
have "1 / real_of_int (prod a {..n}) = (a (n+1) * a (n+2)) / (\<Prod>k\<le>n+2. a k)" for n
proof -
have "a (Suc (Suc n)) \<noteq> 0" "a (Suc n) \<noteq>0"
using a_pos by (metis less_irrefl)+
then show ?thesis
by (simp add: atLeast0_atMost_Suc atMost_atLeast0)
qed
then show ?thesis using asm by auto
qed
then show "summable (\<lambda>n. (a (n-1) * a n) / (\<Prod>k\<le>n. a k))"
apply (subst summable_iff_shift[symmetric,of _ 2])
by auto
qed
ultimately show ?thesis
apply (elim summable_comparison_test_ev[rotated])
by (simp add: eventually_mono)
qed
private fun get_c::"(nat \<Rightarrow> int) \<Rightarrow> (nat \<Rightarrow> int) \<Rightarrow> int \<Rightarrow> nat \<Rightarrow> (nat \<Rightarrow> int)" where
"get_c a' b' B N 0 = round (B * b' N / a' N)"|
"get_c a' b' B N (Suc n) = get_c a' b' B N n * a' (n+N) - B * b' (n+N)"
lemma ab_rationality_imp:
assumes ab_rational:"(\<Sum>n. (b n / (\<Prod>i \<le> n. a i))) \<in> \<rat>"
shows "\<exists> (B::int)>0. \<exists> c::nat\<Rightarrow> int.
(\<forall>\<^sub>F n in sequentially. B*b n = c n * a n - c(n+1) \<and> \<bar>c(n+1)\<bar><a n/2)
\<and> (\<lambda>n. c (Suc n) / a n) \<longlonglongrightarrow> 0"
proof -
have [simp]:"a n \<noteq> 0" for n using a_pos by (metis less_numeral_extra(3))
obtain A::int and B::int where
AB_eq:"(\<Sum>n. real_of_int (b n) / real_of_int (prod a {..n})) = A / B" and "B>0"
proof -
obtain q::rat where "(\<Sum>n. real_of_int (b n) / real_of_int (prod a {..n})) = real_of_rat q"
using ab_rational by (rule Rats_cases) simp
moreover obtain A::int and B::int where "q = Rat.Fract A B" "B > 0" "coprime A B"
by (rule Rat_cases) auto
ultimately show ?thesis by (auto intro!: that[of A B] simp:of_rat_rat)
qed
define f where "f = (\<lambda>n. b n / real_of_int (prod a {..n}))"
define R where "R = (\<lambda>N. (\<Sum>n. B*b (n+N+1) / prod a {N..n+N+1}))"
have all_e_ubound:"\<forall>e>0. \<forall>\<^sub>F M in sequentially. \<forall>n. \<bar>B*b (n+M+1) / prod a {M..n+M+1}\<bar> < e/4 * 1/2^n"
proof safe
fix e::real assume "e>0"
obtain N where N_a2: "\<forall>n \<ge> N. a n \<ge> 2"
and N_ba: "\<forall>n \<ge> N. \<bar>b n\<bar> / (a (n-1) * a n) < e/(4*B)"
proof -
have "\<forall>\<^sub>F n in sequentially. \<bar>b n\<bar> / (a (n - 1) * a n) < e/(4*B)"
using order_topology_class.order_tendstoD[OF ab_tendsto,of "e/(4*B)"] \<open>B>0\<close> \<open>e>0\<close>
by auto
moreover have "\<forall>\<^sub>F n in sequentially. a n \<ge> 2"
using a_large by (auto elim: eventually_mono)
ultimately have "\<forall>\<^sub>F n in sequentially. \<bar>b n\<bar> / (a (n - 1) * a n) < e/(4*B) \<and> a n \<ge> 2"
by eventually_elim auto
then show ?thesis unfolding eventually_at_top_linorder using that
by auto
qed
have geq_N_bound:"\<bar>B*b (n+M+1) / prod a {M..n+M+1}\<bar> < e/4 * 1/2^n" when "M\<ge>N" for n M
proof -
define D where "D = B*b (n+M+1)/ (a (n+M) * a (n+M+1))"
have "\<bar>B*b (n+M+1) / prod a {M..n+M+1}\<bar> = \<bar>D / prod a {M..<n+M}\<bar>"
proof -
have "{M..n+M+1} = {M..<n+M} \<union> {n+M,n+M+1}" by auto
then have "prod a {M..n+M+1} = a (n+M) * a (n+M+1)* prod a {M..<n+M}" by simp
then show ?thesis unfolding D_def by (simp add:algebra_simps)
qed
also have "... < \<bar>e/4 * (1/prod a {M..<n+M})\<bar>"
proof -
have "\<bar>D\<bar> < e/ 4"
unfolding D_def using N_ba[rule_format, of "n+M+1"] \<open>B>0\<close> \<open>M \<ge> N\<close> \<open>e>0\<close> a_pos
by (auto simp:field_simps abs_mult abs_of_pos)
from mult_strict_right_mono[OF this,of "1/prod a {M..<n+M}"] a_pos \<open>e>0\<close>
show ?thesis
apply (auto simp:abs_prod abs_mult prod_pos)
by (subst (2) abs_of_pos,auto)+
qed
also have "... \<le> e/4 * 1/2^n"
proof -
have "prod a {M..<n+M} \<ge> 2^n"
proof (induct n)
case 0
then show ?case by simp
next
case (Suc n)
then show ?case
using \<open>M\<ge>N\<close> by (simp add: N_a2 mult.commute mult_mono' prod.atLeastLessThan_Suc)
qed
then have "real_of_int (prod a {M..<n+M}) \<ge> 2^n"
using numeral_power_le_of_int_cancel_iff by blast
then show ?thesis using \<open>e>0\<close> by (auto simp add:divide_simps)
qed
finally show ?thesis .
qed
show "\<forall>\<^sub>F M in sequentially. \<forall>n. \<bar>real_of_int (B * b (n + M + 1))
/ real_of_int (prod a {M..n + M + 1})\<bar> < e / 4 * 1 / 2 ^ n"
apply (rule eventually_sequentiallyI[of N])
using geq_N_bound by blast
qed
have R_tendsto_0:"R \<longlonglongrightarrow> 0"
proof (rule tendstoI)
fix e::real assume "e>0"
show "\<forall>\<^sub>F x in sequentially. dist (R x) 0 < e" using all_e_ubound[rule_format,OF \<open>e>0\<close>]
proof eventually_elim
case (elim M)
define g where "g = (\<lambda>n. B*b (n+M+1) / prod a {M..n+M+1})"
have g_lt:"\<bar>g n\<bar> < e/4 * 1/2^n" for n
using elim unfolding g_def by auto
have g_abs_summable:"summable (\<lambda>n. \<bar>g n\<bar>)"
proof -
have "summable (\<lambda>n. e/4 * 1/2^n)"
using summable_geometric[of "1/2",THEN summable_mult,of "e/4",simplified]
by (auto simp add:algebra_simps power_divide)
then show ?thesis
apply (elim summable_comparison_test')
using g_lt less_eq_real_def by auto
qed
have "\<bar>\<Sum>n. g n\<bar> \<le> (\<Sum>n. \<bar>g n\<bar>)" by (rule summable_rabs[OF g_abs_summable])
also have "... \<le>(\<Sum>n. e/4 * 1/2^n)"
proof (rule suminf_comparison)
show "summable (\<lambda>n. e/4 * 1/2^n)"
using summable_geometric[of "1/2",THEN summable_mult,of "e/4",simplified]
by (auto simp add:algebra_simps power_divide)
show "\<forall>n. norm \<bar>g n\<bar> \<le> e / 4 * 1 / 2 ^ n" using g_lt less_eq_real_def by auto
qed
also have "... = (e/4) * (\<Sum>n. (1/2)^n)"
apply (subst suminf_mult[symmetric])
subgoal
apply (rule complete_algebra_summable_geometric)
by simp
subgoal by (auto simp:algebra_simps power_divide)
done
also have "... = e/2" by (simp add:suminf_geometric[of "1/2"])
finally have "\<bar>\<Sum>n. g n\<bar> \<le> e / 2" .
then show "dist (R M) 0 < e" unfolding R_def g_def using \<open>e>0\<close> by auto
qed
qed
obtain N where R_N_bound:"\<forall>M \<ge> N. \<bar>R M\<bar> \<le> 1 / 4"
and N_geometric:"\<forall>M\<ge>N. \<forall>n. \<bar>real_of_int (B * b (n + M + 1)) / (prod a {M..n + M + 1})\<bar> < 1 / 2 ^ n"
proof -
obtain N1 where N1:"\<forall>M \<ge> N1. \<bar>R M\<bar> \<le> 1 / 4"
using metric_LIMSEQ_D[OF R_tendsto_0,of "1/4"] all_e_ubound[rule_format,of 4,unfolded eventually_sequentially]
by (auto simp:less_eq_real_def)
obtain N2 where N2:"\<forall>M\<ge>N2. \<forall>n. \<bar>real_of_int (B * b (n + M + 1))
/ (prod a {M..n + M + 1})\<bar> < 1 / 2 ^ n"
using all_e_ubound[rule_format,of 4,unfolded eventually_sequentially]
by (auto simp:less_eq_real_def)
define N where "N=max N1 N2"
show ?thesis using that[of N] N1 N2 unfolding N_def by simp
qed
define C where "C = B * prod a {..<N} * (\<Sum>n<N. f n)"
have "summable f"
unfolding f_def using aux_series_summable .
have "A * prod a {..<N} = C + B * b N / a N + R N"
proof -
have "A * prod a {..<N} = B * prod a {..<N} * (\<Sum>n. f n)"
unfolding AB_eq f_def using \<open>B>0\<close> by auto
also have "... = B * prod a {..<N} * ((\<Sum>n<N+1. f n) + (\<Sum>n. f (n+N+1)))"
using suminf_split_initial_segment[OF \<open>summable f\<close>, of "N+1"] by auto
also have "... = B * prod a {..<N} * ((\<Sum>n<N. f n) + f N + (\<Sum>n. f (n+N+1)))"
using sum.atLeast0_lessThan_Suc by simp
also have "... = C + B * b N / a N + (\<Sum>n. B*b (n+N+1) / prod a {N..n+N+1})"
proof -
have "B * prod a {..<N} * f N = B * b N / a N"
proof -
have "{..N} = {..<N} \<union> {N}" using ivl_disj_un_singleton(2) by blast
then show ?thesis unfolding f_def by auto
qed
moreover have "B * prod a {..<N} * (\<Sum>n. f (n+N+1)) = (\<Sum>n. B*b (n+N+1) / prod a {N..n+N+1})"
proof -
have "summable (\<lambda>n. f (n + N + 1))"
using \<open>summable f\<close> summable_iff_shift[of f "N+1"] by auto
moreover have "prod a {..<N} * f (n + N + 1) = b (n + N + 1) / prod a {N..n + N + 1}" for n
proof -
have "{..n + N + 1} = {..<N} \<union> {N..n + N + 1}" by auto
then show ?thesis
unfolding f_def
apply simp
apply (subst prod.union_disjoint)
by auto
qed
ultimately show ?thesis
apply (subst suminf_mult[symmetric])
by (auto simp add: mult.commute mult.left_commute)
qed
ultimately show ?thesis unfolding C_def by (auto simp:algebra_simps)
qed
also have "... = C +B * b N / a N + R N"
unfolding R_def by simp
finally show ?thesis .
qed
have R_bound:"\<bar>R M\<bar> \<le> 1 / 4" and R_Suc:"R (Suc M) = a M * R M - B * b (Suc M) / a (Suc M)"
when "M \<ge> N" for M
proof -
define g where "g = (\<lambda>n. B*b (n+M+1) / prod a {M..n+M+1})"
have g_abs_summable:"summable (\<lambda>n. \<bar>g n\<bar>)"
proof -
have "summable (\<lambda>n.(1::real)/2^n)"
using summable_geometric[of "(1::real)/2",simplified]
by (auto elim!: back_subst[of "summable"] simp:field_simps)
moreover have "\<bar>g n\<bar> < 1/2^n" for n
using N_geometric[rule_format,OF that] unfolding g_def by simp
ultimately show ?thesis
apply (elim summable_comparison_test')
using less_eq_real_def by auto
qed
show "\<bar>R M\<bar> \<le> 1 / 4" using R_N_bound[rule_format,OF that] .
have "R M = (\<Sum>n. g n)" unfolding R_def g_def by simp
also have "... = g 0 + (\<Sum>n. g (Suc n))"
apply (subst suminf_split_head)
using summable_rabs_cancel[OF g_abs_summable] by auto
also have "... = g 0 + 1/a M * (\<Sum>n. a M * g (Suc n))"
apply (subst suminf_mult)
by (auto simp add: g_abs_summable summable_Suc_iff summable_rabs_cancel)
also have "... = g 0 + 1/a M * R (Suc M)"
proof -
have "a M * g (Suc n) = B * b (n + M + 2) / prod a {Suc M..n + M + 2}" for n
proof -
have "{M..Suc (Suc (M + n))} = {M} \<union> {Suc M..Suc (Suc (M + n))}" by auto
then show ?thesis
unfolding g_def using \<open>B>0\<close> by (auto simp add:algebra_simps)
qed
then have "(\<Sum>n. a M * g (Suc n)) = R (Suc M)"
unfolding R_def by auto
then show ?thesis by auto
qed
finally have "R M = g 0 + 1 / a M * R (Suc M)" .
then have "R (Suc M) = a M * R M - g 0 * a M"
by (auto simp add:algebra_simps)
moreover have "{M..Suc M} = {M,Suc M}" by auto
ultimately show "R (Suc M) = a M * R M - B * b (Suc M) / a (Suc M)"
unfolding g_def by auto
qed
define c where "c = (\<lambda>n. if n\<ge>N then get_c a b B N (n-N) else undefined)"
have c_rec:"c (n+1) = c n * a n - B * b n" when "n \<ge> N" for n
unfolding c_def using that by (auto simp:Suc_diff_le)
have c_R:"c (Suc n) / a n = R n" when "n \<ge> N" for n
using that
proof (induct rule:nat_induct_at_least)
case base
have "\<bar> c (N+1) / a N \<bar> \<le> 1/2"
proof -
have "c N = round (B * b N / a N)" unfolding c_def by simp
moreover have "c (N+1) / a N = c N - B * b N / a N"
using a_pos[rule_format,of N]
by (auto simp add:c_rec[of N,simplified] divide_simps)
ultimately show ?thesis using of_int_round_abs_le by auto
qed
moreover have "\<bar>R N\<bar> \<le> 1 / 4" using R_bound[of N] by simp
ultimately have "\<bar>c (N+1) / a N - R N \<bar> < 1" by linarith
moreover have "c (N+1) / a N - R N \<in> \<int>"
proof -
have "c (N+1) / a N = c N - B * b N / a N"
using a_pos[rule_format,of N]
by (auto simp add:c_rec[of N,simplified] divide_simps)
moreover have " B * b N / a N + R N \<in> \<int>"
proof -
have "C = B * (\<Sum>n<N. prod a {..<N} * (b n / prod a {..n}))"
unfolding C_def f_def by (simp add:sum_distrib_left algebra_simps)
also have "... = B * (\<Sum>n<N. prod a {n<..<N} * b n)"
proof -
have "{..<N} = {n<..<N} \<union> {..n}" if "n<N" for n
by (simp add: ivl_disj_un_one(1) sup_commute that)
then show ?thesis
using \<open>B>0\<close>
apply simp
apply (subst prod.union_disjoint)
by auto
qed
finally have "C = real_of_int (B * (\<Sum>n<N. prod a {n<..<N} * b n))" .
then have "C \<in> \<int>" using Ints_of_int by blast
moreover note \<open>A * prod a {..<N} = C + B * b N / a N + R N\<close>
ultimately show ?thesis
by (metis Ints_diff Ints_of_int add.assoc add_diff_cancel_left')
qed
ultimately show ?thesis by (simp add: diff_diff_add)
qed
ultimately have "c (N+1) / a N - R N = 0"
by (metis Ints_cases less_irrefl of_int_0 of_int_lessD)
then show ?case by simp
next
case (Suc n)
have "c (Suc (Suc n)) / a (Suc n) = c (Suc n) - B * b (Suc n) / a (Suc n)"
apply (subst c_rec[of "Suc n",simplified])
using \<open>N \<le> n\<close> by (auto simp add: divide_simps)
also have "... = a n * R n - B * b (Suc n) / a (Suc n)"
using Suc by (auto simp: divide_simps)
also have "... = R (Suc n)"
using R_Suc[OF \<open>N \<le> n\<close>] by simp
finally show ?case .
qed
have ca_tendsto_zero:"(\<lambda>n. c (Suc n) / a n) \<longlonglongrightarrow> 0"
using R_tendsto_0
apply (elim filterlim_mono_eventually)
using c_R by (auto intro!:eventually_sequentiallyI[of N])
have ca_bound:"\<bar>c (n + 1)\<bar> < a n / 2" when "n \<ge> N" for n
proof -
have "\<bar>c (Suc n)\<bar> / a n = \<bar>c (Suc n) / a n\<bar>" using a_pos[rule_format,of n] by auto
also have "... = \<bar>R n\<bar>" using c_R[OF that] by auto
also have "... < 1/2" using R_bound[OF that] by auto
finally have "\<bar>c (Suc n)\<bar> / a n < 1/2" .
then show ?thesis using a_pos[rule_format,of n] by auto
qed
(* (* the following part corresponds to (2.7) (2.8) in the original paper, but turns out to be
not necessary. *)
have c_round:"c n = round (B * b n / a n)" when "n \<ge> N" for n
proof (cases "n=N")
case True
then show ?thesis unfolding c_def by simp
next
case False
with \<open>n\<ge>N\<close> obtain n' where n_Suc:"n=Suc n'" and "n' \<ge> N"
by (metis le_eq_less_or_eq lessE less_imp_le_nat)
have "B * b n / a n = c n - R n"
proof -
have "R n = c n - B * b n / a n"
using c_R[OF \<open>n'\<ge>N\<close>,symmetric,folded n_Suc] R_Suc[OF \<open>n'\<ge>N\<close>,folded n_Suc]
by (auto simp:field_simps)
then show ?thesis by (auto simp:field_simps)
qed
then have "\<bar>B * b n / a n - c n\<bar> = \<bar>R n\<bar>" by auto
then have "\<bar>B * b n / a n - c n\<bar> < 1/2" using R_bound[OF \<open>n \<ge> N\<close>] by auto
from round_unique'[OF this] show ?thesis by auto
qed
*)
show "\<exists>B>0. \<exists>c. (\<forall>\<^sub>F n in sequentially. B * b n = c n * a n - c (n + 1)
\<and> real_of_int \<bar>c (n + 1)\<bar> < a n / 2) \<and> (\<lambda>n. c (Suc n) / a n) \<longlonglongrightarrow> 0"
unfolding eventually_at_top_linorder
apply (rule exI[of _ B],use \<open>B>0\<close> in simp)
apply (intro exI[of _c] exI[of _ N])
using c_rec ca_bound ca_tendsto_zero
by fastforce
qed
private lemma imp_ab_rational:
assumes "\<exists> (B::int)>0. \<exists> c::nat\<Rightarrow> int.
(\<forall>\<^sub>F n in sequentially. B*b n = c n * a n - c(n+1) \<and> \<bar>c(n+1)\<bar><a n/2)"
shows "(\<Sum>n. (b n / (\<Prod>i \<le> n. a i))) \<in> \<rat>"
proof -
obtain B::int and c::"nat\<Rightarrow>int" and N::nat where "B>0" and
large_n:"\<forall>n\<ge>N. B * b n = c n * a n - c (n + 1) \<and> real_of_int \<bar>c (n + 1)\<bar> < a n / 2
\<and> a n\<ge>2"
proof -
obtain B c where "B>0" and event1:"\<forall>\<^sub>F n in sequentially. B * b n = c n * a n - c (n + 1)
\<and> real_of_int \<bar>c (n + 1)\<bar> < real_of_int (a n) / 2"
using assms by auto
from eventually_conj[OF event1 a_large,unfolded eventually_at_top_linorder]
obtain N where "\<forall>n\<ge>N. (B * b n = c n * a n - c (n + 1)
\<and> real_of_int \<bar>c (n + 1)\<bar> < real_of_int (a n) / 2) \<and> 2 \<le> a n"
by fastforce
then show ?thesis using that[of B N c] \<open>B>0\<close> by auto
qed
define f where "f=(\<lambda>n. real_of_int (b n) / real_of_int (prod a {..n}))"
define S where "S = (\<Sum>n. f n)"
have "summable f"
unfolding f_def by (rule aux_series_summable)
define C where "C=B*prod a {..<N} * (\<Sum>n<N. f n)"
have "B*prod a {..<N} * S = C + real_of_int (c N)"
proof -
define h1 where "h1= (\<lambda>n. (c (n+N) * a (n+N)) / prod a {N..n+N})"
define h2 where "h2 = (\<lambda>n. c (n+N+1) / prod a {N..n+N})"
have f_h12:"B*prod a {..<N}*f (n+N) = h1 n - h2 n" for n
proof -
define g1 where "g1 = (\<lambda>n. B * b (n+N))"
define g2 where "g2 = (\<lambda>n. prod a {..<N} / prod a {..n + N})"
have "B*prod a {..<N}*f (n+N) = (g1 n * g2 n)"
unfolding f_def g1_def g2_def by (auto simp:algebra_simps)
moreover have "g1 n = c (n+N) * a (n+N) - c (n+N+1)"
using large_n[rule_format,of "n+N"] unfolding g1_def by auto
moreover have "g2 n = (1/prod a {N..n+N})"
proof -
have "prod a ({..<N} \<union> {N..n + N}) = prod a {..<N} * prod a {N..n + N}"
apply (rule prod.union_disjoint[of "{..<N}" "{N..n+N}" a])
by auto
moreover have "prod a ({..<N} \<union> {N..n + N}) = prod a {..n+N}"
by (simp add: ivl_disj_un_one(4))
ultimately show ?thesis
unfolding g2_def
apply simp
using a_pos by (metis less_irrefl)
qed
ultimately have "B*prod a {..<N}*f (n+N) = (c (n+N) * a (n+N) - c (n+N+1)) / prod a {N..n+N}"
by auto
also have "... = h1 n - h2 n"
unfolding h1_def h2_def by (auto simp:algebra_simps diff_divide_distrib)
finally show ?thesis by simp
qed
have "B*prod a {..<N} * S = B*prod a {..<N} * ((\<Sum>n<N. f n) + (\<Sum>n. f (n+N)))"
using suminf_split_initial_segment[OF \<open>summable f\<close>,of N]
unfolding S_def by (auto simp:algebra_simps)
also have "... = C + B*prod a {..<N}*(\<Sum>n. f (n+N))"
unfolding C_def by (auto simp:algebra_simps)
also have "... = C + (\<Sum>n. h1 n - h2 n)"
apply (subst suminf_mult[symmetric])
subgoal using \<open>summable f\<close> by (simp add: summable_iff_shift)
subgoal using f_h12 by auto
done
also have "... = C + h1 0"
proof -
have "(\<lambda>n. \<Sum>i\<le>n. h1 i - h2 i) \<longlonglongrightarrow> (\<Sum>i. h1 i - h2 i)"
proof (rule summable_LIMSEQ')
have "(\<lambda>i. h1 i - h2 i) = (\<lambda>i. real_of_int (B * prod a {..<N}) * f (i + N))"
using f_h12 by auto
then show "summable (\<lambda>i. h1 i - h2 i)"
using \<open>summable f\<close> by (simp add: summable_iff_shift summable_mult)
qed
moreover have "(\<Sum>i\<le>n. h1 i - h2 i) = h1 0 - h2 n" for n
proof (induct n)
case 0
then show ?case by simp
next
case (Suc n)
have "(\<Sum>i\<le>Suc n. h1 i - h2 i) = (\<Sum>i\<le>n. h1 i - h2 i) + h1 (n+1) - h2 (n+1)"
by auto
also have "... = h1 0 - h2 n + h1 (n+1) - h2 (n+1)" using Suc by auto
also have "... = h1 0 - h2 (n+1)"
proof -
have "h2 n = h1 (n+1)"
unfolding h2_def h1_def
apply (auto simp:prod.nat_ivl_Suc')
using a_pos by (metis less_numeral_extra(3))
then show ?thesis by auto
qed
finally show ?case by simp
qed
ultimately have "(\<lambda>n. h1 0 - h2 n) \<longlonglongrightarrow> (\<Sum>i. h1 i - h2 i)" by simp
then have "h2 \<longlonglongrightarrow> (h1 0 - (\<Sum>i. h1 i - h2 i))"
apply (elim metric_tendsto_imp_tendsto)
by (auto intro!:eventuallyI simp add:dist_real_def)
moreover have "h2 \<longlonglongrightarrow> 0"
proof -
have h2_n:"\<bar>h2 n\<bar> < (1 / 2)^(n+1)" for n
proof -
have "\<bar>h2 n\<bar> = \<bar>c (n + N + 1)\<bar> / prod a {N..n + N}"
unfolding h2_def abs_divide
using a_pos by (simp add: abs_of_pos prod_pos)
also have "... < (a (N+n) / 2) / prod a {N..n + N}"
unfolding h2_def
apply (rule divide_strict_right_mono)
subgoal using large_n[rule_format,of "N+n"] by (auto simp add:algebra_simps)
subgoal using a_pos by (simp add: prod_pos)
done
also have "... = 1 / (2*prod a {N..<n + N})"
apply (subst ivl_disj_un(6)[of N "n+N",symmetric])
using a_pos[rule_format,of "N+n"] by (auto simp add:algebra_simps)
also have "... \<le> (1/2)^(n+1)"
proof (induct n)
case 0
then show ?case by auto
next
case (Suc n)
define P where "P=1 / real_of_int (2 * prod a {N..<n + N})"
have "1 / real_of_int (2 * prod a {N..<Suc n + N}) = P / a (n+N)"
unfolding P_def by (auto simp add: prod.atLeastLessThan_Suc)
also have "... \<le> ( (1 / 2) ^ (n + 1) ) / a (n+N) "
apply (rule divide_right_mono)
subgoal unfolding P_def using Suc by auto
subgoal by (simp add: a_pos less_imp_le)
done
also have "... \<le> ( (1 / 2) ^ (n + 1) ) / 2 "
apply (rule divide_left_mono)
using large_n[rule_format,of "n+N",simplified] by auto
also have "... = (1 / 2) ^ (n + 2)" by auto
finally show ?case by simp
qed
finally show ?thesis .
qed
have "(\<lambda>n. (1 / 2)^(n+1)) \<longlonglongrightarrow> (0::real)"
using tendsto_mult_right_zero[OF LIMSEQ_abs_realpow_zero2[of "1/2",simplified],of "1/2"]
by auto
then show ?thesis
apply (elim Lim_null_comparison[rotated])
using h2_n less_eq_real_def by (auto intro!:eventuallyI)
qed
ultimately have "(\<Sum>i. h1 i - h2 i) = h1 0"
using LIMSEQ_unique by fastforce
then show ?thesis by simp
qed
also have "... = C + c N"
unfolding h1_def using a_pos
by auto (metis less_irrefl)
finally show ?thesis .
qed
then have "S = (C + real_of_int (c N)) / (B*prod a {..<N})"
by (metis \<open>0 < B\<close> a_pos less_irrefl mult.commute mult_pos_pos
nonzero_mult_div_cancel_right of_int_eq_0_iff prod_pos)
moreover have "... \<in> \<rat>"
unfolding C_def f_def by (intro Rats_divide Rats_add Rats_mult Rats_of_int Rats_sum)
ultimately show "S \<in> \<rat>" by auto
qed
theorem theorem_2_1_Erdos_Straus :
"(\<Sum>n. (b n / (\<Prod>i \<le> n. a i))) \<in> \<rat> \<longleftrightarrow> (\<exists> (B::int)>0. \<exists> c::nat\<Rightarrow> int.
(\<forall>\<^sub>F n in sequentially. B*b n = c n * a n - c(n+1) \<and> \<bar>c(n+1)\<bar><a n/2))"
using ab_rationality_imp imp_ab_rational by auto
text\<open>The following is a Corollary to Theorem 2.1. \<close>
corollary corollary_2_10_Erdos_Straus:
assumes ab_event:"\<forall>\<^sub>F n in sequentially. b n > 0 \<and> a (n+1) \<ge> a n"
and ba_lim_leq:"lim (\<lambda>n. (b(n+1) - b n )/a n) \<le> 0"
and ba_lim_exist:"convergent (\<lambda>n. (b(n+1) - b n )/a n)"
and "liminf (\<lambda>n. a n / b n) = 0 "
shows "(\<Sum>n. (b n / (\<Prod>i \<le> n. a i))) \<notin> \<rat>"
proof
assume "(\<Sum>n. (b n / (\<Prod>i \<le> n. a i))) \<in> \<rat>"
then obtain B c where "B>0" and abc_event:"\<forall>\<^sub>F n in sequentially. B * b n = c n * a n - c (n + 1)
\<and> \<bar>c (n + 1)\<bar> < a n / 2" and ca_vanish: "(\<lambda>n. c (Suc n) / a n) \<longlonglongrightarrow> 0"
using ab_rationality_imp by auto
have bac_close:"(\<lambda>n. B * b n / a n - c n) \<longlonglongrightarrow> 0"
proof -
have "\<forall>\<^sub>F n in sequentially. B * b n - c n * a n + c (n + 1) = 0"
using abc_event by (auto elim!:eventually_mono)
then have "\<forall>\<^sub>F n in sequentially. (B * b n - c n * a n + c (n+1)) / a n = 0 "
apply eventually_elim
by auto
then have "\<forall>\<^sub>F n in sequentially. B * b n / a n - c n + c (n + 1) / a n = 0"
apply eventually_elim
using a_pos by (auto simp:divide_simps) (metis less_irrefl)
then have "(\<lambda>n. B * b n / a n - c n + c (n + 1) / a n) \<longlonglongrightarrow> 0"
by (simp add: eventually_mono tendsto_iff)
from tendsto_diff[OF this ca_vanish]
show ?thesis by auto
qed
have c_pos:"\<forall>\<^sub>F n in sequentially. c n > 0"
proof -
from bac_close have *:"\<forall>\<^sub>F n in sequentially. c n \<ge> 0"
apply (elim tendsto_of_int_diff_0)
using ab_event a_large apply (eventually_elim)
using \<open>B>0\<close> by auto
show ?thesis
proof (rule ccontr)
assume "\<not> (\<forall>\<^sub>F n in sequentially. c n > 0)"
moreover have "\<forall>\<^sub>F n in sequentially. c (Suc n) \<ge> 0 \<and> c n\<ge>0"
using * eventually_sequentially_Suc[of "\<lambda>n. c n\<ge>0"]
by (metis (mono_tags, lifting) eventually_at_top_linorder le_Suc_eq)
ultimately have "\<exists>\<^sub>F n in sequentially. c n = 0 \<and> c (Suc n) \<ge> 0"
using eventually_elim2 frequently_def by fastforce
moreover have "\<forall>\<^sub>F n in sequentially. b n > 0 \<and> B * b n = c n * a n - c (n + 1)"
using ab_event abc_event by eventually_elim auto
ultimately have "\<exists>\<^sub>F n in sequentially. c n = 0 \<and> c (Suc n) \<ge> 0 \<and> b n > 0
\<and> B * b n = c n * a n - c (n + 1)"
using frequently_eventually_frequently by fastforce
from frequently_ex[OF this]
obtain n where "c n = 0" "c (Suc n) \<ge> 0" "b n > 0"
"B * b n = c n * a n - c (n + 1)"
by auto
then have "B * b n \<le> 0" by auto
then show False using \<open>b n>0\<close> \<open>B > 0\<close> using mult_pos_pos not_le by blast
qed
qed
have bc_epsilon:"\<forall>\<^sub>F n in sequentially. b (n+1) / b n > (c (n+1) - \<epsilon>) / c n" when "\<epsilon>>0" "\<epsilon><1" for \<epsilon>::real
proof -
have "\<forall>\<^sub>F x in sequentially. \<bar>c (Suc x) / a x\<bar> < \<epsilon> / 2"
using ca_vanish[unfolded tendsto_iff,rule_format, of "\<epsilon>/2"] \<open>\<epsilon>>0\<close> by auto
moreover then have "\<forall>\<^sub>F x in sequentially. \<bar>c (x+2) / a (x+1)\<bar> < \<epsilon> / 2"
apply (subst (asm) eventually_sequentially_Suc[symmetric])
by simp
moreover have "\<forall>\<^sub>F n in sequentially. B * b (n+1) = c (n+1) * a (n+1) - c (n + 2)"
using abc_event
apply (subst (asm) eventually_sequentially_Suc[symmetric])
by (auto elim:eventually_mono)
moreover have "\<forall>\<^sub>F n in sequentially. c n > 0 \<and> c (n+1) > 0 \<and> c (n+2) > 0"
proof -
have "\<forall>\<^sub>F n in sequentially. 0 < c (Suc n)"
using c_pos by (subst eventually_sequentially_Suc) simp
moreover then have "\<forall>\<^sub>F n in sequentially. 0 < c (Suc (Suc n))"
using c_pos by (subst eventually_sequentially_Suc) simp
ultimately show ?thesis using c_pos by eventually_elim auto
qed
ultimately show ?thesis using ab_event abc_event
proof eventually_elim
case (elim n)
define \<epsilon>\<^sub>0 \<epsilon>\<^sub>1 where "\<epsilon>\<^sub>0 = c (n+1) / a n" and "\<epsilon>\<^sub>1 = c (n+2) / a (n+1)"
have "\<epsilon>\<^sub>0 > 0" "\<epsilon>\<^sub>1 > 0" "\<epsilon>\<^sub>0 < \<epsilon>/2" "\<epsilon>\<^sub>1 < \<epsilon>/2" using a_pos elim by (auto simp add: \<epsilon>\<^sub>0_def \<epsilon>\<^sub>1_def)
have "(\<epsilon> - \<epsilon>\<^sub>1) * c n > 0"
apply (rule mult_pos_pos)
using \<open>\<epsilon>\<^sub>1 > 0\<close> \<open>\<epsilon>\<^sub>1 < \<epsilon>/2\<close> \<open>\<epsilon>>0\<close> elim by auto
moreover have "\<epsilon>\<^sub>0 * (c (n+1) - \<epsilon>) > 0"
apply (rule mult_pos_pos[OF \<open>\<epsilon>\<^sub>0 > 0\<close>])
using elim(4) that(2) by linarith
ultimately have "(\<epsilon> - \<epsilon>\<^sub>1) * c n + \<epsilon>\<^sub>0 * (c (n+1) - \<epsilon>) > 0" by auto
moreover have "c n - \<epsilon>\<^sub>0 > 0" using \<open>\<epsilon>\<^sub>0 < \<epsilon> / 2\<close> elim(4) that(2) by linarith
moreover have "c n > 0" by (simp add: elim(4))
ultimately have "(c (n+1) - \<epsilon>) / c n < (c (n+1) - \<epsilon>\<^sub>1) / (c n - \<epsilon>\<^sub>0)"
by (auto simp add: field_simps)
also have "... \<le> (c (n+1) - \<epsilon>\<^sub>1) / (c n - \<epsilon>\<^sub>0) * (a (n+1) / a n)"
proof -
have "(c (n+1) - \<epsilon>\<^sub>1) / (c n - \<epsilon>\<^sub>0) > 0"
by (smt \<open>0 < (\<epsilon> - \<epsilon>\<^sub>1) * real_of_int (c n)\<close> \<open>0 < real_of_int (c n) - \<epsilon>\<^sub>0\<close>
divide_pos_pos elim(4) mult_le_0_iff of_int_less_1_iff that(2))
moreover have "(a (n+1) / a n) \<ge> 1"
using a_pos elim(5) by auto
ultimately show ?thesis by (metis mult_cancel_left1 real_mult_le_cancel_iff2)
qed
also have "... = (B * b (n+1)) / (B * b n)"
proof -
have "B * b n = c n * a n - c (n + 1)"
using elim by auto
also have "... = a n * (c n - \<epsilon>\<^sub>0)"
using a_pos[rule_format,of n] unfolding \<epsilon>\<^sub>0_def by (auto simp:field_simps)
finally have "B * b n = a n * (c n - \<epsilon>\<^sub>0)" .
moreover have "B * b (n+1) = a (n+1) * (c (n+1) - \<epsilon>\<^sub>1)"
unfolding \<epsilon>\<^sub>1_def
using a_pos[rule_format,of "n+1"]
apply (subst \<open>B * b (n + 1) = c (n + 1) * a (n + 1) - c (n + 2)\<close>)
by (auto simp:field_simps)
ultimately show ?thesis by (simp add: mult.commute)
qed
also have "... = b (n+1) / b n"
using \<open>B>0\<close> by auto
finally show ?case .
qed
qed
have eq_2_11:"\<exists>\<^sub>F n in sequentially. b (n+1) > b n + (1 - \<epsilon>)^2 * a n / B"
when "\<epsilon>>0" "\<epsilon><1" "\<not> (\<forall>\<^sub>F n in sequentially. c (n+1) \<le> c n)" for \<epsilon>::real
proof -
have "\<exists>\<^sub>F x in sequentially. c x < c (Suc x) " using that(3)
by (simp add:not_eventually frequently_elim1)
moreover have "\<forall>\<^sub>F x in sequentially. \<bar>c (Suc x) / a x\<bar> < \<epsilon>"
using ca_vanish[unfolded tendsto_iff,rule_format, of \<epsilon>] \<open>\<epsilon>>0\<close> by auto
moreover have "\<forall>\<^sub>F n in sequentially. c n > 0 \<and> c (n+1) > 0"
proof -
have "\<forall>\<^sub>F n in sequentially. 0 < c (Suc n)"
using c_pos by (subst eventually_sequentially_Suc) simp
then show ?thesis using c_pos by eventually_elim auto
qed
ultimately show ?thesis using ab_event abc_event bc_epsilon[OF \<open>\<epsilon>>0\<close> \<open>\<epsilon><1\<close>]
proof (elim frequently_rev_mp,eventually_elim)
case (elim n)
then have "c (n+1) / a n < \<epsilon>"
using a_pos[rule_format,of n] by auto
also have "... \<le> \<epsilon> * c n" using elim(7) that(1) by auto
finally have "c (n+1) / a n < \<epsilon> * c n" .
then have "c (n+1) / c n < \<epsilon> * a n"
using a_pos[rule_format,of n] elim by (auto simp:field_simps)
then have "(1 - \<epsilon>) * a n < a n - c (n+1) / c n"
by (auto simp:algebra_simps)
then have "(1 - \<epsilon>)^2 * a n / B < (1 - \<epsilon>) * (a n - c (n+1) / c n) / B"
apply (subst (asm) real_mult_less_iff1[symmetric, of "(1-\<epsilon>)/B"])
using \<open>\<epsilon><1\<close> \<open>B>0\<close> by (auto simp:divide_simps power2_eq_square)
then have "b n + (1 - \<epsilon>)^2 * a n / B < b n + (1 - \<epsilon>) * (a n - c (n+1) / c n) / B"
using \<open>B>0\<close> by auto
also have "... = b n + (1 - \<epsilon>) * ((c n *a n - c (n+1)) / c n) / B"
using elim by (auto simp:field_simps)
also have "... = b n + (1 - \<epsilon>) * (b n / c n)"
proof -
have "B * b n = c n * a n - c (n + 1)" using elim by auto
from this[symmetric] show ?thesis
using \<open>B>0\<close> by simp
qed
also have "... = (1+(1-\<epsilon>)/c n) * b n"
by (auto simp:algebra_simps)
also have "... = ((c n+1-\<epsilon>)/c n) * b n"
using elim by (auto simp:divide_simps)
also have "... \<le> ((c (n+1) -\<epsilon>)/c n) * b n"
proof -
define cp where "cp = c n+1"
have "c (n+1) \<ge> cp" unfolding cp_def using \<open>c n < c (Suc n)\<close> by auto
moreover have "c n>0" "b n>0" using elim by auto
ultimately show ?thesis
apply (fold cp_def)
by (auto simp:divide_simps)
qed
also have "... < b (n+1)"
using elim by (auto simp:divide_simps)
finally show ?case .
qed
qed
have "\<forall>\<^sub>F n in sequentially. c (n+1) \<le> c n"
proof (rule ccontr)
assume "\<not> (\<forall>\<^sub>F n in sequentially. c (n + 1) \<le> c n)"
from eq_2_11[OF _ _ this,of "1/2"]
have "\<exists>\<^sub>F n in sequentially. b (n+1) > b n + 1/4 * a n / B"
by (auto simp:algebra_simps power2_eq_square)
then have *:"\<exists>\<^sub>F n in sequentially. (b (n+1) - b n) / a n > 1 / (B * 4)"
apply (elim frequently_elim1)
subgoal for n
using a_pos[rule_format,of n] by (auto simp:field_simps)
done
define f where "f = (\<lambda>n. (b (n+1) - b n) / a n)"
have "f \<longlonglongrightarrow> lim f"
using convergent_LIMSEQ_iff ba_lim_exist unfolding f_def by auto
from this[unfolded tendsto_iff,rule_format, of "1 / (B*4)"]
have "\<forall>\<^sub>F x in sequentially. \<bar>f x - lim f\<bar> < 1 / (B * 4)"
using \<open>B>0\<close> by (auto simp:dist_real_def)
moreover have "\<exists>\<^sub>F n in sequentially. f n > 1 / (B * 4)"
using * unfolding f_def by auto
ultimately have "\<exists>\<^sub>F n in sequentially. f n > 1 / (B * 4) \<and> \<bar>f n - lim f\<bar> < 1 / (B * 4)"
by (auto elim:frequently_eventually_frequently[rotated])
from frequently_ex[OF this]
obtain n where "f n > 1 / (B * 4)" "\<bar>f n - lim f\<bar> < 1 / (B * 4)"
by auto
moreover have "lim f \<le> 0" using ba_lim_leq unfolding f_def by auto
ultimately show False by linarith
qed
then obtain N where N_dec:"\<forall>n\<ge>N. c (n+1) \<le> c n" by (meson eventually_at_top_linorder)
define max_c where "max_c = (MAX n \<in> {..N}. c n)"
have max_c:"c n \<le> max_c" for n
proof (cases "n\<le>N")
case True
then show ?thesis unfolding max_c_def by simp
next
case False
then have "n\<ge>N" by auto
then have "c n\<le>c N"
proof (induct rule:nat_induct_at_least)
case base
then show ?case by simp
next
case (Suc n)
then have "c (n+1) \<le> c n" using N_dec by auto
then show ?case using \<open>c n \<le> c N\<close> by auto
qed
moreover have "c N \<le> max_c" unfolding max_c_def by auto
ultimately show ?thesis by auto
qed
have "max_c > 0 "
proof -
obtain N where "\<forall>n\<ge>N. 0 < c n"
using c_pos[unfolded eventually_at_top_linorder] by auto
then have "c N > 0" by auto
then show ?thesis using max_c[of N] by simp
qed
have ba_limsup_bound:"1/(B*(B+1)) \<le> limsup (\<lambda>n. b n/a n)"
"limsup (\<lambda>n. b n/a n) \<le> max_c / B + 1 / (B+1)"
proof -
define f where "f = (\<lambda>n. b n/a n)"
from tendsto_mult_right_zero[OF bac_close,of "1/B"]
have "(\<lambda>n. f n - c n / B) \<longlonglongrightarrow> 0"
unfolding f_def using \<open>B>0\<close> by (auto simp:algebra_simps)
from this[unfolded tendsto_iff,rule_format,of "1/(B+1)"]
have "\<forall>\<^sub>F x in sequentially. \<bar>f x - c x / B\<bar> < 1 / (B+1)"
using \<open>B>0\<close> by auto
then have *:"\<forall>\<^sub>F n in sequentially. 1/(B*(B+1)) \<le> ereal (f n) \<and> ereal (f n) \<le> max_c / B + 1 / (B+1)"
using c_pos
proof eventually_elim
case (elim n)
then have "f n - c n / B < 1 / (B+1)" by auto
then have "f n < c n / B + 1 / (B+1)" by simp
also have "... \<le> max_c / B + 1 / (B+1)"
using max_c[of n] using \<open>B>0\<close> by (auto simp:divide_simps)
finally have *:"f n < max_c / B + 1 / (B+1)" .
have "1/(B*(B+1)) = 1/B - 1 / (B+1)"
using \<open>B>0\<close> by (auto simp:divide_simps)
also have "... \<le> c n/B - 1 / (B+1)"
using \<open>0 < c n\<close> \<open>B>0\<close> by (auto,auto simp:divide_simps)
also have "... < f n" using elim by auto
finally have "1/(B*(B+1)) < f n" .
with * show ?case by simp
qed
show "limsup f \<le> max_c / B + 1 / (B+1)"
apply (rule Limsup_bounded)
using * by (auto elim:eventually_mono)
have "1/(B*(B+1)) \<le> liminf f"
apply (rule Liminf_bounded)
using * by (auto elim:eventually_mono)
also have "liminf f \<le> limsup f" by (simp add: Liminf_le_Limsup)
finally show "1/(B*(B+1)) \<le> limsup f" .
qed
have "0 < inverse (ereal (max_c / B + 1 / (B+1)))"
using \<open>max_c > 0\<close> \<open>B>0\<close>
by (simp add: pos_add_strict)
also have "... \<le> inverse (limsup (\<lambda>n. b n/a n))"
proof (rule ereal_inverse_antimono[OF _ ba_limsup_bound(2)])
have "0<1/(B*(B+1))" using \<open>B>0\<close> by auto
also have "... \<le> limsup (\<lambda>n. b n/a n)" using ba_limsup_bound(1) .
finally show "0\<le>limsup (\<lambda>n. b n/a n)" using zero_ereal_def by auto
qed
also have "... = liminf (\<lambda>n. inverse (ereal ( b n/a n)))"
apply (subst Liminf_inverse_ereal[symmetric])
using a_pos ab_event by (auto elim!:eventually_mono simp:divide_simps)
also have "... = liminf (\<lambda>n. ( a n/b n))"
apply (rule Liminf_eq)
using a_pos ab_event
apply (auto elim!:eventually_mono)
by (metis less_int_code(1))
finally have "liminf (\<lambda>n. ( a n/b n)) > 0" .
then show False using \<open>liminf (\<lambda>n. a n / b n) = 0\<close> by simp
qed
end
section\<open>Some auxiliary results on the prime numbers. \<close>
lemma nth_prime_nonzero[simp]:"nth_prime n \<noteq> 0"
by (simp add: prime_gt_0_nat prime_nth_prime)
lemma nth_prime_gt_zero[simp]:"nth_prime n >0"
by (simp add: prime_gt_0_nat prime_nth_prime)
lemma ratio_of_consecutive_primes:
"(\<lambda>n. nth_prime (n+1)/nth_prime n) \<longlonglongrightarrow>1"
proof -
define f where "f=(\<lambda>x. real (nth_prime (Suc x)) /real (nth_prime x))"
define g where "g=(\<lambda>x. (real x * ln (real x))
/ (real (Suc x) * ln (real (Suc x))))"
have p_n:"(\<lambda>x. real (nth_prime x) / (real x * ln (real x))) \<longlonglongrightarrow> 1"
using nth_prime_asymptotics[unfolded asymp_equiv_def,simplified] .
moreover have p_sn:"(\<lambda>n. real (nth_prime (Suc n))
/ (real (Suc n) * ln (real (Suc n)))) \<longlonglongrightarrow> 1"
using nth_prime_asymptotics[unfolded asymp_equiv_def,simplified
,THEN LIMSEQ_Suc] .
ultimately have "(\<lambda>x. f x * g x) \<longlonglongrightarrow> 1"
using tendsto_divide[OF p_sn p_n]
unfolding f_def g_def by (auto simp:algebra_simps)
moreover have "g \<longlonglongrightarrow> 1" unfolding g_def
by real_asymp
ultimately have "(\<lambda>x. if g x = 0 then 0 else f x) \<longlonglongrightarrow> 1"
apply (drule_tac tendsto_divide[OF _ \<open>g \<longlonglongrightarrow> 1\<close>])
by auto
then have "f \<longlonglongrightarrow> 1"
proof (elim filterlim_mono_eventually)
have "\<forall>\<^sub>F x in sequentially. (if g (x+3) = 0 then 0
else f (x+3)) = f (x+3)"
unfolding g_def by auto
then show "\<forall>\<^sub>F x in sequentially. (if g x = 0 then 0 else f x) = f x"
apply (subst (asm) eventually_sequentially_seg)
by simp
qed auto
then show ?thesis unfolding f_def by auto
qed
lemma nth_prime_double_sqrt_less:
assumes "\<epsilon> > 0"
shows "\<forall>\<^sub>F n in sequentially. (nth_prime (2*n) - nth_prime n)
/ sqrt (nth_prime n) < n powr (1/2+\<epsilon>)"
proof -
define pp ll where
"pp=(\<lambda>n. (nth_prime (2*n) - nth_prime n) / sqrt (nth_prime n))" and
"ll=(\<lambda>x::nat. x * ln x)"
have pp_pos:"pp (n+1) > 0" for n
unfolding pp_def by simp
have "(\<lambda>x. nth_prime (2 * x)) \<sim>[sequentially] (\<lambda>x. (2 * x) * ln (2 * x))"
using nth_prime_asymptotics[THEN asymp_equiv_compose
,of "(*) 2" sequentially,unfolded comp_def]
using mult_nat_left_at_top pos2 by blast
also have "... \<sim>[sequentially] (\<lambda>x. 2 *x * ln x)"
by real_asymp
finally have "(\<lambda>x. nth_prime (2 * x)) \<sim>[sequentially] (\<lambda>x. 2 *x * ln x)" .
from this[unfolded asymp_equiv_def, THEN tendsto_mult_left,of 2]
have "(\<lambda>x. nth_prime (2 * x) / (x * ln x)) \<longlonglongrightarrow> 2"
unfolding asymp_equiv_def by auto
moreover have *:"(\<lambda>x. nth_prime x / (x * ln x)) \<longlonglongrightarrow> 1"
using nth_prime_asymptotics unfolding asymp_equiv_def by auto
ultimately
have "(\<lambda>x. (nth_prime (2 * x) - nth_prime x) / ll x) \<longlonglongrightarrow> 1"
unfolding ll_def
apply -
apply (drule (1) tendsto_diff)
apply (subst of_nat_diff,simp)
by (subst diff_divide_distrib,simp)
moreover have "(\<lambda>x. sqrt (nth_prime x) / sqrt (ll x)) \<longlonglongrightarrow> 1"
unfolding ll_def
using tendsto_real_sqrt[OF *]
by (auto simp: real_sqrt_divide)
ultimately have "(\<lambda>x. pp x * (sqrt (ll x) / (ll x))) \<longlonglongrightarrow> 1"
apply -
apply (drule (1) tendsto_divide,simp)
by (auto simp:field_simps of_nat_diff pp_def)
moreover have "\<forall>\<^sub>F x in sequentially. sqrt (ll x) / ll x = 1/sqrt (ll x)"
apply (subst eventually_sequentially_Suc[symmetric])
by (auto intro!:eventuallyI simp:ll_def divide_simps)
ultimately have "(\<lambda>x. pp x / sqrt (ll x)) \<longlonglongrightarrow> 1"
apply (elim filterlim_mono_eventually)
by (auto elim!:eventually_mono) (metis mult.right_neutral times_divide_eq_right)
moreover have "(\<lambda>x. sqrt (ll x) / x powr (1/2+\<epsilon>)) \<longlonglongrightarrow> 0"
unfolding ll_def using \<open>\<epsilon>>0\<close> by real_asymp
ultimately have "(\<lambda>x. pp x / x powr (1/2+\<epsilon>) *
(sqrt (ll x) / sqrt (ll x))) \<longlonglongrightarrow> 0"
apply -
apply (drule (1) tendsto_mult)
by (auto elim:filterlim_mono_eventually)
moreover have "\<forall>\<^sub>F x in sequentially. sqrt (ll x) / sqrt (ll x) = 1"
apply (subst eventually_sequentially_Suc[symmetric])
by (auto intro!:eventuallyI simp:ll_def )
ultimately have "(\<lambda>x. pp x / x powr (1/2+\<epsilon>)) \<longlonglongrightarrow> 0"
apply (elim filterlim_mono_eventually)
by (auto elim:eventually_mono)
from tendstoD[OF this, of 1,simplified]
show "\<forall>\<^sub>F x in sequentially. pp x < x powr (1 / 2 + \<epsilon>)"
apply (elim eventually_mono_sequentially[of _ 1])
using pp_pos by auto
qed
section \<open>Theorem 3.1\<close>
text\<open>Theorem 3.1 is an application of Theorem 2.1 with the sequences considered involving
the prime numbers.\<close>
theorem theorem_3_10_Erdos_Straus:
fixes a::"nat \<Rightarrow> int"
assumes a_pos:"\<forall> n. a n >0" and "mono a"
and nth_1:"(\<lambda>n. nth_prime n / (a n)^2) \<longlonglongrightarrow> 0"
and nth_2:"liminf (\<lambda>n. a n / nth_prime n) = 0"
shows "(\<Sum>n. (nth_prime n / (\<Prod>i \<le> n. a i))) \<notin> \<rat>"
proof
assume asm:"(\<Sum>n. (nth_prime n / (\<Prod>i \<le> n. a i))) \<in> \<rat>"
have a2_omega:"(\<lambda>n. (a n)^2) \<in> \<omega>(\<lambda>x. x * ln x)"
proof -
have "(\<lambda>n. real (nth_prime n)) \<in> o(\<lambda>n. real_of_int ((a n)\<^sup>2))"
apply (rule smalloI_tendsto[OF nth_1])
using a_pos by (metis (mono_tags, lifting) less_int_code(1)
not_eventuallyD of_int_0_eq_iff zero_eq_power2)
moreover have "(\<lambda>x. real (nth_prime x)) \<in> \<Omega>(\<lambda>x. real x * ln (real x))"
using nth_prime_bigtheta
by blast
ultimately show ?thesis
using landau_omega.small_big_trans smallo_imp_smallomega by blast
qed
have a_gt_1:"\<forall>\<^sub>F n in sequentially. 1 < a n"
proof -
have "\<forall>\<^sub>F x in sequentially. \<bar>x * ln x\<bar> \<le> (a x)\<^sup>2"
using a2_omega[unfolded smallomega_def,simplified,rule_format,of 1]
by auto
then have "\<forall>\<^sub>F x in sequentially. \<bar>(x+3) * ln (x+3)\<bar> \<le> (a (x+3))\<^sup>2"
apply (subst (asm) eventually_sequentially_seg[symmetric, of _ 3])
by simp
then have "\<forall>\<^sub>F n in sequentially. 1 < a ( n+3)"
proof (elim eventually_mono)
fix x
assume "\<bar>real (x + 3) * ln (real (x + 3))\<bar> \<le> real_of_int ((a (x + 3))\<^sup>2)"
moreover have "\<bar>real (x + 3) * ln (real (x + 3))\<bar> > 3"
proof -
have "ln (real (x + 3)) > 1"
apply simp using ln3_gt_1 ln_gt_1 by force
moreover have "real(x+3) \<ge> 3" by simp
ultimately have "(x+3)*ln (real (x + 3)) > 3*1 "
apply (rule_tac mult_le_less_imp_less)
by auto
then show ?thesis by auto
qed
ultimately have "real_of_int ((a (x + 3))\<^sup>2) > 3"
by auto
then show "1 < a (x + 3)"
by (smt Suc3_eq_add_3 a_pos add.commute of_int_1 one_power2)
qed
then show ?thesis
apply (subst eventually_sequentially_seg[symmetric, of _ 3])
by auto
qed
obtain B::int and c where
"B>0" and Bc_large:"\<forall>\<^sub>F n in sequentially. B * nth_prime n
= c n * a n - c (n + 1) \<and> \<bar>c (n + 1)\<bar> < a n / 2"
and ca_vanish: "(\<lambda>n. c (Suc n) / real_of_int (a n)) \<longlonglongrightarrow> 0"
proof -
note a_gt_1
moreover have "(\<lambda>n. real_of_int \<bar>int (nth_prime n)\<bar>
/ real_of_int (a (n - 1) * a n)) \<longlonglongrightarrow> 0"
proof -
define f where "f=(\<lambda>n. nth_prime (n+1) / (a n * a (n+1)))"
define g where "g=(\<lambda>n. 2*nth_prime n / (a n)^2)"
have "\<forall>\<^sub>F x in sequentially. norm (f x) \<le> g x"
proof -
have "\<forall>\<^sub>F n in sequentially. nth_prime (n+1) < 2*nth_prime n"
using ratio_of_consecutive_primes[unfolded tendsto_iff
,rule_format,of 1,simplified]
apply (elim eventually_mono)
by (auto simp :divide_simps dist_norm)
moreover have "\<forall>\<^sub>F n in sequentially. real_of_int (a n * a (n+1))
\<ge> (a n)^2"
apply (rule eventuallyI)
using \<open>mono a\<close> by (auto simp:power2_eq_square a_pos incseq_SucD)
ultimately show ?thesis unfolding f_def g_def
apply eventually_elim
apply (subst norm_divide)
apply (rule_tac linordered_field_class.frac_le)
using a_pos[rule_format, THEN order.strict_implies_not_eq ]
by auto
qed
moreover have "g \<longlonglongrightarrow> 0 "
using nth_1[THEN tendsto_mult_right_zero,of 2] unfolding g_def
by auto
ultimately have "f \<longlonglongrightarrow> 0"
using Lim_null_comparison[of f g sequentially]
by auto
then show ?thesis
unfolding f_def
by (rule_tac LIMSEQ_imp_Suc) auto
qed
moreover have "(\<Sum>n. real_of_int (int (nth_prime n))
/ real_of_int (prod a {..n})) \<in> \<rat>"
using asm by simp
ultimately have "\<exists>B>0. \<exists>c. (\<forall>\<^sub>F n in sequentially.
B * int (nth_prime n) = c n * a n - c (n + 1) \<and>
real_of_int \<bar>c (n + 1)\<bar> < real_of_int (a n) / 2) \<and>
(\<lambda>n. real_of_int (c (Suc n)) / real_of_int (a n)) \<longlonglongrightarrow> 0"
using ab_rationality_imp[OF a_pos,of nth_prime] by fast
then show thesis
apply clarify
apply (rule_tac c=c and B=B in that)
by auto
qed
have bac_close:"(\<lambda>n. B * nth_prime n / a n - c n) \<longlonglongrightarrow> 0"
proof -
have "\<forall>\<^sub>F n in sequentially. B * nth_prime n - c n * a n + c (n + 1) = 0"
using Bc_large by (auto elim!:eventually_mono)
then have "\<forall>\<^sub>F n in sequentially. (B * nth_prime n - c n * a n + c (n+1)) / a n = 0 "
apply eventually_elim
by auto
then have "\<forall>\<^sub>F n in sequentially. B * nth_prime n / a n - c n + c (n + 1) / a n = 0"
apply eventually_elim
using a_pos by (auto simp:divide_simps) (metis less_irrefl)
then have "(\<lambda>n. B * nth_prime n / a n - c n + c (n + 1) / a n) \<longlonglongrightarrow> 0"
by (simp add: eventually_mono tendsto_iff)
from tendsto_diff[OF this ca_vanish]
show ?thesis by auto
qed
have c_pos:"\<forall>\<^sub>F n in sequentially. c n > 0"
proof -
from bac_close have *:"\<forall>\<^sub>F n in sequentially. c n \<ge> 0"
apply (elim tendsto_of_int_diff_0)
using a_gt_1 apply (eventually_elim)
using \<open>B>0\<close> by auto
show ?thesis
proof (rule ccontr)
assume "\<not> (\<forall>\<^sub>F n in sequentially. c n > 0)"
moreover have "\<forall>\<^sub>F n in sequentially. c (Suc n) \<ge> 0 \<and> c n\<ge>0"
using * eventually_sequentially_Suc[of "\<lambda>n. c n\<ge>0"]
by (metis (mono_tags, lifting) eventually_at_top_linorder le_Suc_eq)
ultimately have "\<exists>\<^sub>F n in sequentially. c n = 0 \<and> c (Suc n) \<ge> 0"
using eventually_elim2 frequently_def by fastforce
moreover have "\<forall>\<^sub>F n in sequentially. nth_prime n > 0
\<and> B * nth_prime n = c n * a n - c (n + 1)"
using Bc_large by eventually_elim auto
ultimately have "\<exists>\<^sub>F n in sequentially. c n = 0 \<and> c (Suc n) \<ge> 0
\<and> B * nth_prime n = c n * a n - c (n + 1)"
using frequently_eventually_frequently by fastforce
from frequently_ex[OF this]
obtain n where "c n = 0" "c (Suc n) \<ge> 0"
"B * nth_prime n = c n * a n - c (n + 1)"
by auto
then have "B * nth_prime n \<le> 0" by auto
then show False using \<open>B > 0\<close>
by (simp add: mult_le_0_iff)
qed
qed
have B_nth_prime:"\<forall>\<^sub>F n in sequentially. nth_prime n > B"
proof -
have "\<forall>\<^sub>F x in sequentially. B+1 \<le> nth_prime x"
using nth_prime_at_top[unfolded filterlim_at_top_ge[where c="nat B+1"]
,rule_format,of "nat B + 1",simplified]
apply (elim eventually_mono)
using \<open>B>0\<close> by auto
then show ?thesis
apply (elim eventually_mono)
by auto
qed
have bc_epsilon:"\<forall>\<^sub>F n in sequentially. nth_prime (n+1)
/ nth_prime n > (c (n+1) - \<epsilon>) / c n" when "\<epsilon>>0" "\<epsilon><1" for \<epsilon>::real
proof -
have "\<forall>\<^sub>F x in sequentially. \<bar>c (Suc x) / a x\<bar> < \<epsilon> / 2"
using ca_vanish[unfolded tendsto_iff,rule_format, of "\<epsilon>/2"] \<open>\<epsilon>>0\<close> by auto
moreover then have "\<forall>\<^sub>F x in sequentially. \<bar>c (x+2) / a (x+1)\<bar> < \<epsilon> / 2"
apply (subst (asm) eventually_sequentially_Suc[symmetric])
by simp
moreover have "\<forall>\<^sub>F n in sequentially. B * nth_prime (n+1) = c (n+1) * a (n+1) - c (n + 2)"
using Bc_large
apply (subst (asm) eventually_sequentially_Suc[symmetric])
by (auto elim:eventually_mono)
moreover have "\<forall>\<^sub>F n in sequentially. c n > 0 \<and> c (n+1) > 0 \<and> c (n+2) > 0"
proof -
have "\<forall>\<^sub>F n in sequentially. 0 < c (Suc n)"
using c_pos by (subst eventually_sequentially_Suc) simp
moreover then have "\<forall>\<^sub>F n in sequentially. 0 < c (Suc (Suc n))"
using c_pos by (subst eventually_sequentially_Suc) simp
ultimately show ?thesis using c_pos by eventually_elim auto
qed
ultimately show ?thesis using Bc_large
proof eventually_elim
case (elim n)
define \<epsilon>\<^sub>0 \<epsilon>\<^sub>1 where "\<epsilon>\<^sub>0 = c (n+1) / a n" and "\<epsilon>\<^sub>1 = c (n+2) / a (n+1)"
have "\<epsilon>\<^sub>0 > 0" "\<epsilon>\<^sub>1 > 0" "\<epsilon>\<^sub>0 < \<epsilon>/2" "\<epsilon>\<^sub>1 < \<epsilon>/2"
using a_pos elim \<open>mono a\<close>
by (auto simp add: \<epsilon>\<^sub>0_def \<epsilon>\<^sub>1_def abs_of_pos)
have "(\<epsilon> - \<epsilon>\<^sub>1) * c n > 0"
apply (rule mult_pos_pos)
using \<open>\<epsilon>\<^sub>1 > 0\<close> \<open>\<epsilon>\<^sub>1 < \<epsilon>/2\<close> \<open>\<epsilon>>0\<close> elim by auto
moreover have "\<epsilon>\<^sub>0 * (c (n+1) - \<epsilon>) > 0"
apply (rule mult_pos_pos[OF \<open>\<epsilon>\<^sub>0 > 0\<close>])
using elim(4) that(2) by linarith
ultimately have "(\<epsilon> - \<epsilon>\<^sub>1) * c n + \<epsilon>\<^sub>0 * (c (n+1) - \<epsilon>) > 0" by auto
moreover have "c n - \<epsilon>\<^sub>0 > 0" using \<open>\<epsilon>\<^sub>0 < \<epsilon> / 2\<close> elim(4) that(2) by linarith
moreover have "c n > 0" by (simp add: elim(4))
ultimately have "(c (n+1) - \<epsilon>) / c n < (c (n+1) - \<epsilon>\<^sub>1) / (c n - \<epsilon>\<^sub>0)"
by (auto simp add:field_simps)
also have "... \<le> (c (n+1) - \<epsilon>\<^sub>1) / (c n - \<epsilon>\<^sub>0) * (a (n+1) / a n)"
proof -
have "(c (n+1) - \<epsilon>\<^sub>1) / (c n - \<epsilon>\<^sub>0) > 0"
by (smt \<open>0 < (\<epsilon> - \<epsilon>\<^sub>1) * real_of_int (c n)\<close> \<open>0 < real_of_int (c n) - \<epsilon>\<^sub>0\<close>
divide_pos_pos elim(4) mult_le_0_iff of_int_less_1_iff that(2))
moreover have "(a (n+1) / a n) \<ge> 1"
using a_pos \<open>mono a\<close> by (simp add: mono_def)
ultimately show ?thesis by (metis mult_cancel_left1 real_mult_le_cancel_iff2)
qed
also have "... = (B * nth_prime (n+1)) / (B * nth_prime n)"
proof -
have "B * nth_prime n = c n * a n - c (n + 1)"
using elim by auto
also have "... = a n * (c n - \<epsilon>\<^sub>0)"
using a_pos[rule_format,of n] unfolding \<epsilon>\<^sub>0_def by (auto simp:field_simps)
finally have "B * nth_prime n = a n * (c n - \<epsilon>\<^sub>0)" .
moreover have "B * nth_prime (n+1) = a (n+1) * (c (n+1) - \<epsilon>\<^sub>1)"
unfolding \<epsilon>\<^sub>1_def
using a_pos[rule_format,of "n+1"]
apply (subst \<open>B * nth_prime (n + 1) = c (n + 1) * a (n + 1) - c (n + 2)\<close>)
by (auto simp:field_simps)
ultimately show ?thesis by (simp add: mult.commute)
qed
also have "... = nth_prime (n+1) / nth_prime n"
using \<open>B>0\<close> by auto
finally show ?case .
qed
qed
have c_ubound:"\<forall>x. \<exists>n. c n > x"
proof (rule ccontr)
assume " \<not> (\<forall>x. \<exists>n. x < c n)"
then obtain ub where "\<forall>n. c n \<le> ub" "ub > 0"
by (meson dual_order.trans int_one_le_iff_zero_less le_cases not_le)
define pa where "pa = (\<lambda>n. nth_prime n / a n)"
have pa_pos:"\<And>n. pa n > 0" unfolding pa_def by (simp add: a_pos)
have "liminf (\<lambda>n. 1 / pa n) = 0"
using nth_2 unfolding pa_def by auto
then have "(\<exists>y<ereal (real_of_int B / real_of_int (ub + 1)).
\<exists>\<^sub>F x in sequentially. ereal (1 / pa x) \<le> y)"
apply (subst less_Liminf_iff[symmetric])
using \<open>0 < B\<close> \<open>0 < ub\<close> by auto
then have "\<exists>\<^sub>F x in sequentially. 1 / pa x < B/(ub+1)"
by (meson frequently_mono le_less_trans less_ereal.simps(1))
then have "\<exists>\<^sub>F x in sequentially. B*pa x > (ub+1)"
apply (elim frequently_elim1)
by (metis \<open>0 < ub\<close> mult.left_neutral of_int_0_less_iff pa_pos pos_divide_less_eq
pos_less_divide_eq times_divide_eq_left zless_add1_eq)
moreover have "\<forall>\<^sub>F x in sequentially. c x \<le> ub"
using \<open>\<forall>n. c n \<le> ub\<close> by simp
ultimately have "\<exists>\<^sub>F x in sequentially. B*pa x - c x > 1"
apply (elim frequently_rev_mp eventually_mono)
by linarith
moreover have "(\<lambda>n. B * pa n - c n) \<longlonglongrightarrow>0"
unfolding pa_def using bac_close by auto
from tendstoD[OF this,of 1]
have "\<forall>\<^sub>F n in sequentially. \<bar>B * pa n - c n\<bar> < 1"
by auto
ultimately have "\<exists>\<^sub>F x in sequentially. B*pa x - c x > 1 \<and> \<bar>B * pa x - c x\<bar> < 1"
using frequently_eventually_frequently by blast
then show False
by (simp add: frequently_def)
qed
have eq_2_11:"\<forall>\<^sub>F n in sequentially. c (n+1)>c n \<longrightarrow>
nth_prime (n+1) > nth_prime n + (1 - \<epsilon>)^2 * a n / B"
when "\<epsilon>>0" "\<epsilon><1" for \<epsilon>::real
proof -
have "\<forall>\<^sub>F x in sequentially. \<bar>c (Suc x) / a x\<bar> < \<epsilon>"
using ca_vanish[unfolded tendsto_iff,rule_format, of \<epsilon>] \<open>\<epsilon>>0\<close> by auto
moreover have "\<forall>\<^sub>F n in sequentially. c n > 0 \<and> c (n+1) > 0"
proof -
have "\<forall>\<^sub>F n in sequentially. 0 < c (Suc n)"
using c_pos by (subst eventually_sequentially_Suc) simp
then show ?thesis using c_pos by eventually_elim auto
qed
ultimately show ?thesis using Bc_large bc_epsilon[OF \<open>\<epsilon>>0\<close> \<open>\<epsilon><1\<close>]
proof (eventually_elim, rule_tac impI)
case (elim n)
assume "c n < c (n + 1)"
have "c (n+1) / a n < \<epsilon>"
using a_pos[rule_format,of n] using elim(1,2) by auto
also have "... \<le> \<epsilon> * c n" using elim(2) that(1) by auto
finally have "c (n+1) / a n < \<epsilon> * c n" .
then have "c (n+1) / c n < \<epsilon> * a n"
using a_pos[rule_format,of n] elim by (auto simp:field_simps)
then have "(1 - \<epsilon>) * a n < a n - c (n+1) / c n"
by (auto simp:algebra_simps)
then have "(1 - \<epsilon>)^2 * a n / B < (1 - \<epsilon>) * (a n - c (n+1) / c n) / B"
apply (subst (asm) real_mult_less_iff1[symmetric, of "(1-\<epsilon>)/B"])
using \<open>\<epsilon><1\<close> \<open>B>0\<close> by (auto simp:divide_simps power2_eq_square)
then have "nth_prime n + (1 - \<epsilon>)^2 * a n / B < nth_prime n + (1 - \<epsilon>) * (a n - c (n+1) / c n) / B"
using \<open>B>0\<close> by auto
also have "... = nth_prime n + (1 - \<epsilon>) * ((c n *a n - c (n+1)) / c n) / B"
using elim by (auto simp:field_simps)
also have "... = nth_prime n + (1 - \<epsilon>) * (nth_prime n / c n)"
proof -
have "B * nth_prime n = c n * a n - c (n + 1)" using elim by auto
from this[symmetric] show ?thesis
using \<open>B>0\<close> by simp
qed
also have "... = (1+(1-\<epsilon>)/c n) * nth_prime n"
by (auto simp:algebra_simps)
also have "... = ((c n+1-\<epsilon>)/c n) * nth_prime n"
using elim by (auto simp:divide_simps)
also have "... \<le> ((c (n+1) -\<epsilon>)/c n) * nth_prime n"
proof -
define cp where "cp = c n+1"
have "c (n+1) \<ge> cp" unfolding cp_def using \<open>c n < c (n + 1)\<close> by auto
moreover have "c n>0" "nth_prime n>0" using elim by auto
ultimately show ?thesis
apply (fold cp_def)
by (auto simp:divide_simps)
qed
also have "... < nth_prime (n+1)"
using elim by (auto simp:divide_simps)
finally show "real (nth_prime n) + (1 - \<epsilon>)\<^sup>2 * real_of_int (a n)
/ real_of_int B < real (nth_prime (n + 1))" .
qed
qed
have c_neq_large:"\<forall>\<^sub>F n in sequentially. c (n+1) \<noteq> c n"
proof (rule ccontr)
assume "\<not> (\<forall>\<^sub>F n in sequentially. c (n + 1) \<noteq> c n)"
then have that:"\<exists>\<^sub>F n in sequentially. c (n + 1) = c n"
unfolding frequently_def .
have "\<forall>\<^sub>F x in sequentially. (B * int (nth_prime x) = c x * a x - c (x + 1)
\<and> \<bar>real_of_int (c (x + 1))\<bar> < real_of_int (a x) / 2) \<and> 0 < c x \<and> B < int (nth_prime x)
\<and> (c (x+1)>c x \<longrightarrow> nth_prime (x+1) > nth_prime x + a x / (2* B))"
using Bc_large c_pos B_nth_prime eq_2_11[of "1-1/ sqrt 2",simplified]
by eventually_elim (auto simp:divide_simps)
then have "\<exists>\<^sub>F m in sequentially. nth_prime (m+1) > (1+1/(2*B))*nth_prime m"
proof (elim frequently_eventually_at_top[OF that, THEN frequently_at_top_elim])
fix n
assume "c (n + 1) = c n \<and>
(\<forall>y\<ge>n. (B * int (nth_prime y) = c y * a y - c (y + 1) \<and>
\<bar>real_of_int (c (y + 1))\<bar> < real_of_int (a y) / 2) \<and>
0 < c y \<and> B < int (nth_prime y) \<and> (c y < c (y + 1) \<longrightarrow>
real (nth_prime y) + real_of_int (a y) / real_of_int (2 * B)
< real (nth_prime (y + 1))))"
then have "c (n + 1) = c n"
and Bc_eq:"\<forall>y\<ge>n. B * int (nth_prime y) = c y * a y - c (y + 1) \<and> 0 < c y
\<and> \<bar>real_of_int (c (y + 1))\<bar> < real_of_int (a y) / 2
\<and> B < int (nth_prime y)
\<and> (c y < c (y + 1) \<longrightarrow>
real (nth_prime y) + real_of_int (a y) / real_of_int (2 * B)
< real (nth_prime (y + 1)))"
by auto
obtain m where "n<m" "c m \<le> c n" "c n<c (m+1)"
proof -
have "\<exists>N. N > n \<and> c N > c n"
using c_ubound[rule_format, of "MAX x\<in>{..n}. c x"]
by (metis Max_ge atMost_iff dual_order.trans finite_atMost finite_imageI image_eqI
linorder_not_le order_refl)
then obtain N where "N>n" "c N>c n" by auto
define A m where "A={m. n<m \<and> (m+1)\<le>N \<and> c (m+1) > c n}" and "m = Min A"
have "finite A" unfolding A_def
by (metis (no_types, lifting) A_def add_leE finite_nat_set_iff_bounded_le mem_Collect_eq)
moreover have "N-1\<in>A" unfolding A_def
using \<open>c n < c N\<close> \<open>n < N\<close> \<open>c (n + 1) = c n\<close>
by (smt Suc_diff_Suc Suc_eq_plus1 Suc_leI Suc_pred add.commute
add_diff_inverse_nat add_leD1 diff_is_0_eq' mem_Collect_eq nat_add_left_cancel_less
zero_less_one)
ultimately have "m\<in>A"
using Min_in unfolding m_def by auto
then have "n<m" "c n<c (m+1)" "m>0"
unfolding m_def A_def by auto
moreover have "c m \<le> c n"
proof (rule ccontr)
assume " \<not> c m \<le> c n"
then have "m-1\<in>A" using \<open>m\<in>A\<close> \<open>c (n + 1) = c n\<close>
unfolding A_def
by auto (smt One_nat_def Suc_eq_plus1 Suc_lessI less_diff_conv)
from Min_le[OF \<open>finite A\<close> this,folded m_def] \<open>m>0\<close> show False by auto
qed
ultimately show ?thesis using that[of m] by auto
qed
have "(1 + 1 / (2 * B)) * nth_prime m < nth_prime m + a m / (2*B)"
proof -
have "nth_prime m < a m"
proof -
have "B * int (nth_prime m) < c m * (a m - 1)"
using Bc_eq[rule_format,of m] \<open>c m \<le> c n\<close> \<open>c n < c (m + 1)\<close> \<open>n < m\<close>
by (auto simp:algebra_simps)
also have "... \<le> c n * (a m - 1)"
by (simp add: \<open>c m \<le> c n\<close> a_pos mult_right_mono)
finally have "B * int (nth_prime m) < c n * (a m - 1)" .
moreover have "c n\<le>B"
proof -
have " B * int (nth_prime n) = c n * (a n - 1)" "B < int (nth_prime n)"
and c_a:"\<bar>real_of_int (c (n + 1))\<bar> < real_of_int (a n) / 2"
using Bc_eq[rule_format,of n] \<open>c (n + 1) = c n\<close> by (auto simp:algebra_simps)
from this(1) have " c n dvd (B * int (nth_prime n))"
by simp
moreover have "coprime (c n) (int (nth_prime n))"
proof -
have "c n < int (nth_prime n)"
proof (rule ccontr)
assume "\<not> c n < int (nth_prime n)"
then have asm:"c n \<ge> int (nth_prime n)" by auto
then have "a n > 2 * nth_prime n"
using c_a \<open>c (n + 1) = c n\<close> by auto
then have "a n -1 \<ge> 2 * nth_prime n"
by simp
then have "a n - 1 > 2 * B"
using \<open>B < int (nth_prime n)\<close> by auto
from mult_le_less_imp_less[OF asm this] \<open>B>0\<close>
have "int (nth_prime n) * (2 * B) < c n * (a n - 1)"
by auto
then show False using \<open>B * int (nth_prime n) = c n * (a n - 1)\<close>
by (smt \<open>0 < B\<close> \<open>B < int (nth_prime n)\<close> combine_common_factor
mult.commute mult_pos_pos)
qed
then have "\<not> nth_prime n dvd c n"
by (simp add: Bc_eq zdvd_not_zless)
then have "coprime (int (nth_prime n)) (c n)"
by (auto intro!:prime_imp_coprime_int)
then show ?thesis using coprime_commute by blast
qed
ultimately have "c n dvd B"
using coprime_dvd_mult_left_iff by auto
then show ?thesis using \<open>0 < B\<close> zdvd_imp_le by blast
qed
moreover have "c n > 0 " using Bc_eq by blast
ultimately show ?thesis
using \<open>B>0\<close> by (smt a_pos mult_mono)
qed
then show ?thesis using \<open>B>0\<close> by (auto simp:field_simps)
qed
also have "... < nth_prime (m+1)"
using Bc_eq[rule_format, of m] \<open>n<m\<close> \<open>c m \<le> c n\<close> \<open>c n < c (m+1)\<close>
by linarith
finally show "\<exists>j>n. (1 + 1 / real_of_int (2 * B)) * real (nth_prime j)
< real (nth_prime (j + 1))" using \<open>m>n\<close> by auto
qed
then have "\<exists>\<^sub>F m in sequentially. nth_prime (m+1)/nth_prime m > (1+1/(2*B))"
by (auto elim:frequently_elim1 simp:field_simps)
moreover have "\<forall>\<^sub>F m in sequentially. nth_prime (m+1)/nth_prime m < (1+1/(2*B))"
using ratio_of_consecutive_primes[unfolded tendsto_iff,rule_format,of "1/(2*B)"]
\<open>B>0\<close>
unfolding dist_real_def
by (auto elim!:eventually_mono simp:algebra_simps)
ultimately show False by (simp add: eventually_mono frequently_def)
qed
have c_gt_half:"\<forall>\<^sub>F N in sequentially. card {n\<in>{N..<2*N}. c n > c (n+1)} > N / 2"
proof -
define h where "h=(\<lambda>n. (nth_prime (2*n) - nth_prime n)
/ sqrt (nth_prime n))"
have "\<forall>\<^sub>F n in sequentially. h n < n / 2"
proof -
have "\<forall>\<^sub>F n in sequentially. h n < n powr (5/6)"
using nth_prime_double_sqrt_less[of "1/3"]
unfolding h_def by auto
moreover have "\<forall>\<^sub>F n in sequentially. n powr (5/6) < (n /2)"
by real_asymp
ultimately show ?thesis
by eventually_elim auto
qed
moreover have "\<forall>\<^sub>F n in sequentially. sqrt (nth_prime n) / a n < 1 / (2*B)"
using nth_1[THEN tendsto_real_sqrt,unfolded tendsto_iff
,rule_format,of "1/(2*B)"] \<open>B>0\<close> a_pos
by (auto simp:real_sqrt_divide abs_of_pos)
ultimately have "\<forall>\<^sub>F x in sequentially. c (x+1) \<noteq> c x
\<and> sqrt (nth_prime x) / a x < 1 / (2*B)
\<and> h x < x / 2
\<and> (c (x+1)>c x \<longrightarrow> nth_prime (x+1) > nth_prime x + a x / (2* B))"
using c_neq_large B_nth_prime eq_2_11[of "1-1/ sqrt 2",simplified]
by eventually_elim (auto simp:divide_simps)
then show ?thesis
proof (elim eventually_at_top_mono)
fix N assume "N\<ge>1" and N_asm:"\<forall>y\<ge>N. c (y + 1) \<noteq> c y \<and>
sqrt (real (nth_prime y)) / real_of_int (a y)
< 1 / real_of_int (2 * B) \<and> h y < y / 2 \<and>
(c y < c (y + 1) \<longrightarrow>
real (nth_prime y) + real_of_int (a y) / real_of_int (2 * B)
< real (nth_prime (y + 1)))"
define S where "S={n \<in> {N..<2 * N}. c n < c (n + 1)}"
define g where "g=(\<lambda>n. (nth_prime (n+1) - nth_prime n)
/ sqrt (nth_prime n))"
define f where "f=(\<lambda>n. nth_prime (n+1) - nth_prime n)"
have g_gt_1:"g n>1" when "n\<ge>N" "c n < c (n + 1)" for n
proof -
have "nth_prime n + sqrt (nth_prime n) < nth_prime (n+1)"
proof -
have "nth_prime n + sqrt (nth_prime n) < nth_prime n + a n / (2*B)"
using N_asm[rule_format,OF \<open>n\<ge>N\<close>] a_pos
by (auto simp:field_simps)
also have "... < nth_prime (n+1)"
using N_asm[rule_format,OF \<open>n\<ge>N\<close>] \<open>c n < c (n + 1)\<close> by auto
finally show ?thesis .
qed
then show ?thesis unfolding g_def
using \<open>c n < c (n + 1)\<close> by auto
qed
have g_geq_0:"g n \<ge> 0" for n
unfolding g_def by auto
have "finite S" "\<forall>x\<in>S. x\<ge>N \<and> c x<c (x+1)"
unfolding S_def by auto
then have "card S \<le> sum g S"
proof (induct S)
case empty
then show ?case by auto
next
case (insert x F)
moreover have "g x>1"
proof -
have "c x < c (x+1)" "x\<ge>N" using insert(4) by auto
then show ?thesis using g_gt_1 by auto
qed
ultimately show ?case by simp
qed
also have "... \<le> sum g {N..<2*N}"
apply (rule sum_mono2)
unfolding S_def using g_geq_0 by auto
also have "... \<le> sum (\<lambda>n. f n/sqrt (nth_prime N)) {N..<2*N}"
apply (rule sum_mono)
unfolding f_def g_def by (auto intro!:divide_left_mono)
also have "... = sum f {N..<2*N} / sqrt (nth_prime N)"
unfolding sum_divide_distrib[symmetric] by auto
also have "... = (nth_prime (2*N) - nth_prime N) / sqrt (nth_prime N)"
proof -
have "sum f {N..<2 * N} = nth_prime (2 * N) - nth_prime N"
proof (induct N)
case 0
then show ?case by simp
next
case (Suc N)
have ?case if "N=0"
proof -
have "sum f {Suc N..<2 * Suc N} = sum f {1}"
using that by (simp add: numeral_2_eq_2)
also have "... = nth_prime 2 - nth_prime 1"
unfolding f_def by (simp add:numeral_2_eq_2)
also have "... = nth_prime (2 * Suc N) - nth_prime (Suc N)"
using that by auto
finally show ?thesis .
qed
moreover have ?case if "N\<noteq>0"
proof -
have "sum f {Suc N..<2 * Suc N} = sum f {N..<2 * Suc N} - f N"
apply (subst (2) sum.atLeast_Suc_lessThan)
using that by auto
also have "... = sum f {N..<2 * N}+ f (2*N) + f(2*N+1) - f N"
by auto
also have "... = nth_prime (2 * Suc N) - nth_prime (Suc N)"
using Suc unfolding f_def by auto
finally show ?thesis .
qed
ultimately show ?case by blast
qed
then show ?thesis by auto
qed
also have "... = h N"
unfolding h_def by auto
also have "... < N/2"
using N_asm by auto
finally have "card S < N/2" .
define T where "T={n \<in> {N..<2 * N}. c n > c (n + 1)}"
have "T \<union> S = {N..<2 * N}" "T \<inter> S = {}" "finite T"
unfolding T_def S_def using N_asm by fastforce+
then have "card T + card S = card {N..<2 * N}"
using card_Un_disjoint \<open>finite S\<close> by metis
also have "... = N"
by simp
finally have "card T + card S = N" .
with \<open>card S < N/2\<close>
show "card T > N/2" by linarith
qed
qed
text\<open>Inequality (3.5) in the original paper required a slight modification: \<close>
have a_gt_plus:"\<forall>\<^sub>F n in sequentially. c n > c (n+1) \<longrightarrow>a (n+1) > a n + (a n - c(n+1) - 1) / c (n+1)"
proof -
note a_gt_1[THEN eventually_all_ge_at_top] c_pos[THEN eventually_all_ge_at_top]
moreover have "\<forall>\<^sub>F n in sequentially.
B * int (nth_prime (n+1)) = c (n+1) * a (n+1) - c (n + 2)"
using Bc_large
apply (subst (asm) eventually_sequentially_Suc[symmetric])
by (auto elim:eventually_mono)
moreover have "\<forall>\<^sub>F n in sequentially.
B * int (nth_prime n) = c n * a n - c (n + 1) \<and> \<bar>c (n + 1)\<bar> < a n / 2"
using Bc_large by (auto elim:eventually_mono)
ultimately show ?thesis
apply (eventually_elim)
proof (rule impI)
fix n
assume "\<forall>y\<ge>n. 1 < a y" "\<forall>y\<ge>n. 0 < c y"
and
Suc_n_eq:"B * int (nth_prime (n + 1)) = c (n + 1) * a (n + 1) - c (n + 2)" and
"B * int (nth_prime n) = c n * a n - c (n + 1) \<and>
real_of_int \<bar>c (n + 1)\<bar> < real_of_int (a n) / 2"
and "c (n + 1) < c n"
then have n_eq:"B * int (nth_prime n) = c n * a n - c (n + 1)" and
c_less_a: "real_of_int \<bar>c (n + 1)\<bar> < real_of_int (a n) / 2"
by auto
from \<open>\<forall>y\<ge>n. 1 < a y\<close> \<open>\<forall>y\<ge>n. 0 < c y\<close>
have *:"a n>1" "a (n+1) > 1" "c n > 0"
"c (n+1) > 0" "c (n+2) > 0"
by auto
then have "(1+1/c (n+1))* (a n - 1)/a (n+1) = (c (n+1)+1) * ((a n - 1) / (c (n+1) * a (n+1)))"
by (auto simp:field_simps)
also have "... \<le> c n * ((a n - 1) / (c (n+1) * a (n+1)))"
apply (rule mult_right_mono)
subgoal using \<open>c (n + 1) < c n\<close> by auto
subgoal by (smt \<open>0 < c (n + 1)\<close> a_pos divide_nonneg_pos mult_pos_pos of_int_0_le_iff
of_int_0_less_iff)
done
also have "... = (c n * (a n - 1)) / (c (n+1) * a (n+1))" by auto
also have "... < (c n * (a n - 1)) / (c (n+1) * a (n+1) - c (n+2))"
apply (rule divide_strict_left_mono)
subgoal using \<open>c (n+2) > 0\<close> by auto
unfolding Suc_n_eq[symmetric] using * \<open>B>0\<close> by auto
also have "... < (c n * a n - c (n+1)) / (c (n+1) * a (n+1) - c (n+2))"
apply (rule frac_less)
unfolding Suc_n_eq[symmetric] using * \<open>B>0\<close> \<open>c (n + 1) < c n\<close>
by (auto simp:algebra_simps)
also have "... = nth_prime n / nth_prime (n+1)"
unfolding Suc_n_eq[symmetric] n_eq[symmetric] using \<open>B>0\<close> by auto
also have "... < 1" by auto
finally have "(1 + 1 / real_of_int (c (n + 1))) * real_of_int (a n - 1)
/ real_of_int (a (n + 1)) < 1 " .
then show "a n + (a n - c (n + 1) - 1) / (c (n + 1)) < (a (n + 1))"
using * by (auto simp:field_simps)
qed
qed
have a_gt_1:"\<forall>\<^sub>F n in sequentially. c n > c (n+1) \<longrightarrow> a (n+1) > a n + 1"
using Bc_large a_gt_plus c_pos[THEN eventually_all_ge_at_top]
apply eventually_elim
proof (rule impI)
fix n assume
"c (n + 1) < c n \<longrightarrow> a n + (a n - c (n + 1) - 1) / c (n + 1) < a (n + 1)"
"c (n + 1) < c n" and B_eq:"B * int (nth_prime n) = c n * a n - c (n + 1) \<and>
\<bar>real_of_int (c (n + 1))\<bar> < real_of_int (a n) / 2" and c_pos:"\<forall>y\<ge>n. 0 < c y"
from this(1,2)
have "a n + (a n - c (n + 1) - 1) / c (n + 1) < a (n + 1)" by auto
moreover have "a n - 2 * c (n+1) > 0"
using B_eq c_pos[rule_format,of "n+1"] by auto
then have "a n - 2 * c (n+1) \<ge> 1" by simp
then have "(a n - c (n + 1) - 1) / c (n + 1) \<ge> 1"
using c_pos[rule_format,of "n+1"] by (auto simp:field_simps)
ultimately show "a n + 1 < a (n + 1)" by auto
qed
text\<open>The following corresponds to inequality (3.6) in the paper, which had to be
slightly corrected: \<close>
have a_gt_sqrt:"\<forall>\<^sub>F n in sequentially. c n > c (n+1) \<longrightarrow> a (n+1) > a n + (sqrt n - 2)"
proof -
have a_2N:"\<forall>\<^sub>F N in sequentially. a (2*N) \<ge> N /2 +1"
using c_gt_half a_gt_1[THEN eventually_all_ge_at_top]
proof eventually_elim
case (elim N)
define S where "S={n \<in> {N..<2 * N}. c (n + 1) < c n}"
define f where "f = (\<lambda>n. a (Suc n) - a n)"
have f_1:"\<forall>x\<in>S. f x\<ge>1" and f_0:"\<forall>x. f x\<ge>0"
subgoal using elim unfolding S_def f_def by auto
subgoal using \<open>mono a\<close>[THEN incseq_SucD] unfolding f_def by auto
done
have "N / 2 < card S"
using elim unfolding S_def by auto
also have "... \<le> sum f S"
unfolding of_int_sum
apply (rule sum_bounded_below[of _ 1,simplified])
using f_1 by auto
also have "... \<le> sum f {N..<2 * N}"
unfolding of_int_sum
apply (rule sum_mono2)
unfolding S_def using f_0 by auto
also have "... = a (2*N) - a N"
unfolding of_int_sum f_def of_int_diff
apply (rule sum_Suc_diff')
by auto
finally have "N / 2 < a (2*N) - a N" .
then show ?case using a_pos[rule_format,of N] by linarith
qed
have a_n4:"\<forall>\<^sub>F n in sequentially. a n > n/4"
proof -
obtain N where a_N:"\<forall>n\<ge>N. a (2*n) \<ge> n /2+1"
using a_2N unfolding eventually_at_top_linorder by auto
have "a n>n/4" when "n\<ge>2*N" for n
proof -
define n' where "n'=n div 2"
have "n'\<ge>N" unfolding n'_def using that by auto
have "n/4 < n' /2+1"
unfolding n'_def by auto
also have "... \<le> a (2*n')"
using a_N \<open>n'\<ge>N\<close> by auto
also have "... \<le>a n" unfolding n'_def
apply (cases "even n")
subgoal by simp
subgoal by (simp add: assms(2) incseqD)
done
finally show ?thesis .
qed
then show ?thesis
unfolding eventually_at_top_linorder by auto
qed
have c_sqrt:"\<forall>\<^sub>F n in sequentially. c n < sqrt n / 4"
proof -
have "\<forall>\<^sub>F x in sequentially. x>1" by simp
moreover have "\<forall>\<^sub>F x in sequentially. real (nth_prime x) / (real x * ln (real x)) < 2"
using nth_prime_asymptotics[unfolded asymp_equiv_def,THEN order_tendstoD(2),of 2]
by simp
ultimately have "\<forall>\<^sub>F n in sequentially. c n < B*8 *ln n + 1" using a_n4 Bc_large
proof eventually_elim
case (elim n)
from this(4) have "c n=(B*nth_prime n+c (n+1))/a n"
using a_pos[rule_format,of n]
by (auto simp:divide_simps)
also have "... = (B*nth_prime n)/a n+c (n+1)/a n"
by (auto simp:divide_simps)
also have "... < (B*nth_prime n)/a n + 1"
proof -
have "c (n+1)/a n < 1" using elim(4) by auto
then show ?thesis by auto
qed
also have "... < B*8 * ln n + 1"
proof -
have "B*nth_prime n < 2*B*n*ln n"
using \<open>real (nth_prime n) / (real n * ln (real n)) < 2\<close> \<open>B>0\<close> \<open> 1 < n\<close>
by (auto simp:divide_simps)
moreover have "real n / 4 < real_of_int (a n)" by fact
ultimately have "(B*nth_prime n) / a n < (2*B*n*ln n) / (n/4)"
apply (rule_tac frac_less)
using \<open>B>0\<close> \<open> 1 < n\<close> by auto
also have "... = B*8 * ln n"
using \<open> 1 < n\<close> by auto
finally show ?thesis by auto
qed
finally show ?case .
qed
moreover have "\<forall>\<^sub>F n in sequentially. B*8 *ln n + 1 < sqrt n / 4"
by real_asymp
ultimately show ?thesis
by eventually_elim auto
qed
have
"\<forall>\<^sub>F n in sequentially. 0 < c (n+1)"
"\<forall>\<^sub>F n in sequentially. c (n+1) < sqrt (n+1) / 4"
"\<forall>\<^sub>F n in sequentially. n > 4"
"\<forall>\<^sub>F n in sequentially. (n - 4) / sqrt (n + 1) + 1 > sqrt n"
subgoal using c_pos[THEN eventually_all_ge_at_top]
by eventually_elim auto
subgoal using c_sqrt[THEN eventually_all_ge_at_top]
by eventually_elim (use le_add1 in blast)
subgoal by simp
subgoal
by real_asymp
done
then show ?thesis using a_gt_plus a_n4
apply eventually_elim
proof (rule impI)
fix n assume asm:"0 < c (n + 1)" "c (n + 1) < sqrt (real (n + 1)) / 4" and
a_ineq:"c (n + 1) < c n \<longrightarrow> a n + (a n - c (n + 1) - 1) / c (n + 1) < a (n + 1)"
"c (n + 1) < c n" and "n / 4 < a n" "n > 4"
and n_neq:" sqrt (real n) < real (n - 4) / sqrt (real (n + 1)) + 1"
have "(n-4) / sqrt(n+1) = (n/4 - 1)/ (sqrt (real (n + 1)) / 4)"
using \<open>n>4\<close> by (auto simp:divide_simps)
also have "... < (a n - 1) / c (n + 1)"
apply (rule frac_less)
using \<open>n > 4\<close> \<open>n / 4 < a n\<close> \<open>0 < c (n + 1)\<close> \<open>c (n + 1) < sqrt (real (n + 1)) / 4\<close>
by auto
also have "... - 1 = (a n - c (n + 1) - 1) / c (n + 1)"
using \<open>0 < c (n + 1)\<close> by (auto simp:field_simps)
also have "a n + ... < a (n+1)"
using a_ineq by auto
finally have "a n + ((n - 4) / sqrt (n + 1) - 1) < a (n + 1)" by simp
moreover have "(n - 4) / sqrt (n + 1) - 1 > sqrt n - 2"
using n_neq[THEN diff_strict_right_mono,of 2] \<open>n>4\<close>
by (auto simp:algebra_simps of_nat_diff)
ultimately show "real_of_int (a n) + (sqrt (real n) - 2) < real_of_int (a (n + 1))"
by argo
qed
qed
text\<open>The following corresponds to inequality $ a_{2N} > N^{3/2}/2$ in the paper,
which had to be slightly corrected: \<close>
have a_2N_sqrt:"\<forall>\<^sub>F N in sequentially. a (2*N) > real N * (sqrt (real N)/2 - 1)"
using c_gt_half a_gt_sqrt[THEN eventually_all_ge_at_top] eventually_gt_at_top[of 4]
proof eventually_elim
case (elim N)
define S where "S={n \<in> {N..<2 * N}. c (n + 1) < c n}"
define f where "f = (\<lambda>n. a (Suc n) - a n)"
have f_N:"\<forall>x\<in>S. f x\<ge>sqrt N - 2"
proof
fix x assume "x\<in>S"
then have "sqrt (real x) - 2 < f x" "x\<ge>N"
using elim unfolding S_def f_def by auto
moreover have "sqrt x - 2 \<ge> sqrt N - 2"
using \<open>x\<ge>N\<close> by simp
ultimately show "sqrt (real N) - 2 \<le> real_of_int (f x)" by argo
qed
have f_0:"\<forall>x. f x\<ge>0"
using \<open>mono a\<close>[THEN incseq_SucD] unfolding f_def by auto
have "(N / 2) * (sqrt N - 2) < card S * (sqrt N - 2)"
apply (rule mult_strict_right_mono)
subgoal using elim unfolding S_def by auto
subgoal using \<open>N>4\<close>
by (metis diff_gt_0_iff_gt numeral_less_real_of_nat_iff real_sqrt_four real_sqrt_less_iff)
done
also have "... \<le> sum f S"
unfolding of_int_sum
apply (rule sum_bounded_below)
using f_N by auto
also have "... \<le> sum f {N..<2 * N}"
unfolding of_int_sum
apply (rule sum_mono2)
unfolding S_def using f_0 by auto
also have "... = a (2*N) - a N"
unfolding of_int_sum f_def of_int_diff
apply (rule sum_Suc_diff')
by auto
finally have "real N / 2 * (sqrt (real N) - 2) < real_of_int (a (2 * N) - a N)"
.
then have "real N / 2 * (sqrt (real N) - 2) < a (2 * N)"
using a_pos[rule_format,of N] by linarith
then show ?case by (auto simp:field_simps)
qed
text\<open>The following part is required to derive the final contradiction of the proof.\<close>
have a_n_sqrt:"\<forall>\<^sub>F n in sequentially. a n > (((n-1)/2) powr (3/2) - (n-1)) /2"
proof (rule sequentially_even_odd_imp)
define f where "f=(\<lambda>N. ((real (2 * N - 1) / 2) powr (3 / 2) - real (2 * N - 1)) / 2)"
define g where "g=(\<lambda>N. real N * (sqrt (real N) / 2 - 1))"
have "\<forall>\<^sub>F N in sequentially. g N > f N"
unfolding f_def g_def
by real_asymp
moreover have "\<forall>\<^sub>F N in sequentially. a (2 * N) > g N"
unfolding g_def using a_2N_sqrt .
ultimately show "\<forall>\<^sub>F N in sequentially. f N < a (2 * N)"
by eventually_elim auto
next
define f where "f=(\<lambda>N. ((real (2 * N + 1 - 1) / 2) powr (3 / 2)
- real (2 * N + 1 - 1)) / 2)"
define g where "g=(\<lambda>N. real N * (sqrt (real N) / 2 - 1))"
have "\<forall>\<^sub>F N in sequentially. g N = f N"
using eventually_gt_at_top[of 0]
apply eventually_elim
unfolding f_def g_def
by (auto simp:algebra_simps powr_half_sqrt[symmetric] powr_mult_base)
moreover have "\<forall>\<^sub>F N in sequentially. a (2 * N) > g N"
unfolding g_def using a_2N_sqrt .
moreover have "\<forall>\<^sub>F N in sequentially. a (2 * N + 1) \<ge> a (2*N)"
apply (rule eventuallyI)
using \<open>mono a\<close> by (simp add: incseqD)
ultimately show "\<forall>\<^sub>F N in sequentially. f N < (a (2 * N + 1))"
apply eventually_elim
by auto
qed
have a_nth_prime_gt:"\<forall>\<^sub>F n in sequentially. a n / nth_prime n > 1"
proof -
define f where "f=(\<lambda>n::nat. (((n-1)/2) powr (3/2) - (n-1)) /2)"
have "\<forall>\<^sub>F x in sequentially. real (nth_prime x) / (real x * ln (real x)) < 2"
using nth_prime_asymptotics[unfolded asymp_equiv_def,THEN order_tendstoD(2),of 2]
by simp
from this[] eventually_gt_at_top[of 1]
have "\<forall>\<^sub>F n in sequentially. real (nth_prime n) < 2*(real n * ln n)"
apply eventually_elim
by (auto simp:field_simps)
moreover have *:"\<forall>\<^sub>F N in sequentially. f N >0 "
unfolding f_def
by real_asymp
moreover have " \<forall>\<^sub>F n in sequentially. f n < a n"
using a_n_sqrt unfolding f_def .
ultimately have "\<forall>\<^sub>F n in sequentially. a n / nth_prime n
> f n / (2*(real n * ln n))"
apply eventually_elim
apply (rule frac_less2)
by auto
moreover have "\<forall>\<^sub>F n in sequentially.
(f n)/ (2*(real n * ln n)) > 1"
unfolding f_def
by real_asymp
ultimately show ?thesis
by eventually_elim argo
qed
have a_nth_prime_lt:"\<exists>\<^sub>F n in sequentially. a n / nth_prime n < 1"
proof -
have "liminf (\<lambda>x. a x / nth_prime x) < 1"
using nth_2 by auto
from this[unfolded less_Liminf_iff]
show ?thesis
apply (auto elim!:frequently_elim1)
by (meson divide_less_eq_1 ereal_less_eq(7) leD leI
nth_prime_nonzero of_nat_eq_0_iff of_nat_less_0_iff order.trans)
qed
from a_nth_prime_gt a_nth_prime_lt show False
by (simp add: eventually_mono frequently_def)
qed
section\<open>Acknowledgements\<close>
text\<open>A.K.-A. and W.L. were supported by the ERC Advanced Grant ALEXANDRIA (Project 742178)
funded by the European Research Council and led by Professor Lawrence Paulson
at the University of Cambridge, UK.\<close>
end |
program main
implicit none
integer,parameter :: n = 1000
real(KIND=4),allocatable,dimension(:) :: a,b
real(KIND=4) :: c
integer :: i
real(KIND=8) :: sum
allocate(a(n),b(n))
c = 2.0
do i = 1, n
a(i) = 10.0
end do
!$acc data copyin(a) copyout(b)
!$acc kernels
!$acc loop independent
do i = 1, n
b(i) = a(i) + c
end do
!$acc end kernels
!$acc end data
sum = 0.d0
do i = 1, n
sum = sum + b(i)
end do
print *, sum/n
deallocate(a,b)
end program main
|
{-# options_ghc -Wno-type-defaults #-}
{- |
Module : Task.Block
Description : Blocks encapsulate the task of rendering a picture of a
dynamical system to one or more tiles.
-}
module Task.Block
( Block(..)
, fillBlock
, progressively
) where
import Task.Concurrent
import Control.Concurrent.MVar
import Control.Monad
import Data.Word
import Foreign.ForeignPtr
import Control.Concurrent
import Data.Array.IO hiding (index)
import System.Random
import Data.Time (diffUTCTime, getCurrentTime)
import Data.Complex
import Foreign (Ptr, peekByteOff, pokeByteOff, allocaArray)
-- import Utilities (groupsOf)
-- | A Block carries the information required to go from a
-- runnable dynamical system and choice of color scheme
-- to a buffer filled with the resulting color data.
data Block =
Block { coordToModel :: (Double, Double) -> (Double, Double)
, compute :: Word32 -> Word32 -> Complex Double -> Complex Double -> Ptr Word8 -> IO ()
-- ^ The arguments of the compute function are:
-- * Block width, in subsamples
-- * Subsamples per point
-- * Array of two doubles: initial (x,y) values
-- * Array of two doubles: (dx,dy)
-- * Output color samples
, logSampleRate :: Int
-- ^ The rate of over- or under-sampling to use.
-- * logSampleRate == 0: draw one point per pixel.
-- * logSampleRate == N < 0: draw 2^-N by 2^-N pixel
-- blocks per model point.
-- * logSampleRate == N > 0: subsample each pixel
-- on a 2^N by 2^N subgrid and average the
-- results, for a smoother picture.
, blockBuffer :: Synchronizable (ForeignPtr Word8)
-- ^ The pixel buffer to write into.
, xStride :: Int
-- ^ The width of the pixel buffer.
, x0 :: Int
-- ^ The upper-left x coordinate of this block in the pixel buffer.
, y0 :: Int
-- ^ The upper-left y coordinate of this block in the pixel buffer.
, deltaX :: Double
-- ^ The model size of a pixel in the X direction
, deltaY :: Double
-- ^ The model size of a pixel in the Y direction
, xSize :: Int
-- ^ The width of the block.
, ySize :: Int
-- ^ The height of the block
, shouldRedraw :: MVar ()
-- ^ A variable used to signal that this block is complete
-- and the pixel buffer should be redrawn.
}
-- | Render the block into its output buffer.
fillBlock :: Block -> IO ()
fillBlock Block{..} = do
let skip = if logSampleRate < 0 then 2^(negate logSampleRate) else 1
k = if logSampleRate > 0 then 2^logSampleRate else 1
let points = [ (x,y) | y <- [0, skip .. ySize - 1]
, x <- [0, skip .. xSize - 1] ]
uv_points = [ (fromIntegral (x0 + x), fromIntegral (y0 + y))
| (x,y) <- points ]
indexOf (u,v) = u + v * xStride
-- Run the computation on each subsampled point.
allocaArray (length points * 3) $ \tmp -> do
compute (fromIntegral (xSize `div` skip)) (floor k)
(deltaX :+ deltaY)
(let (u,v) = coordToModel (fromIntegral x0, fromIntegral y0)
in u :+ v)
tmp
-- Resample the results
--let rgbs = resampleBy averageColor nSubsamples results
-- Fill target buffer with result colors.
with blockBuffer $ \buffer -> withForeignPtr buffer $ \ptr -> do
forM_ (zip uv_points [0..]) $ \((u,v), ix) -> do
let index = floor $ u + v * fromIntegral xStride
forM_ [indexOf (du,dv) | dv <- [0 .. skip - 1]
, du <- [0 .. skip - 1] ] $ \offset -> do
peekByteOff @Word8 tmp (3*ix + 0) >>= pokeByteOff ptr (3*index + offset + 0)
peekByteOff @Word8 tmp (3*ix + 1) >>= pokeByteOff ptr (3*index + offset + 1)
peekByteOff @Word8 tmp (3*ix + 2) >>= pokeByteOff ptr (3*index + offset + 2)
-- Completed the block, signal for a redraw
void (tryPutMVar shouldRedraw ())
{-
-- | Render the block into its output buffer.
fillBlock :: Block -> IO ()
fillBlock Block{..} = do
let skip = if logSampleRate < 0 then 2^(negate logSampleRate) else 1
k = if logSampleRate > 0 then 2^logSampleRate else 1
subsamples = [s / k | s <- [0..k-1]]
nSubsamples = floor (k^2)
let points = [ (x,y) | y <- [0, skip .. ySize - 1]
, x <- [0, skip .. xSize - 1] ]
uv_points = [ (fromIntegral (x0 + x), fromIntegral (y0 + y))
| (x,y) <- points ]
indexOf (u,v) = u + v * xStride
let subsample (u,v) = [ (u + du, v + dv) | du <- subsamples, dv <- subsamples ]
let samples = map coordToModel $ concatMap subsample uv_points
-- Run the computation on each subsampled point.
results <- compute samples
-- Resample the results
let rgbs = resampleBy averageColor nSubsamples results
-- Fill target buffer with result colors.
with blockBuffer $ \buffer -> withForeignPtr buffer $ \ptr -> do
forM_ (zip uv_points rgbs) $ \((u,v), rgb) -> do
let index = floor $ u + v * fromIntegral xStride
forM_ [indexOf (du,dv) | dv <- [0 .. skip - 1]
, du <- [0 .. skip - 1] ] $ \offset -> do
pokeColor ptr (index + offset) rgb
-- Completed the block, signal for a redraw
void (tryPutMVar shouldRedraw ())
resampleBy :: ([a] -> b) -> Int -> [a] -> [b]
resampleBy f n
| n > 0 = map f . groupsOf n
| otherwise = map f . groupsOf 1
-}
-- | Chop up a block into sub-blocks, delegate rendering
-- tasks for sub-blocks, and blit the results back
-- into an image.
progressively :: (Block -> IO ()) -> (Block -> IO ())
progressively render block = do
let subBlockSize = 16
width = xSize block
height = ySize block
xBlocks = case width `divMod` subBlockSize of
(z, 0) -> z
(z, _) -> z + 1
yBlocks = case height `divMod` subBlockSize of
(z, 0) -> z
(z, _) -> z + 1
blockIDs <- shuffle [(x,y) | x <- [0..xBlocks - 1], y <- [0..yBlocks - 1]]
poolSize <- subtract 1 <$> getNumCapabilities
caps <- getNumCapabilities
putStrLn $ show caps ++ " capabilities, pool size " ++ show poolSize ++ " (w=" ++ show (xSize block) ++ ", h=" ++ show (ySize block) ++ ")"
let rates = filter (<= logSampleRate block) [0] -- [-4, -2, 0] --, logSampleRate block]
let todo = [(rate, x, y) | rate <- rates, (x,y) <- blockIDs]
putStrLn $ "***** start @ rates=" ++ show rates
start <- getCurrentTime
forPool_ poolSize todo $ \(rate,x,y) -> do
render $ block { xSize = subBlockSize, ySize = subBlockSize,
x0 = subBlockSize * x, y0 = subBlockSize * y,
logSampleRate = rate }
end <- getCurrentTime
putStrLn $ "***** " ++ show width ++ " x " ++ show height ++ " @ rates " ++ show rates
++ " rendered in " ++ show (diffUTCTime end start)
shuffle :: [a] -> IO [a]
shuffle xs = do
ar <- makeArray xs
forM_ [2..n] $ \i -> do
j <- randomRIO (1,i)
vi <- readArray ar i
vj <- readArray ar j
writeArray ar j vi
writeArray ar i vj
forM [1..n] (readArray ar)
where
n = length xs
makeArray :: [a] -> IO (IOArray Int a)
makeArray = newListArray (1,n)
|
section \<open>Code Generation for the Skeleton Algorithm \label{sec:skel_code}\<close>
theory Gabow_Skeleton_Code
imports
Gabow_Skeleton
CAVA_Automata.Digraph_Impl
CAVA_Base.CAVA_Code_Target
begin
section \<open>Statistics\<close>
text \<open>
In this section, we do the ML setup that gathers statistics about the
algorithm's execution.
\<close>
code_printing
code_module Gabow_Skeleton_Statistics \<rightharpoonup> (SML) \<open>
structure Gabow_Skeleton_Statistics = struct
val active = Unsynchronized.ref false
val num_vis = Unsynchronized.ref 0
val time = Unsynchronized.ref Time.zeroTime
fun is_active () = !active
fun newnode () =
(
num_vis := !num_vis + 1;
if !num_vis mod 10000 = 0 then tracing (IntInf.toString (!num_vis) ^ "\n") else ()
)
fun start () = (active := true; time := Time.now ())
fun stop () = (time := Time.- (Time.now (), !time))
fun to_string () = let
val t = Time.toMilliseconds (!time)
val states_per_ms = real (!num_vis) / real t
val realStr = Real.fmt (StringCvt.FIX (SOME 2))
in
"Required time: " ^ IntInf.toString (t) ^ "ms\n"
^ "States per ms: " ^ realStr states_per_ms ^ "\n"
^ "# states: " ^ IntInf.toString (!num_vis) ^ "\n"
end
val _ = Statistics.register_stat ("Gabow-Skeleton",is_active,to_string)
end
\<close>
code_reserved SML Gabow_Skeleton_Statistics
code_printing
constant stat_newnode \<rightharpoonup> (SML) "Gabow'_Skeleton'_Statistics.newnode"
| constant stat_start \<rightharpoonup> (SML) "Gabow'_Skeleton'_Statistics.start"
| constant stat_stop \<rightharpoonup> (SML) "Gabow'_Skeleton'_Statistics.stop"
section \<open>Automatic Refinement Setup\<close>
consts i_node_state :: interface
definition "node_state_rel \<equiv> {(-1::int,DONE)} \<union> {(int k,STACK k) | k. True }"
lemma node_state_rel_simps[simp]:
"(i,DONE)\<in>node_state_rel \<longleftrightarrow> i=-1"
"(i,STACK n)\<in>node_state_rel \<longleftrightarrow> i = int n"
unfolding node_state_rel_def
by auto
lemma node_state_rel_sv[simp,intro!,relator_props]:
"single_valued node_state_rel"
unfolding node_state_rel_def
by (auto intro: single_valuedI)
lemmas [autoref_rel_intf] = REL_INTFI[of node_state_rel i_node_state]
primrec is_DONE where
"is_DONE DONE = True"
| "is_DONE (STACK _) = False"
lemma node_state_rel_refine[autoref_rules]:
"(-1,DONE)\<in>node_state_rel"
"(int,STACK)\<in>nat_rel\<rightarrow>node_state_rel"
"(\<lambda>i. i<0,is_DONE)\<in>node_state_rel\<rightarrow>bool_rel"
"((\<lambda>f g i. if i\<ge>0 then f (nat i) else g),case_node_state)
\<in>(nat_rel \<rightarrow> R) \<rightarrow> R \<rightarrow> node_state_rel \<rightarrow> R"
unfolding node_state_rel_def
apply auto [3]
apply (fastforce dest: fun_relD)
done
(* TODO: Make changing the Autoref-config simpler, by concentrating
everything here *)
consts i_node :: interface
(* TODO: Move generic part of this locale to Digraph_impl *)
locale fr_graph_impl_loc = fr_graph G
for mrel and node_rel :: "('vi \<times> 'v) set"
and node_eq_impl :: "'vi \<Rightarrow> 'vi \<Rightarrow> bool"
and node_hash_impl :: "nat \<Rightarrow> 'vi \<Rightarrow> nat"
and node_def_hash_size :: nat
and G_impl and G :: "('v,'more) graph_rec_scheme"
+
assumes G_refine: "(G_impl,G)\<in>\<langle>mrel,node_rel\<rangle>g_impl_rel_ext"
and node_eq_refine: "(node_eq_impl, (=)) \<in> node_rel \<rightarrow> node_rel \<rightarrow> bool_rel"
and node_hash: "is_bounded_hashcode node_rel node_eq_impl node_hash_impl"
and node_hash_def_size: "(is_valid_def_hm_size TYPE('vi) node_def_hash_size)"
begin
(*abbreviation "node_rel \<equiv> Id :: ('v \<times> _) set"*)
lemmas [autoref_rel_intf] = REL_INTFI[of node_rel i_node]
lemmas [autoref_rules] = G_refine node_eq_refine
lemmas [autoref_ga_rules] = node_hash node_hash_def_size
lemma locale_this: "fr_graph_impl_loc mrel node_rel node_eq_impl node_hash_impl node_def_hash_size G_impl G"
by unfold_locales
abbreviation "oGSi_rel \<equiv> \<langle>node_rel,node_state_rel\<rangle>(ahm_rel node_hash_impl)"
abbreviation "GSi_rel \<equiv>
\<langle>node_rel\<rangle>as_rel
\<times>\<^sub>r \<langle>nat_rel\<rangle>as_rel
\<times>\<^sub>r oGSi_rel
\<times>\<^sub>r \<langle>nat_rel \<times>\<^sub>r \<langle>node_rel\<rangle>list_set_rel\<rangle>as_rel"
lemmas [autoref_op_pat] = GS.S_def GS.B_def GS.I_def GS.P_def
end
section \<open>Generating the Code\<close>
thm autoref_ga_rules
context fr_graph_impl_loc
begin
schematic_goal push_code_aux: "(?c,push_impl)\<in>node_rel \<rightarrow> GSi_rel \<rightarrow> GSi_rel"
unfolding push_impl_def_opt[abs_def]
using [[autoref_trace_failed_id]]
apply (autoref (keep_goal))
done
concrete_definition (in -) push_code uses fr_graph_impl_loc.push_code_aux
lemmas [autoref_rules] = push_code.refine[OF locale_this]
schematic_goal pop_code_aux: "(?c,pop_impl)\<in>GSi_rel \<rightarrow> \<langle>GSi_rel\<rangle>nres_rel"
unfolding pop_impl_def_opt[abs_def]
unfolding GS.mark_as_done_def
using [[autoref_trace_failed_id]]
apply (autoref (keep_goal))
done
concrete_definition (in -) pop_code uses fr_graph_impl_loc.pop_code_aux
lemmas [autoref_rules] = pop_code.refine[OF locale_this]
schematic_goal S_idx_of_code_aux:
notes [autoref_rules] = IdI[of "undefined::nat"] (* TODO: hack!*)
shows "(?c,GS.S_idx_of)\<in>GSi_rel \<rightarrow> node_rel \<rightarrow> nat_rel"
unfolding GS.S_idx_of_def[abs_def]
using [[autoref_trace_failed_id]]
apply (autoref (keep_goal))
done
concrete_definition (in -) S_idx_of_code
uses fr_graph_impl_loc.S_idx_of_code_aux
lemmas [autoref_rules] = S_idx_of_code.refine[OF locale_this]
schematic_goal idx_of_code_aux:
notes [autoref_rules] = IdI[of "undefined::nat"] (* TODO: hack!*)
shows "(?c,GS.idx_of_impl)\<in> GSi_rel \<rightarrow> node_rel \<rightarrow> \<langle>nat_rel\<rangle>nres_rel"
unfolding
GS.idx_of_impl_def[abs_def, unfolded GS.find_seg_impl_def GS.S_idx_of_def,
THEN opt_GSdef, unfolded GS_sel_simps, abs_def]
using [[autoref_trace_failed_id]]
apply (autoref (keep_goal))
done
concrete_definition (in -) idx_of_code uses fr_graph_impl_loc.idx_of_code_aux
lemmas [autoref_rules] = idx_of_code.refine[OF locale_this]
schematic_goal collapse_code_aux:
"(?c,collapse_impl)\<in>node_rel \<rightarrow> GSi_rel \<rightarrow> \<langle>GSi_rel\<rangle>nres_rel"
unfolding collapse_impl_def_opt[abs_def]
using [[autoref_trace_failed_id]]
apply (autoref (keep_goal))
done
concrete_definition (in -) collapse_code
uses fr_graph_impl_loc.collapse_code_aux
lemmas [autoref_rules] = collapse_code.refine[OF locale_this]
term select_edge_impl
schematic_goal select_edge_code_aux:
"(?c,select_edge_impl)
\<in> GSi_rel \<rightarrow> \<langle>\<langle>node_rel\<rangle>option_rel \<times>\<^sub>r GSi_rel\<rangle>nres_rel"
unfolding select_edge_impl_def_opt[abs_def]
using [[autoref_trace_failed_id]]
using [[goals_limit=1]]
apply (autoref (keep_goal,trace))
done
concrete_definition (in -) select_edge_code
uses fr_graph_impl_loc.select_edge_code_aux
lemmas [autoref_rules] = select_edge_code.refine[OF locale_this]
context begin interpretation autoref_syn .
term fr_graph.pop_impl
lemma [autoref_op_pat]:
"push_impl \<equiv> OP push_impl"
"collapse_impl \<equiv> OP collapse_impl"
"select_edge_impl \<equiv> OP select_edge_impl"
"pop_impl \<equiv> OP pop_impl"
by simp_all
end
find_theorems is_valid_def_hm_size
schematic_goal skeleton_code_aux:
"(?c,skeleton_impl) \<in> \<langle>oGSi_rel\<rangle>nres_rel"
unfolding skeleton_impl_def[abs_def] initial_impl_def GS_initial_impl_def
unfolding path_is_empty_impl_def is_on_stack_impl_def is_done_impl_def
is_done_oimpl_def
unfolding GS.is_on_stack_impl_def GS.is_done_impl_def
using [[autoref_trace_failed_id]]
apply (autoref (keep_goal,trace))
done
concrete_definition (in -) skeleton_code
for node_eq_impl G_impl
uses fr_graph_impl_loc.skeleton_code_aux
thm skeleton_code.refine
lemmas [autoref_rules] = skeleton_code.refine[OF locale_this]
schematic_goal pop_tr_aux: "RETURN ?c \<le> pop_code node_eq_impl node_hash_impl s"
unfolding pop_code_def by refine_transfer
concrete_definition (in -) pop_tr uses fr_graph_impl_loc.pop_tr_aux
lemmas [refine_transfer] = pop_tr.refine[OF locale_this]
schematic_goal select_edge_tr_aux: "RETURN ?c \<le> select_edge_code node_eq_impl s"
unfolding select_edge_code_def by refine_transfer
concrete_definition (in -) select_edge_tr
uses fr_graph_impl_loc.select_edge_tr_aux
lemmas [refine_transfer] = select_edge_tr.refine[OF locale_this]
schematic_goal idx_of_tr_aux: "RETURN ?c \<le> idx_of_code node_eq_impl node_hash_impl v s"
unfolding idx_of_code_def by refine_transfer
concrete_definition (in -) idx_of_tr uses fr_graph_impl_loc.idx_of_tr_aux
lemmas [refine_transfer] = idx_of_tr.refine[OF locale_this]
schematic_goal collapse_tr_aux: "RETURN ?c \<le> collapse_code node_eq_impl node_hash_impl v s"
unfolding collapse_code_def by refine_transfer
concrete_definition (in -) collapse_tr uses fr_graph_impl_loc.collapse_tr_aux
lemmas [refine_transfer] = collapse_tr.refine[OF locale_this]
schematic_goal skeleton_tr_aux: "RETURN ?c \<le> skeleton_code node_hash_impl node_def_hash_size node_eq_impl g"
unfolding skeleton_code_def by refine_transfer
concrete_definition (in -) skeleton_tr uses fr_graph_impl_loc.skeleton_tr_aux
lemmas [refine_transfer] = skeleton_tr.refine[OF locale_this]
end
term skeleton_tr
export_code skeleton_tr checking SML
end
|
import Control.Monad.State
increase : Nat -> State Nat ()
increase inc =
do
current <- get
put (current + inc)
update : (stateType -> stateType) -> State stateType ()
update f =
do
state <- get
put (f state)
increase' : Nat -> State Nat ()
increase' inc = update (+inc)
|
section \<open>Some preliminaries on equivalence relations and quotients\<close>
theory Equiv_Relation2 imports Preliminaries Pick
begin
text\<open>Unary predicates vs. sets:\<close>
definition "S2P A \<equiv> \<lambda> x. x \<in> A"
lemma S2P_app[simp]: "S2P r x \<longleftrightarrow> x \<in> r"
unfolding S2P_def by auto
lemma S2P_Collect[simp]: "S2P (Collect \<phi>) = \<phi>"
apply(rule ext)+ by simp
lemma Collect_S2P[simp]: "Collect (S2P r) = r"
by (metis Collect_mem_eq S2P_Collect)
text\<open>Binary predicates vs. relatipons:\<close>
definition "P2R \<phi> \<equiv> {(x,y). \<phi> x y}"
definition "R2P r \<equiv> \<lambda> x y. (x,y) \<in> r"
lemma in_P2R[simp]: "xy \<in> P2R \<phi> \<longleftrightarrow> \<phi> (fst xy) (snd xy)"
unfolding P2R_def by auto
lemma in_P2R_pair[simp]: "(x,y) \<in> P2R \<phi> \<longleftrightarrow> \<phi> x y"
by simp
lemma R2P_app[simp]: "R2P r x y \<longleftrightarrow> (x,y) \<in> r"
unfolding R2P_def by auto
lemma R2P_P2R[simp]: "R2P (P2R \<phi>) = \<phi>"
apply(rule ext)+ by simp
lemma P2R_R2P[simp]: "P2R (R2P r) = r"
using Collect_mem_eq P2R_def R2P_P2R case_prod_curry by metis
definition "reflP P \<phi> \<equiv> (\<forall> x y. \<phi> x y \<or> \<phi> y x \<longrightarrow> P x) \<and> (\<forall> x. P x \<longrightarrow> \<phi> x x)"
definition "symP \<phi> \<equiv> \<forall> x y. \<phi> x y \<longrightarrow> \<phi> y x"
definition transP where "transP \<phi> \<equiv> \<forall> x y z. \<phi> x y \<and> \<phi> y z \<longrightarrow> \<phi> x z"
definition "equivP A \<phi> \<equiv> reflP A \<phi> \<and> symP \<phi> \<and> transP \<phi>"
lemma refl_on_P2R[simp]: "refl_on (Collect P) (P2R \<phi>) \<longleftrightarrow> reflP P \<phi>"
unfolding reflP_def refl_on_def by force
lemma reflP_R2P[simp]: "reflP (S2P A) (R2P r) \<longleftrightarrow> refl_on A r"
unfolding reflP_def refl_on_def by auto
lemma sym_P2R[simp]: "sym (P2R \<phi>) \<longleftrightarrow> symP \<phi>"
unfolding symP_def sym_def by auto
lemma symP_R2P[simp]: "symP (R2P r) \<longleftrightarrow> sym r"
unfolding symP_def sym_def by auto
lemma trans_P2R[simp]: "trans (P2R \<phi>) \<longleftrightarrow> transP \<phi>"
unfolding transP_def trans_def by auto
lemma transP_R2P[simp]: "transP (R2P r) \<longleftrightarrow> trans r"
unfolding transP_def trans_def by auto
lemma equiv_P2R[simp]: "equiv (Collect P) (P2R \<phi>) \<longleftrightarrow> equivP P \<phi>"
unfolding equivP_def equiv_def by auto
lemma equivP_R2P[simp]: "equivP (S2P A) (R2P r) \<longleftrightarrow> equiv A r"
unfolding equivP_def equiv_def by auto
lemma in_P2R_Im_singl[simp]: "y \<in> P2R \<phi> `` {x} \<longleftrightarrow> \<phi> x y" by simp
definition proj :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> 'a \<Rightarrow> 'a set" where
"proj \<phi> x \<equiv> {y. \<phi> x y}"
lemma proj_P2R: "proj \<phi> x = P2R \<phi> `` {x}" unfolding proj_def by auto
lemma proj_P2R_raw: "proj \<phi> = (\<lambda> x. P2R \<phi> `` {x})"
apply(rule ext) unfolding proj_P2R ..
definition univ :: "('a \<Rightarrow> 'b) \<Rightarrow> ('a set \<Rightarrow> 'b)"
where "univ f X == f (SOME x. x \<in> X)"
definition quotientP ::
"('a \<Rightarrow> bool) \<Rightarrow> ('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> ('a set \<Rightarrow> bool)" (infixl "'/'/'/" 90)
where "P /// \<phi> \<equiv> S2P ((Collect P) // (P2R \<phi>))"
lemma proj_preserves:
"P x \<Longrightarrow> (P /// \<phi>) (proj \<phi> x)"
unfolding proj_P2R quotientP_def
by (metis S2P_def mem_Collect_eq quotientI)
lemma proj_in_iff:
assumes "equivP P \<phi>"
shows "(P///\<phi>) (proj \<phi> x) \<longleftrightarrow> P x"
using assms unfolding quotientP_def proj_def
by (metis (mono_tags) Collect_mem_eq Equiv_Relation2.proj_def
Equiv_Relation2.proj_preserves S2P_Collect empty_Collect_eq equivP_def
equiv_P2R in_quotient_imp_non_empty quotientP_def reflP_def)
lemma proj_iff[simp]:
"\<lbrakk>equivP P \<phi>; P x; P y\<rbrakk> \<Longrightarrow> proj \<phi> x = proj \<phi> y \<longleftrightarrow> \<phi> x y"
unfolding proj_P2R
by (metis (full_types) equiv_P2R equiv_class_eq_iff equiv_class_self
in_P2R_pair mem_Collect_eq proj_P2R proj_def)
lemma in_proj[simp]: "\<lbrakk>equivP P \<phi>; P x\<rbrakk> \<Longrightarrow> x \<in> proj \<phi> x"
unfolding proj_P2R equiv_def refl_on_def equiv_P2R[symmetric]
by auto
lemma proj_image[simp]: "(proj \<phi>) ` (Collect P) = Collect (P///\<phi>)"
unfolding proj_P2R_raw quotientP_def quotient_def by auto
lemma in_quotientP_imp_in_rel:
"\<lbrakk>equivP P \<phi>; (P///\<phi>) X; x \<in> X; y \<in> X\<rbrakk> \<Longrightarrow> \<phi> x y"
unfolding equiv_P2R[symmetric] quotientP_def quotient_eq_iff
by (metis S2P_def in_P2R_pair quotient_eq_iff)
lemma in_quotientP_imp_closed:
"\<lbrakk>equivP P \<phi>; (P///\<phi>) X; x \<in> X; \<phi> x y\<rbrakk> \<Longrightarrow> y \<in> X"
using S2P_Collect S2P_def equivP_def proj_P2R_raw proj_def
quotientE quotientP_def transP_def
by metis
lemma in_quotientP_imp_subset:
assumes "equivP P \<phi>" and "(P///\<phi>) X"
shows "X \<subseteq> Collect P"
by (metis (mono_tags, lifting) CollectI assms equivP_def in_quotientP_imp_in_rel reflP_def subsetI)
lemma equivP_pick_in:
assumes "equivP P \<phi> " and "(P///\<phi>) X"
shows "pick X \<in> X"
by (metis assms in_quotientP_imp_non_empty pick_NE)
lemma equivP_pick_preserves:
assumes "equivP P \<phi> " and "(P///\<phi>) X"
shows "P (pick X)"
by (metis assms equivP_pick_in in_quotientP_imp_subset mem_Collect_eq set_rev_mp)
lemma proj_pick:
assumes \<phi>: "equivP P \<phi>" and X: "(P///\<phi>) X"
shows "proj \<phi> (pick X) = X"
by (smt proj_def Equiv_Relation2.proj_iff Equiv_Relation2.proj_image X
\<phi> equivP_pick_in equivP_pick_preserves image_iff mem_Collect_eq)
lemma pick_proj:
assumes "equivP P \<phi>" and "P x"
shows "\<phi> (pick (proj \<phi> x)) x"
by (metis assms equivP_def in_proj mem_Collect_eq pick proj_def symP_def)
lemma equivP_pick_iff[simp]:
assumes \<phi>: "equivP P \<phi>" and X: "(P///\<phi>) X" and Y: "(P///\<phi>) Y"
shows "\<phi> (pick X) (pick Y) \<longleftrightarrow> X = Y"
by (metis Equiv_Relation2.proj_iff X Y \<phi> equivP_pick_preserves proj_pick)
lemma equivP_pick_inj_on:
assumes "equivP P \<phi>"
shows "inj_on pick (Collect (P///\<phi>))"
using assms unfolding inj_on_def
by (metis assms equivP_pick_iff mem_Collect_eq)
definition congruentP where
"congruentP \<phi> f \<equiv> \<forall> x y. \<phi> x y \<longrightarrow> f x = f y"
abbreviation RESPECTS_P (infixr "respectsP" 80) where
"f respectsP r == congruentP r f"
lemma congruent_P2R: "congruent (P2R \<phi>) f = congruentP \<phi> f"
unfolding congruent_def congruentP_def by auto
lemma univ_commute[simp]:
assumes "equivP P \<phi>" and "f respectsP \<phi>" and "P x"
shows "(univ f) (proj \<phi> x) = f x"
unfolding congruent_P2R[symmetric]
by (metis (full_types) assms pick_def congruentP_def pick_proj univ_def)
lemma univ_unique:
assumes "equivP P \<phi>" and "f respectsP \<phi>" and "\<And> x. P x \<Longrightarrow> G (proj \<phi> x) = f x"
shows "\<forall> X. (P///\<phi>) X \<longrightarrow> G X = univ f X"
by (metis assms equivP_pick_preserves proj_pick univ_commute)
lemma univ_preserves:
assumes "equivP P \<phi> " and "f respectsP \<phi>" and "\<And> x. P x \<Longrightarrow> f x \<in> B"
shows "\<forall> X. (P///\<phi>) X \<longrightarrow> univ f X \<in> B"
by (metis Equiv_Relation2.univ_commute assms
equivP_pick_preserves proj_pick)
end
|
[STATEMENT]
lemma wca_on_warp_on: \<comment> \<open>\citet[T.3 part]{Sen:1970}\<close>
shows "wca_on A f \<longleftrightarrow> warp_on A f"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. wca_on A f = warp_on A f
[PROOF STEP]
unfolding %invisible warp_on_def wca_on_def rsp_on_def rwp_on_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<forall>(x, y)\<in>{(x, y). \<exists>B\<subseteq>A. x \<in> B \<and> y \<in> f B}. \<forall>B\<subseteq>A. x \<in> f B \<and> y \<in> B \<longrightarrow> y \<in> f B) = (\<forall>(x, y)\<in>{(x, y). \<exists>B\<subseteq>A. x \<in> Rf f B \<and> y \<in> f B}. (y, x) \<notin> {(x, y). \<exists>B\<subseteq>A. x \<in> B \<and> y \<in> f B})
[PROOF STEP]
by blast |
State Before: c : ℝ
f g : ℕ → Bool
n : ℕ
h : f n = false
⊢ cantorFunctionAux c f n = 0 State After: no goals Tactic: simp [cantorFunctionAux, h] |
function vars(vh)
num_masses = vh.userdata.num_masses;
lbx = horzcat(-4*ones(1,num_masses), -inf*ones(1,num_masses)).';
ubx = horzcat(4*ones(1,num_masses), inf*ones(1,num_masses)).';
vh.addState('x', [2*num_masses 1], 'lb', lbx, 'ub', ubx);
vh.addControl('u', [num_masses-1 1], 'lb', -0.5, 'ub', 0.5); |
[GOAL]
G : Type u_1
H : Type u_2
inst✝¹ : AddZeroClass G
inst✝ : AddZeroClass H
x : G ≃+ H
⊢ (fun f =>
{
toEquiv :=
{ toFun := ↑(MulEquiv.toMonoidHom f), invFun := ↑(MulEquiv.toMonoidHom (MulEquiv.symm f)),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_add' :=
(_ :
∀ (x y : Multiplicative G),
Equiv.toFun f.toEquiv (x * y) = Equiv.toFun f.toEquiv x * Equiv.toFun f.toEquiv y) })
((fun f =>
{
toEquiv :=
{ toFun := ↑(↑AddMonoidHom.toMultiplicative (toAddMonoidHom f)),
invFun := ↑(↑AddMonoidHom.toMultiplicative (toAddMonoidHom (symm f))),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_mul' :=
(_ : ∀ (x y : G), Equiv.toFun f.toEquiv (x + y) = Equiv.toFun f.toEquiv x + Equiv.toFun f.toEquiv y) })
x) =
x
[PROOFSTEP]
ext
[GOAL]
case h
G : Type u_1
H : Type u_2
inst✝¹ : AddZeroClass G
inst✝ : AddZeroClass H
x : G ≃+ H
x✝ : G
⊢ ↑((fun f =>
{
toEquiv :=
{ toFun := ↑(MulEquiv.toMonoidHom f), invFun := ↑(MulEquiv.toMonoidHom (MulEquiv.symm f)),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_add' :=
(_ :
∀ (x y : Multiplicative G),
Equiv.toFun f.toEquiv (x * y) = Equiv.toFun f.toEquiv x * Equiv.toFun f.toEquiv y) })
((fun f =>
{
toEquiv :=
{ toFun := ↑(↑AddMonoidHom.toMultiplicative (toAddMonoidHom f)),
invFun := ↑(↑AddMonoidHom.toMultiplicative (toAddMonoidHom (symm f))),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_mul' :=
(_ :
∀ (x y : G), Equiv.toFun f.toEquiv (x + y) = Equiv.toFun f.toEquiv x + Equiv.toFun f.toEquiv y) })
x))
x✝ =
↑x x✝
[PROOFSTEP]
rfl
[GOAL]
G : Type u_1
H : Type u_2
inst✝¹ : AddZeroClass G
inst✝ : AddZeroClass H
x : Multiplicative G ≃* Multiplicative H
⊢ (fun f =>
{
toEquiv :=
{ toFun := ↑(↑AddMonoidHom.toMultiplicative (toAddMonoidHom f)),
invFun := ↑(↑AddMonoidHom.toMultiplicative (toAddMonoidHom (symm f))),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_mul' :=
(_ : ∀ (x y : G), Equiv.toFun f.toEquiv (x + y) = Equiv.toFun f.toEquiv x + Equiv.toFun f.toEquiv y) })
((fun f =>
{
toEquiv :=
{ toFun := ↑(MulEquiv.toMonoidHom f), invFun := ↑(MulEquiv.toMonoidHom (MulEquiv.symm f)),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_add' :=
(_ :
∀ (x y : Multiplicative G),
Equiv.toFun f.toEquiv (x * y) = Equiv.toFun f.toEquiv x * Equiv.toFun f.toEquiv y) })
x) =
x
[PROOFSTEP]
ext
[GOAL]
case h
G : Type u_1
H : Type u_2
inst✝¹ : AddZeroClass G
inst✝ : AddZeroClass H
x : Multiplicative G ≃* Multiplicative H
x✝ : Multiplicative G
⊢ ↑((fun f =>
{
toEquiv :=
{ toFun := ↑(↑AddMonoidHom.toMultiplicative (toAddMonoidHom f)),
invFun := ↑(↑AddMonoidHom.toMultiplicative (toAddMonoidHom (symm f))),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_mul' :=
(_ : ∀ (x y : G), Equiv.toFun f.toEquiv (x + y) = Equiv.toFun f.toEquiv x + Equiv.toFun f.toEquiv y) })
((fun f =>
{
toEquiv :=
{ toFun := ↑(MulEquiv.toMonoidHom f), invFun := ↑(MulEquiv.toMonoidHom (MulEquiv.symm f)),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_add' :=
(_ :
∀ (x y : Multiplicative G),
Equiv.toFun f.toEquiv (x * y) = Equiv.toFun f.toEquiv x * Equiv.toFun f.toEquiv y) })
x))
x✝ =
↑x x✝
[PROOFSTEP]
rfl
[GOAL]
G : Type u_1
H : Type u_2
inst✝¹ : MulOneClass G
inst✝ : MulOneClass H
x : G ≃* H
⊢ (fun f =>
{
toEquiv :=
{ toFun := ↑(AddEquiv.toAddMonoidHom f), invFun := ↑(AddEquiv.toAddMonoidHom (AddEquiv.symm f)),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_mul' :=
(_ :
∀ (x y : Additive G),
Equiv.toFun f.toEquiv (x + y) = Equiv.toFun f.toEquiv x + Equiv.toFun f.toEquiv y) })
((fun f =>
{
toEquiv :=
{ toFun := ↑(↑MonoidHom.toAdditive (toMonoidHom f)),
invFun := ↑(↑MonoidHom.toAdditive (toMonoidHom (symm f))),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_add' :=
(_ : ∀ (x y : G), Equiv.toFun f.toEquiv (x * y) = Equiv.toFun f.toEquiv x * Equiv.toFun f.toEquiv y) })
x) =
x
[PROOFSTEP]
ext
[GOAL]
case h
G : Type u_1
H : Type u_2
inst✝¹ : MulOneClass G
inst✝ : MulOneClass H
x : G ≃* H
x✝ : G
⊢ ↑((fun f =>
{
toEquiv :=
{ toFun := ↑(AddEquiv.toAddMonoidHom f), invFun := ↑(AddEquiv.toAddMonoidHom (AddEquiv.symm f)),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_mul' :=
(_ :
∀ (x y : Additive G),
Equiv.toFun f.toEquiv (x + y) = Equiv.toFun f.toEquiv x + Equiv.toFun f.toEquiv y) })
((fun f =>
{
toEquiv :=
{ toFun := ↑(↑MonoidHom.toAdditive (toMonoidHom f)),
invFun := ↑(↑MonoidHom.toAdditive (toMonoidHom (symm f))),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_add' :=
(_ :
∀ (x y : G), Equiv.toFun f.toEquiv (x * y) = Equiv.toFun f.toEquiv x * Equiv.toFun f.toEquiv y) })
x))
x✝ =
↑x x✝
[PROOFSTEP]
rfl
[GOAL]
G : Type u_1
H : Type u_2
inst✝¹ : MulOneClass G
inst✝ : MulOneClass H
x : Additive G ≃+ Additive H
⊢ (fun f =>
{
toEquiv :=
{ toFun := ↑(↑MonoidHom.toAdditive (toMonoidHom f)),
invFun := ↑(↑MonoidHom.toAdditive (toMonoidHom (symm f))),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_add' :=
(_ : ∀ (x y : G), Equiv.toFun f.toEquiv (x * y) = Equiv.toFun f.toEquiv x * Equiv.toFun f.toEquiv y) })
((fun f =>
{
toEquiv :=
{ toFun := ↑(AddEquiv.toAddMonoidHom f), invFun := ↑(AddEquiv.toAddMonoidHom (AddEquiv.symm f)),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_mul' :=
(_ :
∀ (x y : Additive G),
Equiv.toFun f.toEquiv (x + y) = Equiv.toFun f.toEquiv x + Equiv.toFun f.toEquiv y) })
x) =
x
[PROOFSTEP]
ext
[GOAL]
case h
G : Type u_1
H : Type u_2
inst✝¹ : MulOneClass G
inst✝ : MulOneClass H
x : Additive G ≃+ Additive H
x✝ : Additive G
⊢ ↑((fun f =>
{
toEquiv :=
{ toFun := ↑(↑MonoidHom.toAdditive (toMonoidHom f)),
invFun := ↑(↑MonoidHom.toAdditive (toMonoidHom (symm f))),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_add' :=
(_ : ∀ (x y : G), Equiv.toFun f.toEquiv (x * y) = Equiv.toFun f.toEquiv x * Equiv.toFun f.toEquiv y) })
((fun f =>
{
toEquiv :=
{ toFun := ↑(AddEquiv.toAddMonoidHom f), invFun := ↑(AddEquiv.toAddMonoidHom (AddEquiv.symm f)),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_mul' :=
(_ :
∀ (x y : Additive G),
Equiv.toFun f.toEquiv (x + y) = Equiv.toFun f.toEquiv x + Equiv.toFun f.toEquiv y) })
x))
x✝ =
↑x x✝
[PROOFSTEP]
rfl
[GOAL]
G : Type u_1
H : Type u_2
inst✝¹ : MulOneClass G
inst✝ : AddZeroClass H
x : Additive G ≃+ H
⊢ (fun f =>
{
toEquiv :=
{ toFun := ↑(MulEquiv.toMonoidHom f), invFun := ↑(MulEquiv.toMonoidHom (MulEquiv.symm f)),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_add' :=
(_ : ∀ (x y : G), Equiv.toFun f.toEquiv (x * y) = Equiv.toFun f.toEquiv x * Equiv.toFun f.toEquiv y) })
((fun f =>
{
toEquiv :=
{ toFun := ↑(↑AddMonoidHom.toMultiplicative' (toAddMonoidHom f)),
invFun := ↑(↑AddMonoidHom.toMultiplicative'' (toAddMonoidHom (symm f))),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_mul' :=
(_ :
∀ (x y : Additive G),
Equiv.toFun f.toEquiv (x + y) = Equiv.toFun f.toEquiv x + Equiv.toFun f.toEquiv y) })
x) =
x
[PROOFSTEP]
ext
[GOAL]
case h
G : Type u_1
H : Type u_2
inst✝¹ : MulOneClass G
inst✝ : AddZeroClass H
x : Additive G ≃+ H
x✝ : Additive G
⊢ ↑((fun f =>
{
toEquiv :=
{ toFun := ↑(MulEquiv.toMonoidHom f), invFun := ↑(MulEquiv.toMonoidHom (MulEquiv.symm f)),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_add' :=
(_ : ∀ (x y : G), Equiv.toFun f.toEquiv (x * y) = Equiv.toFun f.toEquiv x * Equiv.toFun f.toEquiv y) })
((fun f =>
{
toEquiv :=
{ toFun := ↑(↑AddMonoidHom.toMultiplicative' (toAddMonoidHom f)),
invFun := ↑(↑AddMonoidHom.toMultiplicative'' (toAddMonoidHom (symm f))),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_mul' :=
(_ :
∀ (x y : Additive G),
Equiv.toFun f.toEquiv (x + y) = Equiv.toFun f.toEquiv x + Equiv.toFun f.toEquiv y) })
x))
x✝ =
↑x x✝
[PROOFSTEP]
rfl
[GOAL]
G : Type u_1
H : Type u_2
inst✝¹ : MulOneClass G
inst✝ : AddZeroClass H
x : G ≃* Multiplicative H
⊢ (fun f =>
{
toEquiv :=
{ toFun := ↑(↑AddMonoidHom.toMultiplicative' (toAddMonoidHom f)),
invFun := ↑(↑AddMonoidHom.toMultiplicative'' (toAddMonoidHom (symm f))),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_mul' :=
(_ :
∀ (x y : Additive G),
Equiv.toFun f.toEquiv (x + y) = Equiv.toFun f.toEquiv x + Equiv.toFun f.toEquiv y) })
((fun f =>
{
toEquiv :=
{ toFun := ↑(MulEquiv.toMonoidHom f), invFun := ↑(MulEquiv.toMonoidHom (MulEquiv.symm f)),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_add' :=
(_ : ∀ (x y : G), Equiv.toFun f.toEquiv (x * y) = Equiv.toFun f.toEquiv x * Equiv.toFun f.toEquiv y) })
x) =
x
[PROOFSTEP]
ext
[GOAL]
case h
G : Type u_1
H : Type u_2
inst✝¹ : MulOneClass G
inst✝ : AddZeroClass H
x : G ≃* Multiplicative H
x✝ : G
⊢ ↑((fun f =>
{
toEquiv :=
{ toFun := ↑(↑AddMonoidHom.toMultiplicative' (toAddMonoidHom f)),
invFun := ↑(↑AddMonoidHom.toMultiplicative'' (toAddMonoidHom (symm f))),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_mul' :=
(_ :
∀ (x y : Additive G),
Equiv.toFun f.toEquiv (x + y) = Equiv.toFun f.toEquiv x + Equiv.toFun f.toEquiv y) })
((fun f =>
{
toEquiv :=
{ toFun := ↑(MulEquiv.toMonoidHom f), invFun := ↑(MulEquiv.toMonoidHom (MulEquiv.symm f)),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_add' :=
(_ :
∀ (x y : G), Equiv.toFun f.toEquiv (x * y) = Equiv.toFun f.toEquiv x * Equiv.toFun f.toEquiv y) })
x))
x✝ =
↑x x✝
[PROOFSTEP]
rfl
[GOAL]
G : Type u_1
H : Type u_2
inst✝¹ : AddZeroClass G
inst✝ : MulOneClass H
x : G ≃+ Additive H
⊢ (fun f =>
{
toEquiv :=
{ toFun := ↑(MulEquiv.toMonoidHom f), invFun := ↑(MulEquiv.toMonoidHom (MulEquiv.symm f)),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_add' :=
(_ :
∀ (x y : Multiplicative G),
Equiv.toFun f.toEquiv (x * y) = Equiv.toFun f.toEquiv x * Equiv.toFun f.toEquiv y) })
((fun f =>
{
toEquiv :=
{ toFun := ↑(↑AddMonoidHom.toMultiplicative'' (toAddMonoidHom f)),
invFun := ↑(↑AddMonoidHom.toMultiplicative' (toAddMonoidHom (symm f))),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_mul' :=
(_ : ∀ (x y : G), Equiv.toFun f.toEquiv (x + y) = Equiv.toFun f.toEquiv x + Equiv.toFun f.toEquiv y) })
x) =
x
[PROOFSTEP]
ext
[GOAL]
case h
G : Type u_1
H : Type u_2
inst✝¹ : AddZeroClass G
inst✝ : MulOneClass H
x : G ≃+ Additive H
x✝ : G
⊢ ↑((fun f =>
{
toEquiv :=
{ toFun := ↑(MulEquiv.toMonoidHom f), invFun := ↑(MulEquiv.toMonoidHom (MulEquiv.symm f)),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_add' :=
(_ :
∀ (x y : Multiplicative G),
Equiv.toFun f.toEquiv (x * y) = Equiv.toFun f.toEquiv x * Equiv.toFun f.toEquiv y) })
((fun f =>
{
toEquiv :=
{ toFun := ↑(↑AddMonoidHom.toMultiplicative'' (toAddMonoidHom f)),
invFun := ↑(↑AddMonoidHom.toMultiplicative' (toAddMonoidHom (symm f))),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_mul' :=
(_ :
∀ (x y : G), Equiv.toFun f.toEquiv (x + y) = Equiv.toFun f.toEquiv x + Equiv.toFun f.toEquiv y) })
x))
x✝ =
↑x x✝
[PROOFSTEP]
rfl
[GOAL]
G : Type u_1
H : Type u_2
inst✝¹ : AddZeroClass G
inst✝ : MulOneClass H
x : Multiplicative G ≃* H
⊢ (fun f =>
{
toEquiv :=
{ toFun := ↑(↑AddMonoidHom.toMultiplicative'' (toAddMonoidHom f)),
invFun := ↑(↑AddMonoidHom.toMultiplicative' (toAddMonoidHom (symm f))),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_mul' :=
(_ : ∀ (x y : G), Equiv.toFun f.toEquiv (x + y) = Equiv.toFun f.toEquiv x + Equiv.toFun f.toEquiv y) })
((fun f =>
{
toEquiv :=
{ toFun := ↑(MulEquiv.toMonoidHom f), invFun := ↑(MulEquiv.toMonoidHom (MulEquiv.symm f)),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_add' :=
(_ :
∀ (x y : Multiplicative G),
Equiv.toFun f.toEquiv (x * y) = Equiv.toFun f.toEquiv x * Equiv.toFun f.toEquiv y) })
x) =
x
[PROOFSTEP]
ext
[GOAL]
case h
G : Type u_1
H : Type u_2
inst✝¹ : AddZeroClass G
inst✝ : MulOneClass H
x : Multiplicative G ≃* H
x✝ : Multiplicative G
⊢ ↑((fun f =>
{
toEquiv :=
{ toFun := ↑(↑AddMonoidHom.toMultiplicative'' (toAddMonoidHom f)),
invFun := ↑(↑AddMonoidHom.toMultiplicative' (toAddMonoidHom (symm f))),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_mul' :=
(_ : ∀ (x y : G), Equiv.toFun f.toEquiv (x + y) = Equiv.toFun f.toEquiv x + Equiv.toFun f.toEquiv y) })
((fun f =>
{
toEquiv :=
{ toFun := ↑(MulEquiv.toMonoidHom f), invFun := ↑(MulEquiv.toMonoidHom (MulEquiv.symm f)),
left_inv := (_ : Function.LeftInverse f.invFun f.toFun),
right_inv := (_ : Function.RightInverse f.invFun f.toFun) },
map_add' :=
(_ :
∀ (x y : Multiplicative G),
Equiv.toFun f.toEquiv (x * y) = Equiv.toFun f.toEquiv x * Equiv.toFun f.toEquiv y) })
x))
x✝ =
↑x x✝
[PROOFSTEP]
rfl
|
function grad = B_MVDR_spatialCov(X, curr_layer, beamform_layer, after_power_layer)
% X is the multichannel complex spectrum inputs
[D,C,T,N] = size(X);
% weight is the beamforming weight
weight = reshape(curr_layer.a, D,C,N);
lambda = curr_layer.lambda;
phi_s = curr_layer.phi_s;
phi_n = curr_layer.phi_n;
if isfield(curr_layer, 'noiseCovL2')
noiseCovL2 = curr_layer.noiseCovL2;
else
noiseCovL2 = 0; % add noiseCovRegularization*\lambda*I to noise covariance, where \lambda is the maximum eigenvalue
end
% Y is the beamforming's output
Y = beamform_layer.a;
% future_grad is the gradient of the power specturm of beamformed signal
future_grad = after_power_layer.grad;
if N>1
[validMask, variableLength] = getValidFrameMask(curr_layer);
future_gradUtt = ExtractVariableLengthTrajectory(future_grad, validMask);
YUtt = ExtractVariableLengthTrajectory(Y, validMask);
X = reshape(X, D*C, T, N);
XUtt = ExtractVariableLengthTrajectory(X, validMask);
for i=1:N
grad{i} = GetGradUtt(reshape(XUtt{i},D,C,size(XUtt{i},2)),YUtt{i},phi_s(:,:,:,:,i), phi_n(:,:,:,:,i), ...
weight(:,:,i), lambda(:,:,:,:,i), future_gradUtt{i}, noiseCovL2);
end
grad = cell2mat_gpu(grad);
grad = permute(grad, [1 3 2]);
else
grad = GetGradUtt(X,Y,phi_s, phi_n, weight, lambda, future_grad, noiseCovL2);
end
end
%%
function grad = GetGradUtt(X,Y,phi_s, phi_n, weight, lambda, future_grad, noiseCovL2)
[D,C,T,N] = size(X);
u = zeros(C,1);
u(1) = 1;
for f=1:D
x = squeeze(X(f,:,:));
xx = x*x';
ww = weight(f,:).' * conj(weight(f,:));
phi_n_inv = inv(phi_n{1,1,f});
yy = abs(Y(f,:).*conj(Y(f,:)));
dyyy = sum(future_grad(f,:).*yy);
dyxx = bsxfun(@times, x, future_grad(f,:)) * x';
if 1
grad_phi_s(:,:,f) = 2 * phi_n_inv * dyxx * weight(f,:).' * u' / lambda{1,1,f} -2 * dyyy * phi_n_inv / lambda{1,1,f};
grad_phi_n(:,:,f) = - 2* phi_n_inv * dyxx * ww + 2 * dyyy * phi_n_inv * phi_s{1,1,f} * phi_n_inv / lambda{1,1,f};
elseif 0 % no lambda
grad_phi_s(:,:,f) = 2 * phi_n_inv * dyxx * weight(f,:).' * u';
grad_phi_n(:,:,f) = - 2* phi_n_inv * dyxx * ww;
else % only lambda
grad_phi_s(:,:,f) = -2 * dyyy * phi_n_inv / lambda{1,1,f};
grad_phi_n(:,:,f) = 2 * dyyy * phi_n_inv * phi_s{1,1,f} * phi_n_inv / lambda{1,1,f};
end
end
grad = conj([reshape(grad_phi_s,C*C*D,1); reshape(grad_phi_n,C*C*D,1)]);
end
|
const EAGER_INIT = Ref{Bool}(false)
const EAGER_THUNK_CHAN = Channel(typemax(Int))
const EAGER_THUNK_MAP = Dict{Int,Int}()
const EAGER_CONTEXT = Ref{Context}()
eager_context() = isassigned(EAGER_CONTEXT) ? EAGER_CONTEXT[] : nothing
function init_eager()
EAGER_INIT[] && return
EAGER_INIT[] = true
if eager_context() === nothing
EAGER_CONTEXT[] = Context([myid(),workers()...])
end
ctx = EAGER_CONTEXT[]
@async try
sopts = SchedulerOptions(;allow_errors=true)
topts = ThunkOptions(;single=1)
Dagger.compute(ctx, Dagger.delayed(eager_thunk;options=topts)(); options=sopts)
catch err
iob = IOContext(IOBuffer(), :color=>true)
println(iob, "Error in eager scheduler:")
Base.showerror(iob, err)
Base.show_backtrace(iob, catch_backtrace())
println(iob)
seek(iob.io, 0)
write(stderr, iob)
finally
EAGER_INIT[] = false
end
end
"Adjusts the scheduler's cached pressure indicator for the specified worker by
the specified amount."
function adjust_pressure!(h::SchedulerHandle, proctype::Type, pressure)
uid = Dagger.get_tls().sch_uid
lock(ACTIVE_TASKS_LOCK) do
ACTIVE_TASKS[uid][proctype][] += pressure
notify(TASK_SYNC)
end
exec!(_adjust_pressure!, h, myid(), proctype, pressure)
end
function _adjust_pressure!(ctx, state, task, tid, (pid, proctype, pressure))
state.worker_pressure[pid][proctype] += pressure
nothing
end
"Allows a thunk to safely wait on another thunk, by temporarily reducing its
effective pressure to 0."
function thunk_yield(f)
if Dagger.in_thunk()
h = sch_handle()
tls = Dagger.get_tls()
proctype = typeof(tls.processor)
util = tls.utilization
adjust_pressure!(h, proctype, -util)
try
f()
finally
adjust_pressure!(h, proctype, util)
end
else
f()
end
end
function eager_thunk()
h = sch_handle()
util = Dagger.get_tls().utilization
# Don't apply pressure from this thunk
adjust_pressure!(h, Dagger.ThreadProc, -util)
while isopen(EAGER_THUNK_CHAN)
try
future, uid, f, args, opts = take!(EAGER_THUNK_CHAN)
args = map(x->x isa Dagger.EagerThunk ? ThunkID(EAGER_THUNK_MAP[x.uid]) : x, args)
tid = add_thunk!(f, h, args...; opts...)
register_future!(h, tid, future)
EAGER_THUNK_MAP[uid] = tid.id
catch err
iob = IOContext(IOBuffer(), :color=>true)
println(iob, "Error in eager listener:")
Base.showerror(iob, err)
Base.show_backtrace(iob, catch_backtrace())
println(iob)
seek(iob.io, 0)
write(stderr, iob)
end
end
end
|
(**************************************************************)
(* Copyright Dominique Larchey-Wendling [*] *)
(* *)
(* [*] Affiliation LORIA -- CNRS *)
(**************************************************************)
(* This file is distributed under the terms of the *)
(* CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT *)
(**************************************************************)
Require Import Arith Omega.
Require Import bar.
Set Implicit Arguments.
Tactic Notation "eq" "goal" "with" hyp(H) :=
match goal with |- ?b => match type of H with ?t => replace b with t; auto end end.
Theorem nat_rev_ind (P : nat -> Prop) (HP : forall n, P (S n) -> P n) x y : x <= y -> P y -> P x.
Proof. induction 1; auto. Qed.
Reserved Notation "f ↑ n" (at level 1, left associativity).
Fixpoint iter X (f : X -> X) n x :=
match n with
| 0 => x
| S n => f (f↑n x)
end
where "f ↑ n" := (@iter _ f n).
Section th_min.
Variables (X : Type) (eqdec : forall x y : X, { x = y } + { x <> y }).
Infix "=?" := eqdec (at level 70).
Variable (f : X -> X) (x0 : X)
(Hx0 : exists τ, 0 < τ /\ f↑τ x0 = f↑(2*τ) x0).
Theorem th_min : { τ | 0 < τ /\ f↑τ x0 = f↑(2*τ) x0 }.
Proof.
apply Constructive_Epsilon; trivial.
intros n.
destruct (le_lt_dec n 0) as [ | H ]; [right; omega | ].
destruct (eqdec (f↑n x0) (f↑(2*n) x0)); tauto.
Qed.
End th_min.
Extraction Inline bar_rect.
Extraction Inline Constructive_Epsilon.
Recursive Extraction th_min. |
universe u
constant vec : Type u → ℕ → Type u
namespace vec
constant empty : Π α : Type u, vec α 0
constant cons :
Π {α : Type u} {n : ℕ}, α → vec α n → vec α (n + 1)
constant append :
Π {α : Type u} {n m : ℕ}, vec α m → vec α n → vec α (n + m)
end vec
#check vec
-- Above, we used the example vec α n for vectors of elements of type α of
-- length n. Declare a constant vec_add that could represent a function
-- that adds two vectors of natural numbers of the same length, and a constant
-- vec_reverse that can represent a function that reverses its argument.
-- Use implicit arguments for parameters that can be inferred. Declare some
-- variables and check some expressions involving the constants that you have
-- declared.
constant vec_add : Π {α : Type u} {n : ℕ}, vec α n → vec α n → vec α n
#reduce vec.cons 456 (vec.cons 123 (vec.empty _))
#check vec_add (vec.cons 456 (vec.cons 123 (vec.empty _))) (vec.cons 456 (vec.cons 123 (vec.empty _)))
constant vec_reverse : Π {α : Type u} {n : ℕ}, vec α n → vec α n
#check vec_reverse (vec.cons 456 (vec.cons 123 (vec.empty _)))
-- Similarly, declare a constant matrix so that matrix α m n could represent the
-- type of m by n matrices. Declare some constants to represent functions on
-- this type, such as matrix addition and multiplication, and (using vec)
-- multiplication of a matrix by a vector. Once again, declare some variables
-- and check some expressions involving the constants that you have declared.
constant matrix : Type u → ℕ → ℕ → Type u
constant matrix_add : Π {α : Type u} {n m : ℕ}, matrix α n m → matrix α n m
constant matrix_mul : Π {α : Type u} {n m k : ℕ}, matrix α n m → matrix α m k → matrix α n k
constant matrix_vec_mul : Π {α : Type u} {n m : ℕ}, matrix α n m → vec α m → vec α n
|
text \<open> Version 0.5, last changed 2019-02-01
(C) fovefi ltd, www.fovefi.co
(author: Manfred Kerber [[email protected]] based on Percentile_Code.thy in foveSIMM by Lukas Bulwahn)
Dually licenced under
Creative Commons Attribution (CC-BY) 4.0 [https://creativecommons.org/licenses/by/4.0/]
ISC License (1-clause BSD License) [https://www.isc.org/downloads/software-support-policy/isc-license/]
See LICENSE files for details.
(Rationale for this dual licence: http://arxiv.org/abs/1107.3212)
In the following, an executable definition of the percentile function is given that is
close to the one used in OpenSIMM, a system with a standard implementation for the computation
of risk. Here, the percentile function is extended so that it is defined on the complete interval [0,1].
The extension is done by taking a constant slope at the ends of the interval. To this end the original
implementation was adjusted.
\<close>
theory Percentile_Code
imports Percentile
begin
section \<open>Code Generation of Percentile\<close>
paragraph \<open>The percentile definition close to the Java implementation\<close>
text \<open> In the Java code follows a check that the level is below 1 - 1/(2*size).
* If not, it throws an exception. In the Isabelle implementation (there is no exception
* handling in Isabelle), the code is underspecified, that is, no specific values will be
* returned for larger values. This will be fixed in the definition of the percentile function
* in the next section.
\<close>
text \<open> An integer greater equal 0 considered as a real number is the same as the integer first considered
as a natural number and this then considered as a real number. \<close>
lemma real_of_int:
assumes "0 \<le> i"
shows "real_of_int i = real (nat i)"
by (simp add: assms)
text \<open> The value of the minimum of the domain of equidistant point is determined. \<close>
lemma Min_equidistant_points_on_unit_interval_of_bounded:
fixes x :: real
assumes "ys \<noteq> []"
assumes "1 / (2 * length ys) < x"
assumes "x \<le> 1 - 1 / (2 * length ys)"
shows "Min {x' \<in> dom (equidistant_points_on_unit_interval_of ys). x \<le> x'} = (ceiling (length ys * x - 0.5) + 0.5) / length ys"
(is "Min ?A = ?expr")
proof (rule Min_eqI)
text \<open>let ?A = "{x' \<in> dom (equidistant_points_on_unit_interval_of ys). x \<le> x'}"\<close>
show "finite ?A" by simp
show "?expr \<le> y" if "y \<in> ?A" for y
proof -
from that \<open>ys \<noteq> []\<close> obtain n where "y = (real n + 1 / 2) / real (length ys)" and "x \<le> y"
unfolding equidistant_points_on_unit_interval_of_def
apply auto done
obtain i where "i = int n" by auto
from this \<open>y = _\<close> have y: "y = (real_of_int i + 1 / 2) / real (length ys)"
by simp
have "i \<ge> ceiling (length ys * x - 0.5)"
proof -
have "x \<le> (real_of_int i + 1 / 2) / real (length ys)"
using \<open>x \<le> y\<close> y by blast
from this have "length ys * x \<le> (real_of_int i + 1 / 2)"
apply -
apply (frule mult_left_mono[where c="real (length ys)"])
apply simp
by (simp add: assms(1))
find_theorems "_ * _ \<le> _ * _"
from this have "length ys * x - 1 / 2 \<le> real_of_int i" by linarith
from this show ?thesis
by (simp add: ceiling_le)
qed
from this y have "y \<ge> (real_of_int (ceiling (length ys * x - 0.5)) + 1 / 2) / real (length ys)"
apply simp
find_theorems "_ / _ \<le> _ / _"
apply (rule divide_right_mono)
apply simp
apply simp
done
from this show ?thesis by simp
qed
show "?expr \<in> ?A"
proof -
from assms have "0 \<le> real (length ys) * x - 1 / 2"
apply auto
by (simp add: Groups.mult_ac(2) divide_less_eq)
from this have "0 \<le> \<lceil>real (length ys) * x - 1 / 2\<rceil>" by simp
from this have a: "real_of_int \<lceil>real (length ys) * x - 1 / 2\<rceil> = real (nat \<lceil>real (length ys) * x - 1 / 2\<rceil>)"
by simp
have b: "nat \<lceil>real (length ys) * x - 1 / 2\<rceil> \<in> {0..<length ys}"
proof -
have "real (length ys) * x - 1 / 2 \<le> (length ys - 1)"
proof -
have "real (length ys) * x - 1 / 2 \<le> real (length ys) * (1 - 1 / real (2 * length ys)) - 1 / 2"
using assms(1, 3) by simp
also have "\<dots> = real (length ys) - 1"
apply auto
apply (subst right_diff_distrib)
apply simp
by (simp add: assms(1))
also have "\<dots> = real (length ys - 1)"
by (metis One_nat_def Suc_pred assms(1) diff_Suc_Suc diff_is_0_eq length_greater_0_conv of_nat_1 of_nat_diff zero_diff)
finally show ?thesis .
qed
text \<open>have "\<lceil>real (length ys) * x - 1 / 2\<rceil> \<ge> 0" s_orry\<close>
from this have a: "\<lceil>real (length ys) * x - 1 / 2\<rceil> \<le> \<lceil>real (length ys - 1)\<rceil>"
using ceiling_mono by blast
have "\<lceil>real (length ys - 1)\<rceil> = int (length ys - 1)" by simp
from a this have "nat \<lceil>real (length ys) * x - 1 / 2\<rceil> < length ys"
by (smt assms(1) int_nat_eq length_greater_0_conv nat_less_le of_nat_0_less_iff of_nat_1 of_nat_diff of_nat_less_imp_less zero_less_diff)
from this show ?thesis
apply auto done
qed
have "(real_of_int \<lceil>real (length ys) * x - 5 / 10\<rceil> + 5 / 10) / real (length ys)
\<in> dom (equidistant_points_on_unit_interval_of ys)"
unfolding dom_equidistant_points_on_unit_interval_of
apply auto
apply (subst a)
apply (rule image_eqI)
apply (rule refl)
apply (rule b) done
find_theorems "dom (equidistant_points_on_unit_interval_of _)"
moreover have "x \<le> (real_of_int \<lceil>real (length ys) * x - 5 / 10\<rceil> + 5 / 10) / real (length ys)"
proof -
have "real (length ys) > 0" (* only need \<ge> *)
by (simp add: assms)
have a: "real (length ys) * x - 5 / 10 \<le> real_of_int \<lceil>real (length ys) * x - 5 / 10\<rceil>"
by linarith
have "x \<le> ((real (length ys) * x - 5 / 10) + 5 / 10) / real (length ys)"
using \<open>real (length ys) > 0\<close> by auto
also have "\<dots> \<le> (real_of_int \<lceil>real (length ys) * x - 5 / 10\<rceil> + 5 / 10) / real (length ys)"
using \<open>real (length ys) > 0\<close> a
apply -
apply (rule divide_right_mono)
apply linarith
apply simp done
finally show ?thesis .
qed
ultimately show ?thesis by auto
qed
qed
text \<open> A property of the ceiling function. \<close>
lemma ceiling_minus_leq:
assumes "a + b \<ge> 1"
shows "real_of_int \<lceil>x - a\<rceil> - b \<le> x"
using assms by linarith
text \<open> Relationship between floor and ceiling (floor plus 1 is less equal ceiling). \<close>
lemma floor_leq_ceiling:
fixes x :: real
assumes "x \<notin> real_of_int ` UNIV"
shows "1 + real_of_int (floor x) \<le> real_of_int (ceiling x)"
using assms by (smt UNIV_I ceiling_correct image_eqI int_less_real_le le_floor_iff)
text \<open> If i < y for two integers then i \<le> y - 1 (when converted to real).\<close>
lemma less_to_leq:
fixes y :: real
assumes "real i < y"
assumes "y \<in> real_of_int ` UNIV"
shows "real i \<le> y - 1"
proof -
from assms(2) obtain j where "y = real_of_int j"
apply auto done
obtain k where "j = int k"
by (smt \<open>y = real_of_int j\<close> assms(1) int_less_real_le nat_0_le of_int_1 of_nat_0_le_iff)
from this \<open>y = _\<close> assms(1) show ?thesis by auto
qed
text \<open> The value of the maximum of the domain of equidistant point is determined. \<close>
lemma Max_equidistant_points_on_unit_interval_of_bounded:
fixes x :: real
assumes "ys \<noteq> []"
assumes "1 / (2 * length ys) < x" "x \<le> 1 - 1 / (2 * length ys)"
shows "Max {x' \<in> dom (equidistant_points_on_unit_interval_of ys). x' < x} = (ceiling (length ys * x - 0.5) - 0.5) / length ys"
(is "_ = ?expr")
proof -
let ?A = "{x' \<in> (\<lambda>x. (1 / length ys) * (x + 0.5)) ` {0..<length ys}. x' < x}"
have "Max ?A = ?expr"
find_theorems "_ ` _" "Max"
proof (rule Max_eqI)
show "finite ?A" by simp
show "y \<le> ?expr" if "y \<in> ?A" for y
proof -
show ?thesis
proof (cases "real (length ys) * x - 1 / 2 \<in> range real_of_int")
case True
from that obtain i where "i \<in> {0..<length ys}"
and y: "y = 1 / real (length ys) * (real i + 5 / 10)" and "y < x" by auto
have "(real i + 5 / 10) < real (length ys) * x"
by (metis \<open>y < x\<close> assms(1) divide_less_eq length_greater_0_conv mult.commute mult_numeral_1 numeral_One of_nat_0_less_iff times_divide_eq_right y)
from this have "real i < real (length ys) * x - 0.5"
by linarith
from this have "real i \<le> real (length ys) * x - 1.5"
apply -
apply (frule less_to_leq)
apply (simp add: True)
by linarith
from this have "(real i + 5 / 10) \<le> real (length ys) * x - 1"
apply simp done
have "1 / real (length ys) > 0" by (simp add: assms(1))
from this assms y have y2: "y \<le> 1 / real (length ys) * (real (length ys) * x - 1)"
using \<open>real i + 5 / 10 \<le> real (length ys) * x - 1\<close> real_mult_le_cancel_iff2 by blast
have "real (length ys) * x - 1 / 2 \<le> real_of_int \<lceil>real (length ys) * x - 1 / 2\<rceil>"
by simp
from this have "real (length ys) * x - 1 \<le> real_of_int \<lceil>real (length ys) * x - 1 / 2\<rceil> - 1 / 2"
proof -
have "real (length ys) * x - 1 = (real (length ys) * x - 1 / 2) - 1 / 2" by simp
also have "\<dots> \<le> real_of_int \<lceil>real (length ys) * x - 1 / 2\<rceil> - 1 / 2"
by linarith
finally show ?thesis .
qed
from this y2 show ?thesis
apply auto
find_theorems "?a \<le> ?b \<Longrightarrow> ?b \<le> ?c \<Longrightarrow> ?a \<le> ?c"
apply (rule order.trans)
apply assumption
apply (rule divide_right_mono)
apply simp apply simp done
find_theorems "_ / _ \<le> _ / _"
next
case False
then show ?thesis
proof -
have "y \<le> 1 / real (length ys) * (real_of_int \<lfloor>real (length ys) * x - 5 / 10\<rfloor> + 5 / 10)"
proof -
from that obtain i where "i \<in> {0..<length ys}"
and "y = 1 / real (length ys) * (real i + 5 / 10)" and "y \<le> x" by auto
have "i \<le> \<lfloor>real (length ys) * x - 5 / 10\<rfloor>"
proof -
have a: "1 / real (length ys) * (real i + 5 / 10) \<le> x"
using \<open>y = _\<close> \<open>y \<le> x\<close> by blast
have "(real i + 5 / 10) \<le> real (length ys) * x"
proof -
have "(real i + 5 / 10) = real (length ys) * (1 / real (length ys) * (real i + 5 / 10))"
by (simp add: assms(1))
also have "\<dots> \<le> real (length ys) * x"
using a mult_left_mono of_nat_0_le_iff by blast
finally show ?thesis .
qed
from this have "real i \<le> real (length ys) * x - 5 / 10" by linarith
from this show ?thesis by linarith
qed
from this \<open>y = _\<close> show ?thesis
proof -
have "real (length ys) > 0" by (simp add: assms(1))
from \<open>i \<le> floor _\<close> have "(real i + 5 / 10) \<le> real_of_int \<lfloor>real (length ys) * x - 5 / 10\<rfloor> + 5 / 10"
by linarith
from this \<open>y = _\<close> \<open>real (length ys) > 0\<close> show ?thesis
using real_mult_le_cancel_iff2 by fastforce
qed
qed
also have "\<dots> \<le> (real_of_int \<lceil>real (length ys) * x - 5 / 10\<rceil> - 5 / 10) / real (length ys)"
proof -
from False
have "(real_of_int \<lfloor>real (length ys) * x - 5 / 10\<rfloor> + 5 / 10) \<le> (real_of_int \<lceil>real (length ys) * x - 5 / 10\<rceil> - 5 / 10)"
apply simp
apply (rule floor_leq_ceiling)
apply assumption
done
from this show ?thesis
apply simp
apply (rule divide_right_mono)
apply simp apply simp done
qed
finally show ?thesis .
qed
qed qed
show "?expr \<in> ?A"
proof -
have "?expr \<in> (\<lambda>x. 1 / real (length ys) * (real x + 5 / 10)) ` {0..<length ys}"
proof
have "real (length ys) * x - 1 / 2 > 0"
by (metis assms(1) assms(2) diff_gt_0_iff_gt divide_divide_eq_left divide_less_eq length_greater_0_conv mult.commute of_nat_0_less_iff of_nat_mult of_nat_numeral)
from this have "nat \<lceil>real (length ys) * x - 1 / 2\<rceil> \<ge> 1"
by linarith
from this show "(real_of_int \<lceil>real (length ys) * x - 5 / 10\<rceil> - 5 / 10) / real (length ys) =
1 / real (length ys) * (real (nat \<lceil>real (length ys) * x - 5 / 10\<rceil> - 1) + 5 / 10)"
using \<open>ys \<noteq> []\<close>
apply auto done
have "real (length ys) \<ge> 0" by auto
have "x \<le> 1"
by (smt assms(3) divide_less_0_1_iff of_nat_0_le_iff)
from this have "real (length ys) * x \<le> length ys"
by (simp add: mult_left_le)
from this \<open>real (length ys) \<ge> 0\<close> have "real (length ys) * x \<le> length ys + 1 / 2"
by linarith
from this have "real (length ys) * x - 1 / 2 \<le> length ys"
by fastforce
from this show "nat \<lceil>real (length ys) * x - 5 / 10\<rceil> - 1 \<in> {0..<length ys}"
apply auto
using \<open>1 \<le> nat \<lceil>real (length ys) * x - 1 / 2\<rceil>\<close> by linarith
qed
moreover have "?expr < x"
proof -
have "real_of_int \<lceil>real (length ys) * x - 5 / 10\<rceil> < real (length ys) * x + 5 / 10"
by linarith
then have "real_of_int \<lceil>real (length ys) * x - 5 / 10\<rceil> < x * real (length ys) + 5 / 10"
by (simp add: mult.commute)
have "real_of_int \<lceil>real (length ys) * x - 5 / 10\<rceil> - 5 / 10 < x * real (length ys)"
using \<open>real_of_int \<lceil>real (length ys) * x - 5 / 10\<rceil> < x * real (length ys) + 5 / 10\<close> by linarith
from this show "(real_of_int \<lceil>real (length ys) * x - 5 / 10\<rceil> - 5 / 10) / real (length ys) < x"
apply auto
by (simp add: assms(1) divide_less_eq)
qed
ultimately show ?thesis by auto
qed
qed
from this show ?thesis
unfolding equidistant_points_on_unit_interval_of_def by simp
qed
text \<open> The lemma determines the values of equidistant point on the unit interval. \<close>
lemma equidistant_points_on_unit_interval_of_eq_nth2:
fixes i :: int
assumes "0 \<le> i" "nat i < length ys"
shows "the (equidistant_points_on_unit_interval_of ys ((real_of_int i + 5 / 10) / size ys)) = ys ! (nat i)"
proof -
let ?xs = "map (\<lambda>x. (real x + 1 / 2) / real (length ys)) [0..<length ys]"
have "distinct ?xs" by (auto intro!: inj_onI simp add: distinct_map)
have eq: "(real_of_int i + 1 / 2) / real (length ys) = ?xs ! nat i"
using assms by auto
show ?thesis
unfolding equidistant_points_on_unit_interval_of_def
apply simp
apply (subst eq)
thm map_of_zip_nth
apply (subst map_of_zip_nth)
apply simp
apply (rule \<open>distinct ?xs\<close>)
apply (rule assms)
apply simp done
qed
text \<open> The lemma gives an alternative characterization of the values of equidistant point on the unit interval. \<close>
lemma equidistant_points_on_unit_interval_of_eq_nth1:
fixes i :: int
assumes "1 \<le> i" "i \<le> length ys"
shows "the (equidistant_points_on_unit_interval_of ys ((real_of_int i - 5 / 10) / size ys)) = ys ! nat (i - 1)"
proof -
(* todo: size ys = real (length ys); which is better to write down? *)
let ?f = "\<lambda>x. the (equidistant_points_on_unit_interval_of ys (x / size ys))"
have "?f (real_of_int i - 5 / 10) = ?f (real_of_int (i - 1) + 5 / 10)" by force
also have "\<dots> = ys ! nat (i - 1)"
using assms by (simp only: equidistant_points_on_unit_interval_of_eq_nth2)
finally show ?thesis .
qed
text \<open> The definition contains executable version of the percentile function which is close to the
Java implementation in the OpenSIMM implementation. \<close>
definition percentile_impl_inner :: "real list \<Rightarrow> real \<Rightarrow> real"
where
"percentile_impl_inner values level =
(let (size :: real) = (real (length values));
(sorted :: (real list)) = sort values;
i = (ceiling (size * level - 0.5));
(lower :: real) = (i - 0.5) / size;
(upper ::real) = (i + 0.5) / size;
\<comment>\<open>Note that we convert i to a nat since we want to use it
as an index in a list. This means that we automatically
have values greater equal 0\<close>
(lower_value :: real) = sorted ! (nat (i-1));
(upper_value :: real) = sorted ! (nat i)
in lower_value + (level - lower) * (upper_value - lower_value) / (upper - lower))"
definition percentile_impl :: "(real list) \<Rightarrow> real \<Rightarrow> real" where
"percentile_impl values level =
(let (size :: nat) = (length values);
(sorted :: real list) = sort values
in
(if (0 \<le> level \<and> level < 1/(2 *size))
then (linear (0, (extrapolation_0 sorted)) (1/(2*size), sorted!0)) level
else (if (1 - 1/(2 *size) < level \<and> level \<le> 1)
then (linear (1 - 1/(2 *size), sorted!(size - 1)) (1, (extrapolation_1 sorted))) level
else percentile_impl_inner sorted level)))"
text \<open> The theorem states the equivalence of the abstract definition of the percentile function from
the Percentile theory and the computational version in the standard interval. \<close>
theorem percentile_inner_java_equiv:
assumes "sorted values"
assumes "length values > 1"
assumes "1 / (2 * length values) < level" (* todo: lesseq instead of less *)
assumes "level \<le> 1 - 1 / (2 * length values)"
shows "Percentile.percentile values level = percentile_impl_inner values level"
proof -
have non_empty: "values \<noteq> []" using assms(2) by auto
have Percentile_inner_equ: "Percentile.percentile values level = Percentile.percentile_inner values level"
using percentile_alt1 using assms by simp
from assms(3) have "level \<noteq> 1 / real (2 * length values)" by blast
let ?def = "(let p = equidistant_points_on_unit_interval_of (sort values);
(x1, x2) = (Max {x' \<in> dom p. x' < level}, Min {x' \<in> dom p. level \<le> x'});
(y1, y2) = (the (p x1), the (p x2))
in linear (x1, y1) (x2, y2) level)"
{
fix size sorted i lower upper lower_value upper_value
assume "size = real (length values)"
assume "sorted = sort values"
assume "i = \<lceil>size * level - 5 / 10\<rceil>"
assume "lower = (real_of_int i - 5 / 10) / size"
assume "upper = (real_of_int i + 5 / 10) / size"
assume "lower_value = sorted ! nat (i - 1)"
assume "upper_value = sorted ! nat i"
have "length values = length sorted" and "sorted \<noteq> []" (* is this noteq Nil fact needed? *) and
"length sorted > 0"
using \<open>sorted = _\<close> \<open>_ \<noteq> []\<close> apply auto
by (metis length_0_conv length_sort) (* todo: find a better lemma *)
have "lower_value + (level - lower) * (upper_value - lower_value) / (upper - lower) =
linear (lower, lower_value) (upper, upper_value) level"
apply (subst linear_eq[symmetric]) ..
also have "\<dots> = ?def"
proof -
have b1: "0 \<le> \<lceil>real (length sorted) * level - 5 / 10\<rceil>"
proof -
have "- 1 / 2 \<le> real (length sorted) * level - 5 / 10"
apply simp
by (meson assms(3) le_less_trans less_eq_real_def of_nat_0_le_iff zero_le_divide_1_iff zero_le_mult_iff)
(* strange proof? *)
from this show ?thesis by linarith
qed
have b2: "nat \<lceil>real (length sorted) * level - 5 / 10\<rceil> < length sorted"
proof -
have "real (length sorted) * level \<le> real (length sorted) - 1 / 2"
proof -
from assms(4) have "level \<le> 1 - 1 / real (2 * length sorted)"
using \<open>length values = length sorted\<close> by simp
from this have "real (length sorted) * level \<le> real (length sorted) * (1 - 1 / real (2 * length sorted))"
using \<open>0 < length sorted\<close> by auto
also have "\<dots> = real (length sorted) - 1 / 2"
apply simp
by (metis \<open>length values = length sorted\<close> \<open>size = real (length values)\<close> non_empty
length_0_conv mult.commute mult.right_neutral mult_cancel_left
nonzero_mult_divide_mult_cancel_left of_nat_eq_iff of_nat_mult
right_diff_distrib' times_divide_eq_right)
finally show ?thesis .
qed
from this show ?thesis
using b1 by linarith
qed
have b3: "1 \<le> \<lceil>real (length sorted) * level - 5 / 10\<rceil>"
proof -
show ?thesis
using assms(3) \<open>length _ = _\<close> \<open>length sorted > 0\<close>
by (simp add: Groups.mult_ac(2) divide_less_eq)
qed
from b2 have b4: "\<lceil>real (length sorted) * level - 5 / 10\<rceil> \<le> int (length sorted)" by simp
have "Max {x' \<in> dom (equidistant_points_on_unit_interval_of sorted). x' < level} = lower"
using \<open>lower = _\<close> \<open>i = _\<close> \<open>size = _\<close> \<open>length values = _\<close>
apply (subst Max_equidistant_points_on_unit_interval_of_bounded)
prefer 4
apply simp
using \<open>sorted \<noteq> []\<close> apply blast
using assms(3) apply auto[1]
using assms(4) by auto
moreover have "Min {x' \<in> dom (equidistant_points_on_unit_interval_of sorted). level \<le> x'} = upper"
using \<open>upper = _\<close> \<open>i = _\<close> \<open>size = _\<close> \<open>length values = _\<close>
apply (subst Min_equidistant_points_on_unit_interval_of_bounded)
prefer 4
apply simp
using \<open>sorted \<noteq> []\<close> apply blast
using assms(3) apply auto[1]
using assms(4) by auto
moreover have "the (equidistant_points_on_unit_interval_of sorted lower) = lower_value"
using \<open>i = _\<close> \<open>size = _\<close> \<open>lower_value = _\<close> \<open>lower = _\<close> \<open>length values = _\<close>
apply (simp only:)
apply (subst equidistant_points_on_unit_interval_of_eq_nth1)
apply (rule b3)
apply (rule b4)
apply simp
done
moreover have "the (equidistant_points_on_unit_interval_of sorted upper) = upper_value"
using \<open>i = _\<close> \<open>size = _\<close> \<open>upper_value = _\<close> \<open>upper = _\<close> \<open>length values = _\<close>
apply (simp only:)
apply (subst equidistant_points_on_unit_interval_of_eq_nth2)
apply (rule b1)
apply (rule b2)
apply simp done
ultimately show ?thesis
using \<open>sorted = _\<close> by simp
qed
finally have "lower_value + (level - lower) * (upper_value - lower_value) / (upper - lower) =
?def" by simp (* intermediate proof step not needed? change proof structure? *)
}
from this \<open>level \<noteq> _\<close> show ?thesis using percentile_inner_alternative_pseudo_def percentile_impl_inner_def
Percentile_inner_equ
by (simp add: percentile_inner_alternative_pseudo_def percentile_impl_inner_def)
qed
theorem percentile_java_equiv_left:
assumes "length values > 1"
assumes "sorted values"
assumes "1 / real (2 * length values) = level"
shows "Percentile.percentile values level = percentile_impl values level"
proof -
have "(length values) * level = 1/2" using assms by auto
then have ceil: "ceiling ((length values) * level - 0.5) = 0" using ceiling_def
by (simp add: \<open>real (length values) * level = 1 / 2\<close>)
have "(sort values)!0 = (sort values)!(nat (0-1))" by simp
have "2 * length values \<ge> 4"
using assms(1) by linarith
then have "1/(2 * length values) \<le> 1/4"
using inverse_of_nat_le by fastforce
then have "1/(2*length values) < 1 - 1/(2 *length values)"
by linarith
then have "percentile_impl values level = percentile_impl_inner values level" using assms percentile_impl_def
by (simp add: sorted_sort_id)
then have "percentile_impl values level = (sort values)!0"
using ceil percentile_impl_inner_def by auto
then have "percentile_impl_inner values level = (sort values)!0" using ceil
by (simp add: percentile_impl_inner_def)
have "length values = length (sort values)" by simp
have left_most: "(\<lambda>x. (1 / length values) * (x + 0.5)) 0 = level"
using \<open>real (length values) * level = 1 / 2\<close> add_divide_distrib eq_divide_eq_1 mult_cancel_right1
nonzero_mult_div_cancel_left times_divide_eq_left assms by auto
have "level = ((map (\<lambda>x. (1 /length values) * (x + 0.5)) [0..<length values]))!0"
using assms left_most
by (smt add.left_neutral diff_zero gr0I not_less_zero nth_map_upt of_nat_0)
then have "level \<in> set (map (\<lambda>x. (1 /length values) * (x + 0.5)) [0..<length values])"
using assms(1)
by (metis gr_implies_not0 length_map length_upt neq0_conv nth_mem zero_less_diff)
then have "level \<in> set (map (\<lambda>x. (1 /length values) * (x + 0.5)) [0..<length values])"
using left_most by blast
then have "level \<in> dom (equidistant_points_on_unit_interval_of (sort values))"
using equidistant_points_on_unit_interval_of_def
by simp
then have "neighbors (equidistant_points_on_unit_interval_of (sort values)) level = (level, level)"
using defined_point_neighbors_eq finite_equidistant_points_on_unit_interval_of by blast
then have val_0: "linear_approximation (equidistant_points_on_unit_interval_of (sort values)) level = (sort values)!0"
using one_point_interpolation \<open>length values = length (sort values)\<close>
\<open>level \<in> dom (equidistant_points_on_unit_interval_of (sort values))\<close> assms(1)
equidistant_points_on_unit_interval_of_eq_nth2 finite_equidistant_points_on_unit_interval_of
left_most length_greater_0_conv mult_cancel_right1 nat_zero_as_int of_nat_eq_0_iff
real_of_int times_divide_eq_left
proof -
have f1: "(0::int) \<le> 0"
by auto
have f3: "length values \<noteq> 0 \<longrightarrow> (5 / 10 + real_of_int 0) / (of_nat_1 (length (sort values))) = 1 * (5 / 10) / (if length values = 0 then 0 else of_nat_1 (length values))"
by auto
have f4: "1 / (if length values = 0 then 0 else (length values)) * (5 / 10) = level"
using left_most by auto
have "\<forall>x1. real_of_int x1 + 5 / 10 = 5 / 10 + real_of_int x1"
by auto
then have "length values \<noteq> 0 \<longrightarrow> linear_approximation (equidistant_points_on_unit_interval_of (sort values)) level = sort values ! 0"
using f4 f3 f1 \<open>\<And>c b a. b / c * a = b * a / c\<close> \<open>length values = length (sort values)\<close>
\<open>level \<in> dom (equidistant_points_on_unit_interval_of (sort values))\<close> assms
equidistant_points_on_unit_interval_of_eq_nth2 finite_equidistant_points_on_unit_interval_of
length_greater_0_conv nat_zero_as_int one_point_interpolation
divide_inverse_commute divide_numeral_1 inverse_divide of_int_0
by (smt length_0_conv)
then show ?thesis using assms(1) by linarith
qed
then have "Percentile.percentile values level = Percentile.percentile_inner values level"
using percentile_alt1[of "values" "level"] assms
by (smt Max_equidistant_points_on_unit_interval_of Max_ge
\<open>level \<in> dom (equidistant_points_on_unit_interval_of (sort values))\<close>
finite_equidistant_points_on_unit_interval_of le_less_trans le_numeral_extra(1)
length_greater_0_conv sorted_sort_id)
then have "Percentile.percentile values level = (sort values)!0" using linear_approximation_def
using one_point_interpolation percentile_alt1 using val_0
by (simp add: percentile_inner_def)
then show ?thesis
by (simp add: \<open>percentile_impl values level = percentile_impl_inner values level\<close>
\<open>percentile_impl_inner values level = sort values ! 0\<close>)
qed
theorem percentile_java_equiv:
assumes "sorted values"
assumes "length values > 1"
assumes "0 \<le> level \<and> level \<le> 1"
shows "Percentile.percentile values level = percentile_impl values level"
proof -
have l1: "0 \<le> level \<and> level < 1/(2* (length values)) \<longrightarrow>
Percentile.percentile values level =
(linear (0, extrapolation_0 values) (1/(2* (length values)), values!0)) level"
using assms(1) assms(2) percentile_alt2 by blast
have "0 \<le> level \<and> level < 1/(2* (length values)) \<longrightarrow>
percentile_impl values level =
(linear (0, (extrapolation_0 values)) (1/(2* (length values)), values!0)) level"
using percentile_impl_def by (simp add: assms(1) sorted_sort_id)
then have low: "0 \<le> level \<and> level < 1/(2* (length values)) \<longrightarrow> ?thesis" using l1 by auto
have w: "1/(2* length values) < level \<and> level \<le> 1 - 1/(2* length values) \<longrightarrow>
1/(2* length values) \<le> level \<and> level \<le> 1 - 1/(2* length values)" by auto
have l2: "1/(2* length values) < level \<and> level \<le> 1 - 1/(2* length values) \<longrightarrow>
Percentile.percentile values level = percentile_impl_inner values level"
using percentile_inner_java_equiv[of "values" "level"] using assms(1) assms(2)
by blast
have "1/(2* length values) < level \<and> level \<le> 1 - 1/(2* length values) \<longrightarrow>
percentile_impl values level = percentile_impl_inner values level"
using assms percentile_impl_def by (simp add: sorted_sort_id)
then have mid: "1/(2* length values) < level \<and> level \<le> 1 - 1/(2* length values) \<longrightarrow> ?thesis"
using l2 percentile_inner_java_equiv by simp
have l3: "1 - 1/(2 * (length values)) < level \<and> level \<le> 1 \<longrightarrow>
Percentile.percentile values level =
(linear (1-1/(2* (length values)), values!(length values -1)) (1, extrapolation_1 values)) level"
using assms(1) assms(2) percentile_alt3 by blast
have "2 \<le> length values" using assms(2) by linarith
then have quarter: "1/(2*(length values)) \<le> 1/4"
using inverse_of_nat_le by fastforce
then have "3/4 \<le> 1 - 1/(2*(length values))"
using inverse_of_nat_le by fastforce
then have "1/(2 * (length values)) < 1 - 1/(2 * (length values))" by linarith
then have "1 - 1/(2 * (length values)) < level \<and> level \<le> 1 \<longrightarrow> \<not> ( level \<le> 1/(2 * (length values)))"
by linarith
then have "1 - 1/(2 * (length values)) < level \<and> level \<le> 1 \<longrightarrow>
percentile_impl values level =
(linear (1-1/(2* (length values)), values!(length values -1)) (1, extrapolation_1 values)) level"
using percentile_impl_def
by (smt assms(1) sorted_sort_id)
then have up: "1 - 1/(2* (length values)) < level \<and> level \<le> 1 \<longrightarrow> ?thesis"
using l3 by linarith
have border_left: "1/(2* (length values)) = level \<longrightarrow> ?thesis"
using assms(1) assms(2) percentile_java_equiv_left by blast
then show ?thesis using low mid up assms by linarith
qed
export_code percentile_impl in Scala
end
|
# this rule fails because it overwrites default fields
myRule {
*key_values = list("URL2", "dont_do_that", "IRODS/WEBDAV_URL", "custom_value2");
# or *key_values = ""
msiPidCreate(*path,
*key_values,
*handle);
writeLine("stdout", "*handle");
}
INPUT *path="/tempZone/home/rods/example2.txt"
OUTPUT ruleExecOut
|
Formal statement is: lemma Dynkin_system_trivial: shows "Dynkin_system A (Pow A)" Informal statement is: The power set of a set $A$ is a Dynkin system. |
function call(::Types.Help, args::Vector, storage, conn::IO)
write(conn, Types.help_msg)
end
|
\chapter{Yaschas Massif 01XAF}
Force an encounter near the rock where you farmed the Gahongas. Reveal and grab the Mysterious Artefact on the top of the stairs. Take the 600 Gil if you accidentally reveal it. Use the Chocobo, \pickup{Unicorn Horn}{up the stone ledge before the wide area} Get the 960 Gil chest if you haven't already while heading to the gate.
\newline
|
%We then discuss design goals and introduce proposals for their
% implementation.
%Details of the proposals are discussed in individual sections.
%In this chapter we discuss the challenge of building a software package to
% maintain primary and derivative data of images and annotations.
% CHALLENGES:
%(\eg{} image URIs, GPS data, annotation bounding boxes, \ldots),
%(\eg{} SIFT descriptors, annotation matches, detection models, \ldots),
% Abstracted away caching w/ cache invalidation.
% Ease of experimentation and comparision between algorithms
% Hyperparamter optimization
%
% are examples of primary data and
% are examples of derived data
% This is the problem we intend to address in this chapter --- we want to
% develop a framework to abstract algorithm inputs and dependencies away
% from the developer and allows for the developer to interactively write
% algorithms to extract features, train models, and perform comparisons
% between objects while also testing different hyperparamter settings.
\newcommand{\DependencyCache}{Dependency Cache}
\chapter{System architecture}\label{chap:system}
In this chapter we describe a system architecture designed to aid in the
development and deployment of the computer vision algorithms used by
IBEIS{}.
It is common to use directed acyclic graphs implement pipelines.
Other related work is GNU Make, Luigi, Oozie, Azkaban, Airflow.
Ours differs because instead of specifying general task
dependencies we are specifying object dependencies.
The design of our dependency cache is to efficiently compute
multiple levels of hierarchical derivative information from a
single root object.
This is well suited for computer vision applications because often
there are many choices of algorithms and features that are
repeatably applied to many instances of the same base object
(\eg{} an image).
In addition to computing dependencies of a single object, multiple
objects can be specified as input to a function.
In this way a function can train a model (\eg{} an SVM, Neighbor
Indexer, DCNN, \ldots).
This multi-input model can then be referenced either by the input
that created it, or it can be detached from it and referenced by a
unique UUID{}.
This allows for efficient and organized training, testing, and
distribution of learned models.
The provenance information of how this model was created is always
maintained even if the original inputs cease to exist.
Furthermore, algorithms that make comparisons, classifications,
and or just output results in general can also be implemented
here.
These algorithms are testable and comparable through the test
harness which is available in an IPython notebook interface.
The main differences between us and Luigi are:
* we have less boilerplate code because we implement a less
general design.
* we support a more functional design.
Functions can be executed and tested completely outside the scope
of the depcache.
* We are focused on quickly changing parameters settings and
searching for good values for parameter settings.
Therefore configuration objects are central to our design.
* The test harness is a good example of this.
What we do not do:
Hadoop integration, everything currently runs locally.
However, Luigi could be used to implement the back end of our data
registration interface.
The main novelty of this interface is not to be yet another DAG
workflow manager.
We believe the main contribution of this interface is a low
barrier to entry model of implementing and testing computer vision
algorithms.
TODO:{} abstract away row-id inputs.
Row-id input is nice because of its efficiency.
Every object is represented by an integer akin to a C++ pointer.
However, this is less friendly to a new user.
There should be an alternative mode to have inputs to registered
functions be native types of the variables that are needed.
The depcache should do any loading that is needed behind the
scenes.
% https://github.com/spotify/luigi
% https://media.readthedocs.org/pdf/luigi/latest/luigi.pdf
Not only must the image analysis system Between the raw images and
all of the derived information, there is a large amount of data
that needs to be maintained by the IBEIS image analysis system.
In order to
* developing algorithms
* testing and comparing multiple configurations on different
datasets
* maintaining large amounts of datasets
* Information is derived under multiple configurations
* Models are trained on multiple pieces of information
We maintain a common structure that handles
* Precomputed Features
* Models (nn indexer)
* Algorithms (nn indexer)
* User interactions?
the system architecture of the IBEIS image
analysis module, which allows for the development, testing, and
maintenance of computer vision algorithms.
The image analysis component of IBEIS fundamentally keeps track of
two primary objects:
images and annotations.
However, between all of the computer vision algorithms and their
different settings the system can end up generating a lot of
derived data.
This introduces a problem that is often dealt with using
memoization or caching, however when the bounding box of an
annotation is changed many of these derived properties become
invalid.
To handle these problems we defined the
\glossterm{\DependencyCache{}} class.
This is a directed acyclic multi-graph that is able to store the
results of feature extraction algorithms, and set-to-set
comparison results.
This cache is primarily built for handling data that can be
deterministically derived given its input and configuration
parameters.
This cache is extensible and allows for new algorithms to be
incorporated into Image Analysis as plugins.
The user simply writes the algorithm as a function which accepts
input annotations and a configuration.
If any features not provided by the system are required those are
written as standalone functions which again just take in a parent
object (like an annotation) and return a result.
These functions or classes are registered as plugins using Python
decorators.
Optionally, a configuration object can be specified.
The system can use these configurations to grid search for an
optimal set of parameters.
\section{Dependency cache}\label{sec:depc}
\subsection{Root nodes}
This are the non-recomputable root of the graph.
This is a first class object like an annotation or an
image.
It is possible for there to be more than one root node.
For instance image and annotation could be in the same
graph, with annotation being an ancestor of image.
However, because an annotation is not automatically
recomputable, there must be is a user interaction that
separates any two root nodes in the graph.
Any non-recomputable node in the system can be viewed as
the root of its own \DependencyCache{}.
\subsection{Derived single-input nodes}
For a configuration and a single set of parents (at most
one parent from each ancestor node), a single-input
function computes a Dependant property and returns the
result.
\subsection{Derived multi-input nodes}
An algorithm might also take in multiple sets of parents
from of the same type.
For instance an identification algorithm might take in a
set of query annotations and a set of database
annotations, or a neighbor index might just take in a
single set of annotations.
There is a case when the two inputs are from the same
table.
This is a Cartesian-product-input node.
\subsection{Non-derived nodes}
The system also allows for non-derived nodes.
These nodes store the result of some user interaction, and
as such, are not deterministic.
If a parent of a non-derived node is altered, by default
the non-derived node must be deleted.
However, if the manual interaction is a segmentation mask,
and the bounding box of the parent annotation was simply
translated by a few pixels, it would be best if the system
was able to modify the original input.
Thus the user can specify a modification function for a
node that can alter a user input given a change to a
parent.
\subsection{Implicit Edges}
The computation of a node is allowed to use another node
in its computation function.
This implicitly adds an edge between these two nodes that
is not expressed in the DAG visualization.
It is ok to do this if the configuration for the accessed
node is specified in the configuration to the first node.
It is even ok to access node in a cyclic fashion as long
as there are no cycles in configuration space.
(\ie{} a chip with config1 can ask for the keypoints
computed on a chip with config2)
\subsection{Configuration}
Configurations are combined over paths in the DAG{}.
\subsection{External Storage}
Data in the cache can either be stored internally or
externally
\subsection{Getters}
A getter in the dependency cache is asked to return the properties
of a table at rows that correspond to a root under a
configuration.
If the row does not exist there are three options:
return None, recompute it, or get the input from an external
source (such as Wildbook).
In the case of a manual interaction, recomputation is
marked as requested, and execution is blocked until the
interaction is complete or an error is thrown.
\subsection{Setters}
Setters are used to either modify a manual node or set
information from an external source.
\subsection{Test Harness}\label{sec:testharn}
The test harness makes use of the configurations.
An algorithm is simply a node in the DAG and a test
harness iterates over different configuration settings.
\subsection{Graph modification}\label{sec:modification}
Any modification made to the headers appropriately
modifies the structure and steps are taken to rectify the
database.
Recomputation occurs as necessary.
Algorithm modifications can be made by adding a config
param and preserving old behavior or bumping an algorithm
version flag which indicates that all previous results
must be invalidated.
%\section{Testing}\label{sec:testing}
%utool doctests
\section{IBEIS-IA definition}\label{sec:ibeisdepc}
Enumerates the exact way the dependency cache is used to
create the IBEIS image analysis system.
\subsection{IBEIS DAG / DAM}
\begin{comment}
python -m ibeis.control.IBEISControl --test-show_depc_graph --save figures5/digraph.png --dpath ~/latex/crall-candidacy-2015/ --diskshow --clipwhite --reduced --dpi=120
python -m ibeis.control.IBEISControl --test-show_depc_graph --save figures5/digraph.png --dpath ~/latex/crall-candidacy-2015/
\end{comment}
\ImageCommand{figures5/digraph.png}{\textwidth}{
% ---
dependency digraph
% ---
}{digraph}
\digraph{}
\subsection{Using system to handle photobombs}
\keywords{heuristic, turking, segmentation\\}
\relatedto{annotation property}
It is a challenging task to segment two overlapping
animals with similar textures.
At this only provides a minor barrier to identification we
choose to manually segment photobombs when they become a
problem.
This will allow for the system to build up training data
that can eventually be used to learn how to segment out a
foreground animal in an annotation.
To address the issue of photobombing in the \GGR{}, I will
manually paint over the photobombed sections of images
using a matplotlib \ucite{mpl} interaction whenever a
photobomb occurs in matching.
Ideally we would have trained a state of the art segmentation
technique --- like a CNN --- to segment out the primary animal in
each annotation.
However, the implementation, training, testing, and evaluation of
such techniques is outside the scope of this work.
\begin{comment}
./mass_tex_fixes.py --outline --fpaths chapter5-systemchapter.tex --numlines=1
\end{comment}
\section{Dependency Cache Design}\label{sec:depc}
\paragraph{Related Work}
It is common to use directed acyclic graphs implement
pipelines.
Other related work is GNU Make, Luigi, Oozie, Azkaban,
Airflow, and Dryad.
Of these, Luigi --- a python based pipeline manager --- is the
most similar to our system.
Ours differs because instead of specifying general task
dependencies we are specifying object dependencies.
\subsection{Assumptions}
We distinguish ourselves from previous work by targeting a
more niche application:
dependency caches for computer vision algorithm development in
Python.
\begin{itemize}
\item It is assumed that there is one root-object and multiple
instances of these objects will be created.
\end{itemize}
\subsection{Types of derived data}
We identify and distinguish between three types of derived
data:
(1) features,
(2) comparisons, and
(3) models.
%
Features are properties directly derived from an object and
correspond with an object in a one-to-one manner (\eg{} an
annotation and its chip, or an image and a set of raw
detections from a bounding box detector).
%
Comparisons determine a notion of similarity or difference
between a fixed size set of objects.
Typically comparisons are pairwise.
(\eg{} SIFT descriptors between two annotations are compared
to find correspondences).
%
Models are often learned from a set of multiple objects and
are described with a many-to-one relationship (\eg{} a kd-tree
indexer indexes the features of many annotations, and a neural
network may be trained to detect bounding boxes using many
images.).
Models are often used to generate features or make
comparisons.
This introduces a problem that is often dealt with using
memoization or caching.
However, when certain properties of a primary object (such as
a bounding box of an annotation) are changed many of these
derived properties become invalid.
\section{Dependency Cache Details}\label{sec:depcdetails}
For each dependency cache there is a single root object.
Multiple instances of this object can be created.
A table is made for each property in the \depcache{}.
Tables may have multiple properties.
All properties of a table are computed at the same time for some
number of root instances.
Results of a property are either stored internally in an SQL Database
or externally in a file.
Filenames are derived automatically from dependency information.
Multiple roots can be used to specify models.
When a model is a dependency of a computation the model is either
specified in the input using the input to the model, or using the
model's UUID{}.
\subsection{Determining root-most inputs}
Inputs to a table are determined by finding the ``root most'' tables
in an ``expanded input graph''.
An expanded input graph takes the table node and creates an expanded
input graph based on its parents.
\paragraph{Expanded input graph}
An expanded input graph is computed between the root node and the
table node.
First all paths from the root to the table are enumerated as a list of
edges (recall the \depcache{} is a multi-digraph, so an edge is
specified as a 3-tuple $(u, v, k)$).
Each edge is associated with a ``local input-id'' which specifies if
an edge is one-to-one or many-to-one as well as the $k$ edge key.
Different inputs will be distinguished by accumulated local input-ids.
Each path is then traversed from the table to the root.
The local-input ids along the way are accumulated in a list and
appended to the node label at each step (duplicate consecutive
input-ids are removed).
This results in a graph where the table node is the only sink and
there are multiple source nodes which are specify a different set of
root objects.
\paragraph{Root-most tables}
To specify the inputs to a table it is convenient to specify only the
ids of the root objects and a configuration object.
However, when some dependencies have multiple inputs (such as model
classifications) it is more convenient to specify multiple inputs.
A specifiable node is one that is either a source node or a node with
multiple inputs.
The ``root-most'' tables a subset of specifiable inputs such that all
paths from source nodes to the sink node there is exactly one
specifiable node identified as ``root-most''.
(Removing all the child edges of the root-most nodes would cut all
sources from the sink).
These represent the sets of inputs that must be specified by a user.
In the case where all paths are one-to-one properties the user
specifies just a single root object.
In the case where two root objects are compared the list of root pairs
is specified.
If a model is involved the id of the model must be specified as well
(for convenience a default values can be specified in the
configuration).
\paragraph{Computing input order}
Given the set of inputs we must walk down the dependency graph and
lookup or compute intermediate values between the specified nodes and
the target node.
To do this we topologically sort the nodes in the expanded input graph
and compute them in this order.
For each branch in the tree (a set of paths from a source to the sink)
we compute a branch id.
\expandedinput{}
\section{Test Harness}\label{sec:testharn}
We have developed a test harness to explore the configuration space of
our algorithms.
Currently the test harness is only capable of performing grid search
and interactive search.
\paragraph{Major goals}:
\begin{itemize}
\item Reproducibility of experiments.
\item Ease of algorithm comparisons.
\item Reporting of results.
\end{itemize}
There are many related works on hyper-parameter optimization that are
applicable here.
Extensions would be to incorporate random search, A/B testing, and
Bayesian hyper-parameter optimization methods.
Random search has shown to be superior to grid search for hyper parameter
optimization of neural networks~\cite{bergstra_random_2012}.
%pass
\cite{hutter_sequential_2011}
\paragraph{Bulleted lists (for draft document only)}
A summary of the design goals of the images analysis module are:
\begin{itemize}
\item Dependant property storage and retrieval of data with automatic
dependency pipeline execution.
\item Reproducible experiments.
\item Distribution through ``publication'' of trained models.
\item Extensible for new algorithm integration.
\item Automatic hyper parameter optimization.
\item Maintain data provenance / data lineage. (The history of data ownership, where did this data come from?)
\end{itemize}
A summary of \depcache{} features are:
\begin{itemize}
\item New algorithms are integrated into the system by
registering the algorithms, its output types, its
dependencies, and its configurations.
\item Algorithms can be implemented to accept single inputs
for feature extraction, multiple inputs for model training,
and pairwise inputs for primary object comparisions.
\item Results are cached based on a unique hash of their input
and configuration dependencies.
This allows for results to be implicitly invalidated if the
parent object changes.
\item Registered configurations define hyper paraemters of
models.
A result comparison function can be registered in order to
automatically optimize hyper-parameters through grid-search,
random search, or baysian based techniques.
\item Registered configurations also allow for experiments to
be reproduced.
Experiemnts are tagged with a hash and manifest file
indicating how the experiment was run.
\item Trained models that are ``publishable'' are not
invalidated if a source of parent data is removed.
These models can be downloaded to other instances of image
analysis and used without the parent data.
However at least a fingerprint of what the parent data was is
always maintained.
\end{itemize}
These challenges are summarized as:
\begin{itemize}
\item Adding, removing, and modifying primary data.
\item Algorithm configurations.
\item Dependant computations.
\end{itemize}
\paragraph{The system architecture should}
\begin{itemize}
\item Integrate of algorithms from multiple sources across
multiple languages.
\item Correctly compute and cache algorithm results based on
all relevant inputs.
\item Allow trained models to be distributed and used by other
instances of the image analysis software.
\item Invalidate cached results if the source data changes
(note that there is an exception for ``publishable'' results
such as trained models such as quality classifiers)
\item Have the capacity to augment models without completely
rebuilding their structure (\eg{} adding points to a nearest
neighbor kd-tree index).
\item Optimize hyper-parameters of an algorithm given a method
to compare results.
\end{itemize}
\paragraph{Goals}
\begin{itemize}
\item \textbf{Abstract need for caching away from the developer}:
We aim to have all caches created and invalided based on the
algorithm dependency structure and the requested
configurations.
\item \textbf{Lazy and configurable and computation of
heirarchical derivative data}:
Make derived data such as features a top-level attribute
of a root-object (annotation) such that it is evaluated as
needed and stored as specified.
\item \textbf{Efficient integration of new algorithms}:
Functional design with minimal boilerplate.
To integrate a new table into the \depcache{} all that is
needed is a function that computes the requested outputs
given the appropriate inputs.
This function is register with the \depcache{} using a
decorator.
This makes it simple to integrate independently developed
algorithms.
\item \textbf{Train models in a reproducible manner}:
Models can be simple such as a kd-tree indexer or complex
such as a neural network classifier.
A model should contain at least a fingerprint of the data
and configuration that was used to compute it.
Models should also be distributable so they can be used in
systems they were not necessarily trained on.
\item \textbf{Modular testing}:
Functions registered with the \depcache{} should be able
to be tested without heavy reliance on the \depcache{}
itself.
However, the \depcache{} should make testing easier by
having the ability to quickly supply test input data.
Any property of the \depcache{} should be recomputable
on-the-fly without effecting the state of the cache for
both testing and timing purposes.
The \depcache{} should be able to automatically test and
time each table.
\end{itemize}
\paragraph{Image Analysis Modules Design}
\begin{itemize}
\item We designed the module to have a low barrier to
entry.
We aim to clearly point out entry points into program
execution.
We have aim to have a small startup time with both low
import module overhead and low open database overhead.
\item Doc-strings are used as documentation, examples, and
unit tests.
Most functions show an example that loads the necessary
data to step through an understand / debug / enhance or
develop a function.
\item \Depcache{} marshals data around with getters (lazy
computation) and setters.
\item Module functionality split between different
standalone packages.
Helpers and general utilities are in \utool{}.
Computer vision algorithms are in \vtool{}.
Plotting functions are in \plottool{}, GUI functions are
in \guitool{}.
\end{itemize}
\paragraph{Features}
\begin{itemize}
\item One-to-one properties that belong to each
root-object.
\item One-vs-one comparisons between objects.
\item One-vs-many comparisons between an object and a set of
objects.
\item Training or building of many-to-one models.
\item Properties and models computed by the \depcache{} are
highly configuration.
\end{itemize}
% Sources to cite:
% http://www.mitre.org/sites/default/files/publications/pr-15-1254-architectural-model-mitre-research-blueridge.pdf
% http://www.computer.org/csdl/proceedings/ssdbm/2004/2146/00/21460423.pdf
% http://www.alexanderpokluda.ca/coursework/cs848/CS848%20Paper%20Presentation%20-%20Alexander%20Pokluda.pdf
% http://uazone.org/demch/papers/bddac2013-bigdata-infrastructure-v06.pdf
% http://www.rosebt.com/uploads/8/1/8/1/8181762/big_data_the_management_revolution.pdf
% http://www.sciencedirect.com/science/article/pii/S0167739X14002015 - Pegasus, has transformation from abstract to executable workflow
%We propose extensions to this architecture to support both result caching
% and hyperparameter optimization as well as reproducible model training
% and distribution.
\item \textbf{Maintain data provenance}:
\item \textbf{Interactity}
Development should be an interactive experience.
Computer algorithms tend have more empirically than
theoretical justification.
This process of trail and error should be reflected in the
algorithm development process.
\begin{itemize}
\item \textbf{Data and algorithm interaction}:
The developer should have the ability to explore
the data interactively and manually specify tags or
properties (such as causes of failure cases) that
may be relevant to a specific task.
The developer should be able to browse root
objects, inspect dependant properties, and run
algorithms from an interactive interface.
Algorithms should have an intuitive ``entry point''
which demonstrates how to acquire the necessary
data to start stepping through algorithm logic.
\item \textbf{Discoverablity}:
Ideally the learning curve should be low by making
the system have a high level of discoverability ---
that is a new developer should be able to sit down
at the system and be able to intuitively ``play
with'' and manipulate objects to see an immediate % tangible
results.
We envision that this design goal will be met using
IPython and autocompletion.
It is then our challenge to develop a discoverable
API{}.
\end{itemize}
Of these goals, interactivity is the least important for addressing
the challenges.
Maintaining data providence is essential.
%There are several factors that cause the design of such an
% organization scheme to be challenging.
%Developers must be able to run feasibility studies to test if the system
%is able to identify a new species of animal. The system is demoed on a
%regular basis and is regularly updated for live use in the field. New
%algorithms are integrated. Existing algorithms are updated and modified.
%Algorithms are often run with different configurations.
%We envision a framework which addresses these challenges by
% satisfying several design goals.
|
Formal statement is: lemma Re_i_times [simp]: "Re (\<i> * z) = - Im z" Informal statement is: The real part of $\i z$ is $-\text{Im}(z)$. |
import librosa
import numpy as np
import glob
import matplotlib.pyplot as plt
data, sampling_rate = librosa.load("./bin/audio.mp3")
|
State Before: R : Type u
S : Type v
σ : Type u_1
τ : Type ?u.474475
r : R
e : ℕ
n✝ m : σ
s : σ →₀ ℕ
inst✝¹ : CommSemiring R
p q : MvPolynomial σ R
inst✝ : Fintype σ
f : MvPolynomial σ R
n : ℕ
h : totalDegree f < n * Fintype.card σ
d : σ →₀ ℕ
hd : d ∈ support f
⊢ ∃ i, ↑d i < n State After: R : Type u
S : Type v
σ : Type u_1
τ : Type ?u.474475
r : R
e : ℕ
n✝ m : σ
s : σ →₀ ℕ
inst✝¹ : CommSemiring R
p q : MvPolynomial σ R
inst✝ : Fintype σ
f : MvPolynomial σ R
n : ℕ
d : σ →₀ ℕ
hd : d ∈ support f
h : ∀ (i : σ), n ≤ ↑d i
⊢ n * Fintype.card σ ≤ totalDegree f Tactic: contrapose! h State Before: R : Type u
S : Type v
σ : Type u_1
τ : Type ?u.474475
r : R
e : ℕ
n✝ m : σ
s : σ →₀ ℕ
inst✝¹ : CommSemiring R
p q : MvPolynomial σ R
inst✝ : Fintype σ
f : MvPolynomial σ R
n : ℕ
d : σ →₀ ℕ
hd : d ∈ support f
h : ∀ (i : σ), n ≤ ↑d i
⊢ n * Fintype.card σ ≤ totalDegree f State After: no goals Tactic: calc
n * Fintype.card σ = ∑ _s : σ, n := by
rw [Finset.sum_const, Nat.nsmul_eq_mul, mul_comm, Finset.card_univ]
_ ≤ ∑ s, d s := (Finset.sum_le_sum fun s _ => h s)
_ ≤ d.sum fun _ e => e := by
rw [Finsupp.sum_fintype]
intros
rfl
_ ≤ f.totalDegree := le_totalDegree hd State Before: R : Type u
S : Type v
σ : Type u_1
τ : Type ?u.474475
r : R
e : ℕ
n✝ m : σ
s : σ →₀ ℕ
inst✝¹ : CommSemiring R
p q : MvPolynomial σ R
inst✝ : Fintype σ
f : MvPolynomial σ R
n : ℕ
d : σ →₀ ℕ
hd : d ∈ support f
h : ∀ (i : σ), n ≤ ↑d i
⊢ n * Fintype.card σ = ∑ _s : σ, n State After: no goals Tactic: rw [Finset.sum_const, Nat.nsmul_eq_mul, mul_comm, Finset.card_univ] State Before: R : Type u
S : Type v
σ : Type u_1
τ : Type ?u.474475
r : R
e : ℕ
n✝ m : σ
s : σ →₀ ℕ
inst✝¹ : CommSemiring R
p q : MvPolynomial σ R
inst✝ : Fintype σ
f : MvPolynomial σ R
n : ℕ
d : σ →₀ ℕ
hd : d ∈ support f
h : ∀ (i : σ), n ≤ ↑d i
⊢ ∑ s : σ, ↑d s ≤ sum d fun x e => e State After: case h
R : Type u
S : Type v
σ : Type u_1
τ : Type ?u.474475
r : R
e : ℕ
n✝ m : σ
s : σ →₀ ℕ
inst✝¹ : CommSemiring R
p q : MvPolynomial σ R
inst✝ : Fintype σ
f : MvPolynomial σ R
n : ℕ
d : σ →₀ ℕ
hd : d ∈ support f
h : ∀ (i : σ), n ≤ ↑d i
⊢ σ → 0 = 0 Tactic: rw [Finsupp.sum_fintype] State Before: case h
R : Type u
S : Type v
σ : Type u_1
τ : Type ?u.474475
r : R
e : ℕ
n✝ m : σ
s : σ →₀ ℕ
inst✝¹ : CommSemiring R
p q : MvPolynomial σ R
inst✝ : Fintype σ
f : MvPolynomial σ R
n : ℕ
d : σ →₀ ℕ
hd : d ∈ support f
h : ∀ (i : σ), n ≤ ↑d i
⊢ σ → 0 = 0 State After: case h
R : Type u
S : Type v
σ : Type u_1
τ : Type ?u.474475
r : R
e : ℕ
n✝ m : σ
s : σ →₀ ℕ
inst✝¹ : CommSemiring R
p q : MvPolynomial σ R
inst✝ : Fintype σ
f : MvPolynomial σ R
n : ℕ
d : σ →₀ ℕ
hd : d ∈ support f
h : ∀ (i : σ), n ≤ ↑d i
i✝ : σ
⊢ 0 = 0 Tactic: intros State Before: case h
R : Type u
S : Type v
σ : Type u_1
τ : Type ?u.474475
r : R
e : ℕ
n✝ m : σ
s : σ →₀ ℕ
inst✝¹ : CommSemiring R
p q : MvPolynomial σ R
inst✝ : Fintype σ
f : MvPolynomial σ R
n : ℕ
d : σ →₀ ℕ
hd : d ∈ support f
h : ∀ (i : σ), n ≤ ↑d i
i✝ : σ
⊢ 0 = 0 State After: no goals Tactic: rfl |
Location privacy took a hit in California yesterday when Governor Jerry Brown vetoed SB 1434, an EFF- and ACLU-sponsored bill that would have required law enforcement to apply for a search warrant in order to obtain location tracking information. Despite the bill's passing through the state legislature with overwhelming bipartisan support, despite local newspaper editorials in favor of the bill, and despite more than 1,300 concerned Californians using our action center to urge him to sign the bill into law, Governor Brown instead decided to sell out privacy rights to law enforcement.
It's not the first time, either. Last year, he did the same thing with SB 914, a bill that would have required police to obtain a search warrant before searching an arrested individual’s cell phone incident to arrest.
It may be that legislative action is needed to keep the law current in our rapidly evolving electronic age. But I am not convinced that this bill strikes the right balance between the operational needs of law enforcement and individual expectations of privacy.
Skeptical about a law enforcement sponsored bill claiming to protect privacy? You should be. As we explained to Governor Brown, AB 2055 doesn’t do anything at all.
AB 2055 is a narrow response to the U.S. Supreme Court’s decision in United States v. Jones, which held the Fourth Amendment required law enforcement to obtain a search warrant before installing a GPS device on a car. In theory, AB 2055 changes California law to explicitly permit law enforcement to apply to a judge for a search warrant to install a GPS device. But in fact, it does not require police to obtain a search warrant. It just says they can apply for one. So to the extent it attempts to codify Jones, it fails. And, more basically, there’s no need to codify Jones: the Supreme Court’s decision is the law and California law enforcement officials have to follow it, regardless of what state law says.
That’s not the only problem with AB 2055. That law only applies to GPS devices, and not the other myriad ways law enforcement can obtain location information without installing a GPS device. With increasing concern about law enforcement’s growing addiction to warrantless cell phone tracking — which a federal appeals court in New Orleans will be hearing argument about tomorrow — any legislative action needs to be forward-looking and future-proof. And while we might expect a state that boasts the world's biggest technology companies and just legalized self-driving cars to move the law forward, Governor Brown has instead decided to maintain the status quo.
Ultimately law enforcement got exactly what it wanted with AB 2055, which is nothing at all. And while Governor Brown joins the chorus — which included Justice Alito in his concurring opinion in Jones — that solemnly speaks of the need to update our electronic privacy laws to reflect the changing technological landscape, his words ring hollow when he vetoes a bill that had bipartisan legislative support. Because in the end, all that's been done since the first federal electronic privacy bill was passed in 1986 has been a steady diet of allowing law enforcement to gorge itself on as much data and information they can eat without a warrant. It's no surprise that now they're hooked, they'll do whatever it takes to keep the information faucet on. Governor Brown's veto of SB 1434 only continues this dangerous trend. |
Formal statement is: lemma nonneg_bounded: "\<exists>K\<ge>0. \<forall>a b. norm (a ** b) \<le> norm a * norm b * K" Informal statement is: There exists a constant $K \geq 0$ such that for all matrices $a$ and $b$, we have $\|ab\| \leq \|a\| \|b\| K$. |
!-------------------------------------------------------------------------------
! Copyright (c) 2019 FrontISTR Commons
! This software is released under the MIT License, see LICENSE.txt
!-------------------------------------------------------------------------------
!> \brief Adaptive Mesh Refinement
module hecmw_adapt_INT_SR
contains
!C
!C***
!C*** hecmw_adapt_INT_SEND_RECV
!C***
!C
subroutine hecmw_adapt_INT_SEND_RECV &
& ( N, NEIBPETOT,NEIBPE,STACK_IMPORT, NOD_IMPORT, &
& STACK_EXPORT, NOD_EXPORT, &
& WS, WR, X, SOLVER_COMM,my_rank, NB, m)
use hecmw_util
implicit real*8 (A-H,O-Z)
integer(kind=kint) , intent(in) :: N, m
integer(kind=kint) , intent(in) :: NEIBPETOT
integer(kind=kint), pointer :: NEIBPE (:)
integer(kind=kint), pointer :: STACK_IMPORT(:)
integer(kind=kint), pointer :: NOD_IMPORT (:)
integer(kind=kint), pointer :: STACK_EXPORT(:)
integer(kind=kint), pointer :: NOD_EXPORT (:)
integer(kind=kint), dimension(NB*m), intent(inout):: WS
integer(kind=kint), dimension(NB*m), intent(inout):: WR
integer(kind=kint), dimension(NB*N), intent(inout):: X
integer(kind=kint) , intent(in) ::SOLVER_COMM
integer(kind=kint) , intent(in) :: my_rank
integer(kind=kint ), dimension(:,:), save, allocatable :: sta1
integer(kind=kint ), dimension(:,:), save, allocatable :: sta2
integer(kind=kint ), dimension(: ), save, allocatable :: req1
integer(kind=kint ), dimension(: ), save, allocatable :: req2
integer(kind=kint ), save :: NFLAG
data NFLAG/0/
!C
!C-- INIT.
if (NFLAG.eq.0) then
allocate (sta1(MPI_STATUS_SIZE,NEIBPETOT))
allocate (sta2(MPI_STATUS_SIZE,NEIBPETOT))
allocate (req1(NEIBPETOT))
allocate (req2(NEIBPETOT))
NFLAG= 1
endif
!C
!C-- SEND
do neib= 1, NEIBPETOT
istart= STACK_EXPORT(neib-1)
inum = STACK_EXPORT(neib ) - istart
do k= istart+1, istart+inum
ii= NB*NOD_EXPORT(k) - NB
ik= NB*k - NB
do j= 1, NB
WS(ik+j)= X(ii+j)
enddo
enddo
call MPI_ISEND (WS(NB*istart+1), NB*inum, MPI_INTEGER, &
& NEIBPE(neib), 0, SOLVER_COMM, req1(neib), ierr)
enddo
!C
!C-- RECEIVE
do neib= 1, NEIBPETOT
istart= STACK_IMPORT(neib-1)
inum = STACK_IMPORT(neib ) - istart
call MPI_IRECV (WR(NB*istart+1), NB*inum, MPI_INTEGER, &
& NEIBPE(neib), 0, SOLVER_COMM, req2(neib), ierr)
enddo
call MPI_WAITALL (NEIBPETOT, req2, sta2, ierr)
do neib= 1, NEIBPETOT
istart= STACK_IMPORT(neib-1)
inum = STACK_IMPORT(neib ) - istart
do k= istart+1, istart+inum
ii= NB*NOD_IMPORT(k) - NB
ik= NB*k - NB
do j= 1, NB
X(ii+j)= WR(ik+j)
enddo
enddo
enddo
call MPI_WAITALL (NEIBPETOT, req1, sta1, ierr)
end subroutine hecmw_adapt_INT_SEND_RECV
end module hecmw_adapt_INT_SR
|
{- Byzantine Fault Tolerant Consensus Verification in Agda, version 0.9.
Copyright (c) 2020, 2021, Oracle and/or its affiliates.
Licensed under the Universal Permissive License v 1.0 as shown at https://opensource.oracle.com/licenses/upl
-}
open import LibraBFT.Prelude
open import LibraBFT.Lemmas
open import LibraBFT.Base.ByteString
open import LibraBFT.Base.Encode
open import LibraBFT.Base.KVMap
open import LibraBFT.Base.PKCS
open import LibraBFT.Hash
open import LibraBFT.Impl.Base.Types
open import LibraBFT.Impl.Consensus.Types
open import LibraBFT.Impl.Util.Util
-- This module provides some scaffolding to define the handlers for our fake/simple
-- "implementation" and connect them to the interface of the SystemModel.
module LibraBFT.Impl.Handle
(hash : BitString → Hash)
(hash-cr : ∀{x y} → hash x ≡ hash y → Collision hash x y ⊎ x ≡ y)
where
open import LibraBFT.Impl.Consensus.ChainedBFT.EventProcessor hash hash-cr
open RWST-do
-- This represents an uninitialised EventProcessor, about which we know nothing, which we use as
-- the initial EventProcessor for every peer until it is initialised.
postulate
fakeEP : EventProcessor
-- Eventually, the initialization should establish some properties we care about, but for now we
-- just initialise again to fakeEP, which means we cannot prove the base case for various
-- properties, e.g., in Impl.Properties.VotesOnce
initialEventProcessorAndMessages
: (a : Author) → EpochConfig → EventProcessor
→ EventProcessor × List NetworkMsg
initialEventProcessorAndMessages a _ _ = fakeEP , []
handle : NodeId → NetworkMsg → Instant → LBFT Unit
handle _self msg now
with msg
...| P p = processProposalMsg now p
...| V v = processVote now v
...| C c = return unit -- We don't do anything with commit messages, they are just for defining Correctness.
-- For now, the SystemModel supports only one kind of action: to send a Message. Later it might
-- include things like logging, crashes, assertion failures, etc. At that point, definitions like
-- the following might become part of the SystemModel, but they are included here to enable the
-- temporary scaffolding below.
data Action (Msg : Set) : Set where
send : Msg → Action Msg
action-send-injective : ∀ {Msg}{m m' : Msg} → send m ≡ send m' → m ≡ m'
action-send-injective refl = refl
msgToSend : {Msg : Set} → Action Msg → Msg
msgToSend (send m) = m
msgToSend≡ : ∀ {Msg x}{m : Msg} → m ≡ msgToSend x → send m ≡ x
msgToSend≡ {_} {send m} {m} refl = refl
-- Note: the SystemModel allows anyone to receive any message sent, so intended recipient is ignored;
-- it is included in the model only to facilitate future work on liveness properties, when we will need
-- assumptions about message delivery between honest peers.
outputToActions : EventProcessor → Output → List (Action NetworkMsg)
outputToActions ep (BroadcastProposal p) = List-map (const (Action.send (P p)))
(List-map proj₁
(kvm-toList (:vvAddressToValidatorInfo (₋epValidators (₋epEC ep)))))
outputToActions _ (LogErr x) = []
outputToActions _ (SendVote v toList) = List-map (const (Action.send (V v))) toList
outputsToActions : ∀ {State} → List Output → List (Action NetworkMsg)
outputsToActions {st} = concat ∘ List-map (outputToActions st)
runHandler : EventProcessor → LBFT Unit → EventProcessor × List (Action NetworkMsg)
runHandler st handler = ×-map₂ (outputsToActions {st}) (proj₂ (LBFT-run handler st))
-- And ultimately, the all-knowing system layer only cares about the
-- step function.
peerStep : NodeId → NetworkMsg → Instant → EventProcessor → EventProcessor × List (Action NetworkMsg)
peerStep nid msg ts st = runHandler st (handle nid msg ts)
-- This (temporary) wrapper bridges the gap between our (draft) concrete handler and
-- the form required by the new system model, which does not (yet) support actions other
-- than send.
peerStepWrapper : NodeId → NetworkMsg → EventProcessor → EventProcessor × List NetworkMsg
peerStepWrapper nid msg st = ×-map₂ (List-map msgToSend) (peerStep nid msg 0 st)
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
-- | Module containing 'Homoiconic' and 'FromCode' type classes and its instance
-- declarations.
module Language.Finkel.Homoiconic
( -- * Homoiconic class
Homoiconic(..)
, fromCode
, Result(..)
-- * Generic functions
, genericToCode
, genericFromCode
, genericParseCode
-- * Generic classes
, GToCode(..)
, GParseCode(..)
-- * Data.Data function
, dataToCode
) where
#include "ghc_modules.h"
-- base
import Control.Applicative (Alternative (..))
import Data.Complex (Complex (..))
import Data.Data
import Data.Fixed (Fixed (..))
import Data.Functor.Compose (Compose (..))
import Data.Functor.Const (Const (..))
import Data.Functor.Identity (Identity (..))
import Data.Int (Int16, Int32, Int64, Int8)
import Data.List.NonEmpty (NonEmpty (..))
import Data.Monoid (All (..), Alt (..), Any (..),
Dual (..), First (..),
Last (..), Product (..),
Sum (..))
import Data.Ratio (Ratio, denominator, numerator,
(%))
import Data.Version (Version (..))
import Data.Word (Word16, Word32, Word64, Word8)
import GHC.Generics (C, Constructor (..), D,
Generic (..), K1 (..),
M1 (..), S, U1 (..), V1,
(:*:) (..), (:+:) (..))
import Numeric.Natural (Natural)
import qualified Data.Functor.Product as Product
import qualified Data.Functor.Sum as Sum
import qualified Data.Semigroup as Semigroup
#if !MIN_VERSION_ghc(8,8,0)
import Control.Monad.Fail (MonadFail (..))
import Prelude hiding (fail)
#endif
-- ghc
import GHC_Data_FastString (FastString, unpackFS)
import GHC_Types_SrcLoc (GenLocated (..), SrcSpan,
getLoc)
-- Internal
import Language.Finkel.Form
-- -------------------------------------------------------------------
--
-- Homoiconic type class
--
-- -------------------------------------------------------------------
-- | Class for handling Haskell value as 'Code'.
--
-- Instance of 'Homoiconic' should satisfy the law:
--
-- @
-- 'parseCode' ('toCode' x) ≡ 'Success' x
-- @
--
-- The function 'listToCode' and 'parseHsListCode' are used when handling
-- Haskell list values specially (e.g., 'Char'). These functions have default
-- implementations, which simply applies 'toCode' to elements of the argument
-- list, and which parses elements of 'HsList', respectively.
--
-- One can implement 'Homoiconic' instance with 'GHC.Generics.Generic', e.g.:
--
-- @
-- {-# LANGUAGE DeriveGeneric #-}
--
-- data MyData
-- = MyInt Int
-- | MyChar Char
-- deriving (Generic)
--
-- instance Homoiconic MyData
-- @
--
-- Sample snippet using above @MyData@:
--
-- >>> toCode (MyInt 42)
-- (MyInt 42)
-- >>> fromCode (toCode (MyChar 'a')) :: Maybe MyData
-- Just (MyChar 'a')
---
class Homoiconic a where
-- | Convert Haskell value to 'Code'.
toCode :: a -> Code
{-# INLINE toCode #-}
default toCode :: (Generic a, GToCode (Rep a)) => a -> Code
toCode = genericToCode
-- | Convert list of Haskell values to 'Code'.
listToCode :: [a] -> Code
listToCode xs =
let xs' = map toCode xs
l = getLoc (mkLocatedForm xs')
in LForm (L l (HsList xs'))
{-# INLINE listToCode #-}
-- | Convert 'Code' to Haskell value, or 'Failure' if the code could
-- not be converted.
parseCode :: Code -> Result a
{-# INLINE parseCode #-}
default parseCode :: (Generic a, GParseCode (Rep a)) => Code -> Result a
parseCode = genericParseCode
-- | Convert 'Code' to list of Haskell values, or 'Failure' if the code
-- could not be converted.
parseHsListCode :: Code -> Result [a]
parseHsListCode xs =
case unCode xs of
HsList as -> mapM parseCode as
_ -> fail "got non HsList value"
{-# INLINE parseHsListCode #-}
-- | Like 'parseCode', but the result wrapped with 'Maybe' instead of 'Result'.
fromCode :: Homoiconic a => Code -> Maybe a
fromCode code = case parseCode code of
Success a -> Just a
_ -> Nothing
-- -------------------------------------------------------------------
--
-- Instances of Homoiconic
--
-- -------------------------------------------------------------------
--
-- Prelude
--
instance Homoiconic () where
toCode _ = LForm (genSrc (Atom AUnit))
parseCode a =
case unCode a of
Atom AUnit -> pure ()
_ -> failedToParse "()"
instance Homoiconic Char where
toCode = LForm . genSrc . Atom . AChar NoSourceText
listToCode = LForm . genSrc . Atom . aString NoSourceText
parseCode a =
case unCode a of
Atom (AChar _ x) -> pure x
_ -> failedToParse "Char"
parseHsListCode a = case unCode a of
Atom (AString _ s) -> pure (unpackFS s)
_ -> failedToParse "String"
instance Homoiconic Int where
toCode = integralToCode
parseCode = integralFromCode
instance Homoiconic Word where
toCode = integralToCode
parseCode = integralFromCode
instance Homoiconic Integer where
toCode = integralToCode
parseCode = integralFromCode
instance Homoiconic Float where
toCode = realFracToCode
parseCode = fractionalFromCode
instance Homoiconic Double where
toCode = realFracToCode
parseCode = fractionalFromCode
instance Homoiconic a => Homoiconic [a] where
toCode = listToCode
parseCode = parseHsListCode
instance Homoiconic Bool where
toCode = showAsSymbolCode
parseCode a =
case unCode a of
Atom (ASymbol sym) | sym == "True" -> pure True
| sym == "False" -> pure False
_ -> failedToParse "Bool"
instance Homoiconic Ordering where
toCode = showAsSymbolCode
parseCode a =
case unCode a of
Atom (ASymbol sym) | sym == "EQ" -> pure EQ
| sym == "LT" -> pure LT
| sym == "GT" -> pure GT
_ -> failedToParse "Ordering"
instance Homoiconic a => Homoiconic (Maybe a) where
toCode a =
case a of
Nothing -> toCode (aSymbol "Nothing")
Just x -> toCode1 "Just" x
parseCode a =
case unCode a of
Atom (ASymbol "Nothing") -> pure Nothing
List [LForm (L _ (Atom (ASymbol "Just"))), x] -> pure <$> parseCode x
_ -> failedToParse "Maybe"
instance (Homoiconic a, Homoiconic b) => Homoiconic (Either a b) where
toCode a =
case a of
Right x -> toCode1 "Right" x
Left x -> toCode1 "Left" x
parseCode a =
case unCode a of
List [LForm (L _ (Atom (ASymbol x))), y]
| x == "Right" -> fmap Right (parseCode y)
| x == "Left" -> fmap Left (parseCode y)
_ -> failedToParse "Either"
instance (Homoiconic a, Homoiconic b) => Homoiconic (a, b) where
toCode (a1, a2) = toCode2 "," a1 a2
parseCode = parseCode2 "," (,)
instance (Homoiconic a, Homoiconic b, Homoiconic c)
=> Homoiconic (a, b, c) where
toCode (a1, a2, a3) =
toCode (List [symbolCode ",", toCode a1, toCode a2, toCode a3])
parseCode a =
case unCode a of
List [LForm (L _ (Atom (ASymbol ","))), a1, a2, a3]
-> (,,) <$> parseCode a1 <*> parseCode a2 <*> parseCode a3
_ -> failedToParse "(,,)"
instance (Homoiconic a, Homoiconic b, Homoiconic c, Homoiconic d)
=> Homoiconic (a, b, c, d) where
toCode (a1, a2, a3, a4) =
toCode (List [ symbolCode ",", toCode a1, toCode a2, toCode a3
, toCode a4])
parseCode a =
case unCode a of
List [LForm (L _ (Atom (ASymbol ","))), a1, a2, a3, a4]
-> (,,,) <$>
parseCode a1 <*> parseCode a2 <*> parseCode a3 <*> parseCode a4
_ -> failedToParse "(,,,)"
instance (Homoiconic a, Homoiconic b, Homoiconic c, Homoiconic d, Homoiconic e)
=> Homoiconic (a, b, c, d, e) where
toCode (a1, a2, a3, a4, a5) =
toCode (List [ symbolCode ",", toCode a1, toCode a2, toCode a3
, toCode a4, toCode a5])
parseCode a =
case unCode a of
List [LForm (L _ (Atom (ASymbol ","))), a1, a2, a3, a4, a5]
-> (,,,,) <$>
parseCode a1 <*> parseCode a2 <*> parseCode a3 <*>
parseCode a4 <*> parseCode a5
_ -> failedToParse "(,,,,)"
instance (Homoiconic a, Homoiconic b, Homoiconic c, Homoiconic d, Homoiconic e, Homoiconic f)
=> Homoiconic (a, b, c, d, e, f) where
toCode (a1, a2, a3, a4, a5, a6) =
toCode (List [ symbolCode ",", toCode a1, toCode a2, toCode a3
, toCode a4, toCode a5, toCode a6])
parseCode a =
case unCode a of
List [LForm (L _ (Atom (ASymbol ","))), a1, a2, a3, a4, a5, a6]
-> (,,,,,) <$>
parseCode a1 <*> parseCode a2 <*> parseCode a3 <*>
parseCode a4 <*> parseCode a5 <*> parseCode a6
_ -> failedToParse "(,,,,,)"
--
-- Data.Complex
--
instance Homoiconic a => Homoiconic (Complex a) where
toCode (a :+ b) = toCode2 ":+" a b
parseCode = parseCode2 ":+" (:+)
--
-- Data.Fixed
--
instance Homoiconic (Fixed a) where
toCode (MkFixed a) = toCode1 "MkFixed" a
parseCode = parseCode1 "MkFixed" MkFixed
--
-- Data.Functor.Compose
instance Homoiconic (f (g a)) => Homoiconic (Compose f g a) where
toCode (Compose a) = toCode1 "Compose" a
parseCode = parseCode1 "Compose" Compose
--
-- Data.Functor.Const
--
instance Homoiconic a => Homoiconic (Const a b) where
toCode (Const a) = toCode1 "Const" a
parseCode = parseCode1 "Const" Const
--
-- Data.Functor.Identity
--
instance Homoiconic a=> Homoiconic (Identity a) where
toCode (Identity a) = toCode1 "Identity" a
parseCode = parseCode1 "Identity" Identity
--
-- Data.Functor.Product
--
instance (Homoiconic (f a), Homoiconic (g a))
=> Homoiconic (Product.Product f g a) where
toCode (Product.Pair a b) = toCode2 "Pair" a b
parseCode = parseCode2 "Pair" Product.Pair
--
-- Data.Functor.Sum
--
instance (Homoiconic (f a), Homoiconic (g a)) => Homoiconic (Sum.Sum f g a) where
toCode a =
case a of
Sum.InL x -> toCode1 "InL" x
Sum.InR x -> toCode1 "InR" x
parseCode a =
case unCode a of
List [LForm (L _ (Atom (ASymbol tag))), b]
| tag == "InL" -> Sum.InL <$> parseCode b
| tag == "InR" -> Sum.InR <$> parseCode b
_ -> failedToParse "Sum"
--
-- Data.Int
--
instance Homoiconic Int8 where
toCode = integralToCode
parseCode = integralFromCode
instance Homoiconic Int16 where
toCode = integralToCode
parseCode = integralFromCode
instance Homoiconic Int32 where
toCode = integralToCode
parseCode = integralFromCode
instance Homoiconic Int64 where
toCode = integralToCode
parseCode = integralFromCode
--
-- Data.List.NonEmpty
--
instance Homoiconic a => Homoiconic (NonEmpty a) where
toCode (a :| as) = toCode2 ":|" a as
parseCode = parseCode2 ":|" (:|)
--
-- Data.Monoid
--
instance Homoiconic All where
toCode (All a) = toCode1 "All" a
parseCode = parseCode1 "All" All
instance Homoiconic (f a) => Homoiconic (Alt f a) where
toCode (Alt a) = toCode1 "Alt" a
parseCode = parseCode1 "Alt" Alt
instance Homoiconic Any where
toCode (Any a) = toCode1 "Any" a
parseCode = parseCode1 "Any" Any
instance Homoiconic a => Homoiconic (Dual a) where
toCode (Dual a) = toCode1 "Dual" a
parseCode = parseCode1 "Dual" Dual
instance Homoiconic a => Homoiconic (First a) where
toCode (First a) = toCode1 "First" a
parseCode = parseCode1 "First" First
instance Homoiconic a => Homoiconic (Last a) where
toCode (Last a) = toCode1 "Last" a
parseCode = parseCode1 "Last" Last
instance Homoiconic a => Homoiconic (Product a) where
toCode (Product a) = toCode1 "Product" a
parseCode = parseCode1 "Product" Product
instance Homoiconic a => Homoiconic (Sum a) where
toCode (Sum a) = toCode1 "Sum" a
parseCode = parseCode1 "Sum" Sum
--
-- Data.Proxy
--
instance Homoiconic a => Homoiconic (Proxy a) where
toCode _ = symbolCode "Proxy"
parseCode a = case unCode a of
Atom (ASymbol "Proxy") -> pure Proxy
_ -> failedToParse "Proxy"
--
-- Data.Version
--
instance Homoiconic Version where
toCode (Version b t) = toCode2 "Version" b t
parseCode = parseCode2 "Version" Version
--
-- Data.Ratio
--
instance (Integral a, Homoiconic a) => Homoiconic (Ratio a) where
toCode a =
let n = toCode (numerator a)
d = toCode (denominator a)
in toCode (List [symbolCode ":%", n, d])
parseCode = parseCode2 ":%" (%)
--
-- Data.Semigroup
--
instance (Homoiconic a, Homoiconic b) => Homoiconic (Semigroup.Arg a b) where
toCode (Semigroup.Arg a b) = toCode2 "Arg" a b
parseCode = parseCode2 "Arg" Semigroup.Arg
instance Homoiconic a => Homoiconic (Semigroup.First a) where
toCode (Semigroup.First a) = toCode1 "First" a
parseCode = parseCode1 "First" Semigroup.First
instance Homoiconic a => Homoiconic (Semigroup.Last a) where
toCode (Semigroup.Last a) = toCode1 "Last" a
parseCode = parseCode1 "Last" Semigroup.Last
instance Homoiconic a => Homoiconic (Semigroup.Max a) where
toCode (Semigroup.Max a) = toCode1 "Max" a
parseCode = parseCode1 "Max" Semigroup.Max
instance Homoiconic a => Homoiconic (Semigroup.Min a) where
toCode (Semigroup.Min a) = toCode1 "Min" a
parseCode = parseCode1 "Min" Semigroup.Min
#if !MIN_VERSION_ghc(9,0,0)
instance Homoiconic a => Homoiconic (Semigroup.Option a) where
toCode (Semigroup.Option a) = toCode1 "Option" a
parseCode = parseCode1 "Option" Semigroup.Option
#endif
instance Homoiconic a => Homoiconic (Semigroup.WrappedMonoid a) where
toCode (Semigroup.WrapMonoid a) = toCode1 "WrapMonoid" a
parseCode = parseCode1 "WrapMonoid" Semigroup.WrapMonoid
--
-- Data.Word
--
instance Homoiconic Word8 where
toCode = integralToCode
parseCode = integralFromCode
instance Homoiconic Word16 where
toCode = integralToCode
parseCode = integralFromCode
instance Homoiconic Word32 where
toCode = integralToCode
parseCode = integralFromCode
instance Homoiconic Word64 where
toCode = integralToCode
parseCode = integralFromCode
--
-- Numeric.Natural
--
instance Homoiconic Natural where
toCode = integralToCode
parseCode = integralFromCode
--
-- Language.Finkel.Form
--
instance Homoiconic Atom where
toCode = LForm . genSrc . Atom
parseCode a =
case unCode a of
Atom x -> pure x
_ -> failedToParse "Atom"
instance Homoiconic (Form Atom) where
toCode = LForm . genSrc
parseCode = pure . unCode
instance Homoiconic (LForm Atom) where
toCode = id
parseCode = pure
-- -------------------------------------------------------------------
--
-- Generic toCode
--
-- -------------------------------------------------------------------
-- | Generic variant of 'toCode'.
genericToCode :: (Generic a, GToCode (Rep a)) => a -> Code
genericToCode = unCodeArgs . gToCode . from
{-# INLINABLE genericToCode #-}
-- | To distinguish arguments of constructor from non-argument.
data CodeArgs
= NonArg Code
| Args [Code]
unCodeArgs :: CodeArgs -> Code
unCodeArgs ca = case ca of
NonArg c -> c
Args cs -> toCode (List cs)
{-# INLINABLE unCodeArgs #-}
instance Semigroup.Semigroup CodeArgs where
Args xs <> Args ys = Args (xs Semigroup.<> ys)
Args xs <> NonArg y = Args (xs Semigroup.<> [y])
NonArg x <> Args ys = Args (x : ys)
NonArg x <> NonArg y = Args [x, y]
{-# INLINE (<>) #-}
-- | For making 'Code' with 'Generic' instances.
class GToCode f where
gToCode :: f a -> CodeArgs
instance GToCode V1 where
gToCode _ = NonArg undefined
{-# INLINE gToCode #-}
instance GToCode U1 where
gToCode U1 = NonArg nil
{-# INLINE gToCode #-}
instance (GToCode f, GToCode g) => GToCode (f :+: g) where
gToCode lr = case lr of
L1 x -> gToCode x
R1 x -> gToCode x
{-# INLINE gToCode #-}
instance (GToCode f, GToCode g) => GToCode (f :*: g) where
gToCode (f :*: g) = gToCode f Semigroup.<> gToCode g
{-# INLINE gToCode #-}
instance Homoiconic c => GToCode (K1 i c) where
gToCode (K1 x) = NonArg (toCode x)
{-# INLINE gToCode #-}
instance GToCode f => GToCode (M1 D c f) where
gToCode (M1 x) = gToCode x
{-# INLINE gToCode #-}
instance (Constructor c, GToCode f) => GToCode (M1 C c f) where
gToCode m1@(M1 x) =
let constr = toCode (aSymbol (conName m1))
in case gToCode x of
NonArg c -> if null c
then NonArg constr
else NonArg (toCode (List [constr, c]))
Args cs -> NonArg (toCode (List (constr : cs)))
{-# INLINE gToCode #-}
instance GToCode f => GToCode (M1 S c f) where
gToCode (M1 x) = gToCode x
{-# INLINE gToCode #-}
-- -------------------------------------------------------------------
--
-- Generic FromCode
--
-- -------------------------------------------------------------------
-- | Generic variant of 'fromCode'.
genericFromCode :: (Generic a, GParseCode (Rep a)) => Code -> Maybe a
genericFromCode x = case genericParseCode x of
Success a -> Just a
_ -> Nothing
{-# INLINABLE genericFromCode #-}
-- | Generic function to get result value from 'Code'.
genericParseCode :: (Generic a, GParseCode (Rep a)) => Code -> Result a
genericParseCode =
let f a xs = if null xs
then pure (to a)
else fail "Unexpected leftover"
in runCodeP gParseCode fail f
{-# INLINABLE genericParseCode #-}
-- | For getting value from 'Code' with 'Generic' instances.
class GParseCode f where
gParseCode :: CodeP (f a)
instance GParseCode V1 where
gParseCode = pure undefined
{-# INLINE gParseCode #-}
instance GParseCode U1 where
gParseCode = pure U1
{-# INLINE gParseCode #-}
instance (GParseCode f, GParseCode g) => GParseCode (f :+: g) where
gParseCode = fmap L1 gParseCode <|> fmap R1 gParseCode
{-# INLINE gParseCode #-}
instance (GParseCode f, GParseCode g) => GParseCode (f :*: g) where
gParseCode = (:*:) <$> gParseCode <*> gParseCode
{-# INLINE gParseCode #-}
instance Homoiconic c => GParseCode (K1 i c) where
gParseCode =
unconsP (\l c cs ->
case parseCode c of
Success a -> contP (K1 a) (LForm (L l (List cs)))
_ -> failP ("Unexpected: " ++ show c))
{-# INLINE gParseCode #-}
instance GParseCode f => GParseCode (M1 D c f) where
gParseCode = fmap M1 gParseCode
{-# INLINE gParseCode #-}
instance {-# OVERLAPPABLE #-} Constructor c => GParseCode (M1 C c U1) where
gParseCode =
let c1 :: M1 C c U1 a
c1 = undefined
in eqP (toCode (aSymbol (conName c1))) *> fmap M1 gParseCode
{-# INLINE gParseCode #-}
instance {-# OVERLAPPABLE #-} (Constructor c, GParseCode f)
=> GParseCode (M1 C c f) where
gParseCode =
let c1 :: M1 C c f a
c1 = undefined
in eqCarP (toCode (aSymbol (conName c1))) *> fmap M1 gParseCode
{-# INLINE gParseCode #-}
instance GParseCode f => GParseCode (M1 S c f) where
gParseCode = fmap M1 gParseCode
{-# INLINE gParseCode #-}
-- -------------------------------------------------------------------
--
-- Code parser for GParseCode
--
-- -------------------------------------------------------------------
-- | Dedicated data type to hold parsed result of 'Code'.
--
-- Using dedicated data type when parsing 'Code' data type for 'parseCode'. This
-- data type is intentionally not defined as an instance of 'Homoiconic', so
-- that the user defined data types can tell the parse error from explicit
-- failure constructor of the target type, e,g, 'Nothing' for 'Maybe', 'Left'
-- for 'Either', ... etc.
data Result a
= Success a
| Failure String
deriving (Eq, Show)
instance Functor Result where
fmap f r = case r of
Success a -> Success (f a)
Failure e -> Failure e
{-# INLINE fmap #-}
instance Applicative Result where
pure a = Success a
{-# INLINE pure #-}
f <*> m = f >>= flip fmap m
{-# INLINE (<*>) #-}
instance Monad Result where
m >>= k = case m of
Success a -> k a
Failure e -> Failure e
{-# INLINE (>>=) #-}
instance MonadFail Result where
fail = Failure
{-# INLINE fail #-}
failedToParse :: String -> Result a
failedToParse ty = Failure ("Failed to parse " ++ ty)
{-# INLINABLE failedToParse #-}
-- | Simple parser for 'Code'.
newtype CodeP a =
CodeP {runCodeP :: forall r. (String -> r) -- On failure
-> (a -> Code -> r) -- On success
-> Code -- Input
-> r}
instance Functor CodeP where
fmap f p = CodeP (\err go -> runCodeP p err (go . f))
{-# INLINE fmap #-}
instance Applicative CodeP where
pure a = CodeP (\_ go -> go a)
{-# INLINE pure #-}
f <*> p = f >>= flip fmap p
{-# INLINE (<*>) #-}
instance Monad CodeP where
m >>= k = CodeP (\err go -> runCodeP m err (\a -> runCodeP (k a) err go))
{-# INLINE (>>=) #-}
instance Alternative CodeP where
empty = failP "Alternative.empty"
{-# INLINE empty #-}
p1 <|> p2 =
CodeP (\err go cs ->
runCodeP p1 (\_ -> runCodeP p2 err go cs) go cs)
{-# INLINE (<|>) #-}
failP :: String -> CodeP a
failP msg = CodeP (\err _ _ -> err msg)
{-# INLINABLE failP #-}
contP :: a -> Code -> CodeP a
contP a cs = CodeP (\_ go _ -> go a cs)
{-# INLINEABLE contP #-}
unconsP :: (SrcSpan -> Code -> [Code] -> CodeP a) -> CodeP a
unconsP f =
CodeP (\err go cs ->
case cs of
LForm (L l (List (x : xs))) -> runCodeP (f l x xs) err go cs
_ -> err "Not a list")
{-# INLINEABLE unconsP #-}
eqP :: Code -> CodeP ()
eqP x =
CodeP (\err go cs ->
if cs == x
then go () nil
else err ("eqP: unexpected " ++ show cs))
{-# INLINABLE eqP #-}
eqCarP :: Code -> CodeP ()
eqCarP x =
unconsP (\l c cs ->
if x == c
then contP () (LForm (L l (List cs)))
else failP ("eqCarP: unexpected " ++ show c))
{-# INLINABLE eqCarP #-}
-- -------------------------------------------------------------------
--
-- Data to Code
--
-- -------------------------------------------------------------------
dataToCode :: Data d => d -> Code
dataToCode x =
let constr = toConstr x
isTupleStr cs = case cs of
'(':cs1 -> go cs1
_ -> False
where go xs = case xs of
',':xs' -> go xs'
[')'] -> True
_ -> False
cstr = case showConstr constr of
str | isTupleStr str -> ","
| otherwise -> str
hd = toCode (aSymbol cstr)
in case constrRep constr of
IntConstr n -> toCode (aIntegral n)
FloatConstr f -> toCode (aFractional (fromRational f :: Double))
CharConstr c -> toCode c
_ ->
case gmapQ dataToCode x of
[] -> hd
_ -> toCode (List (hd:gmapQ dataToCode x))
-- -------------------------------------------------------------------
--
-- Auxiliary
--
-- -------------------------------------------------------------------
realFracToCode :: (Real a, Show a) => a -> Code
realFracToCode = LForm . genSrc . Atom . aFractional
{-# INLINABLE realFracToCode #-}
fractionalFromCode :: Fractional a => Code -> Result a
fractionalFromCode a =
case unCode a of
Atom (AFractional x) -> pure (fromRational (fl_value x))
_ -> failedToParse "fractional"
{-# INLINABLE fractionalFromCode #-}
symbolCode :: String -> Code
symbolCode = LForm . genSrc . Atom . aSymbol
{-# INLINABLE symbolCode #-}
showAsSymbolCode :: Show a => a -> Code
showAsSymbolCode = symbolCode . show
{-# INLINABLE showAsSymbolCode #-}
integralToCode :: Integral a => a -> Code
integralToCode = LForm . genSrc . Atom . aIntegral
{-# INLINABLE integralToCode #-}
integralFromCode :: Integral a => Code -> Result a
integralFromCode a =
case unCode a of
Atom (AInteger n) -> pure (fromIntegral (il_value n))
_ -> failedToParse "integral"
toCode1 :: Homoiconic a => FastString -> a -> Code
toCode1 tag arg1 =
toCode (List [LForm (genSrc (Atom (ASymbol tag))), toCode arg1])
{-# INLINABLE toCode1 #-}
toCode2 :: (Homoiconic a, Homoiconic b) => FastString -> a -> b -> Code
toCode2 tag arg1 arg2 =
toCode (List [ LForm (genSrc (Atom (ASymbol tag)))
, toCode arg1, toCode arg2 ])
{-# INLINABLE toCode2 #-}
parseCode1 :: (Homoiconic a) => FastString -> (a -> h) -> Code -> Result h
parseCode1 tag f a =
case unCode a of
List [LForm (L _ (Atom (ASymbol tag'))), x]
| tag == tag' -> f <$> parseCode x
_ -> failedToParse (unpackFS tag)
{-# INLINABLE parseCode1 #-}
parseCode2 :: (Homoiconic a, Homoiconic b)
=> FastString -> (a -> b -> h) -> Code -> Result h
parseCode2 tag f a =
case unCode a of
List [LForm (L _ (Atom (ASymbol tag'))), x, y]
| tag == tag' -> f <$> parseCode x <*> parseCode y
_ -> failedToParse (unpackFS tag)
{-# INLINABLE parseCode2 #-}
|
c ****************************************************************
c * *
c * extract indexes into the global *
c * displacmenent, velocity, acceleration vectors *
c * for equations for a list of elements. this *
c * essentially de-blocks the indexes for a set of *
c * elements *
c * *
c * written by : rhd *
c * last modified : 02/18/98 *
c * *
c ****************************************************************
subroutine get_edest_terms( table, elem_list, list_length )
use global_data ! old common.main
use elem_block_data, only : edest_blocks
use main_data, only : elems_to_blocks
c
implicit integer (a-z)
c
dimension table(mxedof,*), elem_list(*)
integer, dimension (:,:), pointer :: edest
c
do i = 1, list_length
elem = elem_list(i)
if ( elem .le. 0 ) cycle
totdof = iprops(2,elem) * iprops(4,elem)
blk = elems_to_blocks(elem,1)
rel_elem = elems_to_blocks(elem,2)
edest => edest_blocks(blk)%ptr
do dof = 1, totdof
table(dof,i) = edest(dof,rel_elem)
end do
end do
c
return
end
c ****************************************************************
c * *
c * extract indexes into the global *
c * displacmenent, velocity, acceleration vectors *
c * for equations for a single element. *
c * *
c * written by : rhd *
c * last modified : 02/18/98 *
c * *
c ****************************************************************
c
subroutine get_single_edest_terms( edest_vec, elem )
use global_data ! old common.main
use elem_block_data, only : edest_blocks
use main_data, only : elems_to_blocks
c
implicit integer (a-z)
c
dimension edest_vec(*)
integer, dimension (:,:), pointer :: edest
c
if ( elem .le. 0 ) return
totdof = iprops(2,elem) * iprops(4,elem)
blk = elems_to_blocks(elem,1)
rel_elem = elems_to_blocks(elem,2)
edest => edest_blocks(blk)%ptr
do dof = 1, totdof
edest_vec(dof) = edest(dof,rel_elem)
end do
c
return
end
|
# coding=utf-8
###############################################################################
# La section avec les paramètres à changer
from glob import glob
from setuptools import find_packages
info = dict(
packages=['server_file_handler'], # La liste des dossiers contenant les modules python (généralement un seul)
name="server-utils",
# Le nom du projet python
version='0.1', # La version du code
description='Server utility package',
# La description du paquet
author='Leo Granier', # Auteur du paquet
author_email='[email protected]', # email de l'auteur
)
console_scripts = [
# Here you can specify some CLI entry points for you software with the following format:
# 'name=package:function_name'
# See https://amir.rachum.com/blog/2017/07/28/python-entry-points/ for details
# You can also not specify anything, all files __main__.py at the root of a module with a "main" function will
# be declared as entry points
'server-file-handler=server_file_handler.run_server:run_forever'
]
##############################################################################
if __name__ == '__main__':
import os
import re
from multiprocessing import cpu_count
from os import listdir
from os.path import join, splitext, basename, isfile, isdir
from setuptools import setup, Extension
# On regarde si le mode debug est activé
DEBUG = os.environ.get("DEBUG")
DEBUG = DEBUG is not None and DEBUG == "1"
if DEBUG:
print("Debug enabled")
# Reformatage du nom de projet
info["name"] = info["name"].lower().replace(" ", "_")
# En cas de compilation de code C il faut connaitre le chemin vers les librairies numpy
try:
import numpy
numpy_include_path = numpy.get_include()
except ImportError:
import sys
numpy_include_path = join(sys.executable, "site-packages/numpy/core/include/numpy")
# Compilation de code C. Cette section cherche des fichiers cython à compiler
def generate_extensions(filenames):
extra_compile_args = ['-fopenmp']
if DEBUG:
extra_compile_args.append("-O0")
extensions = []
language = "c++"
for base_folder in info["packages"]:
# base_folder = abspath(base_folder)
for i in filenames:
extension_name = join(base_folder, i.split(".")[0]).replace("/", ".")
extension_file = join(base_folder, i)
if splitext(basename(i))[1] == ".pyx":
ext = cythonize(extension_file, annotate=DEBUG, gdb_debug=DEBUG,
nthreads=cpu_count(), language=language)[0]
ext.name = extension_name
else:
ext = Extension(extension_name, [extension_file],
language=language, extra_compile_args=extra_compile_args,
include_dirs=[numpy_include_path],
extra_link_args=['-fopenmp'])
extensions.append(ext)
return extensions
# On essaie de compiler les fichiers C et les fichiers Cython
kwargs = {}
files = sum((listdir(base_folder) for base_folder in info["packages"]), [])
try:
from Cython.Build import cythonize
r = re.compile(".+\.pyx")
try:
cython_files = [i for i in files if r.fullmatch(i) is not None]
except AttributeError:
cython_files = [i for i in files if r.match(i) is not None]
if len(cython_files):
extensions = generate_extensions(cython_files)
kwargs.update(dict(
ext_modules=extensions
))
except ImportError:
# Cython not present, compiling C files only
r = re.compile(".+\.c(pp)?")
c_files = [i for i in files if r.fullmatch(i)]
extensions = generate_extensions(c_files)
kwargs.update(dict(
ext_modules=extensions,
))
# On recupere la liste des requirements depuis le fichier requirements
requirements_file = "requirements.txt"
if isfile(requirements_file):
with open(requirements_file, "r") as fp:
requirements = fp.read().splitlines()
else:
requirements = []
# On supprime les commentaires des requirements
requirements = [i for i in requirements if len(i) and i[0] != "#"]
# On transforme les requirements qui sont des urls Git
required = []
EGG_MARK = '#egg='
for line in requirements:
if line.startswith('-e git:') or line.startswith('-e git+') or \
line.startswith('git:') or line.startswith('git+'):
if EGG_MARK in line:
package_name = line[line.find(EGG_MARK) + len(EGG_MARK):]
required.append(f"{package_name} @ {line.split(EGG_MARK)[0]}")
# dependency_links.append(line)
else:
raise ValueError('Dependency to a git repository should have the format:\n'
'git+ssh://[email protected]/xxxxx/xxxxxx#egg=package_name')
else:
required.append(line)
# On ajoute les scripts
script_folder = "bin"
if isdir(script_folder):
kwargs["scripts"] = list(glob(join(script_folder, "*")))
# On ajoute les entry points
if len(console_scripts) == 0:
for package in info["packages"]:
if isfile(join(package, "__main__.py")):
console_scripts.append(f"{package} = {package}:main")
# On ajoute eventuellement les donnees
data_folder = "data"
package_data = []
for package in info["packages"]:
package_folder = join(package, data_folder)
if isdir(package_folder):
for folder, _, files in os.walk(package_folder):
package_data.append((folder.replace("%s/data" % package, package),
[join(folder, file) for file in files]))
if len(package_data):
kwargs["data_files"] = package_data
kwargs.update(dict(install_requires=required,
entry_points=dict(console_scripts=console_scripts)))
kwargs.update(info)
setup(**kwargs) |
(*
* Copyright (C) BedRock Systems Inc. 2021
*
* This software is distributed under the terms of the BedRock Open-Source License.
* See the LICENSE-BedRock file in the repository root for details.
*)
(*
* The following code contains code derived from code original to the
* stdpp project. That original code is
*
* Copyright stdpp developers and contributors
*
* and used according to the following license.
*
* SPDX-License-Identifier: BSD-3-Clause
*
* Original stdpp License:
* https://gitlab.mpi-sws.org/iris/stdpp/-/blob/221197c43d43ce34b211068b84eff0ec4a9ee57a/LICENSE
*)
Require Export stdpp.list.
From bedrock.prelude Require Import base numbers.
Export bedrock.prelude.base.
(** * Small extensions to [stdpp.list]. *)
(** ** Type-level list quantifier *)
Inductive ForallT {A} (P : A -> Type) : list A -> Type :=
| ForallT_nil : ForallT P []
| ForallT_cons x l : P x -> ForallT P l -> ForallT P (x :: l).
Definition ForallT_true {A} (P : A -> Type) (go : ∀ x, P x) : ∀ l, ForallT P l :=
fix go_list l :=
match l with
| [] => ForallT_nil _
| x :: l => ForallT_cons _ _ _ (go x) (go_list l)
end.
(** ** Teach [set_solver] to reason about more list operations, similarly to set
operations. *)
(* Upstreamed in https://gitlab.mpi-sws.org/iris/stdpp/-/merge_requests/366 *)
#[global] Instance set_unfold_list_bind {A B} (f : A → list B) l P Q y :
(∀ x, SetUnfoldElemOf x l (P x)) → (∀ x, SetUnfoldElemOf y (f x) (Q x)) →
SetUnfoldElemOf y (l ≫= f) (∃ x, Q x ∧ P x).
Proof. constructor. rewrite elem_of_list_bind. naive_solver. Qed.
#[global] Instance list_bind_mono {A B} :
Proper (pointwise_relation _ (⊆) ==> (⊆) ==> (⊆))
(mbind (M := list) (A := A) (B := B)).
Proof. rewrite /pointwise_relation =>f1 f2 Hf xs1 xs2 Hxs. set_solver. Qed.
#[global] Instance list_bind_perm {A B} :
Proper (pointwise_relation _ Permutation ==> Permutation ==> Permutation)
(mbind (M := list) (A := A) (B := B)).
Proof. move =>f1 f2 Hf xs _ <-. elim: xs => [//|x xs IH]; csimpl. by rewrite {}IH (Hf x). Qed.
(* To upstream, based on upstream [set_unfold_filter]. *)
#[global] Instance set_unfold_list_filter
{A} (P : A → Prop) `{!∀ x, Decision (P x)}
(xs : list A) Q x :
SetUnfoldElemOf x xs Q →
SetUnfoldElemOf x (filter P xs) (P x ∧ Q).
Proof. constructor. rewrite elem_of_list_filter. set_solver. Qed.
#[global] Instance set_unfold_list_difference `{EqDecision A} (x : A) l k P Q :
SetUnfoldElemOf x l P → SetUnfoldElemOf x k Q →
SetUnfoldElemOf x (list_difference l k) (P ∧ ¬ Q).
Proof. constructor. rewrite elem_of_list_difference. set_solver. Qed.
#[global] Instance set_unfold_list_intersection `{EqDecision A} (x : A) l k P Q :
SetUnfoldElemOf x l P → SetUnfoldElemOf x k Q →
SetUnfoldElemOf x (list_intersection l k) (P ∧ Q).
Proof. constructor. rewrite elem_of_list_intersection. set_solver. Qed.
#[global] Instance set_unfold_list_union `{EqDecision A} (x : A) l k P Q :
SetUnfoldElemOf x l P → SetUnfoldElemOf x k Q →
SetUnfoldElemOf x (list_union l k) (P ∨ Q).
Proof. constructor. rewrite elem_of_list_union. set_solver. Qed.
#[global] Instance set_unfold_list_intersection_with `{EqDecision A} (y : A) l k P Q R f :
(∀ x, SetUnfoldElemOf x l (P x)) → (∀ x, SetUnfoldElemOf x k (Q x)) →
(∀ x1 x2, SetUnfold (f x1 x2 = Some y) (R x1 x2)) →
SetUnfoldElemOf y (list_intersection_with f l k) (∃ x1 x2 : A, P x1 ∧ Q x2 ∧ R x1 x2).
Proof. constructor. rewrite elem_of_list_intersection_with. set_solver. Qed.
(* [list_union_with] does not exist. *)
#[global] Instance set_unfold_in {A} (x : A) l P :
SetUnfoldElemOf x l P → SetUnfold (In x l) P.
Proof. constructor. rewrite -elem_of_list_In. set_solver. Qed.
#[global] Instance set_unfold_list_ret {A} (x y : A) P :
SetUnfold (x = y) P →
SetUnfoldElemOf x (mret (M := list) y) P.
Proof. constructor. rewrite elem_of_list_ret. set_solver. Qed.
#[global] Instance set_unfold_list_mjoin {A} (x : A) (xss : list (list A)) P Q :
(∀ xs, SetUnfoldElemOf x xs (P xs)) → (∀ xs, SetUnfoldElemOf xs xss (Q xs)) →
SetUnfoldElemOf x (mjoin (M := list) xss) (∃ xs, P xs ∧ Q xs).
Proof. constructor. rewrite elem_of_list_join. set_solver. Qed.
#[global] Instance set_unfold_list_omap {A B} (y : B) xs (f : A → option B) P Q :
(∀ x, SetUnfoldElemOf x xs (P x)) → (∀ x, SetUnfold (f x = Some y) (Q x)) →
SetUnfoldElemOf y (omap (M := list) f xs) (∃ x : A, P x ∧ Q x).
Proof. constructor. rewrite elem_of_list_omap. set_solver. Qed.
(*
Outside this theory remain [elem_of_list_split*], [elem_of_list_lookup] and
[elem_of_list_lookup_total].
Of those, [elem_of_list_lookup] seems interesting but might be a breaking
change.
*)
Lemma foldr_cons {A B} (f : A -> B -> B) x y ys : foldr f x (y :: ys) = f y (foldr f x ys).
Proof. done. Qed.
(* From stdlib's [repeat] to stdpp's [replicate]. *)
Lemma repeat_replicate {A} (x : A) n :
repeat x n = replicate n x.
Proof. by elim: n => [//| n /= ->]. Qed.
Section list.
Context {A : Type}.
Implicit Types (l k xs : list A) (i j : nat).
Lemma fmap_ext_in {B} (f g : A → B) l :
(∀ a : A, a ∈ l → f a = g a) → f <$> l = g <$> l.
Proof.
elim: l => [//|x l IHl Hext]; cbn; f_equiv.
{ apply Hext, elem_of_cons, or_introl, eq_refl. }
apply IHl => y Hin. apply Hext, elem_of_cons, or_intror, Hin.
Qed.
(** List disjointness is decidable *)
Section disjoint_dec.
Notation Disjoint l k :=
(List.Forall (λ x, List.Forall (x ≠.) k) l) (only parsing).
#[local] Lemma list_disjoint_alt l k : l ## k <-> Disjoint l k.
Proof. rewrite Forall_forall. setoid_rewrite Forall_forall. set_solver. Qed.
#[global] Instance list_disjoint_dec `{EqDecision A} : RelDecision (##@{list A}).
Proof.
refine (λ l k, cast_if (decide (Disjoint l k)));
by rewrite list_disjoint_alt.
Defined.
End disjoint_dec.
(** Witnesses for non-disjoint lists *)
Lemma list_not_disjoint `{EqDecision A} l k :
¬ l ## k <-> exists x, x ∈ l /\ x ∈ k.
Proof.
split; last set_solver+. rewrite list_disjoint_alt.
move/not_Forall_Exists=>/Exists_exists [] x [] ? /=.
move/not_Forall_Exists=>/Exists_exists [] y [] ? /=.
destruct (decide (x = y)); [by exists x; simplify_eq|done].
Qed.
Lemma disjoint_cons_r l x k : l ## x :: k <-> x ∉ l /\ l ## k.
Proof. set_solver+. Qed.
Lemma list_alter_insert l i f :
alter f i l = if l !! i is Some x then <[i:=f x]> l else l.
Proof.
elim: l i => [//|x l IHl] [//|i]; csimpl.
rewrite IHl. by case_match.
Qed.
Lemma list_filter_empty_iff xs `(∀ x, Decision (P x)) :
filter P xs = [] ↔ List.Forall (λ x, ¬P x) xs.
Proof.
elim: xs => [//|x xs IH] /=.
rewrite filter_cons Forall_cons.
case_decide; naive_solver.
Qed.
(** List variant of
<< map_filter_insert : ...
filter P (<[i:=x]> m) =
if decide (P (i, x))
then <[i:=x]> (filter P m)
else filter P (delete i m) ].
In the [P x] branch, we cannot reuse [<[i:=x]> (filter P m)]:
[x] must be inserted not at position [i] but [length (filter P (take i xs))].
Instead, we use an alternative version. *)
Lemma list_filter_insert i x xs P `(∀ x, Decision (P x)) :
i < length xs →
filter P (<[i:=x]> xs) =
if decide (P x) then
filter P (take i xs) ++ [x] ++ filter P (drop (S i) xs)
else
filter P (delete i xs).
Proof.
move=> Hle; rewrite insert_take_drop // delete_take_drop.
by rewrite !(filter_app, filter_cons, filter_nil); case_decide.
Qed.
(** Properties of [list_fmap] *)
Lemma list_fmap_filter {B} P Q xs (f : A -> B)
`(∀ x, Decision (P x)) `(∀ x, Decision (Q x)) :
(∀ x, P x <-> Q (f x)) →
f <$> filter P xs = filter Q (f <$> xs).
Proof.
move=> Heq. elim: xs => [//|x xs IH]; csimpl; rewrite !filter_cons.
repeat case_decide; csimpl; rewrite IH; naive_solver.
Qed.
Lemma list_fmap_id' l (f : A -> A):
(forall x, f x = x) -> f <$> l = l.
Proof. move => ?. elim: l => // ?? {2}<-. csimpl. by f_equal. Qed.
(** Properties of [list_delete] *)
Lemma list_delete_elem_of_1 l i x y:
l !! i = Some y -> x ≠ y ->
x ∈ l -> x ∈ delete i l.
Proof. move => Hl ?. rewrite {1}(delete_Permutation _ _ _ Hl). set_solver. Qed.
Lemma list_delete_elem_of_2 l x i:
x ∈ delete i l -> x ∈ l.
Proof. elim: l i => // a l IH [ |i]/=; set_solver. Qed.
(** Properties of [NoDup] *)
Lemma NoDup_Permutation' l k:
NoDup l -> length l = length k -> (∀ x : A, x ∈ l -> x ∈ k) → l ≡ₚ k.
Proof. move => ???. apply submseteq_Permutation_length_eq => //. by apply NoDup_submseteq. Qed.
Lemma NoDup_not_in_delete l i x:
NoDup l -> l !! i = Some x -> x ∉ delete i l.
Proof. move => + Hin. by rewrite {1}(delete_Permutation _ _ _ Hin) => /NoDup_cons[??]. Qed.
End list.
#[global] Hint Resolve NoDup_nil_2 | 0 : core.
#[global] Hint Resolve NoDup_cons_2 : core.
#[global] Hint Resolve not_elem_of_nil | 0 : core.
Section lists.
Context {A B : Type}.
Implicit Types (xs : list A) (ys : list B).
Section zip_with.
Context {C : Type}.
Lemma NoDup_zip_with_fst_gen xs ys (f : A -> B -> C) :
(∀ x1 x2 y1 y2, f x1 y1 = f x2 y2 -> x1 = x2) ->
NoDup xs → NoDup (zip_with f xs ys).
Proof.
move=> Hinj. elim: xs ys => /= [//|x xs IHxs] [//|y ys] /NoDup_cons [Hni Hnd].
apply NoDup_cons, conj, IHxs, Hnd.
intros ?%elem_of_zip_with. naive_solver.
Qed.
Lemma NoDup_zip_with_fst_inj xs ys (f : A -> B -> C) `{!Inj2 eq eq eq f} :
NoDup xs → NoDup (zip_with f xs ys).
Proof. apply NoDup_zip_with_fst_gen. naive_solver. Qed.
Lemma NoDup_zip_with_snd_gen xs ys (f : A -> B -> C) :
(∀ x1 x2 y1 y2, f x1 y1 = f x2 y2 -> y1 = y2) ->
NoDup ys → NoDup (zip_with f xs ys).
Proof.
move=> Hinj. elim: xs ys => /= [//|x xs IHxs] [//|y ys] /NoDup_cons [Hni Hnd].
apply NoDup_cons, conj, IHxs, Hnd.
intros ?%elem_of_zip_with. naive_solver.
Qed.
Lemma NoDup_zip_with_snd_inj xs ys `(f : A -> B -> C) `{!Inj2 eq eq eq f} :
NoDup ys → NoDup (zip_with f xs ys).
Proof. apply NoDup_zip_with_snd_gen. naive_solver. Qed.
End zip_with.
Lemma NoDup_zip_fst xs ys :
NoDup xs → NoDup (zip xs ys).
Proof. exact: NoDup_zip_with_fst_inj. Qed.
Lemma NoDup_zip_snd xs ys :
NoDup ys → NoDup (zip xs ys).
Proof. exact: NoDup_zip_with_snd_inj. Qed.
Lemma elem_of_zip x1 x2 xs ys :
(x1, x2) ∈ zip xs ys → x1 ∈ xs ∧ x2 ∈ ys.
Proof. intros. eauto using elem_of_zip_l, elem_of_zip_r. Qed.
(** Properties of [Forall] *)
(** Strengthens [mapM_fmap_Some_inv] by weakening the second premiss *)
Lemma mapM_fmap_Forall_Some_inv (f : A -> option B) (g : B -> A) l k :
mapM f l = Some k ->
Forall (fun x => ∀ y, f x = Some y -> g y = x) l ->
g <$> k = l.
Proof.
intros Hmap Hl. have Hlen := mapM_length _ _ _ Hmap.
apply mapM_Some_1 in Hmap. elim: Hl k Hmap Hlen; intros.
- by rewrite (nil_length_inv k).
- decompose_Forall_hyps. auto with f_equal.
Qed.
Lemma Forall_fmap_fmap_1 (f : A -> B) (g : B -> A) l :
Forall (fun x => g (f x) = x) l -> g <$> (f <$> l) = l.
Proof.
intros. rewrite -list_fmap_compose -{2}(list_fmap_id l).
exact: Forall_fmap_ext_1.
Qed.
Lemma Forall_fmap_fmap (f : A -> B) (g : B -> A) l :
Forall (fun x => g (f x) = x) l <-> g <$> (f <$> l) = l.
Proof.
split; first apply Forall_fmap_fmap_1.
rewrite -list_fmap_compose -{2}(list_fmap_id l).
by rewrite -Forall_fmap_ext.
Qed.
End lists.
Section list_difference.
Context `{EqDecision A}.
Implicit Types l k : list A.
Implicit Types x y : A.
Lemma list_difference_nil_r l : list_difference l [] = l.
Proof. induction l; simpl; auto with f_equal. Qed.
Lemma list_difference_cons_r y l k :
list_difference l (y :: k) =
list_difference (list_difference l [y]) k.
Proof.
induction l as [|x l IH]; [done | ].
rewrite [RHS]/=. case_decide as Hy.
{ simpl. rewrite decide_True; set_solver. }
rewrite [RHS]/=. case_decide as Hk; simpl.
- rewrite decide_True; set_solver.
- rewrite IH decide_False; set_solver.
Qed.
Lemma list_difference_app_r l k1 k2 :
list_difference l (k1 ++ k2) = list_difference (list_difference l k1) k2.
Proof.
revert l. induction k1 as [|y k1 IH]=>l; simpl.
- by rewrite list_difference_nil_r.
- by rewrite (list_difference_cons_r y) IH -(list_difference_cons_r y).
Qed.
Lemma list_difference_singleton_not_in l x :
x ∉ l -> list_difference l [x] = l.
Proof.
elim: l => /= [//|y l IHl] /not_elem_of_cons [Hne Hni].
rewrite decide_False.
2: { by intros ->%elem_of_list_singleton. }
f_equal. apply IHl, Hni.
Qed.
End list_difference.
#[deprecated(note="Use list_difference_singleton_not_in")]
Notation list_difference_id := list_difference_singleton_not_in.
Lemma tail_length {A} (l : list A):
length (tail l) <= length l <= length (tail l) + 1.
Proof.
induction l; simpl; by lia.
Qed.
Lemma tail_length_eq {A} (l : list A):
0 < length l ->
length (tail l) + 1 = length l.
Proof.
intros H.
destruct l; simpl in *; by lia.
Qed.
(* Make [take 0 xs] reduce with [cbn] *)
#[global] Arguments take : simpl nomatch.
Lemma head_Some_elem_of {A} (x : A) (xs : list A) : head xs = Some x → x ∈ xs.
Proof. destruct xs => [//|[->]]. by apply elem_of_cons; left. Qed.
Lemma list_empty_eq_ext {A} (xs : list A) :
(∀ x : A, x ∈ xs ↔ False) ↔ xs = [].
Proof. case: xs; set_solver. Qed.
Lemma list_singleton_eq_ext {A} (x : A) xs (HnoDup : NoDup xs) :
(∀ y, y ∈ xs ↔ y = x) ↔ xs = [x].
Proof.
split => [H | -> y]; last by set_solver.
apply symmetry, Permutation_singleton_l, NoDup_Permutation;
[apply NoDup_singleton|done|..] => z.
set_solver.
Qed.
Lemma not_elem_of_list_lookup {A} {i} {xs : list A} {x} y :
xs !! i = Some x → y ∉ xs → x ≠ y.
Proof. intros Hl Hni ->. eapply Hni, elem_of_list_lookup_2, Hl. Qed.
Lemma list_difference_delete `{EqDecision A} i (x : A) (xs : list A) :
xs !! i = Some x →
NoDup xs -> (* Needed because [list_difference xs [x]] removes all occurrences of [x]. *)
list_difference xs [x] = delete i xs.
Proof.
elim: xs i => [//|y xs /= IHxs] [[->] |i /= Hl] /NoDup_cons [Hni HnoDup] /=. {
by rewrite decide_True ?list_difference_singleton_not_in ?elem_of_list_singleton.
}
rewrite decide_False ?(IHxs i) // elem_of_list_singleton.
by have := not_elem_of_list_lookup _ Hl Hni.
Qed.
Lemma list_remove_delete `{EqDecision A} i (x : A) (xs : list A) :
xs !! i = Some x →
NoDup xs -> (* Needed because [i] might not be the first occurrence. *)
list_remove x xs = Some (delete i xs).
Proof.
elim: xs i => /= [|y xs IHxs] // [/= [->]|i /= Hl] //= /NoDup_cons [Hni HnoDup].
{ by rewrite decide_True. }
rewrite decide_False ?(IHxs i Hl) //.
by have := not_elem_of_list_lookup _ Hl Hni.
Qed.
Lemma list_difference_remove `{EqDecision A} (x : A) (xs : list A) :
x ∈ xs →
NoDup xs ->
list_remove x xs = Some (list_difference xs [x]).
Proof.
intros [i Hl]%elem_of_list_lookup_1 HnoDup.
by rewrite !(list_remove_delete i, list_difference_delete i).
Qed.
#[global] Instance map_Inj A B (f : A -> B) : Inj eq eq f -> Inj eq eq (map f).
Proof.
move=>Hinj x.
induction x; induction y; first done.
- by move=>H; case:( nil_cons H).
- by rewrite eq_comm; move=>H; case:( nil_cons H).
- by move=>[/Hinj<-/IHx->].
Qed.
|
lemma (in ring_of_sets) Diff [intro]: assumes "a \<in> M" "b \<in> M" shows "a - b \<in> M" |
module GUIgeneric.loadAllRepository where
open import GUIgeneric.GUI
open import GUIgeneric.GUIDefinitions
open import GUIgeneric.GUIExample
open import GUIgeneric.GUIExampleBankAccount
open import GUIgeneric.GUIExampleLib
open import GUIgeneric.GUIFeatures
open import GUIgeneric.GUIFeaturesPart2
open import GUIgeneric.GUIFeaturesPart3
open import GUIgeneric.GUIFeaturesPart4
open import GUIgeneric.GUIFeaturesPart5
open import GUIgeneric.GUIModel
open import GUIgeneric.GUIModelExample
open import GUIgeneric.Prelude
|
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE BangPatterns #-}
module Numeric.MCMC.Langevin (
MarkovChain(..), Options(..)
, runChain
) where
import Control.Monad
import Control.Monad.Trans
import Control.Monad.Reader
import Control.Monad.Primitive
import Control.Arrow
import System.Random.MWC
import System.Random.MWC.Distributions
import Data.List
import Statistics.Distribution
import Statistics.Distribution.Normal hiding (standard)
import GHC.Float
-- | State of the Markov chain. Current parameter values are held in 'theta',
-- while accepts counts the number of proposals accepted.
data MarkovChain = MarkovChain { theta :: [Double]
, accepts :: {-# UNPACK #-} !Int }
-- | Options for the chain. The target (expected to be a log density), its
-- gradient, and a step size tuning parameter.
data Options = Options { _target :: [Double] -> Double
, _gTarget :: [Double] -> [Double]
, _eps :: {-# UNPACK #-} !Double }
-- | A result with this type has a view of the chain options.
type ViewsOptions = ReaderT Options
-- | Display the current state.
instance Show MarkovChain where
show config = filter (`notElem` "[]") $ show (map double2Float (theta config))
-- | Density function for an isotropic Gaussian. The (identity) covariance
-- matrix is multiplied by the scalar 'sig'.
isoGauss :: [Double] -> [Double] -> Double -> Double
isoGauss xs mu sig = foldl1' (*) (zipWith density nds xs)
where nds = map (`normalDistr` sig) mu
{-# INLINE isoGauss #-}
-- | Mean function for the discretized Langevin diffusion.
localMean :: Monad m
=> [Double] -- Current state
-> ViewsOptions m [Double] -- Localized mean
localMean t = do
Options _ gTarget e <- ask
return $! zipWith (+) t (map (* (0.5 * e^(2 :: Int))) (gTarget t))
{-# INLINE localMean #-}
-- | Perturb the state, creating a new proposal.
perturb :: PrimMonad m
=> [Double] -- Current state
-> Gen (PrimState m) -- MWC PRNG
-> ViewsOptions m [Double] -- Resulting perturbation.
perturb t g = do
Options _ _ e <- ask
zs <- replicateM (length t) (lift $ standard g)
t0 <- localMean t
let perturbedState = zipWith (+) t0 t1
t1 = map (* e) zs
return $! perturbedState
{-# INLINE perturb #-}
-- | Perform a Metropolis accept/reject step.
metropolisStep :: PrimMonad m
=> MarkovChain -- Current state
-> Gen (PrimState m) -- MWC PRNG
-> ViewsOptions m MarkovChain -- New state
metropolisStep state g = do
Options target _ e <- ask
let (t0, nacc) = (theta &&& accepts) state
zc <- lift $ uniformR (0, 1) g
proposal <- perturb t0 g
t0Mean <- localMean t0
proposalMean <- localMean proposal
let mc = if zc < acceptProb
then (proposal, 1)
else (t0, 0)
acceptProb = if isNaN val then 0 else val where val = arRatio
arRatio = exp . min 0 $
target proposal + log (isoGauss proposal t0Mean (e^(2 :: Int)))
- target t0 - log (isoGauss t0 proposalMean (e^(2 :: Int)))
return $! MarkovChain (fst mc) (nacc + snd mc)
{-# INLINE metropolisStep #-}
-- | Diffuse through states.
runChain :: Options -- Options of the Markov chain.
-> Int -- Number of epochs to iterate the chain.
-> Int -- Print every nth iteration
-> MarkovChain -- Initial state of the Markov chain.
-> Gen RealWorld -- MWC PRNG
-> IO MarkovChain -- End state of the Markov chain, wrapped in IO.
runChain = go
where go o n t !c g | n == 0 = return c
| n `rem` t /= 0 = do
r <- runReaderT (metropolisStep c g) o
go o (n - 1) t r g
| otherwise = do
r <- runReaderT (metropolisStep c g) o
print r
go o (n - 1) t r g
{-# INLINE runChain #-}
|
# demo of PCA fitting
# phase shifted data courtesy of Vladimir Galogaza.
# list of image files
# these are stored in zernike/psidata in the R library, so must expand path name
require(zernike)
fpath <- file.path(find.package(package="zernike"), "psidata")
files <- scan(file.path(fpath, "files_pca.txt"), what="character")
for (i in 1:length(files)) files[i] <- file.path(fpath, files[i])
# load the images into an array
images <- load.images(files)
nr <- dim(images)[1]
nc <- dim(images)[2]
nf <- dim(images)[3]
# parameters for this run
source(file.path(fpath, "parameters.txt"))
# phase shifts
phases <- wrap((0:(nf-1))/frames.per.cycle*2*pi)
phases <- switch(ps.dir, ccw = -phases, cw = phases, phases)
# target SA coefficients for numerical null.
sa.t <- sconic(diam,roc,lambda=wavelength)
zopt <- psfit_options()
zopt$plots <- FALSE
zopt$satarget <- sa.t
cat("Performing PSI analysis. Please wait...\n")
flush.console()
system.time(psfit <- psifit(images, phases, psialg="ls", options=zopt))
cat("Zernike fit to wavefront from PSI analysis\n")
flush.console()
plot(psfit$wf.smooth)
mtext(paste("RMS =",format(pupilrms(psfit$wf.smooth),digits=3)))
cat("Performing PCA analysis. Please wait...\n")
system.time(pcfit <- psifit(images, phases, cp=psfit$cp, psialg="pc1", options=zopt))
cat("Wavefront from PCA routine\n")
flush.console()
if (tolower(.Platform$OS.type) == "windows") windows() else x11()
plot(pcfit$wf.smooth)
mtext(paste("RMS =",format(pupilrms(pcfit$wf.smooth),digits=3)))
cat("Performing 'Advanced iterative algorithm'. Please wait...\n")
system.time(aifit <- psifit(images, phases=pcfit$phases, cp=psfit$cp, psialg="aia", options=zopt))
cat("Wavefront from 'AIA'\n")
flush.console()
if (tolower(.Platform$OS.type) == "windows") windows() else x11()
plot(aifit$wf.smooth)
mtext(paste("RMS =",format(pupilrms(aifit$wf.smooth),digits=3)))
# full intercomparison
wfnets <- array(0, dim=c(nr, nc, 3))
wfsmooth <- array(0, dim=c(nr,nc,3))
legends=c("baseline PSI", "PCA", "AIA")
plotn(psfit, pcfit, aifit, labels=legends)
plotn(psfit, pcfit, aifit, labels=legends, wftype="smooth", qt=c(0,1))
cat("Why it works\n")
cat("Calculating principal components...\n")
flush.console()
im.mat <- matrix(images,nr*nc,nf)
im.mat <- im.mat-rowMeans(im.mat)
im.svd <- svd(im.mat)
pcs <- array(im.svd$u, dim=c(nr,nc,nf))
cat("And here they are...\n")
cat("The quadrature signal is assumed to be in the first two slots\n")
flush.console()
if (tolower(.Platform$OS.type) == "windows") {
windows(width=10, height=2.5*nf)} else {
x11(width=10, height=2.5*nf)
}
par(mar=rep(0,4))
split.screen(figs=c(nf/2,2))
for (i in 1:nf) {
screen(i)
image(pcs[,,i], col=grey256, axes=FALSE, asp=nc/nr, useRaster=TRUE)
}
close.screen(all.screens=TRUE)
#clean up
rm(im.mat, im.svd, pcs)
|
lemma set_coeffs_not_only_0 [simp]: "set (coeffs p) \<noteq> {0}" |
REBOL [
Title: "date - Tests"
Version: 1.0.0
Rights: {
Copyright 2017 Brett Handley
}
License: {
Licensed under the Apache License, Version 2.0
See: http://www.apache.org/licenses/LICENSE-2.0
}
Author: "Brett Handley"
Purpose: {Testing.}
]
script-needs [
%requirements.r
%../date.r
]
requirements 'date [
[
equal? "2017-08-01" date/as/excel 1-Aug-2017
]
[
equal? "2017-08-01 10:00:00" date/as/excel 1-Aug-2017/10:00
]
[
equal? "20170801T130000+10:00" date/as/iso8601 1-Aug-2017/13:00+10:00
]
[
equal? "2017-08-01T13:00:00+10:00" date/as/w3c 1-Aug-2017/13:00+10:00
]
[
equal? 1-Aug-2017/3:00 date/as/utc 1-Aug-2017/13:00+10:00
]
[
equal? 31-Jul-2017/19:00-8:00 date/as/zone -8:00 1-Aug-2017/13:00+10:00
]
[
equal? date/from/iso8601 date/as/iso8601 d: 1-aug-2017 d
]
[
equal? 1-Aug-2017 date/from/unspecified "20170801"
]
[
equal? 1-Aug-2017 date/from/unspecified "1 aug 2017"
]
[
equal? date/from/w3c date/as/w3c d: 1-aug-2017 d
]
[
equal? date/from/w3c date/as/w3c d: 1-aug-2017 d
]
[
date/is/leap-year? 1-aug-2016
]
[
equal? 31-Aug-2017 date/of/month/end 1-Aug-2017
]
[
equal? 1-Aug-2017 date/of/month/start 1-Aug-2017
]
]
|
function [C, Ceq] = multipleShooting2(z,pack,dyn)
%
% This function enforces the dynamics of the cart-pole system
% using 4th-order runge kutta:
%
%
% INPUTS:
% z = [N,1] = vector of decision variables
% pack = struct with matrix dimensions
% dyn = struct with physical parameters
%
% OUTPUTS:
% C = []
% Ceq = column vector of defects. Trajectory is feasible iff norm(Ceq)->0
%
% NOTES:
% [t,x,u] = unPackDecVar(z,pack);
% size(t) == [1,1];
% size(x) == [nState, nSegment+1]
% size(u) == [nControl, nSubStep*nSegment+1]
%
% * The trajectory is represented with piecewise-linear control
% and piece-wise quartic state (implicityly).
%
[t,x,u] = unPackDecVar(z,pack);
nx = size(x,2);
nu = size(u,2);
nSubStep = (nu-1)/(nx-1);
dt = t/(nu-1);
xLow = x(:,1:(nx-1)); %Each segment starts here
xUpp = x(:,2:nx); %And goes here
% Time-step along each trajectory segment in parallel
xStar = xLow;
uIdx = 0:nSubStep:(nu-1);
for i=1:nSubStep
uStarLow = u(:,i + uIdx);
uStarUpp = u(:,i+1 + uIdx);
uStarMid = 0.5*(uStarLow+uStarUpp);
k1 = cartPoleDynamics(xStar,uStarLow,dyn);
k2 = cartPoleDynamics(xStar+0.5*k1,uStarMid,dyn);
k3 = cartPoleDynamics(xStar+0.5*k2,uStarMid,dyn);
k4 = cartPoleDynamics(xStar+k3,uStarUpp,dyn);
xStar = xStar + (dt/6)*(k1 + 2*k2 + 2*k3 + k4);
end
% Defect constraint:
defect = xStar-xUpp;
% Pack up and return:
C = [];
Ceq = reshape(defect,numel(defect),1);
end |
---------------------------------------
-- Pairs of sets
---------------------------------------
{-# OPTIONS --allow-unsolved-meta #-}
module sv20.assign2.SetTheory.Pairs where
-- Everything involving pairs, be them unordered
-- or ordered pairs. Also the definition of power set
-- and cartesian product between sets.
open import sv20.assign2.SetTheory.Logic
open import sv20.assign2.SetTheory.Algebra
open import sv20.assign2.SetTheory.Subset
open import sv20.assign2.SetTheory.ZAxioms
-- Pairs, justified by the pair axiom
_ₚ_ : 𝓢 → 𝓢 → 𝓢
x ₚ y = proj₁ (pair x y)
pair-d : (x y : 𝓢) → ∀ {z} → z ∈ x ₚ y ⇔ (z ≡ x ∨ z ≡ y)
pair-d x y = proj₂ _ (pair x y)
-- Both ∧-projections
pair-d₁ : (x y : 𝓢) → ∀ {z} → z ∈ x ₚ y → (z ≡ x ∨ z ≡ y)
pair-d₁ x y = ∧-proj₁ (pair-d x y)
pair-d₂ : (x y : 𝓢) → ∀ {z} → (z ≡ x ∨ z ≡ y) → z ∈ x ₚ y
pair-d₂ x y = ∧-proj₂ (pair-d x y)
pair-p₁ : (x y : 𝓢) → x ₚ y ≡ y ₚ x
pair-p₁ x y = equalitySubset (x ₚ y) (y ₚ x) (p₁ , p₂)
where
p₁ : (z : 𝓢) → z ∈ x ₚ y → z ∈ y ₚ x
p₁ z z∈x,y = pair-d₂ y x (∨-sym _ _ (pair-d₁ x y z∈x,y))
p₂ : (z : 𝓢) → z ∈ y ₚ x → z ∈ x ₚ y
p₂ z z∈y,x = pair-d₂ x y (∨-sym _ _ (pair-d₁ y x z∈y,x))
singleton : 𝓢 → 𝓢
singleton x = x ₚ x
singletonp : (x : 𝓢) → ∀ {z} → z ∈ singleton x → z ≡ x
singletonp x x₁ = ∨-idem _ (pair-d₁ x x x₁)
singletonp₂ : (x : 𝓢) → x ∈ singleton x
singletonp₂ x = pair-d₂ x x (inj₁ refl)
singletonp₃ : (x : 𝓢) → ∀ {y} → x ≡ y → x ∈ singleton y
singletonp₃ x x≡y = pair-d₂ _ _ (inj₁ x≡y)
singletonp₄ : (x y : 𝓢) → x ∈ singleton y → x ∩ singleton y ≡ ∅
singletonp₄ x y h = {!!}
where
p₁ : x ≡ y
p₁ = singletonp _ h
p₂ : x ∩ singleton x ≡ ∅
p₂ = {!!}
pair-prop-helper₁ : {a b c : 𝓢} → a ≡ b ∨ a ≡ c → a ≢ b → a ≡ c
pair-prop-helper₁ (inj₁ a≡b) h = ⊥-elim (h a≡b)
pair-prop-helper₁ (inj₂ refl) _ = refl
pair-prop-helper₂ : {a b : 𝓢} → a ≢ b → b ≢ a
pair-prop-helper₂ h b≡a = h (sym _ _ b≡a)
-- Theorem 44, p. 31 (Suppes, 1972).
pair-prop : (x y u v : 𝓢) → x ₚ y ≡ u ₚ v → (u ≡ x ∧ v ≡ y) ∨ (v ≡ x ∧ u ≡ y)
pair-prop x y u v eq = ∨-e _ _ _ (pem (x ≡ y)) h-x≡y h-x≢y
where
u∈u,v : u ∈ (u ₚ v)
u∈u,v = ∨-prop₁ (pair-d₂ u v) refl
u∈x,y : u ∈ (x ₚ y)
u∈x,y = memberEq u (u ₚ v) (x ₚ y) (u∈u,v , (sym _ _ eq))
disj₁ : u ≡ x ∨ u ≡ y
disj₁ = pair-d₁ _ _ u∈x,y
v∈u,v : v ∈ (u ₚ v)
v∈u,v = ∨-prop₂ (pair-d₂ u v) refl
v∈x,y : v ∈ (x ₚ y)
v∈x,y = memberEq v (u ₚ v) (x ₚ y) (v∈u,v , (sym _ _ eq))
disj₂ : v ≡ x ∨ v ≡ y
disj₂ = pair-d₁ _ _ v∈x,y
x∈x,y : x ∈ (x ₚ y)
x∈x,y = ∨-prop₁ (pair-d₂ x y) refl
x∈u,v : x ∈ (u ₚ v)
x∈u,v = memberEq x (x ₚ y) (u ₚ v) (x∈x,y , eq)
disj₃ : x ≡ u ∨ x ≡ v
disj₃ = pair-d₁ _ _ x∈u,v
y∈x,y : y ∈ (x ₚ y)
y∈x,y = ∨-prop₂ (pair-d₂ x y) refl
y∈u,v : y ∈ (u ₚ v)
y∈u,v = memberEq y (x ₚ y) (u ₚ v) (y∈x,y , eq)
disj₄ : y ≡ u ∨ y ≡ v
disj₄ = pair-d₁ _ _ y∈u,v
h-x≡y : x ≡ y → (u ≡ x ∧ v ≡ y) ∨ (v ≡ x ∧ u ≡ y)
h-x≡y eq₂ = inj₁ (x≡u , v≡y)
where
x≡u : u ≡ x
x≡u = ∨-idem _ disj-aux
where
disj-aux : u ≡ x ∨ u ≡ x
disj-aux = subs _ (sym _ _ eq₂) disj₁
v≡y : v ≡ y
v≡y = ∨-idem _ disj-aux
where
disj-aux : v ≡ y ∨ v ≡ y
disj-aux = subs _ eq₂ disj₂
h-x≢y : x ≢ y → (u ≡ x ∧ v ≡ y) ∨ (v ≡ x ∧ u ≡ y)
h-x≢y ¬eq = ∨-e _ _ _ (pem (x ≡ u)) h₁ h₂
where
h₁ : x ≡ u → (u ≡ x ∧ v ≡ y) ∨ (v ≡ x ∧ u ≡ y)
h₁ x≡u = ∨-e _ _ _ (pem (y ≡ u)) h₁₁ h₁₂
where
h₁₁ : y ≡ u → (u ≡ x ∧ v ≡ y) ∨ (v ≡ x ∧ u ≡ y)
h₁₁ y≡u = ⊥-elim (¬eq (trans x≡u (sym _ _ y≡u)))
h₁₂ : y ≢ u → (u ≡ x ∧ v ≡ y) ∨ (v ≡ x ∧ u ≡ y)
h₁₂ h = inj₁ (sym _ _ x≡u , sym _ _ (pair-prop-helper₁ disj₄ h))
h₂ : x ≢ u → (u ≡ x ∧ v ≡ y) ∨ (v ≡ x ∧ u ≡ y)
h₂ h = inj₂ (sym _ _ (pair-prop-helper₁ disj₃ h)
,
(pair-prop-helper₁ disj₁ (pair-prop-helper₂ h)))
-- Theorem 45, p. 32 (Suppes 1960).
singleton-eq : (x y : 𝓢) → singleton x ≡ singleton y → x ≡ y
singleton-eq x y eq = sym _ _ (∧-proj₁ (∨-idem _ aux))
where
aux : ((y ≡ x) ∧ (y ≡ x)) ∨ ((y ≡ x) ∧ (y ≡ x))
aux = pair-prop x x y y eq
singleton-⊆ : (x A : 𝓢) → x ∈ A → singleton x ⊆ A
singleton-⊆ x A x∈A t t∈xₛ = subs _ (sym _ _ (singletonp _ t∈xₛ)) x∈A
prop-p₂ : (y z : 𝓢) → y ₚ z ≡ singleton y ∪ singleton z
prop-p₂ y z = equalitySubset _ _ (p₁ , p₂)
where
p₁ : (x : 𝓢) → x ∈ y ₚ z → x ∈ singleton y ∪ singleton z
p₁ _ h = ∪-d₂ _ _ (∨-prop₅ (pair-d₁ _ _ h) (singletonp₃ _) (singletonp₃ _))
p₂ : (x : 𝓢) → x ∈ singleton y ∪ singleton z → x ∈ y ₚ z
p₂ x h = pair-d₂ _ _ (∨-prop₅ (∪-d₁ _ _ h) (singletonp _) (singletonp _))
-- Ordered pairs
_ₒ_ : 𝓢 → 𝓢 → 𝓢
x ₒ y = singleton x ₚ (x ₚ y)
-- Just an abvreviation for next theorem
abv₁ : 𝓢 → 𝓢 → 𝓢 → 𝓢 → Set
abv₁ u x v y = (u ₚ u ≡ x ₚ x ∧ u ₚ v ≡ x ₚ y) ∨ (u ₚ v ≡ x ₚ x ∧ u ₚ u ≡ x ₚ y)
-- Theorem 46, p. 32 (Suppes).
ord-p : (x y u v : 𝓢) → x ₒ y ≡ u ₒ v → x ≡ u ∧ y ≡ v
ord-p x y u v eq = ∨-e _ _ _ aux a→c b→c
where
aux : (singleton u ≡ singleton x ∧ (u ₚ v) ≡ (x ₚ y)) ∨
((u ₚ v) ≡ singleton x ∧ singleton u ≡ (x ₚ y))
aux = pair-prop _ _ _ _ eq
a→c : singleton u ≡ singleton x ∧ u ₚ v ≡ x ₚ y → x ≡ u ∧ y ≡ v
a→c (eqₚ , eqₛ) = x≡u , y≡v
where
x≡u : x ≡ u
x≡u = singleton-eq _ _ (sym _ _ eqₚ)
p₁ : (x ≡ u ∧ y ≡ v) ∨ (y ≡ u ∧ x ≡ v)
p₁ = pair-prop _ _ _ _ eqₛ
p₂ : x ≡ u ∧ y ≡ v → y ≡ v
p₂ (h₁ , h₂) = h₂
p₃ : y ≡ u ∧ x ≡ v → y ≡ v
p₃ (h₁ , h₂) = subs (λ w → w ≡ v) x≡y h₂
where
x≡y : x ≡ y
x≡y = subs (λ w → x ≡ w) (sym y u h₁) x≡u
y≡v : y ≡ v
y≡v = ∨-e _ _ _ p₁ p₂ p₃
b→c : u ₚ v ≡ singleton x ∧ singleton u ≡ x ₚ y → x ≡ u ∧ y ≡ v
b→c (h₁ , h₂) = p₃ , subs (λ w → w ≡ v) p₈ p₄
where
p₁ : (x ≡ u ∧ x ≡ v) ∨ (x ≡ u ∧ x ≡ v)
p₁ = pair-prop _ _ _ _ h₁
p₂ : x ≡ u ∧ x ≡ v
p₂ = ∨-idem _ p₁
p₃ : x ≡ u
p₃ = ∧-proj₁ p₂
p₄ : x ≡ v
p₄ = ∧-proj₂ p₂
p₅ : (x ≡ u ∧ y ≡ u) ∨ (y ≡ u ∧ x ≡ u)
p₅ = pair-prop _ _ _ _ h₂
p₆ : x ≡ u ∧ y ≡ u
p₆ = ∨-∧ p₅
p₇ : y ≡ u
p₇ = ∧-proj₂ p₆
p₈ : x ≡ y
p₈ = subs (λ w → w ≡ y) (sym _ _ p₃) (sym _ _ p₇)
-- Power sets
𝓟_ : 𝓢 → 𝓢
𝓟 x = proj₁ (pow x)
-- Theorem 86, p. 47 (Suppes 1960)
𝓟-d : (x : 𝓢) → ∀ {z} → z ∈ (𝓟 x) ⇔ z ⊆ x
𝓟-d x = proj₂ _ (pow x)
-- Both projections.
𝓟-d₁ : (x : 𝓢) → ∀ {z} → z ∈ (𝓟 x) → z ⊆ x
𝓟-d₁ _ = ∧-proj₁ (𝓟-d _)
𝓟-d₂ : (x : 𝓢) → ∀ {z} → z ⊆ x → z ∈ (𝓟 x)
𝓟-d₂ _ = ∧-proj₂ (𝓟-d _)
-- Theorem 87, p. 47 (Suppes 1960).
A∈𝓟A : (A : 𝓢) → A ∈ 𝓟 A
A∈𝓟A A = 𝓟-d₂ A subsetOfItself
-- Theorem 91, p. 48 (Suppes 1960).
⊆𝓟 : (A B : 𝓢) → A ⊆ B ⇔ 𝓟 A ⊆ 𝓟 B
⊆𝓟 A B = iₗ , iᵣ
where
iₗ : A ⊆ B → 𝓟 A ⊆ 𝓟 B
iₗ A⊆B t t∈𝓟A = 𝓟-d₂ _ t⊆B
where
t⊆A : t ⊆ A
t⊆A = 𝓟-d₁ A t∈𝓟A
t⊆B : t ⊆ B
t⊆B = trans-⊆ _ _ _ (t⊆A , A⊆B)
iᵣ : 𝓟 A ⊆ 𝓟 B → A ⊆ B
iᵣ 𝓟A⊆𝓟B t t∈A = 𝓟-d₁ _ A∈𝓟B _ t∈A
where
A∈𝓟B : A ∈ 𝓟 B
A∈𝓟B = 𝓟A⊆𝓟B _ (A∈𝓟A _)
-- Theorem 92, p. 48 (Suppes 1960).
𝓟∪ : (A B : 𝓢) → (𝓟 A) ∪ (𝓟 B) ⊆ 𝓟 (A ∪ B)
𝓟∪ A B t t∈𝓟A∪𝓟B = 𝓟-d₂ _ t⊆A∪B
where
∪₁ : t ∈ 𝓟 A ∨ t ∈ 𝓟 B
∪₁ = ∪-d₁ _ _ t∈𝓟A∪𝓟B
p : t ⊆ A ∨ t ⊆ B
p = ∨-prop₄ aux₁ (𝓟-d₁ _)
where
aux₁ : t ⊆ A ∨ t ∈ 𝓟 B
aux₁ = ∨-prop₃ ∪₁ (𝓟-d₁ _)
t⊆A∪B : t ⊆ A ∪ B
t⊆A∪B = ∪-prop₂ _ _ _ p
-- Cartesian Product. First we have to prove some things using
-- the subset axiom in order to be able to define cartesian products.
-- Two abvreviations to make sub₄ shorter.
abv₂ : 𝓢 → 𝓢 → 𝓢 → Set
abv₂ z A B = z ∈ 𝓟 (𝓟 (A ∪ B))
abv₃ : 𝓢 → 𝓢 → 𝓢 → Set
abv₃ z A B = ∃ (λ y → ∃ (λ w → (y ∈ A ∧ w ∈ B) ∧ z ≡ y ₒ w))
--Instance of the subset axiom.
sub₄ : (A B : 𝓢) → ∃ (λ C → {z : 𝓢} → z ∈ C ⇔ abv₂ z A B ∧ abv₃ z A B)
sub₄ A B = sub (λ x → abv₃ x A B) (𝓟 (𝓟 (A ∪ B)))
-- Proved inside theorem 95, p. 49 (Suppes 1960)
prop₁ : (A B x : 𝓢) → abv₃ x A B → abv₂ x A B
prop₁ A B x (y , (z , ((y∈A , z∈B) , eqo))) = subs _ (sym _ _ eqo) yₒz∈𝓟𝓟A∪B
where
yₛ⊆A : singleton y ⊆ A
yₛ⊆A = singleton-⊆ _ _ y∈A
yₛ⊆A∪B : singleton y ⊆ A ∪ B
yₛ⊆A∪B t t∈yₛ = trans-⊆ _ _ _ (yₛ⊆A , (∪-prop _ _)) _ t∈yₛ
zₛ⊆B : singleton z ⊆ B
zₛ⊆B = singleton-⊆ _ _ z∈B
zₛ⊆A∪B : singleton z ⊆ A ∪ B
zₛ⊆A∪B t t∈zₛ = trans-⊆ _ _ _ (zₛ⊆B , ∪-prop₃ _ _) _ t∈zₛ
y,z⊆A∪B : y ₚ z ⊆ A ∪ B
y,z⊆A∪B t t∈y,z = ∪-prop₄ _ _ _ yₛ⊆A∪B zₛ⊆A∪B _ p
where
p : t ∈ singleton y ∪ singleton z
p = subs (λ w → t ∈ w) (prop-p₂ y z) t∈y,z
yₛ∈𝓟A∪B : singleton y ∈ 𝓟 (A ∪ B)
yₛ∈𝓟A∪B = 𝓟-d₂ _ yₛ⊆A∪B
y,z∈𝓟A∪B : y ₚ z ∈ 𝓟 (A ∪ B)
y,z∈𝓟A∪B = 𝓟-d₂ _ y,z⊆A∪B
yₒz⊆𝓟A∪B : y ₒ z ⊆ 𝓟 (A ∪ B)
yₒz⊆𝓟A∪B t t∈o = ∨-e _ _ _ (pair-d₁ _ _ t∈o) i₁ i₂
where
i₁ : t ≡ singleton y → t ∈ 𝓟 (A ∪ B)
i₁ eq = subs _ (sym t (singleton y) eq) yₛ∈𝓟A∪B
i₂ : t ≡ y ₚ z → t ∈ 𝓟 (A ∪ B)
i₂ eq = subs _ (sym t (y ₚ z) eq) y,z∈𝓟A∪B
yₒz∈𝓟𝓟A∪B : y ₒ z ∈ 𝓟 (𝓟 (A ∪ B))
yₒz∈𝓟𝓟A∪B = 𝓟-d₂ _ yₒz⊆𝓟A∪B
Aᵤ : 𝓢 → 𝓢 → 𝓢
Aᵤ A B = proj₁ (sub₄ A B)
-- Theorem 95, p 49 (Suppes 1960).
pAᵤ : (A B : 𝓢) → {z : 𝓢} → z ∈ (Aᵤ A B) ⇔ abv₂ z A B ∧ abv₃ z A B
pAᵤ A B = proj₂ _ (sub₄ A B)
crts : (A B : 𝓢) → ∃ (λ C → (z : 𝓢) → z ∈ C ⇔ abv₃ z A B)
crts A B = (Aᵤ A B) , (λ w → ⇔-p₂ w (pAᵤ A B) (prop₁ A B w))
_X_ : 𝓢 → 𝓢 → 𝓢
A X B = proj₁ (crts A B)
-- Theorem 97, p. 50 (Suppes 1960).
crts-p : (A B x : 𝓢) → x ∈ A X B ⇔ abv₃ x A B
crts-p A B x = proj₂ _ (crts A B) x
-- Both projections
crts-p₁ : (A B x : 𝓢) → x ∈ A X B → abv₃ x A B
crts-p₁ A B x = ∧-proj₁ (crts-p A B x)
crts-p₂ : (A B x : 𝓢) → abv₃ x A B → x ∈ A X B
crts-p₂ A B x = ∧-proj₂ (crts-p A B x)
crts-d₁ : (x y A B : 𝓢) → x ₒ y ∈ A X B → x ∈ A ∧ y ∈ B
crts-d₁ x y A B h = (subs (λ w → w ∈ A) (sym _ _ eq₁) aux∈A)
,
subs (λ w → w ∈ B) (sym _ _ eq₂) aux₂∈B
where
foo : ∃ (λ z → ∃ (λ w → (z ∈ A ∧ w ∈ B) ∧ (x ₒ y) ≡ (z ₒ w)))
foo = crts-p₁ A B (x ₒ y) h
aux : 𝓢
aux = proj₁ foo
aux-p : ∃ (λ w → (aux ∈ A ∧ w ∈ B) ∧ (x ₒ y) ≡ (aux ₒ w))
aux-p = proj₂ _ foo
aux₂ : 𝓢
aux₂ = proj₁ aux-p
aux₂-p : (aux ∈ A ∧ aux₂ ∈ B) ∧ (x ₒ y) ≡ (aux ₒ aux₂)
aux₂-p = proj₂ _ aux-p
aux∈A : aux ∈ A
aux∈A = ∧-proj₁ (∧-proj₁ aux₂-p)
aux₂∈B : aux₂ ∈ B
aux₂∈B = ∧-proj₂ (∧-proj₁ aux₂-p)
eq : x ₒ y ≡ aux ₒ aux₂
eq = ∧-proj₂ aux₂-p
eqs : x ≡ aux ∧ y ≡ aux₂
eqs = ord-p _ _ _ _ eq
eq₁ : x ≡ aux
eq₁ = ∧-proj₁ eqs
eq₂ : y ≡ aux₂
eq₂ = ∧-proj₂ eqs
-- References
--
-- Suppes, Patrick (1960). Axiomatic Set Theory.
-- The University Series in Undergraduate Mathematics.
-- D. Van Nostrand Company, inc.
--
-- Enderton, Herbert B. (1977). Elements of Set Theory.
-- Academic Press Inc.
|
Require Export MoreCoq.
Check (3=3).
Check (forall (n : nat), n = 2).
Theorem silly :
0 * 3 = 0.
reflexivity.
Qed.
Print silly.
Check eq_refl.
Check Prop.
Check silly.
Theorem silly_1 :
forall (n:nat),
n = n.
reflexivity.
Qed.
Check silly_1.
Check (0*3 =0).
Check (0).
Check (forall (n m:nat),n = m).
Check (eq_refl).
Print silly.
Lemma silly_implication :
(1+1)=2 -> 0*3 = 0.
intros H.
reflexivity.
Qed.
Print silly_implication.
Print silly_1.
Check mult.
Check (nat -> nat -> nat).
Check (forall p q, p -> q).
Inductive and (P Q : Prop) : Prop :=
conj : P -> Q -> (and P Q).
Notation "P /\ Q" := (and P Q) : type_scope.
Check and.
Check (conj).
Check (forall (p : Prop), p -> p -> and p p).
Check (0 = 0).
Check (nat).
Theorem aaaaaa:
Prop -> Prop -> Prop.
apply and.
Qed.
Theorem and_example :
(0 = 0) /\ (4 = mult 2 2).
apply conj.
reflexivity.
reflexivity.
Qed.
Print and_example.
Print conj.
Print and.
Theorem proj1 :
forall (P Q : Prop),
P /\ Q -> P.
intros P Q H.
destruct H.
apply H.
Qed.
Print proj1.
Check proj1.
Theorem and_commut :
forall (P Q : Prop),
P /\ Q -> Q /\ P.
intros P Q.
intros H.
destruct H.
apply conj.
apply H0.
apply H.
Qed.
Theorem and_assoc :
forall (P Q R : Prop),
P /\ ( Q /\ R ) -> (P /\ Q) /\ R.
intros P Q R h.
destruct h.
destruct H0.
apply conj.
apply conj.
apply H.
apply H0.
apply H1.
Qed.
Definition iff ( P Q :Prop) := (P -> Q) /\ (Q /\ P).
Notation "P <-> Q" := (iff P Q)
(at level 95, no associativity)
: type_scope.
Theorem iff_implies :
forall (P Q :Prop),
(P <-> Q) -> P -> Q.
intros P Q.
intros H.
intros H1.
destruct H.
apply H in H1.
apply H1.
Qed.
Theorem iff_sym :
forall (P Q : Prop),
(P <-> Q) -> (Q <-> P).
intros P Q h.
destruct h.
destruct H0.
apply conj.
intros q.
apply H1.
apply conj.
apply H1.
apply H0.
Qed.
Inductive or (P Q : Prop) : Prop :=
| or_introl : P -> or P Q
| or_intror : Q -> or P Q.
Notation "P \/ Q" := (or P Q) : type_scope.
Check (or_introl).
Theorem or_commut :
forall (P Q : Prop),
P \/ Q -> Q \/ P.
intros P Q h.
destruct h.
apply or_intror.
apply H.
apply or_introl.
apply H.
Qed.
Theorem or_distributes_over_and_1 :
forall (P Q R : Prop),
P \/ (Q /\ R) -> (P \/ Q) /\ (P \/ R).
intros P Q R h.
apply conj.
destruct h.
left.
apply H.
destruct H.
right.
apply H.
destruct h.
left.
apply H.
destruct H.
right.
apply H0.
Qed.
Theorem andb_prop :
forall (b c : bool),
andb b c = true ->
b = true /\ c = true.
intros b c h.
unfold andb in h.
destruct b.
rewrite -> h.
apply conj.
reflexivity.
reflexivity.
apply conj.
apply h.
inversion h.
Qed.
Check true.
Check and.
Inductive False : Prop :=.
Theorem False_implies_nonsense :
False -> 2 + 2 = 5.
intros h.
inversion h.
Qed.
Theorem False_iiiiiiiiiii :
False -> 1 + 1 = 3.
intros h.
destruct h.
Qed.
Theorem nonsense_implies_False :
2 + 2 = 5 -> False.
intros h.
inversion h.
Qed.
Inductive Truth : Prop :=
| fact : Truth.
Definition not (P : Prop) := P -> False.
Notation "~ x" := (not x) : type_scope.
Check not.
Theorem contradiction_implies_anything :
forall (P Q :Prop),
(P /\ (~P)) -> Q.
intros P Q.
intros H.
unfold not in H.
destruct H.
apply H0 in H.
inversion H.
Qed.
Theorem double_neg :
forall (P : Prop),
P -> ~~P.
intros P p.
unfold not.
unfold not.
intros h.
apply h in p.
inversion p.
Qed.
Definition peirce :=
forall (P Q : Prop),
((P -> Q) -> P) -> P.
Definition classic :=
forall (P : Prop),
~~P -> P.
Theorem O :
peirce <-> classic.
apply conj.
intro h.
unfold peirce in h.
unfold classic.
unfold not.
intro P.
intro h1.
Abort.
Theorem contrapositive:
forall (P Q : Prop),
(P -> Q) -> (~Q -> ~P).
intros P Q.
intros h.
unfold not.
intros h1.
intros p.
apply h in p.
apply h1 in p.
destruct p.
Qed.
Theorem not_False:
False -> False.
intros h.
inversion h.
Qed.
Print not_False.
Theorem excluded_middle_irrefutable:
forall (P : Prop),
~~(P \/ (~P)).
intros p.
unfold not.
intros h.
apply h.
right.
intros p1.
apply h.
left.
apply p1.
Qed.
Print excluded_middle_irrefutable.
Theorem peirce_classic :
peirce -> classic.
unfold peirce.
unfold classic.
intros h.
unfold not.
intros P.
assert (((P -> False) -> P) -> P) as H.
apply h.
intros h1.
apply H.
intro h2.
apply h1 in h2.
inversion h2.
Qed.
Definition excluded_middle :=
forall (P : Prop),
P \/ ~P.
Theorem classic_excluded_middle :
classic -> excluded_middle.
unfold classic.
unfold excluded_middle.
intros H.
intros P.
assert (~~(P\/~P)) as h.
apply excluded_middle_irrefutable.
apply H in h.
apply h.
Qed.
Definition de_morgan_not_and_not :=
forall (P Q :Prop),
~(~P /\ ~Q) -> P\/Q.
(*
Theorem excluded_middle_de_morgan_not_and_not :
classic -> de_morgan_not_and_not.
unfold de_morgan_not_and_not.
unfold classic.
unfold not.
intros h.
intros p q.
intros h1.
apply h.
intros h2.
apply h1.
apply conj.
intros p1.
apply h2.
left.
apply p1.
intros q1.
apply h2.
right.
apply q1.
Qed.
*)
Theorem excluded_middle_classic :
excluded_middle -> classic.
unfold excluded_middle.
unfold classic.
unfold not.
intros h1.
intros p.
intros h.
assert (p \/ (p -> False)) as H.
apply h1.
destruct H.
apply H.
apply h in H.
inversion H.
Qed.
Theorem excluded_middle_de_morgan_not_and_not :
excluded_middle -> de_morgan_not_and_not.
unfold excluded_middle.
unfold de_morgan_not_and_not.
unfold not.
intros h.
intros p q.
intro h1.
assert (p \/ ( p -> False)) as H.
apply h.
destruct H.
left.
apply H.
assert (q \/ (q -> False)) as H2.
apply h.
destruct H2.
right.
apply H0.
assert ((p -> False) /\ (q -> False)) as H3.
apply conj.
apply H.
apply H0.
apply h1 in H3.
inversion H3.
Qed.
Definition implies_to_or :=
forall p q:Prop,
(p -> q) -> (~p\/q).
Theorem de_morgan_not_and_not_implies_to_or:
de_morgan_not_and_not -> implies_to_or.
unfold de_morgan_not_and_not.
unfold implies_to_or.
unfold not.
intros H.
intros p q.
intros h1.
apply H.
intros h2.
destruct h2.
apply H0.
intros p'.
apply H1.
apply h1.
apply p'.
Qed.
Theorem implies_to_or_peirce :
implies_to_or -> peirce.
unfold implies_to_or.
unfold peirce.
unfold not.
intros H.
intros p q.
intros h.
assert ((p -> p) -> (p -> False) \/ p) as h1.
apply H.
assert ( p->p) as h2.
intros p'.
apply p'.
apply h1 in h2.
destruct h2.
apply h.
intros p'.
apply H0 in p'.
inversion p'.
apply H0.
Qed.
(* Please all use excluded_middle *)
Notation "x <> y" := (~ (x = y)) : type_scope.
Theorem not_false_then_true :
forall (b : bool),
b <> false -> b = true.
intros b.
intros h.
destruct b.
reflexivity.
unfold not in h.
assert (false = false) as h'.
reflexivity.
apply h in h'.
inversion h'.
Qed.
|
/// \file python_module.cpp
///
/// \brief This contains the bindings
///
/// \details To facilitate quick building, we create a single Python binary
/// module. We programmatically create scopes to create submodules
/// from a single file. This integrates with the Python code which
/// follows the regular folder structure/submodule layout.
/// We also flatten the esl namespaces through usage of the 'using'
/// namespace declaration.
///
/// We simplify the interface to the identity<t> system, by
/// creating a python_identity type that can be converted without
/// checking to all other identities.
///
///
/// \authors Maarten P. Scholl
/// \date 2020-08-30
/// \copyright Copyright 2017-2020 The Institute for New Economic Thinking,
/// Oxford Martin School, University of Oxford
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing,
/// software distributed under the License is distributed on an "AS
/// IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
/// express or implied. See the License for the specific language
/// governing permissions and limitations under the License.
///
/// You may obtain instructions to fulfill the attribution
/// requirements in CITATION.cff
///
#include <esl/python_module_esl.hpp>
#ifdef WITH_PYTHON
using namespace boost::python;
#include <boost/python/to_python_converter.hpp> // to_python
////////////////////////////////////////////////////////////////////////////////
// utility
////////////////////////////////////////////////////////////////////////////////
#include <boost/shared_ptr.hpp>
#include <boost/smart_ptr/make_shared.hpp>
#include <random>
boost::shared_ptr<std::seed_seq> construct_seed_seq_from_list(boost::python::list list)
{
std::vector<std::seed_seq::result_type> result_;
for(boost::python::ssize_t i = 0; i < boost::python::len(list); ++i) {
result_.push_back(boost::python::extract<std::seed_seq::result_type>(list[i]));
}
return boost::make_shared<std::seed_seq>(result_.begin(), result_.end());
}
///
/// \brief
///
/// \tparam object_t_
template<typename object_t_>
void do_release(typename boost::shared_ptr<object_t_> const &, object_t_ *)
{
}
template<typename object_t_>
typename std::shared_ptr<object_t_> to_std(typename boost::shared_ptr<object_t_> const &p)
{
return std::shared_ptr<object_t_>(p.get(), [p](auto &&PH1)
{
return do_release<object_t_>(p, std::forward<decltype(PH1)>(PH1));
});
}
template<typename object_t_>
boost::shared_ptr<object_t_> to_boost(std::shared_ptr<object_t_>& ptr)
{
return boost::shared_ptr<object_t_>(ptr.get(), [ptr](object_t_ *) mutable
{
ptr.reset();
});
}
#include <optional>
template<typename element_t_>
boost::python::object optional_to_python(const std::optional<element_t_> &o)
{
if(o.has_value()){
return boost::python::object(o.value());
}
return boost::python::object(); // Python's None
}
////////////////////////////////////////////////////////////////////////////////
// map indexing suite
# include <boost/python/suite/indexing/indexing_suite.hpp>
// Forward declaration
template <class Container, bool NoProxy, class DerivedPolicies>
class map_indexing_suite;
namespace detail2
{
template <class Container, bool NoProxy>
class final_map_derived_policies
: public map_indexing_suite<Container,
NoProxy, final_map_derived_policies<Container, NoProxy> >
{
};
}
// By default indexed elements are returned by proxy. This can be
// disabled by supplying *true* in the NoProxy template parameter.
//
template <
class Container,
bool NoProxy = false,
class DerivedPolicies
= detail2::final_map_derived_policies<Container, NoProxy> >
class map_indexing_suite
: public indexing_suite<
Container
, DerivedPolicies
, NoProxy
, true
, typename Container::value_type::second_type
, typename Container::key_type
, typename Container::key_type
>
{
public:
typedef typename Container::value_type value_type;
typedef typename Container::value_type::second_type data_type;
typedef typename Container::key_type key_type;
typedef typename Container::key_type index_type;
typedef typename Container::size_type size_type;
typedef typename Container::difference_type difference_type;
template <class Class>
static void
extension_def(Class& cl)
{
cl.def("keys", &keys);
cl.def("values", &values);
// Wrap the map's element (value_type)
std::string elem_name = "map_indexing_suite_";
object class_name(cl.attr("__name__"));
extract<std::string> class_name_extractor(class_name);
elem_name += class_name_extractor();
elem_name += "_entry";
typedef typename boost::mpl::if_<
boost::mpl::and_<boost::is_class<data_type>, boost::mpl::bool_<!NoProxy> >
, return_internal_reference<>
, default_call_policies
>::type get_data_return_policy;
class_<value_type>(elem_name.c_str())
.def("__repr__", &DerivedPolicies::print_elem)
.def("data", &DerivedPolicies::get_data, get_data_return_policy())
.def("key", &DerivedPolicies::get_key)
;
}
static object
print_elem(typename Container::value_type const& e)
{
return "(%s, %s)" % boost::python::make_tuple(e.first, e.second);
}
static
typename boost::mpl::if_<
boost::mpl::and_<boost::is_class<data_type>, boost::mpl::bool_<!NoProxy> >
, data_type&
, data_type
>::type
get_data(typename Container::value_type& e)
{
return e.second;
}
static typename Container::key_type
get_key(typename Container::value_type& e)
{
return e.first;
}
static data_type&
get_item(Container& container, index_type i_)
{
auto i = container.find(i_);
if (i == container.end()){
PyErr_SetString(PyExc_KeyError, "Invalid key");
throw_error_already_set();
}
return i->second;
}
static void
set_item(Container& container, index_type i, data_type const& v)
{
container[i] = v;
}
static void
delete_item(Container& container, index_type i)
{
container.erase(i);
}
static size_t
size(Container& container)
{
return container.size();
}
static bool
contains(Container& container, key_type const& key)
{
return container.find(key) != container.end();
}
static bool
compare_index(Container& container, index_type a, index_type b)
{
return container.key_comp()(a, b);
}
[[nodiscard]] static boost::python::list keys(const Container &container)
{
boost::python::list result_;
for(const auto &[k, v]: container){
result_.append(k);
}
return result_;
}
[[nodiscard]] static boost::python::list values(const Container &container)
{
boost::python::list result_;
for(const auto &[k, v]: container){
result_.append(v);
}
return result_;
}
static index_type
convert_index(Container& /*container*/, PyObject* i_)
{
extract<key_type const&> i(i_);
if (i.check())
{
return i();
}else{
extract<key_type> i(i_);
if (i.check())
return i();
}
PyErr_SetString(PyExc_TypeError, "Invalid index type");
throw_error_already_set();
return index_type();
}
};
////////////////////////////////////////////////////////////////////////////////
// esl top level
////////////////////////////////////////////////////////////////////////////////
#include <esl/agent.hpp>
#include <esl/exception.hpp>
#include <esl/version.hpp>
#include <esl/quantity.hpp>
using namespace esl;
#include <esl/simulation/identity.hpp>
using esl::python_identity;
class python_agent
: public agent
, public boost::python::wrapper<agent>
{
public:
python_agent(python_identity i)
: agent(reinterpret_identity_cast<agent>(i))
{
}
simulation::time_point act(simulation::time_interval step,
std::seed_seq &seed) override
{
auto o = get_override("act");
if(o){
boost::python::object result_ = o(step, boost::ref(seed));
if(result_.is_none()){
return simulation::time_point(step.upper);
}
return boost::python::extract<simulation::time_point>(result_);
}
return agent::act(step, boost::ref(seed));
}
std::string describe() const override
{
auto o = get_override("describe");
if(o){
boost::python::object result_ = o();
return boost::python::extract<std::string>(result_);
}
return agent::describe();
}
};
///
/// \brief Translates C++ exceptions to Python errors, by setting the
/// Python error text equal to the C++ exception message.
///
/// \details This is a fallback converter for all exceptions,
/// we can design more friendly converters
///
/// \param e
void translate_exception(const exception &e)
{
PyErr_SetString ( PyExc_RuntimeError, e.what());
}
////////////////////////////////////////////////////////////////////////////////
// esl.computation
////////////////////////////////////////////////////////////////////////////////
#include <esl/computation/python_module_computation.hpp>
#include <esl/computation/block_pool.hpp>
#include <esl/computation/environment.hpp>
#include <esl/computation/timing.hpp>
using namespace esl::computation;
///
/// \brief This class enables access to the computation::environment
/// internal functions for Python derived classes.
///
/// \details Python does not have access via inheritance of protected
/// members, so we need to make everything public
///
class python_environment
: public esl::computation::environment
, public wrapper<esl::computation::environment>
{
public:
python_environment()
: esl::computation::environment()
{
}
virtual ~python_environment() = default;
void step(simulation::model &simulation) override
{
boost::python::override method_ = get_override("step");
if(!method_.is_none()){
method_(simulation);
return;
}
environment::step(simulation);
}
void run(simulation::model &simulation) override
{
boost::python::override o = get_override("run");
if(!o.is_none()){
o(simulation);
return;
}
environment::run(simulation);
}
size_t activate() override
{
boost::python::override method_ = get_override("activate");
if(!method_.is_none()){
boost::python::object result_ = method_();
return boost::python::extract<size_t>(result_);
}
return environment::activate();
}
size_t deactivate() override
{
boost::python::override method_ = get_override("deactivate");
if(!method_.is_none()){
boost::python::object result_ = method_();
return boost::python::extract<size_t>(result_);
}
return environment::deactivate();
}
void before_step() override
{
boost::python::override method_ = get_override("before_step");
if(!method_.is_none()){
method_();
}else {
environment::before_step();
}
}
void after_step(simulation::model &simulation) override
{
boost::python::override method_ = get_override("after_step");
if(!method_.is_none()){
method_(simulation);
}else{
environment::after_step(simulation);
}
}
void after_run(simulation::model &simulation) override
{
boost::python::override method_ = get_override("after_run");
if(!method_.is_none()){
method_(simulation);
}else {
environment::after_run(simulation);
}
}
void activate_agent_python(const python_identity a)
{
environment::activate_agent(reinterpret_identity_cast<agent>(a));
}
void deactivate_agent_python(const python_identity a)
{
environment::deactivate_agent(reinterpret_identity_cast<agent>(a));
}
size_t send_messages(simulation::model &simulation)
{
boost::python::override method_ = get_override("send_messages");
if(!method_.is_none()){
boost::python::object result_ = method_(simulation);
return boost::python::extract<size_t>(result_);
}else {
return environment::send_messages(simulation);
}
}
};
////////////////////////////////////////////////////////////////////////////////
// esl.computation.distributed
////////////////////////////////////////////////////////////////////////////////
#include <esl/computation/distributed/protocol.hpp>
using namespace esl::computation::distributed;
////////////////////////////////////////////////////////////////////////////////
// esl.data
////////////////////////////////////////////////////////////////////////////////
#include <esl/data/severity.hpp>
#include <esl/data/log.hpp>
void python_log_detailed( esl::data::severity level
, boost::python::object o
, const std::string &function
, const std::string &file
, size_t line
)
{
auto render_ = boost::python::extract<const char *>(boost::python::str(o));
switch(level){
case severity::trace:
main_log.get<severity::trace>(function.c_str(), file.c_str(), line) << render_ << std::endl;
break;
case severity::notice:
main_log.get<severity::notice>(function.c_str(), file.c_str(), line) << render_ << std::endl;
break;
case severity::warning:
main_log.get<severity::notice>(function.c_str(), file.c_str(), line) << render_ << std::endl;
break;
case severity::errorlog:
main_log.get<severity::notice>(function.c_str(), file.c_str(), line) << render_ << std::endl;
break;
default:
break;
}
}
////////////////////////////////////////////////////////////////////////////////
//esl.economics
////////////////////////////////////////////////////////////////////////////////
#include <esl/economics/iso_4217.hpp>
#include <esl/economics/currencies.hpp>
#include <esl/economics/price.hpp>
#include <esl/economics/company.hpp>
using namespace esl::economics;
#include <esl/law/jurisdiction.hpp>
#include <esl/law/organization.hpp>
using namespace esl::law;
std::string python_currency_code(const iso_4217 &c)
{
return (std::string() + c.code[0]) + c.code[1];
}
double python_price_to_floating_point(const price &p)
{
return double(p);
}
struct python_organization
: public virtual organization
, public wrapper<organization>
{
python_organization(const python_identity &i, const jurisdiction &j)
: organization(reinterpret_identity_cast<organization>(i),j)
{
}
};
struct python_company
: public company
, public wrapper<company>
{
public:
python_company(const python_identity &i, const law::jurisdiction &j)
: company(reinterpret_identity_cast<company>(i),j)
, wrapper<company>()
{
}
std::optional<finance::dividend_policy>
upcoming_dividend(simulation::time_interval interval,
std::seed_seq &seed) override
{
boost::python::override policy_ = wrapper<company>::get_override("upcoming_dividend")(interval, seed);
if(policy_.is_none()){
return {};
}
return extract<finance::dividend_policy>(policy_);
}
};
////////////////////////////////////////////////////////////////////////////////
//esl.economics.accounting
////////////////////////////////////////////////////////////////////////////////
#include <esl/economics/accounting/standard.hpp>
using namespace esl::economics::accounting;
//we need to forward declare items from the finance submodule
#include <esl/economics/finance/stock.hpp>
#include <esl/economics/finance/bond.hpp>
#include <esl/economics/cash.hpp>
using namespace esl::economics::finance;
// because python has no ad-hoc polymorphism for function overloads,
// we need to wrap these.
price value_money(standard &s, const money &p, const quantity &q)
{
return s.value(p, q);
}
price value_cash(standard &s, const cash &p, const quantity &q)
{
return s.value(p, q);
}
price value_stock(standard &s, const stock &p, const quantity &q)
{
return s.value(p, q);
}
price value_loan(standard &s, const loan &p, const quantity &q)
{
return s.value(p, q);
}
price value_securities_lending_contract(standard &s, const securities_lending_contract &p, const quantity &q)
{
return s.value(p, q);
}
////////////////////////////////////////////////////////////////////////////////
// esl.economics.finance
////////////////////////////////////////////////////////////////////////////////
#include <esl/economics/finance/share_class.hpp>
#include <esl/economics/finance/isin.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
std::string get_isin_code(const finance::isin &i)
{
return std::string(i.code.data(), i.code.data() + i.code.size());
}
void set_isin_code(finance::isin &i, const std::string &code)
{
i.code = esl::to_array<0,9,char>(code);
}
////////////////////////////////////////////////////////////////////////////////
// esl.economics.markets
////////////////////////////////////////////////////////////////////////////////
#include <esl/economics/markets/quote.hpp>
#include <esl/economics/markets/iso_10383.hpp>
#include <esl/economics/markets/ticker.hpp>
using namespace esl::economics::markets;
price quote_helper_get_price(const quote &q)
{
auto p = std::get_if<price>(&q.type);
return *p;
}
void quote_helper_set_price(quote &q, price p)
{
q.type = p;
}
double quote_helper_operator_double(const quote &q)
{
return double(q);
}
boost::shared_ptr<quote> construct_quote_from_price(price p)
{
return boost::make_shared<quote>(p);
}
boost::shared_ptr<quote> construct_quote_from_exchange_rate(const exchange_rate &e)
{
return boost::make_shared<quote>(e);
}
boost::shared_ptr<ticker> python_ticker_constructor(const python_identity &base_property = python_identity()
, const python_identity "e_property = python_identity())
{
return boost::make_shared<ticker>( reinterpret_identity_cast<esl::law::property>(base_property)
, reinterpret_identity_cast<esl::law::property>(quote_property));
}
////////////////////////////////////////////////////////////////////////////////
// esl.economics.markets.order_book
////////////////////////////////////////////////////////////////////////////////
#include <esl/economics/markets/order_book/basic_book.hpp>
#include <esl/economics/markets/order_book/binary_tree_order_book.hpp>
#include <esl/economics/markets/order_book/static_order_book.hpp>
#include <esl/economics/markets/order_book/matching_engine.hpp>
#include <esl/economics/markets/order_book/python_module_order_book.hpp>
using namespace esl::economics::markets::order_book;
boost::shared_ptr<limit_order> python_limit_order_message_constructor
(ticker symbol
, const python_identity &owner
, limit_order::side_t side
, const quote &limit
, std::uint64_t quantity
, limit_order::lifetime_t lifetime // = good_until_cancelled
)
{
return boost::make_shared<limit_order>(
symbol, reinterpret_identity_cast<agent>(owner), side, limit, quantity, lifetime
);
}
////////////////////////////////////////////////////////////////////////////////
// esl.economics.markets.walras
////////////////////////////////////////////////////////////////////////////////
//#include <esl/economics/markets/walras/python_module_walras.hpp>
#include <esl/economics/markets/walras/price_setter.hpp>
#include <esl/economics/markets/walras/tatonnement.hpp>
using namespace esl::economics::markets::walras;
class python_differentiable_order_message
: public esl::economics::markets::walras::differentiable_order_message
, public wrapper<esl::economics::markets::walras::differentiable_order_message>
{
public:
python_differentiable_order_message(
const python_identity &sender = python_identity(),
const python_identity& recipient = python_identity(),
esl::simulation::time_point sent = esl::simulation::time_point(),
esl::simulation::time_point received = esl::simulation::time_point())
: esl::economics::markets::walras::differentiable_order_message
( esl::reinterpret_identity_cast<esl::agent>(sender)
, esl::reinterpret_identity_cast<esl::agent>(recipient)
, sent
, received)
, wrapper<esl::economics::markets::walras::differentiable_order_message>()
{
}
// the default implementation is to demand zero for all
[[nodiscard]] std::map<esl::identity<esl::law::property>, esl::variable> excess_demand(const std::map<
esl::identity<esl::law::property>
, std::tuple<quote, esl::variable>> "es) const override
{
dict quotes_;
for(const auto &[i, v]: quotes){
auto t = make_tuple(std::get<0>(v), esl::value(std::get<1>(v)));
quotes_.setdefault(i, t);
}
// specify the type, so that the return value is converted to python::object
//boost::python::override return_value_ = get_override("excess_demand")(quotes_);
boost::python::override method_ = get_override("excess_demand");
if(!method_.is_none()){
boost::python::object return_value_ = method_(quotes_);
dict excess_ = extract<dict>(return_value_);
auto keys = list(excess_.keys());
auto values = list(excess_.values());
std::map<esl::identity<esl::law::property>, esl::variable> result_;
for(int i = 0; i < len(keys); ++i) {
extract<esl::identity<esl::law::property>> extractor(keys[i]);
extract<double> value_extractor(values[i]);
if(extractor.check() && value_extractor.check()) {
auto key = extractor();
auto value = value_extractor();
result_.emplace(key, esl::variable(value));
}
}
return result_;
}//else{
return {};
}
};
boost::python::dict get_differentiable_order_message_supply(const esl::economics::markets::walras::differentiable_order_message &m)
{
boost::python::dict result_;
for(const auto &[k,v] : m.supply){
result_[k] = boost::python::make_tuple(boost::python::object(std::get<0>(v)), boost::python::object(std::get<1>(v)));
}
return result_;
}
void set_differentiable_order_message_supply(esl::economics::markets::walras::differentiable_order_message &m, boost::python::dict t)
{
m.supply.clear();
auto items_ = t.items();
for(boost::python::ssize_t i = 0; i < boost::python::len(items_); ++i){
boost::python::tuple tuple_ = boost::python::tuple(items_[i]);
python_identity k = boost::python::extract<python_identity>(tuple_[0]);
auto v = boost::python::tuple(tuple_[1]);
esl::quantity long_ = boost::python::extract<quantity>(v[0]);
esl::quantity short_ = boost::python::extract<quantity>(v[1]);
std::tuple<esl::quantity, esl::quantity> T = { long_, short_};
m.supply.insert({esl::identity<esl::law::property>(k.digits), T});
}
}
///
/// \brief Excess demand model wrapper
///
class python_excess_demand_model
: public esl::economics::markets::tatonnement ::excess_demand_model
, public wrapper<esl::economics::markets::tatonnement ::excess_demand_model>
{
public:
explicit python_excess_demand_model(esl::law::property_map<quote> initial_quotes)
: excess_demand_model(std::move(initial_quotes))
, wrapper<esl::economics::markets::tatonnement ::excess_demand_model>()
{
}
};
///
/// \brief Helper funciton
///
/// \param e
/// \return
boost::python::dict compute_clearing_quotes(python_excess_demand_model *e)
{
auto quotes_ = e->compute_clearing_quotes();
boost::python::dict result_;
if(quotes_.has_value()){
for(const auto &[k,v]: quotes_.value()){
auto i = python_identity(k);
result_[boost::python::object(i)] = boost::python::object(v);
}
}
return result_;
}
///
/// \brief Constructor wrapper that deals with the Python-supplied mapping
///
/// \param Python dict with property base pointers as keys, and quote s as value
/// \return
boost::shared_ptr<python_excess_demand_model> excess_demand_model_python_constructor(const dict &d)
{
esl::law::property_map<quote> pm;
list keys = list(d.keys());
list values = list(d.values());
for (int i = 0; i < len(keys); ++i) {
extract<boost::shared_ptr<esl::law::property>> extractor(keys[i]);
extract<quote> value_extractor(values[i]);
if (extractor.check() && value_extractor.check()){
auto key = extractor();
auto value = value_extractor();
pm.try_emplace(to_std(key), value);
}
}
auto model_ = boost::make_shared<python_excess_demand_model>(pm);
model_->methods =
{ python_excess_demand_model::derivative_free_root
, python_excess_demand_model::derivative_free_minimization};
return model_;
}
/*
list get_differentiable_order_message(const excess_demand_model* e)
{
boost::shared_ptr<walras::differentiable_order_message>
e->excess_demand_functions_
}*/
typedef std::vector<boost::shared_ptr<walras::differentiable_order_message>> messages_t;
///
/// \brief converts the list of demand messages to Python
///
/// \param e
/// \return
messages_t get_excess_demand_functions(const tatonnement::excess_demand_model &e)
{
std::vector<boost::shared_ptr<walras::differentiable_order_message>> result_;
for(auto m: e.excess_demand_functions_){
result_.push_back(to_boost(m));
}
return result_;
}
///
/// \brief accepts Python list back to
///
/// \param e
/// \param l
void set_excess_demand_functions(tatonnement::excess_demand_model &e, const list& l)
{
std::vector<boost::shared_ptr<walras::differentiable_order_message>> result_;
e.excess_demand_functions_.clear();
for(int i = 0; i < len(l); ++i){
extract<boost::shared_ptr<python_differentiable_order_message>> extractor(l[i]);
e.excess_demand_functions_.push_back(to_std(extractor()));
}
}
////////////////////////////////////////////////////////////////////////////////
// esl.geography
////////////////////////////////////////////////////////////////////////////////
///
/// \brief
/// \param c
/// \return
std::string python_country_code(const esl::geography::iso_3166_1_alpha_2 &c)
{
return (std::string() + c.code[0]) + c.code[1];
}
////////////////////////////////////////////////////////////////////////////////
// esl.interaction
////////////////////////////////////////////////////////////////////////////////
//? #include <boost/serialization/export.hpp>
//? BOOST_CLASS_EXPORT(esl::interaction::python_message);
# include <boost/python/suite/indexing/indexing_suite.hpp>
# include <boost/python/suite/indexing/vector_indexing_suite.hpp>
//# include <boost/python/suite/indexing/map_indexing_suite.hpp>
#include <esl/interaction/python_module_interaction.hpp>
#include <esl/interaction/transfer.hpp>
using namespace esl::interaction;
///
/// \brief Takes a python function object and wraps it, so we can call it
/// from C++
///
/// \details See communicator.hpp for callback_handle type definition
///
///
/// \param f The python function that handles the message
/// \return
communicator::callback_handle make_callback_handle(boost::python::object f)
{
// std::function<simulation::time_point( message_t
// , simulation::time_interval
// , std::seed_seq &
// )>;
return [&]( communicator::message_t m
, simulation::time_interval i
, std::seed_seq &s
)
{
auto result_ = f(m, i, s);
return boost::python::extract<simulation::time_point>(result_);
};
}
///
/// \brief Since the main class is a template, we must expose a
/// non-template to python.
///
class python_message
: public message<python_message, library_message_code<0x1u>()>
{
public:
// this helps the linker resolve the message code
constexpr const static message_code python_code = code;
template<class archive_t>
void serialize(archive_t &archive, const unsigned int version)
{
(void)version;
//BOOST_SERIALIZATION_BASE_OBJECT_NVP(message);
archive &boost::serialization::make_nvp("message",
boost::serialization::base_object<message<python_message, library_message_code<0x1u>()>>(
*this));
}
};
///
/// \brief Provides interface for a multimap<k,v> to Python
///
///
template <class container_t_, bool NoProxy, class DerivedPolicies>
class multimap_indexing_suite;
namespace detail
{
template <class container_t_, bool NoProxy>
class final_map_derived_policies
: public multimap_indexing_suite<container_t_, NoProxy, final_map_derived_policies<container_t_, NoProxy> > {};
}
template < typename multimap_t_
, bool NoProxy = false
, typename DerivedPolicies = ::detail::final_map_derived_policies<multimap_t_, NoProxy> >
class multimap_indexing_suite
: public indexing_suite<multimap_t_, DerivedPolicies
, NoProxy
, true
, typename multimap_t_::value_type::second_type
, typename multimap_t_::key_type
, typename multimap_t_::key_type
>
{
public:
typedef typename multimap_t_::value_type value_type;
typedef typename multimap_t_::value_type::second_type data_type;
typedef typename multimap_t_::key_type key_type;
typedef typename multimap_t_::key_type index_type;
typedef typename multimap_t_::size_type size_type;
typedef typename multimap_t_::difference_type difference_type;
template <class Class> static void extension_def(Class& cl)
{
cl.def("keys", &keys);
cl.def("values", &values);
// Wrap the map's element (value_type)
std::string name_ = "multimap_indexing_suite_";
object class_name(cl.attr("__name__"));
extract<std::string> class_name_extractor(class_name);
name_ += class_name_extractor();
name_ += "_entry";
typedef typename boost::mpl::if_<
boost::mpl::and_<boost::is_class<data_type>, boost::mpl::bool_<!NoProxy> >
, return_internal_reference<>
, default_call_policies
>::type get_data_return_policy;
class_<value_type>(name_.c_str())
.def("__repr__", &DerivedPolicies::representation)
.def("data", &DerivedPolicies::get_data, get_data_return_policy())
.def("key", &DerivedPolicies::get_key)
;
}
static object representation(typename multimap_t_::value_type const &e)
{
return "(%s, %s)" % boost::python::make_tuple(e.first, e.second);
}
static
typename boost::mpl::if_<
boost::mpl::and_<boost::is_class<data_type>, boost::mpl::bool_<!NoProxy> >
, data_type &
, data_type
>::type
get_data(typename multimap_t_::value_type &e)
{
return e.second;
}
static typename multimap_t_::key_type
get_key(typename multimap_t_::value_type &e)
{
return e.first;
}
static data_type &get_item(multimap_t_ &container, index_type i_)
{
typename multimap_t_::iterator i = container.find(i_);
if (i == container.end()){
PyErr_SetString(PyExc_KeyError, "Invalid key");
throw_error_already_set();
}
return i->second;
}
static void set_item(multimap_t_ &container, index_type i, data_type const& v)
{
for(auto &[k,value_]: container){
if(k == i){
value_ = v;
}
}
}
static void
delete_item(multimap_t_ &container, index_type i)
{
container.erase(i);
}
static size_t
size(multimap_t_ &container)
{
return container.size();
}
static bool
contains(multimap_t_ &container, key_type const &key)
{
return container.find(key) != container.end();
}
static bool
compare_index(multimap_t_ &container, index_type a, index_type b)
{
return container.key_comp()(a, b);
}
static index_type
convert_index(multimap_t_ &container, PyObject *i_)
{
(void) container;
extract<key_type const&> i(i_);
if (i.check()){
return i();
}else{
extract<key_type> i2(i_);
if (i2.check()) {
return i2();
}
}
PyErr_SetString(PyExc_TypeError, "Invalid index type");
throw_error_already_set();
return index_type();
}
[[nodiscard]] static boost::python::list keys(const multimap_t_ &container)
{
boost::python::list result_;
for(const auto &[k, v]: container){
result_.append(k);
}
return result_;
}
[[nodiscard]] static boost::python::list values(const multimap_t_ &container)
{
boost::python::list result_;
for(const auto &[k, v]: container){
result_.append(v);
}
return result_;
}
};
///
/// \rbrief
///
/// \param c
/// \param o
void send_message_python(communicator &c, boost::python::object o)
{
(void)c;
(void)o;
extract<const communicator::message_t &> extractor_(o);
}
////////////////////////////////////////////////////////////////////////////////
// esl.law
////////////////////////////////////////////////////////////////////////////////
#include <esl/law/legal_person.hpp>
#include <esl/law/natural_person.hpp>
#include <esl/law/property.hpp>
#include <esl/law/organization.hpp>
#include <esl/law/government.hpp>
#include <esl/law/jurisdictions.hpp>
#include <esl/law/legal_entity.hpp>
#include <esl/economics/company.hpp>
using namespace esl::law;
std::string python_iso_17442_local(esl::law::iso_17442 &e)
{
std::stringstream stream_;
stream_.write(e.local.data(), e.local.size());
return stream_.str();
}
std::string python_iso_17442_code(esl::law::iso_17442 &e)
{
std::stringstream stream_;
stream_.write(e.code.data(), e.code.size());
return stream_.str();
}
std::string python_iso_17442_checksum(esl::law::iso_17442 &e)
{
std::stringstream stream_;
auto t = e.checksum();
stream_<< std::get<0>(t) << std::get<1>(t);
return stream_.str();
}
///
/// \brief This is needed because we need to deal with the default argument
/// \param p
/// \return
std::string python_represent_property_identity(const esl::identity<esl::law::property> &p)
{
return p.representation();
}
size_t python_property_identity_hash(const esl::identity<esl::law::property> &p)
{
return std::hash<esl::identity<esl::law::property>>()(p);
}
////////////////////////////////////////////////////////////////////////////////
// esl.simulation
////////////////////////////////////////////////////////////////////////////////
#include <esl/simulation/model.hpp>
#include <esl/simulation/time.hpp>
#include <esl/simulation/world.hpp>
using namespace esl::simulation;
template<typename entity_t_>
python_identity create_identity(entity_t_ &e)
{
auto i = e.template create<object>();
return i;
}
template<typename identity_t_>
boost::shared_ptr<identity_t_>
convert_digit_list_generic(const boost::python::list &list)
{
std::vector<uint64_t> result_;
for(boost::python::ssize_t i = 0; i < boost::python::len(list); ++i) {
result_.push_back(boost::python::extract<std::uint64_t>(list[i]));
}
return boost::make_shared<identity_t_>(result_);
}
boost::python::dict agent_collection_local_agents(const agent_collection &c)
{
boost::python::dict result_;
for(const auto &[k,v]: c.local_agents_){
result_[boost::python::object(k)] = boost::python::object(v);
}
return result_;
}
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS( python_identity_representation_overload
, python_identity::representation
, 0
, 1);
size_t python_identity_hash(const python_identity &p)
{
return std::hash<python_identity>()(p);
}
///
///
///
/// \param agent_constructor
/// \return
boost::shared_ptr<esl::agent> python_agent_collection_create_identifier(
esl::simulation::agent_collection &a
, boost::python::object parent)
{
(void)a;
(void)parent;
boost::shared_ptr<esl::agent> result_;
return result_;
}
///
///
///
/// \param agent_constructor
/// \return
boost::shared_ptr<esl::agent> python_agent_collection_create( agent_collection &
, boost::python::object )
{
boost::shared_ptr<esl::agent> result_;
//boost::python::call<int>(agent_constructor);
return result_;
}
///
/// \param agent
void python_agent_collection_activate(agent_collection &c, boost::shared_ptr<esl::agent> a)
{
c.activate(to_std(a));
}
///
/// \param agent
void python_agent_collection_deactivate(agent_collection &c, boost::shared_ptr<esl::agent> a)
{
c.deactivate(to_std(a));
}
/// \brief Export time_point constructor to Python.
///
/// \param o
/// \return
time_point python_time_point(const object& o)
{
return extract<time_point>(o);
}
///
/// \brief Export time_duration constructor to Python.
///
/// \param o
/// \return
time_duration python_time_duration(const object& o)
{
return extract<time_duration>(o);
}
////////////////////////////////////////////////////////////////////////////////
// esl.simulation.parameter
////////////////////////////////////////////////////////////////////////////////
#include <esl/simulation/parameter/parametrization.hpp>
using namespace esl::simulation::parameter;
class python_model
: public model
, public wrapper<model>
{
public:
python_model(environment &e, const parameter::parametrization &p)
: model(e, p)
, wrapper<model>()
{
}
~python_model() override = default;
void initialize() override
{
boost::python::override method_ = get_override("initialize");
if(method_.is_none()){
model::initialize();
}else{
method_();
}
}
///
/// \brief Call Python code for user defined model logic.
/// Because we can't enforce return type as we would in C++,
/// we are more permissive and default to jumping over the entire
/// interval if no next event has been specified.
///
/// \param step
/// \return
time_point step(time_interval step) override
{
boost::python::override method_ = get_override("step");
if(method_.is_none()){
return model::step(step);
}
boost::python::object result_ = method_(step);
if(result_.is_none()){
return step.upper;
}
return boost::python::extract<time_point>(result_);
}
void terminate() override
{
boost::python::override method_ = get_override("terminate");
if(method_.is_none()){
model::terminate();
}else{
method_();
}
}
};
template<typename parameter_t_>
std::optional<boost::python::object> pack(std::shared_ptr<parameter_base> parameter)
{
auto value_ =
std::dynamic_pointer_cast<constant<parameter_t_>>(parameter);
if(value_) {
return boost::python::object(parameter_t_(*value_));
}
return {};
}
///
/// \brief Because Python allows returning many types from a single function,
/// we can wrap the function by packing the result in a python object.
///
/// \param p The parameter set
/// \param name The parameter name
/// \return The parameter value as a python object
boost::python::object parametrization_get_helper(const parametrization &p, const std::string &name)
{
auto parameter_ = p.values.find(name);
if(p.values.end() == parameter_) {
throw esl::exception("not a valid parameter: " + name + "");
}
auto result_ = pack<double>(parameter_->second);
if(result_.has_value()){
return result_.value();
}
result_ = pack<std::int64_t>(parameter_->second);
if(result_.has_value()){
return result_.value();
}
result_ = pack<std::uint64_t>(parameter_->second);
if(result_.has_value()){
return result_.value();
}
throw esl::exception("parametrization[" + name + "] can't be converted to Python");
}
////////////////////////////////////////////////////////////////////////////////
// IMPLEMENTATION
////////////////////////////////////////////////////////////////////////////////
namespace esl {
scope create_scope(const std::string &name)
{
std::string nested_name = extract<std::string>(scope().attr("__name__") + "." + name);
object nested_module(handle<>(borrowed(PyImport_AddModule(nested_name.c_str()))));
scope().attr(name.c_str()) = nested_module;
scope parent = nested_module;
return parent;
}
///
/// \brief Python module structure follows directory structure and
/// C++ namespaces. We use __init__.py for submodules, so we can mix
/// native code and Python-binding specific Python code. Thus, we
/// protect the name of the module with an underscore, and import it
/// from __init__.py
///
BOOST_PYTHON_MODULE(_esl)
{
////////////////////////////////////////////////////////////////////////////
// utility
////////////////////////////////////////////////////////////////////////////
class_<std::seed_seq, boost::shared_ptr<std::seed_seq>, boost::noncopyable>("seed", no_init)\
.def("__init__", boost::python::make_constructor( construct_seed_seq_from_list))
.def_readonly("size", &std::seed_seq::size)
.def("generate", +[](std::seed_seq &seed){
std::vector<std::uint32_t> seeds_(1);
seed.generate(seeds_.begin(), seeds_.end());
return seeds_[0];
})
.def("__str__", +[](std::seed_seq &seed){
std::stringstream stream_;
stream_ << "seed {";
seed.param(std::ostream_iterator<typename std::seed_seq::result_type>(stream_, ", "));
stream_ << "}";
return stream_.str();
})
;
////////////////////////////////////////////////////////////////////////////
// top level module
////////////////////////////////////////////////////////////////////////////
class_<esl::exception>("exception", init<std::string>())
.def("message", &esl::exception::what);
register_exception_translator<esl::exception>(translate_exception);
class_<quantity>("quantity", init<>())
.def(init<std::uint64_t>())
.def(self += self)
.def(self + self)
.def(self -= self)
.def(self - self)
//.def(self *= self)
.def(self * self)
.def(self < self)
.def(self > self)
.def(self == self)
.def(self != self)
.def(self <= self)
.def(self >= self)
//.def(self /= self)
//.def(self / self)
//.def(self %= self)
//.def(self % self)
// conversion to floating point type
.def(float_(self))
.def("__repr__", &quantity::representation)
.def("__str__", &quantity::representation)
.def(self *= std::uint64_t())
.def(self * std::uint64_t())
.def(self / std::uint64_t());
//class_<entity<void>>("entity");
class_< python_agent
, boost::noncopyable
//, bases<communicator>
>("agent", init<python_identity>())
.def("describe", &python_agent::describe)
.def("act", &python_agent::act)
.add_property( "identifier"
, +[](const python_agent &a){return (python_identity)(a.identifier); }
)
.add_property( "inbox"
, +[](const python_agent &a){return a.inbox; }
)
.add_property("outbox"
, +[](const python_agent &a){return a.outbox; }
)
.def("create", &create_identity<agent>)
.def("__repr__", &python_agent::describe)
.def("__str__", &python_agent::describe)
;
def("version", version, "Print the library's version.");
////////////////////////////////////////////////////////////////////////////
// esl.computation
////////////////////////////////////////////////////////////////////////////
{
boost::python::scope scope_computation_ = create_scope("_computation");
class_<block_pool::block<object>>(
"block", "The block is a unit of memory used by the block_pool allocator, and has fixed size.")
.def_readwrite("data",
&computation::block_pool::block<object>::data)
.def_readwrite("index",
&computation::block_pool::block<object>::index);
// computational environment base class with default single thread
class_<python_environment, boost::noncopyable>(
"environment", "The environment class runs models: it schedules agents and delivers messages sent between agents.")
.def("step", &python_environment::step)
.def("run", &python_environment::run)
.def("activate", &python_environment::activate)
.def("deactivate", &python_environment::deactivate)
.def("before_step", &python_environment::before_step)
.def("after_step", &python_environment::after_step)
.def("after_run", &python_environment::after_run)
.def("activate_agent", &python_environment::activate_agent)
.def("deactivate_agent", &python_environment::deactivate_agent)
.def("send_messages", &python_environment::send_messages)
;
// timing information
class_<computation::agent_timing>(
"agent_timing",
"Contains performance metrics for individual agents.")
.def_readwrite("messaging", &agent_timing::messaging)
.def_readwrite("acting", &agent_timing::acting);
{
boost::python::scope scope_distributed_ =
create_scope("_distributed");
scope().attr("__doc__") = "submodule for distributed computing using MPI";
class_<activation>("activation")
.def_readwrite("location", &activation::location)
.def_readwrite("activated", &activation::activated);
class_<migration>("migration")
.def_readwrite("source", &migration::source)
.def_readwrite("target", &migration::target)
.def_readwrite("migrant", &migration::migrant);
class_<deactivation>("deactivation")
.def_readwrite("deactivated", &deactivation::deactivated);
}
// class_<environment>("environment")
// .def("run", &environment::run)
// .def("step", &environment::step)
// .def("activate", &environment::activate)
// .def("deactivate", &environment::deactivate)
// .def("before_step", &environment::before_step)
// .def("after_step", &environment::after_step)
// .def("after_run", &environment::after_run)
// .def("activate_agent", &environment::activate_agent)
// .def("deactivate_agent", &environment::deactivate_agent)
// .def("send_messages", &environment::send_messages)
// ;
//
}
////////////////////////////////////////////////////////////////////////////
// esl.data
////////////////////////////////////////////////////////////////////////////
{
boost::python::scope scope_data_ = create_scope("_data");
enum_<severity>("severity")
.value("trace", severity::trace)
.value("notice", severity::notice)
.value("warning", severity::warning)
.value("error", severity::errorlog)
;
def("log_detailed", &python_log_detailed);
// esl::data::main_log.get<level>(BOOST_CURRENT_FUNCTION, __FILE__, __LINE__)
////////////////////////////////////////////////////////////////////////
// esl.format
////////////////////////////////////////////////////////////////////////
{
boost::python::scope scope_format_ = create_scope("_format");
}
}
////////////////////////////////////////////////////////////////////////////
// esl.economics
////////////////////////////////////////////////////////////////////////////
{
boost::python::scope scope_economics_ = create_scope("_economics");
class_<iso_4217>("iso_4217")
.add_property("code", python_currency_code)
.add_property("denominator", &iso_4217::denominator)
.add_property("__repr__", python_currency_code)
.add_property("__str__", python_currency_code);
class_<std::map<finance::share_class, std::uint64_t>>("map_share_class_uint64_t")
.def(map_indexing_suite<std::map<finance::share_class, std::uint64_t>>())
;
//class_<std::unordered_map<identity<shareholder>, std::map<finance::share_class, std::uint64_t>>>("unordered_map_shareholder_identity_share_class_uint64_t")
// .def(map_indexing_suite<std::unordered_map<identity<shareholder>, std::map<finance::share_class, std::uint64_t>>>())
//**;
class_<python_organization /*, bases<legal_person>*/, boost::noncopyable>("organization"
, init<const python_identity &,const jurisdiction &>())
;
class_< python_company, bases<python_organization>, boost::noncopyable
>( "company", init<const python_identity &, const law::jurisdiction &>())
.add_property("balance_sheet", +[](python_company &c) { return c.balance_sheet; })
.add_property("shares_outstanding", +[](python_company &c) { return c.shares_outstanding; })
.add_property("shareholders", +[](python_company &c) { return c.shareholders; })
.def("unique_shareholders", +[](const python_company &c)
{
boost::python::list result_;
for(const auto &sh : c.unique_shareholders()){
result_.append((python_identity)sh);
}
return result_;
})
.def("total_shares", &python_company::company::total_shares)
;
////////////////////////////////////////////////////////////////////////////
// esl.economics.accounting
////////////////////////////////////////////////////////////////////////////
{
boost::python::scope scope_accounting_ = create_scope("_accounting");
class_<std::map<identity<law::property>, markets::quote> >("map_property_identifier_quote")
.def(map_indexing_suite<std::map<identity<law::property>, markets::quote>>())
;
class_<standard>("standard"
, "A basic accounting standard"
,init<iso_4217>())
.add_property("reporting_currency", &standard::reporting_currency)
.add_property("foreign_currencies", &standard::foreign_currencies)
.def("value", &value_money)
.def("value", &value_cash)
.def("value", &value_stock)
.def("value", &value_loan)
.def("value", &value_securities_lending_contract)
;
}
////////////////////////////////////////////////////////////////////////////
// esl.economics.currencies
////////////////////////////////////////////////////////////////////////////
{
boost::python::scope scope_currencies_ = create_scope("_currencies");
scope().attr("AED") = currencies::AED;
scope().attr("AFN") = currencies::AFN;
scope().attr("ALL") = currencies::ALL;
scope().attr("AMD") = currencies::AMD;
scope().attr("ANG") = currencies::ANG;
scope().attr("AOA") = currencies::AOA;
scope().attr("ARS") = currencies::ARS;
scope().attr("AUD") = currencies::AUD;
scope().attr("AWG") = currencies::AWG;
scope().attr("AZN") = currencies::AZN;
scope().attr("BAM") = currencies::BAM;
scope().attr("BBD") = currencies::BBD;
scope().attr("BDT") = currencies::BDT;
scope().attr("BGN") = currencies::BGN;
scope().attr("BHD") = currencies::BHD;
scope().attr("BIF") = currencies::BIF;
scope().attr("BMD") = currencies::BMD;
scope().attr("BND") = currencies::BND;
scope().attr("BOB") = currencies::BOB;
scope().attr("BOV") = currencies::BOV;
scope().attr("BRL") = currencies::BRL;
scope().attr("BSD") = currencies::BSD;
scope().attr("BTN") = currencies::BTN;
scope().attr("BWP") = currencies::BWP;
scope().attr("BYN") = currencies::BYN;
scope().attr("BZD") = currencies::BZD;
scope().attr("CAD") = currencies::CAD;
scope().attr("CDF") = currencies::CDF;
scope().attr("CHE") = currencies::CHE;
scope().attr("CHF") = currencies::CHF;
scope().attr("CHW") = currencies::CHW;
scope().attr("CLF") = currencies::CLF;
scope().attr("CLP") = currencies::CLP;
scope().attr("CNY") = currencies::CNY;
scope().attr("COP") = currencies::COP;
scope().attr("COU") = currencies::COU;
scope().attr("CRC") = currencies::CRC;
scope().attr("CUC") = currencies::CUC;
scope().attr("CUP") = currencies::CUP;
scope().attr("CVE") = currencies::CVE;
scope().attr("CZK") = currencies::CZK;
scope().attr("DJF") = currencies::DJF;
scope().attr("DKK") = currencies::DKK;
scope().attr("DOP") = currencies::DOP;
scope().attr("DZD") = currencies::DZD;
scope().attr("EGP") = currencies::EGP;
scope().attr("ERN") = currencies::ERN;
scope().attr("ETB") = currencies::ETB;
scope().attr("EUR") = currencies::EUR;
scope().attr("FJD") = currencies::FJD;
scope().attr("FKP") = currencies::FKP;
scope().attr("GBP") = currencies::GBP;
scope().attr("GEL") = currencies::GEL;
scope().attr("GHS") = currencies::GHS;
scope().attr("GIP") = currencies::GIP;
scope().attr("GMD") = currencies::GMD;
scope().attr("GNF") = currencies::GNF;
scope().attr("GTQ") = currencies::GTQ;
scope().attr("GYD") = currencies::GYD;
scope().attr("HKD") = currencies::HKD;
scope().attr("HNL") = currencies::HNL;
scope().attr("HRK") = currencies::HRK;
scope().attr("HTG") = currencies::HTG;
scope().attr("HUF") = currencies::HUF;
scope().attr("IDR") = currencies::IDR;
scope().attr("ILS") = currencies::ILS;
scope().attr("INR") = currencies::INR;
scope().attr("IQD") = currencies::IQD;
scope().attr("IRR") = currencies::IRR;
scope().attr("ISK") = currencies::ISK;
scope().attr("JMD") = currencies::JMD;
scope().attr("JOD") = currencies::JOD;
scope().attr("JPY") = currencies::JPY;
scope().attr("KES") = currencies::KES;
scope().attr("KGS") = currencies::KGS;
scope().attr("KHR") = currencies::KHR;
scope().attr("KMF") = currencies::KMF;
scope().attr("KPW") = currencies::KPW;
scope().attr("KRW") = currencies::KRW;
scope().attr("KWD") = currencies::KWD;
scope().attr("KYD") = currencies::KYD;
scope().attr("KZT") = currencies::KZT;
scope().attr("LAK") = currencies::LAK;
scope().attr("LBP") = currencies::LBP;
scope().attr("LKR") = currencies::LKR;
scope().attr("LRD") = currencies::LRD;
scope().attr("LSL") = currencies::LSL;
scope().attr("LYD") = currencies::LYD;
scope().attr("MAD") = currencies::MAD;
scope().attr("MDL") = currencies::MDL;
scope().attr("MGA") = currencies::MGA;
scope().attr("MKD") = currencies::MKD;
scope().attr("MMK") = currencies::MMK;
scope().attr("MNT") = currencies::MNT;
scope().attr("MOP") = currencies::MOP;
scope().attr("MRU") = currencies::MRU;
scope().attr("MUR") = currencies::MUR;
scope().attr("MVR") = currencies::MVR;
scope().attr("MWK") = currencies::MWK;
scope().attr("MXN") = currencies::MXN;
scope().attr("MXV") = currencies::MXV;
scope().attr("MYR") = currencies::MYR;
scope().attr("MZN") = currencies::MZN;
scope().attr("NAD") = currencies::NAD;
scope().attr("NGN") = currencies::NGN;
scope().attr("NIO") = currencies::NIO;
scope().attr("NOK") = currencies::NOK;
scope().attr("NPR") = currencies::NPR;
scope().attr("NZD") = currencies::NZD;
scope().attr("OMR") = currencies::OMR;
scope().attr("PAB") = currencies::PAB;
scope().attr("PEN") = currencies::PEN;
scope().attr("PGK") = currencies::PGK;
scope().attr("PHP") = currencies::PHP;
scope().attr("PKR") = currencies::PKR;
scope().attr("PLN") = currencies::PLN;
scope().attr("PYG") = currencies::PYG;
scope().attr("QAR") = currencies::QAR;
scope().attr("RON") = currencies::RON;
scope().attr("RSD") = currencies::RSD;
scope().attr("RUB") = currencies::RUB;
scope().attr("RWF") = currencies::RWF;
scope().attr("SAR") = currencies::SAR;
scope().attr("SBD") = currencies::SBD;
scope().attr("SCR") = currencies::SCR;
scope().attr("SDG") = currencies::SDG;
scope().attr("SEK") = currencies::SEK;
scope().attr("SGD") = currencies::SGD;
scope().attr("SHP") = currencies::SHP;
scope().attr("SLL") = currencies::SLL;
scope().attr("SOS") = currencies::SOS;
scope().attr("SRD") = currencies::SRD;
scope().attr("SSP") = currencies::SSP;
scope().attr("STN") = currencies::STN;
scope().attr("SVC") = currencies::SVC;
scope().attr("SYP") = currencies::SYP;
scope().attr("SZL") = currencies::SZL;
scope().attr("THB") = currencies::THB;
scope().attr("TJS") = currencies::TJS;
scope().attr("TMT") = currencies::TMT;
scope().attr("TND") = currencies::TND;
scope().attr("TOP") = currencies::TOP;
scope().attr("TRY") = currencies::TRY;
scope().attr("TTD") = currencies::TTD;
scope().attr("TWD") = currencies::TWD;
scope().attr("TZS") = currencies::TZS;
scope().attr("UAH") = currencies::UAH;
scope().attr("UGX") = currencies::UGX;
scope().attr("USD") = currencies::USD;
scope().attr("USN") = currencies::USN;
scope().attr("UYI") = currencies::UYI;
scope().attr("UYU") = currencies::UYU;
scope().attr("UZS") = currencies::UZS;
scope().attr("VEF") = currencies::VEF;
scope().attr("VND") = currencies::VND;
scope().attr("VUV") = currencies::VUV;
scope().attr("WST") = currencies::WST;
scope().attr("XAF") = currencies::XAF;
scope().attr("XAG") = currencies::XAG;
scope().attr("XAU") = currencies::XAU;
scope().attr("XBA") = currencies::XBA;
scope().attr("XBB") = currencies::XBB;
scope().attr("XBC") = currencies::XBC;
scope().attr("XBD") = currencies::XBD;
scope().attr("XCD") = currencies::XCD;
scope().attr("XDR") = currencies::XDR;
scope().attr("XOF") = currencies::XOF;
scope().attr("XPD") = currencies::XPD;
scope().attr("XPF") = currencies::XPF;
scope().attr("XPT") = currencies::XPT;
scope().attr("XSU") = currencies::XSU;
scope().attr("XUA") = currencies::XUA;
// scope().attr("XXX") = currencies::XXX;
scope().attr("YER") = currencies::YER;
scope().attr("ZAR") = currencies::ZAR;
scope().attr("ZMW") = currencies::ZMW;
scope().attr("ZWL") = currencies::ZWL;
}
class_<price>("price", init<std::int64_t, iso_4217>())
.add_property("value", &price::value)
.add_property("valuation", &price::valuation)
.def("approximate", &price::approximate)
.def(self == self)
.def(self != self)
.def(self < self)
.def(self <= self)
.def(self > self)
.def(self >= self)
//.def(self * std::uint64_t)
.def("__repr__", &price::representation)
.def("__str__", &price::representation)
.def("__float__", &python_price_to_floating_point);
////////////////////////////////////////////////////////////////////////
// esl.economics.finance
////////////////////////////////////////////////////////////////////////
{
boost::python::scope scope_finance = create_scope("_finance");
class_<finance::isin>("iso_6166", no_init)
.def(init<geography::iso_3166_1_alpha_2, std::string>())
.def(init<std::string>())
.def(init<std::string, std::string>())
.def(init<geography::iso_3166_1_alpha_2, cusip>())
.add_property("issuer", &finance::isin::issuer)
.add_property("code", &get_isin_code, &set_isin_code)
.def("__repr__", &finance::isin::representation)
.def("__str__", &finance::isin::representation)
.def("checksum", +[](const finance::isin &i){ std::string s = ""; s += i.checksum(); return s;})
;
class_<finance::cusip>("cusip", no_init)
.def(init<std::string>())
.add_property("issuer"
, +[](const finance::cusip &c){
return std::string(c.issuer.begin(), c.issuer.end());
})
.def("__repr__", &finance::cusip::representation)
.def("__str__", &finance::cusip::representation)
.def("checksum", +[](const finance::cusip &c){ std::string s = ""; s += c.checksum(); return s; })
;
class_<finance::share_class>(
"share_class",
init<std::uint8_t, std::uint8_t, float, bool, bool, bool>())
.add_property("rank", &finance::share_class::rank)
.add_property("votes", &finance::share_class::votes)
.add_property("preference", &finance::share_class::preference)
.add_property("dividend", &finance::share_class::dividend)
.add_property("cumulative", &finance::share_class::cumulative)
.add_property("redeemable", &finance::share_class::redeemable)
.def(self == self)
.def(self < self);
class_<std::map<share_class, std::tuple<std::uint64_t, price>>>("map_share_class_uint64_t_price")
.def(map_indexing_suite<std::map<share_class, std::tuple<std::uint64_t, price>>>());
class_<finance::dividend_policy>("dividend_policy",
init<time_point, time_point,time_interval,time_point,iso_4217,std::map<share_class, std::tuple<std::uint64_t, price>>>()
)
.add_property("announcement_date", ÷nd_policy::announcement_date)
.add_property("ex_dividend_date", ÷nd_policy::ex_dividend_date)
.add_property("dividend_period", ÷nd_policy::dividend_period)
.add_property("payable_date", ÷nd_policy::payable_date)
.add_property("dividend_currency", ÷nd_policy::dividend_currency)
.add_property("dividend_per_share", ÷nd_policy::dividend_per_share)
.def("total_dividends", ÷nd_policy::total_dividends)
;
}
////////////////////////////////////////////////////////////////////////
// esl.economics.markets
////////////////////////////////////////////////////////////////////////
{
boost::python::scope scope_markets_ = create_scope("_markets");
class_<iso_10383>("iso_10383", init<std::string>())
.def("__repr__", &iso_10383::representation)
.def(self_ns::str(self_ns::self))
.def(self == self)
.def(self != self)
.def(self < self)
.def(self > self)
.def(self <= self)
.def(self >= self);
class_<quote, boost::shared_ptr<quote>>("quote", no_init)
.def("__init__", boost::python::make_constructor( construct_quote_from_price))
.def("__init__", boost::python::make_constructor( construct_quote_from_exchange_rate))
.add_property("price", "e_helper_get_price, "e_helper_set_price)
.def_readwrite("lot", "e::lot)
.def(self == self)
.def(self != self)
.def(self < self)
.def(self > self)
.def(self <= self)
.def(self >= self)
.def("__float__", "e_helper_operator_double)
.def("__repr__", "e::representation)
.def("__str__", "e::representation);
implicitly_convertible<quote, double>();
class_<ticker>(
"ticker", no_init)
.def("__init__", make_constructor(python_ticker_constructor))
.add_property("base"
, +[](const ticker &r){return reinterpret_identity_cast<python_identity>(r.base); }
, +[](ticker &r, const python_identity &i){ r.base = reinterpret_identity_cast<law::property>(i); }
)
.add_property("quote"
, +[](const ticker &r){return (python_identity)(r.quote); }
, +[](ticker &r, const python_identity &i){ r.quote = reinterpret_identity_cast<law::property>(i); }
)
.def(self == self)
.def(self != self)
.def(self < self)
.def(self > self)
.def(self <= self)
.def(self >= self);
enum_<indication>("indication")
.value("firm", indication::firm)
.value("indicative", indication::indicative);
////////////////////////////////////////////////////////////////////
// esl.economics.markets.impact_function
////////////////////////////////////////////////////////////////////
{
boost::python::scope scope_impact_function_ =
create_scope("_impact_function");
}
////////////////////////////////////////////////////////////////////
// esl.economics.markets.order_book
////////////////////////////////////////////////////////////////////
{
boost::python::scope scope_order_book_ =
create_scope("_order_book");
class_<std::vector<execution_report>>("execution_reports")
.def(vector_indexing_suite<std::vector<execution_report>>())
.def("clear", +[](std::vector<execution_report> &e){return e.clear();})
//.def("size", +[](const std::vector<execution_report> &e){return e.size();}) // superseeded by len(e)
;
enum_<execution_report::state_t>("execution_state")
.value("invalid", execution_report::state_t::invalid)
.value("cancel", execution_report::state_t::cancel)
.value("match", execution_report::state_t::match)
.value("placement", execution_report::state_t::placement);
class_<execution_report>("execution_report"
, init<execution_report::state_t
, limit_order::side_t
, std::uint32_t
, std::uint64_t
, quote
, python_identity >())
.def_readwrite("state", &execution_report::state)
.def_readwrite("quantity", &execution_report::quantity)
.def_readwrite("identifier", &execution_report::identifier)
.def_readwrite("side", &execution_report::side)
.def_readwrite("limit", &execution_report::limit)
.add_property ("owner"
, +[](const execution_report &r){return reinterpret_identity_cast<python_identity>(r.owner); }
, +[](execution_report &r, const python_identity &i){ r.owner = reinterpret_identity_cast<agent>(i); }
)
.def("__repr__", &execution_report::representation)
.def("__str__", &execution_report::representation);
// for list of order identifiers
class_<std::vector<basic_book::order_identifier>>("order_identifier_list")
.def(vector_indexing_suite<std::vector<basic_book::order_identifier>>())
.def("clear", +[](std::vector<basic_book::order_identifier> &e){return e.clear();})
;
enum_<limit_order::side_t>("side_t")
.value("buy", limit_order::side_t::buy)
.value("sell", limit_order::side_t::sell)
;
enum_<limit_order::lifetime_t>("lifetime_t")
.value("good_until_cancelled", limit_order::lifetime_t::good_until_cancelled)
.value("fill_or_kill", limit_order::lifetime_t::fill_or_kill)
.value("immediate_or_cancel", limit_order::lifetime_t::immediate_or_cancel)
;
///
/// \brief Export the abstract base class, so that python users too can
/// implement new order books.
///
class_<limit_order>("limit_order", no_init)
.def("__init__", make_constructor(python_limit_order_message_constructor))
.def_readwrite("lifetime", &limit_order::lifetime)
.def_readwrite("side", &limit_order::side)
.def_readwrite("symbol", &limit_order::symbol)
.add_property ( "owner"
, +[](const limit_order &r){return reinterpret_identity_cast<python_identity>(r.owner); }
, +[](limit_order &r, const python_identity &i){ r.owner = reinterpret_identity_cast<agent>(i); } )
.def_readwrite("limit", &limit_order::limit)
.def_readwrite("quantity", &limit_order::quantity)
;
class_<std::vector<limit_order>>("limit_orders")
.def(vector_indexing_suite<std::vector<limit_order>>());
///
/// \brief Export the abstract base class, so that python users too can
/// implement new order books.
///
class_<basic_book, boost::noncopyable>("basic_book", no_init)
.def_readwrite("reports", &basic_book::reports)
.def("ask", +[](const basic_book& b) { return optional_to_python<quote>(b.ask()); })
.def("bid", +[](const basic_book& b) { return optional_to_python<quote>(b.bid()); })
.def("insert", &basic_book::insert)
.def("cancel", &basic_book::cancel)
.def("orders", +[](const basic_book& b) {
boost::python::list result_;
for(auto i: b.orders()){
result_.append(i);
}
return result_;
})
.def("display", &basic_book::display);
//
class_<static_order_book, bases<basic_book>>
( "static_order_book"
, "Limit order book optimized for fast throughput. Uses statically allocated memory pool."
, init<quote, quote, size_t>())
.def_readwrite("reports", &basic_book::reports)
;
class_<binary_tree_order_book, bases<basic_book>>(
"binary_tree_order_book", init<>())
.def_readwrite("reports", &basic_book::reports)
.def("ask", &basic_book::ask)
.def("bid", &basic_book::bid)
.def("insert", &basic_book::insert)
.def("cancel", &basic_book::cancel)
.def("display", &basic_book::display);
class_<matching_engine>("matching_engine", init<>())
.def_readwrite("books", &matching_engine::books)
;
}
////////////////////////////////////////////////////////////////////
// esl.economics.markets.walras
////////////////////////////////////////////////////////////////////
{
boost::python::scope scope_walras_ = create_scope("_walras");
enum_<tatonnement::excess_demand_model::solver>("solver")
// TODO: implement automatic differentiation for Python
//.value("root", excess_demand_model::root)
//.value("minimization", excess_demand_model::minimization)
.value(
"derivative_free_root",
tatonnement::excess_demand_model::derivative_free_root)
.value("derivative_free_minimization",
tatonnement::excess_demand_model::
derivative_free_minimization)
.export_values();
class_<python_differentiable_order_message, boost::noncopyable>(
"differentiable_order_message",
init<python_identity,
python_identity,
esl::simulation::time_point,
esl::simulation::time_point>())
.add_property(
"supply",
&get_differentiable_order_message_supply, &set_differentiable_order_message_supply);
// expose vector of messages to Python
class_<messages_t>("messages_t")
.def(vector_indexing_suite<messages_t>());
class_<python_excess_demand_model, boost::noncopyable>(
"excess_demand_model", no_init) // non-trivial constructor
.def("__init__",
make_constructor(
&excess_demand_model_python_constructor))
.def_readwrite("circuit_breaker", &tatonnement::excess_demand_model::circuit_breaker)
.def_readwrite("methods", &tatonnement::excess_demand_model::methods)
.def_readwrite("quotes", &tatonnement::excess_demand_model::quotes)
.def("compute_clearing_quotes", &compute_clearing_quotes)
.add_property("excess_demand_functions",
&get_excess_demand_functions,
&set_excess_demand_functions);
}
}
}
////////////////////////////////////////////////////////////////////////////
// esl.geography
////////////////////////////////////////////////////////////////////////////
{
boost::python::scope scope_geography_ = create_scope("_geography");
class_<esl::geography::iso_3166_1_alpha_2>("iso_3166_1_alpha_2", init<std::string>())
.add_property("code", python_country_code)
.def("__repr__",
&esl::geography::iso_3166_1_alpha_2::representation)
.def("__str__",
&esl::geography::iso_3166_1_alpha_2::representation);
{
boost::python::scope scope_countries_ = create_scope("_countries");
scope().attr("AE") = esl::geography::countries::AE;
scope().attr("AF") = esl::geography::countries::AF;
scope().attr("AG") = esl::geography::countries::AG;
scope().attr("AI") = esl::geography::countries::AI;
scope().attr("AL") = esl::geography::countries::AL;
scope().attr("AM") = esl::geography::countries::AM;
scope().attr("AO") = esl::geography::countries::AO;
scope().attr("AQ") = esl::geography::countries::AQ;
scope().attr("AR") = esl::geography::countries::AR;
scope().attr("AS") = esl::geography::countries::AS;
scope().attr("AT") = esl::geography::countries::AT;
scope().attr("AU") = esl::geography::countries::AU;
scope().attr("AW") = esl::geography::countries::AW;
scope().attr("AX") = esl::geography::countries::AX;
scope().attr("AZ") = esl::geography::countries::AZ;
scope().attr("BA") = esl::geography::countries::BA;
scope().attr("BB") = esl::geography::countries::BB;
scope().attr("BD") = esl::geography::countries::BD;
scope().attr("BE") = esl::geography::countries::BE;
scope().attr("BF") = esl::geography::countries::BF;
scope().attr("BG") = esl::geography::countries::BG;
scope().attr("BH") = esl::geography::countries::BH;
scope().attr("BI") = esl::geography::countries::BI;
scope().attr("BJ") = esl::geography::countries::BJ;
scope().attr("BL") = esl::geography::countries::BL;
scope().attr("BM") = esl::geography::countries::BM;
scope().attr("BN") = esl::geography::countries::BN;
scope().attr("BO") = esl::geography::countries::BO;
scope().attr("BQ") = esl::geography::countries::BQ;
scope().attr("BR") = esl::geography::countries::BR;
scope().attr("BS") = esl::geography::countries::BS;
scope().attr("BT") = esl::geography::countries::BT;
scope().attr("BV") = esl::geography::countries::BV;
scope().attr("BW") = esl::geography::countries::BW;
scope().attr("BY") = esl::geography::countries::BY;
scope().attr("BZ") = esl::geography::countries::BZ;
scope().attr("CA") = esl::geography::countries::CA;
scope().attr("CC") = esl::geography::countries::CC;
scope().attr("CD") = esl::geography::countries::CD;
scope().attr("CF") = esl::geography::countries::CF;
scope().attr("CG") = esl::geography::countries::CG;
scope().attr("CH") = esl::geography::countries::CH;
scope().attr("CI") = esl::geography::countries::CI;
scope().attr("CK") = esl::geography::countries::CK;
scope().attr("CL") = esl::geography::countries::CL;
scope().attr("CM") = esl::geography::countries::CM;
scope().attr("CN") = esl::geography::countries::CN;
scope().attr("CO") = esl::geography::countries::CO;
scope().attr("CR") = esl::geography::countries::CR;
scope().attr("CU") = esl::geography::countries::CU;
scope().attr("CV") = esl::geography::countries::CV;
scope().attr("CW") = esl::geography::countries::CW;
scope().attr("CX") = esl::geography::countries::CX;
scope().attr("CY") = esl::geography::countries::CY;
scope().attr("CZ") = esl::geography::countries::CZ;
scope().attr("DE") = esl::geography::countries::DE;
scope().attr("DJ") = esl::geography::countries::DJ;
scope().attr("DK") = esl::geography::countries::DK;
scope().attr("DM") = esl::geography::countries::DM;
scope().attr("DO") = esl::geography::countries::DO;
scope().attr("DZ") = esl::geography::countries::DZ;
scope().attr("EC") = esl::geography::countries::EC;
scope().attr("EE") = esl::geography::countries::EE;
scope().attr("EG") = esl::geography::countries::EG;
scope().attr("EH") = esl::geography::countries::EH;
scope().attr("ER") = esl::geography::countries::ER;
scope().attr("ES") = esl::geography::countries::ES;
scope().attr("ET") = esl::geography::countries::ET;
scope().attr("FI") = esl::geography::countries::FI;
scope().attr("FJ") = esl::geography::countries::FJ;
scope().attr("FK") = esl::geography::countries::FK;
scope().attr("FM") = esl::geography::countries::FM;
scope().attr("FO") = esl::geography::countries::FO;
scope().attr("FR") = esl::geography::countries::FR;
scope().attr("GA") = esl::geography::countries::GA;
scope().attr("GB") = esl::geography::countries::GB;
scope().attr("GD") = esl::geography::countries::GD;
scope().attr("GE") = esl::geography::countries::GE;
scope().attr("GF") = esl::geography::countries::GF;
scope().attr("GG") = esl::geography::countries::GG;
scope().attr("GH") = esl::geography::countries::GH;
scope().attr("GI") = esl::geography::countries::GI;
scope().attr("GL") = esl::geography::countries::GL;
scope().attr("GM") = esl::geography::countries::GM;
scope().attr("GN") = esl::geography::countries::GN;
scope().attr("GP") = esl::geography::countries::GP;
scope().attr("GQ") = esl::geography::countries::GQ;
scope().attr("GR") = esl::geography::countries::GR;
scope().attr("GS") = esl::geography::countries::GS;
scope().attr("GT") = esl::geography::countries::GT;
scope().attr("GU") = esl::geography::countries::GU;
scope().attr("GW") = esl::geography::countries::GW;
scope().attr("GY") = esl::geography::countries::GY;
scope().attr("HK") = esl::geography::countries::HK;
scope().attr("HM") = esl::geography::countries::HM;
scope().attr("HN") = esl::geography::countries::HN;
scope().attr("HR") = esl::geography::countries::HR;
scope().attr("HT") = esl::geography::countries::HT;
scope().attr("HU") = esl::geography::countries::HU;
scope().attr("ID") = esl::geography::countries::ID;
scope().attr("IE") = esl::geography::countries::IE;
scope().attr("IL") = esl::geography::countries::IL;
scope().attr("IM") = esl::geography::countries::IM;
scope().attr("IN") = esl::geography::countries::IN;
scope().attr("IO") = esl::geography::countries::IO;
scope().attr("IQ") = esl::geography::countries::IQ;
scope().attr("IR") = esl::geography::countries::IR;
scope().attr("IS") = esl::geography::countries::IS;
scope().attr("IT") = esl::geography::countries::IT;
scope().attr("JE") = esl::geography::countries::JE;
scope().attr("JM") = esl::geography::countries::JM;
scope().attr("JO") = esl::geography::countries::JO;
scope().attr("JP") = esl::geography::countries::JP;
scope().attr("KE") = esl::geography::countries::KE;
scope().attr("KG") = esl::geography::countries::KG;
scope().attr("KH") = esl::geography::countries::KH;
scope().attr("KI") = esl::geography::countries::KI;
scope().attr("KM") = esl::geography::countries::KM;
scope().attr("KN") = esl::geography::countries::KN;
scope().attr("KP") = esl::geography::countries::KP;
scope().attr("KR") = esl::geography::countries::KR;
scope().attr("KW") = esl::geography::countries::KW;
scope().attr("KY") = esl::geography::countries::KY;
scope().attr("KZ") = esl::geography::countries::KZ;
scope().attr("LA") = esl::geography::countries::LA;
scope().attr("LB") = esl::geography::countries::LB;
scope().attr("LC") = esl::geography::countries::LC;
scope().attr("LI") = esl::geography::countries::LI;
scope().attr("LK") = esl::geography::countries::LK;
scope().attr("LR") = esl::geography::countries::LR;
scope().attr("LS") = esl::geography::countries::LS;
scope().attr("LT") = esl::geography::countries::LT;
scope().attr("LU") = esl::geography::countries::LU;
scope().attr("LV") = esl::geography::countries::LV;
scope().attr("LY") = esl::geography::countries::LY;
scope().attr("MA") = esl::geography::countries::MA;
scope().attr("MC") = esl::geography::countries::MC;
scope().attr("MD") = esl::geography::countries::MD;
scope().attr("ME") = esl::geography::countries::ME;
scope().attr("MF") = esl::geography::countries::MF;
scope().attr("MG") = esl::geography::countries::MG;
scope().attr("MH") = esl::geography::countries::MH;
scope().attr("MK") = esl::geography::countries::MK;
scope().attr("ML") = esl::geography::countries::ML;
scope().attr("MM") = esl::geography::countries::MM;
scope().attr("MN") = esl::geography::countries::MN;
scope().attr("MO") = esl::geography::countries::MO;
scope().attr("MP") = esl::geography::countries::MP;
scope().attr("MQ") = esl::geography::countries::MQ;
scope().attr("MR") = esl::geography::countries::MR;
scope().attr("MS") = esl::geography::countries::MS;
scope().attr("MT") = esl::geography::countries::MT;
scope().attr("MU") = esl::geography::countries::MU;
scope().attr("MV") = esl::geography::countries::MV;
scope().attr("MW") = esl::geography::countries::MW;
scope().attr("MX") = esl::geography::countries::MX;
scope().attr("MY") = esl::geography::countries::MY;
scope().attr("MZ") = esl::geography::countries::MZ;
scope().attr("NA") = esl::geography::countries::NA;
scope().attr("NC") = esl::geography::countries::NC;
scope().attr("NE") = esl::geography::countries::NE;
scope().attr("NF") = esl::geography::countries::NF;
scope().attr("NG") = esl::geography::countries::NG;
scope().attr("NI") = esl::geography::countries::NI;
scope().attr("NL") = esl::geography::countries::NL;
scope().attr("NO") = esl::geography::countries::NO;
scope().attr("NP") = esl::geography::countries::NP;
scope().attr("NR") = esl::geography::countries::NR;
scope().attr("NU") = esl::geography::countries::NU;
scope().attr("NZ") = esl::geography::countries::NZ;
scope().attr("OM") = esl::geography::countries::OM;
scope().attr("PA") = esl::geography::countries::PA;
scope().attr("PE") = esl::geography::countries::PE;
scope().attr("PF") = esl::geography::countries::PF;
scope().attr("PG") = esl::geography::countries::PG;
scope().attr("PH") = esl::geography::countries::PH;
scope().attr("PK") = esl::geography::countries::PK;
scope().attr("PL") = esl::geography::countries::PL;
scope().attr("PM") = esl::geography::countries::PM;
scope().attr("PN") = esl::geography::countries::PN;
scope().attr("PR") = esl::geography::countries::PR;
scope().attr("PS") = esl::geography::countries::PS;
scope().attr("PT") = esl::geography::countries::PT;
scope().attr("PW") = esl::geography::countries::PW;
scope().attr("PY") = esl::geography::countries::PY;
scope().attr("QA") = esl::geography::countries::QA;
scope().attr("RE") = esl::geography::countries::RE;
scope().attr("RO") = esl::geography::countries::RO;
scope().attr("RS") = esl::geography::countries::RS;
scope().attr("RU") = esl::geography::countries::RU;
scope().attr("RW") = esl::geography::countries::RW;
scope().attr("SA") = esl::geography::countries::SA;
scope().attr("SB") = esl::geography::countries::SB;
scope().attr("SC") = esl::geography::countries::SC;
scope().attr("SD") = esl::geography::countries::SD;
scope().attr("SE") = esl::geography::countries::SE;
scope().attr("SG") = esl::geography::countries::SG;
scope().attr("SH") = esl::geography::countries::SH;
scope().attr("SI") = esl::geography::countries::SI;
scope().attr("SJ") = esl::geography::countries::SJ;
scope().attr("SK") = esl::geography::countries::SK;
scope().attr("SL") = esl::geography::countries::SL;
scope().attr("SM") = esl::geography::countries::SM;
scope().attr("SN") = esl::geography::countries::SN;
scope().attr("SO") = esl::geography::countries::SO;
scope().attr("SR") = esl::geography::countries::SR;
scope().attr("SS") = esl::geography::countries::SS;
scope().attr("ST") = esl::geography::countries::ST;
scope().attr("SV") = esl::geography::countries::SV;
scope().attr("SX") = esl::geography::countries::SX;
scope().attr("SY") = esl::geography::countries::SY;
scope().attr("SZ") = esl::geography::countries::SZ;
scope().attr("TC") = esl::geography::countries::TC;
scope().attr("TD") = esl::geography::countries::TD;
scope().attr("TF") = esl::geography::countries::TF;
scope().attr("TG") = esl::geography::countries::TG;
scope().attr("TH") = esl::geography::countries::TH;
scope().attr("TJ") = esl::geography::countries::TJ;
scope().attr("TK") = esl::geography::countries::TK;
scope().attr("TL") = esl::geography::countries::TL;
scope().attr("TM") = esl::geography::countries::TM;
scope().attr("TN") = esl::geography::countries::TN;
scope().attr("TO") = esl::geography::countries::TO;
scope().attr("TR") = esl::geography::countries::TR;
scope().attr("TT") = esl::geography::countries::TT;
scope().attr("TV") = esl::geography::countries::TV;
scope().attr("TW") = esl::geography::countries::TW;
scope().attr("TZ") = esl::geography::countries::TZ;
scope().attr("UA") = esl::geography::countries::UA;
scope().attr("UG") = esl::geography::countries::UG;
scope().attr("UM") = esl::geography::countries::UM;
scope().attr("US") = esl::geography::countries::US;
scope().attr("UY") = esl::geography::countries::UY;
scope().attr("UZ") = esl::geography::countries::UZ;
scope().attr("VA") = esl::geography::countries::VA;
scope().attr("VC") = esl::geography::countries::VC;
scope().attr("VE") = esl::geography::countries::VE;
scope().attr("VG") = esl::geography::countries::VG;
scope().attr("VI") = esl::geography::countries::VI;
scope().attr("VN") = esl::geography::countries::VN;
scope().attr("VU") = esl::geography::countries::VU;
scope().attr("WF") = esl::geography::countries::WF;
scope().attr("WS") = esl::geography::countries::WS;
scope().attr("YE") = esl::geography::countries::YE;
scope().attr("YT") = esl::geography::countries::YT;
scope().attr("ZA") = esl::geography::countries::ZA;
scope().attr("ZM") = esl::geography::countries::ZM;
scope().attr("ZW") = esl::geography::countries::ZW;
}
}
////////////////////////////////////////////////////////////////////////////
// esl.interaction
////////////////////////////////////////////////////////////////////////////
{
boost::python::scope scope_interaction_ = create_scope("_interaction");
def("make_callback_handle", &make_callback_handle);
class_<communicator::callback_handle>("callback_handle");
class_<communicator::callback_t>("callback_t")
.def_readwrite("function", &communicator::callback_t::function)
.def_readwrite("description",
&communicator::callback_t::description)
.def_readwrite("message", &communicator::callback_t::message)
.def_readwrite("file", &communicator::callback_t::file)
.def_readwrite("line", &communicator::callback_t::line)
//.def("__call__", &communicator::callback_t::operator ())
;
enum_<communicator::scheduling>("scheduling")
.value("in_order", communicator::scheduling::in_order)
.value("random", communicator::scheduling::random);
class_<communicator::inbox_t>("inbox_t").def(
multimap_indexing_suite<communicator::inbox_t>())
// .def( "insert"
// , +[](const ... &r){return ; }
// )
;
class_<communicator::outbox_t>("outbox_t")
.def(
boost::python::vector_indexing_suite<communicator::outbox_t>());
class_<communicator>("communicator")
.def("send_message", send_message_python)
.def_readwrite("inbox", &communicator::inbox)
.def_readwrite("outbox", &communicator::outbox);
class_<header>("header",
init<message_code, python_identity, python_identity,
simulation::time_point, simulation::time_point>())
.def(init<message_code, python_identity, python_identity,
simulation::time_point>())
.def(init<message_code, python_identity, python_identity>())
.def(init<message_code, python_identity>())
.def(init<message_code>())
.def(init<message_code>())
.def_readwrite("type", &header::type)
.add_property("sender"
, +[](const header &r){return (python_identity)(r.sender); }
, +[](header &r, const python_identity &i){ r.sender = reinterpret_identity_cast<agent>(i); }
)
.add_property("recipient"
, +[](const header &r){return (python_identity)(r.recipient); }
, +[](header &r, const python_identity &i){ r.recipient = reinterpret_identity_cast<agent>(i); }
)
.def_readwrite("sent", &header::sent)
.def_readwrite("received", &header::received);
class_<python_message, bases<header>>("message").def_readonly(
"code", &python_message::python_code);
}
////////////////////////////////////////////////////////////////////////////
// esl.law
////////////////////////////////////////////////////////////////////////////
{
boost::python::scope scope_law_ = create_scope("_law");
class_<iso_17442>("iso_17442", init<std::string>())
.add_property("local", &python_iso_17442_local)
.add_property("code", &python_iso_17442_code)
.def("checksum", &python_iso_17442_checksum)
;
class_<legal_entity>("legal_entity")
;
class_<jurisdiction>("jurisdiction", init<geography::iso_3166_1_alpha_2, economics::iso_4217>())
.add_property("sovereign", &esl::law::jurisdiction::sovereign)
.add_property("tender", &esl::law::jurisdiction::tender)
;
//
// \brief this is not to be used, it is there to complete the type system
//
class_<identity<property>>( "property_identity")
.def("__init__", make_constructor(convert_digit_list_generic<identity<property>>))
.def("__str__", &python_represent_property_identity)
.def("__repr__", &python_represent_property_identity)
.def(self == self)
.def(self != self)
.def(self < self)
.def(self <= self)
.def(self > self)
.def(self >= self)
.def("__hash__", &python_property_identity_hash)
;
class_< property
//, bases<entity<void>>
>( "property", init<python_identity>())
.def("__init__", make_constructor(+[](const python_identity &i) { return boost::make_shared<property>(reinterpret_identity_cast<property>(i)); }))
.def("name", &property::name)
.add_property("identifier"
, +[](const property &r){return (python_identity)(r.identifier); }
)
;
class_<natural_person>
( "natural_person", init<esl::geography::iso_3166_1_alpha_2>())
.add_property("nationality", &natural_person::nationality)
;
{
boost::python::scope scope_jurisdictions_ = create_scope("_jurisdictions");
scope().attr("AF") = esl::law::jurisdictions::AF;
scope().attr("AL") = esl::law::jurisdictions::AL;
scope().attr("DZ") = esl::law::jurisdictions::DZ;
scope().attr("AS") = esl::law::jurisdictions::AS;
scope().attr("AD") = esl::law::jurisdictions::AD;
scope().attr("AO") = esl::law::jurisdictions::AO;
scope().attr("AI") = esl::law::jurisdictions::AI;
scope().attr("AG") = esl::law::jurisdictions::AG;
scope().attr("AR") = esl::law::jurisdictions::AR;
scope().attr("AM") = esl::law::jurisdictions::AM;
scope().attr("AW") = esl::law::jurisdictions::AW;
scope().attr("AU") = esl::law::jurisdictions::AU;
scope().attr("AT") = esl::law::jurisdictions::AT;
scope().attr("AZ") = esl::law::jurisdictions::AZ;
scope().attr("BS") = esl::law::jurisdictions::BS;
scope().attr("BH") = esl::law::jurisdictions::BH;
scope().attr("BD") = esl::law::jurisdictions::BD;
scope().attr("BB") = esl::law::jurisdictions::BB;
scope().attr("BY") = esl::law::jurisdictions::BY;
scope().attr("BE") = esl::law::jurisdictions::BE;
scope().attr("BZ") = esl::law::jurisdictions::BZ;
scope().attr("BJ") = esl::law::jurisdictions::BJ;
scope().attr("BM") = esl::law::jurisdictions::BM;
scope().attr("BT") = esl::law::jurisdictions::BT;
scope().attr("BO") = esl::law::jurisdictions::BO;
scope().attr("BQ") = esl::law::jurisdictions::BQ;
scope().attr("BA") = esl::law::jurisdictions::BA;
scope().attr("BW") = esl::law::jurisdictions::BW;
scope().attr("BV") = esl::law::jurisdictions::BV;
scope().attr("BR") = esl::law::jurisdictions::BR;
scope().attr("IO") = esl::law::jurisdictions::IO;
scope().attr("VG") = esl::law::jurisdictions::VG;
scope().attr("BN") = esl::law::jurisdictions::BN;
scope().attr("BG") = esl::law::jurisdictions::BG;
scope().attr("BF") = esl::law::jurisdictions::BF;
scope().attr("BI") = esl::law::jurisdictions::BI;
scope().attr("CV") = esl::law::jurisdictions::CV;
scope().attr("KH") = esl::law::jurisdictions::KH;
scope().attr("CM") = esl::law::jurisdictions::CM;
scope().attr("CA") = esl::law::jurisdictions::CA;
scope().attr("KY") = esl::law::jurisdictions::KY;
scope().attr("CF") = esl::law::jurisdictions::CF;
scope().attr("TD") = esl::law::jurisdictions::TD;
scope().attr("CL") = esl::law::jurisdictions::CL;
scope().attr("CN") = esl::law::jurisdictions::CN;
scope().attr("HK") = esl::law::jurisdictions::HK;
scope().attr("MO") = esl::law::jurisdictions::MO;
scope().attr("CX") = esl::law::jurisdictions::CX;
scope().attr("CC") = esl::law::jurisdictions::CC;
scope().attr("CO") = esl::law::jurisdictions::CO;
scope().attr("KM") = esl::law::jurisdictions::KM;
scope().attr("CG") = esl::law::jurisdictions::CG;
scope().attr("CK") = esl::law::jurisdictions::CK;
scope().attr("CR") = esl::law::jurisdictions::CR;
scope().attr("HR") = esl::law::jurisdictions::HR;
scope().attr("CU") = esl::law::jurisdictions::CU;
scope().attr("CW") = esl::law::jurisdictions::CW;
scope().attr("CY") = esl::law::jurisdictions::CY;
scope().attr("CZ") = esl::law::jurisdictions::CZ;
scope().attr("CI") = esl::law::jurisdictions::CI;
scope().attr("KP") = esl::law::jurisdictions::KP;
scope().attr("CD") = esl::law::jurisdictions::CD;
scope().attr("DK") = esl::law::jurisdictions::DK;
scope().attr("DJ") = esl::law::jurisdictions::DJ;
scope().attr("DM") = esl::law::jurisdictions::DM;
scope().attr("DO") = esl::law::jurisdictions::DO;
scope().attr("EC") = esl::law::jurisdictions::EC;
scope().attr("EG") = esl::law::jurisdictions::EG;
scope().attr("SV") = esl::law::jurisdictions::SV;
scope().attr("GQ") = esl::law::jurisdictions::GQ;
scope().attr("ER") = esl::law::jurisdictions::ER;
scope().attr("EE") = esl::law::jurisdictions::EE;
scope().attr("ET") = esl::law::jurisdictions::ET;
scope().attr("FO") = esl::law::jurisdictions::FO;
scope().attr("FJ") = esl::law::jurisdictions::FJ;
scope().attr("FI") = esl::law::jurisdictions::FI;
scope().attr("FR") = esl::law::jurisdictions::FR;
scope().attr("GF") = esl::law::jurisdictions::GF;
scope().attr("PF") = esl::law::jurisdictions::PF;
scope().attr("TF") = esl::law::jurisdictions::TF;
scope().attr("GA") = esl::law::jurisdictions::GA;
scope().attr("GM") = esl::law::jurisdictions::GM;
scope().attr("GE") = esl::law::jurisdictions::GE;
scope().attr("DE") = esl::law::jurisdictions::DE;
scope().attr("GH") = esl::law::jurisdictions::GH;
scope().attr("GI") = esl::law::jurisdictions::GI;
scope().attr("GR") = esl::law::jurisdictions::GR;
scope().attr("GL") = esl::law::jurisdictions::GL;
scope().attr("GD") = esl::law::jurisdictions::GD;
scope().attr("GP") = esl::law::jurisdictions::GP;
scope().attr("GU") = esl::law::jurisdictions::GU;
scope().attr("GT") = esl::law::jurisdictions::GT;
scope().attr("GG") = esl::law::jurisdictions::GG;
scope().attr("GN") = esl::law::jurisdictions::GN;
scope().attr("GW") = esl::law::jurisdictions::GW;
scope().attr("GY") = esl::law::jurisdictions::GY;
scope().attr("HT") = esl::law::jurisdictions::HT;
scope().attr("HM") = esl::law::jurisdictions::HM;
scope().attr("VA") = esl::law::jurisdictions::VA;
scope().attr("HN") = esl::law::jurisdictions::HN;
scope().attr("HU") = esl::law::jurisdictions::HU;
scope().attr("IS") = esl::law::jurisdictions::IS;
scope().attr("IN") = esl::law::jurisdictions::IN;
scope().attr("ID") = esl::law::jurisdictions::ID;
scope().attr("IR") = esl::law::jurisdictions::IR;
scope().attr("IQ") = esl::law::jurisdictions::IQ;
scope().attr("IE") = esl::law::jurisdictions::IE;
scope().attr("IM") = esl::law::jurisdictions::IM;
scope().attr("IL") = esl::law::jurisdictions::IL;
scope().attr("IT") = esl::law::jurisdictions::IT;
scope().attr("JM") = esl::law::jurisdictions::JM;
scope().attr("JP") = esl::law::jurisdictions::JP;
scope().attr("JE") = esl::law::jurisdictions::JE;
scope().attr("JO") = esl::law::jurisdictions::JO;
scope().attr("KZ") = esl::law::jurisdictions::KZ;
scope().attr("KE") = esl::law::jurisdictions::KE;
scope().attr("KI") = esl::law::jurisdictions::KI;
scope().attr("KW") = esl::law::jurisdictions::KW;
scope().attr("KG") = esl::law::jurisdictions::KG;
scope().attr("LA") = esl::law::jurisdictions::LA;
scope().attr("LV") = esl::law::jurisdictions::LV;
scope().attr("LB") = esl::law::jurisdictions::LB;
scope().attr("LS") = esl::law::jurisdictions::LS;
scope().attr("LR") = esl::law::jurisdictions::LR;
scope().attr("LY") = esl::law::jurisdictions::LY;
scope().attr("LI") = esl::law::jurisdictions::LI;
scope().attr("LT") = esl::law::jurisdictions::LT;
scope().attr("LU") = esl::law::jurisdictions::LU;
scope().attr("MG") = esl::law::jurisdictions::MG;
scope().attr("MW") = esl::law::jurisdictions::MW;
scope().attr("MY") = esl::law::jurisdictions::MY;
scope().attr("MV") = esl::law::jurisdictions::MV;
scope().attr("ML") = esl::law::jurisdictions::ML;
scope().attr("MT") = esl::law::jurisdictions::MT;
scope().attr("MH") = esl::law::jurisdictions::MH;
scope().attr("MQ") = esl::law::jurisdictions::MQ;
scope().attr("MR") = esl::law::jurisdictions::MR;
scope().attr("MU") = esl::law::jurisdictions::MU;
scope().attr("YT") = esl::law::jurisdictions::YT;
scope().attr("MX") = esl::law::jurisdictions::MX;
scope().attr("FM") = esl::law::jurisdictions::FM;
scope().attr("MC") = esl::law::jurisdictions::MC;
scope().attr("MN") = esl::law::jurisdictions::MN;
scope().attr("ME") = esl::law::jurisdictions::ME;
scope().attr("MS") = esl::law::jurisdictions::MS;
scope().attr("MA") = esl::law::jurisdictions::MA;
scope().attr("MZ") = esl::law::jurisdictions::MZ;
scope().attr("MM") = esl::law::jurisdictions::MM;
scope().attr("NA") = esl::law::jurisdictions::NA;
scope().attr("NR") = esl::law::jurisdictions::NR;
scope().attr("NP") = esl::law::jurisdictions::NP;
scope().attr("NL") = esl::law::jurisdictions::NL;
scope().attr("NC") = esl::law::jurisdictions::NC;
scope().attr("NZ") = esl::law::jurisdictions::NZ;
scope().attr("NI") = esl::law::jurisdictions::NI;
scope().attr("NE") = esl::law::jurisdictions::NE;
scope().attr("NG") = esl::law::jurisdictions::NG;
scope().attr("NU") = esl::law::jurisdictions::NU;
scope().attr("NF") = esl::law::jurisdictions::NF;
scope().attr("MP") = esl::law::jurisdictions::MP;
scope().attr("NO") = esl::law::jurisdictions::NO;
scope().attr("OM") = esl::law::jurisdictions::OM;
scope().attr("PK") = esl::law::jurisdictions::PK;
scope().attr("PW") = esl::law::jurisdictions::PW;
scope().attr("PA") = esl::law::jurisdictions::PA;
scope().attr("PG") = esl::law::jurisdictions::PG;
scope().attr("PY") = esl::law::jurisdictions::PY;
scope().attr("PE") = esl::law::jurisdictions::PE;
scope().attr("PH") = esl::law::jurisdictions::PH;
scope().attr("PN") = esl::law::jurisdictions::PN;
scope().attr("PL") = esl::law::jurisdictions::PL;
scope().attr("PT") = esl::law::jurisdictions::PT;
scope().attr("PR") = esl::law::jurisdictions::PR;
scope().attr("QA") = esl::law::jurisdictions::QA;
scope().attr("KR") = esl::law::jurisdictions::KR;
scope().attr("MD") = esl::law::jurisdictions::MD;
scope().attr("RO") = esl::law::jurisdictions::RO;
scope().attr("RU") = esl::law::jurisdictions::RU;
scope().attr("RW") = esl::law::jurisdictions::RW;
scope().attr("RE") = esl::law::jurisdictions::RE;
scope().attr("BL") = esl::law::jurisdictions::BL;
scope().attr("SH") = esl::law::jurisdictions::SH;
scope().attr("KN") = esl::law::jurisdictions::KN;
scope().attr("LC") = esl::law::jurisdictions::LC;
scope().attr("MF") = esl::law::jurisdictions::MF;
scope().attr("PM") = esl::law::jurisdictions::PM;
scope().attr("VC") = esl::law::jurisdictions::VC;
scope().attr("WS") = esl::law::jurisdictions::WS;
scope().attr("SM") = esl::law::jurisdictions::SM;
scope().attr("ST") = esl::law::jurisdictions::ST;
scope().attr("SA") = esl::law::jurisdictions::SA;
scope().attr("SN") = esl::law::jurisdictions::SN;
scope().attr("RS") = esl::law::jurisdictions::RS;
scope().attr("SC") = esl::law::jurisdictions::SC;
scope().attr("SL") = esl::law::jurisdictions::SL;
scope().attr("SG") = esl::law::jurisdictions::SG;
scope().attr("SX") = esl::law::jurisdictions::SX;
scope().attr("SK") = esl::law::jurisdictions::SK;
scope().attr("SI") = esl::law::jurisdictions::SI;
scope().attr("SB") = esl::law::jurisdictions::SB;
scope().attr("SO") = esl::law::jurisdictions::SO;
scope().attr("ZA") = esl::law::jurisdictions::ZA;
scope().attr("SS") = esl::law::jurisdictions::SS;
scope().attr("ES") = esl::law::jurisdictions::ES;
scope().attr("LK") = esl::law::jurisdictions::LK;
scope().attr("SD") = esl::law::jurisdictions::SD;
scope().attr("SR") = esl::law::jurisdictions::SR;
scope().attr("SJ") = esl::law::jurisdictions::SJ;
scope().attr("SZ") = esl::law::jurisdictions::SZ;
scope().attr("SE") = esl::law::jurisdictions::SE;
scope().attr("CH") = esl::law::jurisdictions::CH;
scope().attr("SY") = esl::law::jurisdictions::SY;
scope().attr("TJ") = esl::law::jurisdictions::TJ;
scope().attr("TH") = esl::law::jurisdictions::TH;
scope().attr("MK") = esl::law::jurisdictions::MK;
scope().attr("TL") = esl::law::jurisdictions::TL;
scope().attr("TG") = esl::law::jurisdictions::TG;
scope().attr("TK") = esl::law::jurisdictions::TK;
scope().attr("TO") = esl::law::jurisdictions::TO;
scope().attr("TT") = esl::law::jurisdictions::TT;
scope().attr("TN") = esl::law::jurisdictions::TN;
scope().attr("TR") = esl::law::jurisdictions::TR;
scope().attr("TM") = esl::law::jurisdictions::TM;
scope().attr("TC") = esl::law::jurisdictions::TC;
scope().attr("TV") = esl::law::jurisdictions::TV;
scope().attr("UG") = esl::law::jurisdictions::UG;
scope().attr("UA") = esl::law::jurisdictions::UA;
scope().attr("AE") = esl::law::jurisdictions::AE;
scope().attr("GB") = esl::law::jurisdictions::GB;
scope().attr("TZ") = esl::law::jurisdictions::TZ;
scope().attr("UM") = esl::law::jurisdictions::UM;
scope().attr("VI") = esl::law::jurisdictions::VI;
scope().attr("US") = esl::law::jurisdictions::US;
scope().attr("UY") = esl::law::jurisdictions::UY;
scope().attr("UZ") = esl::law::jurisdictions::UZ;
scope().attr("VU") = esl::law::jurisdictions::VU;
scope().attr("VE") = esl::law::jurisdictions::VE;
scope().attr("VN") = esl::law::jurisdictions::VN;
scope().attr("WF") = esl::law::jurisdictions::WF;
scope().attr("EH") = esl::law::jurisdictions::EH;
scope().attr("YE") = esl::law::jurisdictions::YE;
scope().attr("ZM") = esl::law::jurisdictions::ZM;
scope().attr("ZW") = esl::law::jurisdictions::ZW;
scope().attr("AX") = esl::law::jurisdictions::AX;
}
}
////////////////////////////////////////////////////////////////////////////
// esl.mathematics
////////////////////////////////////////////////////////////////////////////
{
boost::python::scope scope_mathematics_ = create_scope("_mathematics");
// class_<adept::Stack>("stack", init<>())
// .def("pause_recording", &adept::Stack::pause_recording)
// .def("continue_recording", &adept::Stack::continue_recording)
// .def("new_recording", &adept::Stack::new_recording)
// .def("compute_adjoint", &adept::Stack::compute_adjoint)
// ;
}
////////////////////////////////////////////////////////////////////////////
// esl.simulation
////////////////////////////////////////////////////////////////////////////
{
boost::python::scope scope_simulation_ = create_scope("_simulation");
class_<esl::entity<object>, boost::noncopyable>(
"entity", init<python_identity>())
.def_readonly("identifier", &esl::entity<object>::identifier)
.def(self_ns::str(self_ns::self))
.def("create", &create_identity<esl::entity<object>>)
.def(self == self)
.def(self != self)
;
class_<python_identity>("identity")
.def("__init__", make_constructor(convert_digit_list_generic<python_identity>))
.def_readonly("digits", &python_identity::digits)
.def("__str__", &python_identity::representation,
python_identity_representation_overload(args("width"), ""))
.def("__repr__", &python_identity::representation,
python_identity_representation_overload(args("width"), ""))
.def(self < self)
.def(self > self)
.def(self == self)
.def(self != self)
.def(self <= self)
.def(self >= self)
.def("__hash__", &python_identity_hash)
;
class_<agent_collection>("agent_collection", init<std::reference_wrapper<computation::environment>>())
.def("create_identifier", python_agent_collection_create_identifier)
.def("create", python_agent_collection_create)
.def("activate", python_agent_collection_activate)
.def("deactivate", python_agent_collection_deactivate)
.def("local_agents", agent_collection_local_agents)
;
class_<python_model, boost::noncopyable>("model",init<environment &, const parameter::parametrization &>())
.def_readonly("start", &python_model::start)
.def_readwrite("end", &python_model::end)
.def_readwrite("time", &python_model::time)
.def_readonly("sample", &python_model::sample)
.def("initialize", &python_model::initialize)
.def("step", &python_model::step)
.def("terminate", &python_model::terminate)
.def_readonly("world", &python_model::world)
.def_readwrite("agents", &python_model::agents)
;
def("time_point", python_time_point);
def("time_duration", python_time_duration);
class_<time_interval>("time_interval",
init<time_point, time_point>())
.def_readwrite("lower", &time_interval::lower)
.def_readwrite("upper", &time_interval::upper)
.def("empty", &time_interval::empty)
.def("singleton", &time_interval::singleton)
.def("degenerate", &time_interval::degenerate)
.def("contains", &time_interval::contains)
.def("__repr__", &time_interval::representation)
.def("__str__", &time_interval::representation);
class_<world, boost::noncopyable>("world")
.def_readonly("identifier", &world::identifier)
.def("__repr__", &world::representation)
.def("__str__", &world::representation)
.def("create", &create_identity<world>)
;
implicitly_convertible<python_identity,identity<agent>>();
implicitly_convertible<identity<agent>,python_identity>();
implicitly_convertible<python_identity,identity<property>>();
implicitly_convertible<identity<property>,python_identity>();
{
////////////////////////////////////////////////////////////////////
// esl.simulation.parameter
////////////////////////////////////////////////////////////////////
boost::python::scope scope_parameter_ = create_scope("_parameter");
class_<parameter_base, std::shared_ptr<parameter_base>>("parameter_base", "Abstract base class of model parameters.",init<>());
class_<constant<double>,bases<parameter_base>>("constant_double", "Floating point number model parameter.",init<double>());
implicitly_convertible<std::shared_ptr<constant<double>>, std::shared_ptr<parameter_base>>();
class_<constant<std::int64_t>,bases<parameter_base>>("constant_int64", "Signed 64-bit integer model parameter.", init<int64_t>());
implicitly_convertible<std::shared_ptr<constant<std::int64_t>>, std::shared_ptr<parameter_base>>();
class_<constant<std::uint64_t>,bases<parameter_base>>("constant_uint64","Unsigned 64-bit integer model parameter.", init<uint64_t>());
implicitly_convertible<std::shared_ptr<constant<std::uint64_t>>, std::shared_ptr<parameter_base>>();
class_<constant<price>,bases<parameter_base>>("constant_price", "Price model parameter.", init<price>());
implicitly_convertible<std::shared_ptr<constant<price>>, std::shared_ptr<parameter_base>>();
class_<std::map<std::string, std::shared_ptr<parameter_base> > >("parameter_values", "Stores model parameters by parameter name.")
.def(map_indexing_suite<std::map<std::string, std::shared_ptr<parameter_base> >>())
//.def("keys", map_indexing_suite<std::map<std::string, std::shared_ptr<parameter_base> >>::)
;
class_<parametrization>("parametrization", init<>())
.def("__getitem__", parametrization_get_helper)
.def_readwrite("values", ¶metrization::values)
;
}
}
}
}//namespace esl
#endif |
" Love Words " – 2 : 54
|
[STATEMENT]
lemma borel_eq_atLeastAtMost:
"borel = sigma UNIV (range (\<lambda>(a,b). {a..b} ::'a::ordered_euclidean_space set))"
(is "_ = ?SIGMA")
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. borel = sigma UNIV (range (\<lambda>(a, b). {a..b}))
[PROOF STEP]
proof (rule borel_eq_sigmaI5[OF borel_eq_atMost])
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<And>a. {..a} \<in> sets (sigma UNIV (range (\<lambda>(a, b). {a..b})))
2. \<And>a b. {a..b} \<in> sets borel
[PROOF STEP]
fix a::'a
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<And>a. {..a} \<in> sets (sigma UNIV (range (\<lambda>(a, b). {a..b})))
2. \<And>a b. {a..b} \<in> sets borel
[PROOF STEP]
have *: "{..a} = (\<Union>n::nat. {- real n *\<^sub>R One .. a})"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. {..a} = (\<Union>n. {- real n *\<^sub>R One..a})
[PROOF STEP]
proof (safe, simp_all add: eucl_le[where 'a='a])
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>x. \<forall>i\<in>Basis. x \<bullet> i \<le> a \<bullet> i \<Longrightarrow> \<exists>xa. \<forall>i\<in>Basis. - real xa \<le> x \<bullet> i
[PROOF STEP]
fix x :: 'a
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>x. \<forall>i\<in>Basis. x \<bullet> i \<le> a \<bullet> i \<Longrightarrow> \<exists>xa. \<forall>i\<in>Basis. - real xa \<le> x \<bullet> i
[PROOF STEP]
obtain k where k: "Max ((\<bullet>) (- x) ` Basis) \<le> real k"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>k. Max ((\<bullet>) (- x) ` Basis) \<le> real k \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
using real_arch_simple
[PROOF STATE]
proof (prove)
using this:
\<exists>n. ?x \<le> of_nat n
goal (1 subgoal):
1. (\<And>k. Max ((\<bullet>) (- x) ` Basis) \<le> real k \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
Max ((\<bullet>) (- x) ` Basis) \<le> real k
goal (1 subgoal):
1. \<And>x. \<forall>i\<in>Basis. x \<bullet> i \<le> a \<bullet> i \<Longrightarrow> \<exists>xa. \<forall>i\<in>Basis. - real xa \<le> x \<bullet> i
[PROOF STEP]
{
[PROOF STATE]
proof (state)
this:
Max ((\<bullet>) (- x) ` Basis) \<le> real k
goal (1 subgoal):
1. \<And>x. \<forall>i\<in>Basis. x \<bullet> i \<le> a \<bullet> i \<Longrightarrow> \<exists>xa. \<forall>i\<in>Basis. - real xa \<le> x \<bullet> i
[PROOF STEP]
fix i :: 'a
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>x. \<forall>i\<in>Basis. x \<bullet> i \<le> a \<bullet> i \<Longrightarrow> \<exists>xa. \<forall>i\<in>Basis. - real xa \<le> x \<bullet> i
[PROOF STEP]
assume "i \<in> Basis"
[PROOF STATE]
proof (state)
this:
i \<in> Basis
goal (1 subgoal):
1. \<And>x. \<forall>i\<in>Basis. x \<bullet> i \<le> a \<bullet> i \<Longrightarrow> \<exists>xa. \<forall>i\<in>Basis. - real xa \<le> x \<bullet> i
[PROOF STEP]
with k
[PROOF STATE]
proof (chain)
picking this:
Max ((\<bullet>) (- x) ` Basis) \<le> real k
i \<in> Basis
[PROOF STEP]
have "- x\<bullet>i \<le> real k"
[PROOF STATE]
proof (prove)
using this:
Max ((\<bullet>) (- x) ` Basis) \<le> real k
i \<in> Basis
goal (1 subgoal):
1. - x \<bullet> i \<le> real k
[PROOF STEP]
by (subst (asm) Max_le_iff) (auto simp: field_simps)
[PROOF STATE]
proof (state)
this:
- x \<bullet> i \<le> real k
goal (1 subgoal):
1. \<And>x. \<forall>i\<in>Basis. x \<bullet> i \<le> a \<bullet> i \<Longrightarrow> \<exists>xa. \<forall>i\<in>Basis. - real xa \<le> x \<bullet> i
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
- x \<bullet> i \<le> real k
[PROOF STEP]
have "- real k \<le> x\<bullet>i"
[PROOF STATE]
proof (prove)
using this:
- x \<bullet> i \<le> real k
goal (1 subgoal):
1. - real k \<le> x \<bullet> i
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
- real k \<le> x \<bullet> i
goal (1 subgoal):
1. \<And>x. \<forall>i\<in>Basis. x \<bullet> i \<le> a \<bullet> i \<Longrightarrow> \<exists>xa. \<forall>i\<in>Basis. - real xa \<le> x \<bullet> i
[PROOF STEP]
}
[PROOF STATE]
proof (state)
this:
?i2 \<in> Basis \<Longrightarrow> - real k \<le> x \<bullet> ?i2
goal (1 subgoal):
1. \<And>x. \<forall>i\<in>Basis. x \<bullet> i \<le> a \<bullet> i \<Longrightarrow> \<exists>xa. \<forall>i\<in>Basis. - real xa \<le> x \<bullet> i
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
?i2 \<in> Basis \<Longrightarrow> - real k \<le> x \<bullet> ?i2
[PROOF STEP]
show "\<exists>n::nat. \<forall>i\<in>Basis. - real n \<le> x \<bullet> i"
[PROOF STATE]
proof (prove)
using this:
?i2 \<in> Basis \<Longrightarrow> - real k \<le> x \<bullet> ?i2
goal (1 subgoal):
1. \<exists>n. \<forall>i\<in>Basis. - real n \<le> x \<bullet> i
[PROOF STEP]
by (auto intro!: exI[of _ k])
[PROOF STATE]
proof (state)
this:
\<exists>n. \<forall>i\<in>Basis. - real n \<le> x \<bullet> i
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
{..a} = (\<Union>n. {- real n *\<^sub>R One..a})
goal (2 subgoals):
1. \<And>a. {..a} \<in> sets (sigma UNIV (range (\<lambda>(a, b). {a..b})))
2. \<And>a b. {a..b} \<in> sets borel
[PROOF STEP]
show "{..a} \<in> ?SIGMA"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. {..a} \<in> sets (sigma UNIV (range (\<lambda>(a, b). {a..b})))
[PROOF STEP]
unfolding *
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<Union>n. {- real n *\<^sub>R One..a}) \<in> sets (sigma UNIV (range (\<lambda>(a, b). {a..b})))
[PROOF STEP]
by (intro sets.countable_UN)
(auto intro!: sigma_sets_top)
[PROOF STATE]
proof (state)
this:
{..a} \<in> sets (sigma UNIV (range (\<lambda>(a, b). {a..b})))
goal (1 subgoal):
1. \<And>a b. {a..b} \<in> sets borel
[PROOF STEP]
qed auto |
\subsection{Bounds for Data Types} \label{sec:overview:data}
Bounded refinements are also very useful in the first-order
setting, for example, when working with data types.
\subsubsection*{Abstracting Refinements over Data}
Lets start by abstracting refinements over data
definitions~\cite{vazou13}. Consider the @List@ type
abstractly refined with @p :: a -> a -> Prop@, a binary relation
between two values of type @a@:
%
\begin{code}
data List <p> a
= [] | (:) {h :: a, t :: List<p> a<p h>}
\end{code}
%
Intuitively, the definition states that each "tail" is a list of
elements that are @p@-related to the ``head'' @h@. That is,
in a list $[x_1,\ldots,x_n]$ for each $1 \leq i < j \leq n$, we
have $(\cc{p}\ x_i\ x_j)$.
\paragraph{Ordered Lists} To see why this abstraction is useful,
observe that we can define concrete refinements:
%
\begin{code}
inc = \hd v -> hd <= v
\end{code}
%
and use them to specify and verify that sorting routines return
lists in increasing order:
%
\begin{code}
isort :: List a -> List<inc> a
isort = foldr insert []
insert :: a -> List<inc> a -> List<inc> a
insert = -- elided for brevity
\end{code}
\paragraph{QuickSort} However, when we try to verify:
%
\begin{code}
qsort :: List a -> List<inc> a
qsort [] = []
qsort (x:xs) = qsort ls ++ x : qsort rs
where
ls = [y | y <- xs, y <= x]
rs = [z | z <- xs, x < z]
\end{code}
%
we run into a surprising problem: how can we type the \emph{append}
function @(++)@ in a way that lets us prove that the concatenation
above preserves order?
\subsubsection*{Appending Lists}
Actually, even talking about order is presumes that we are interested
in a particular instantiation for the @List@ refinement. How can we
generically ensure that some abstract refinement @p@? Here's how; we
define a bound:
%
\begin{code}
bound Meet p q r = \x1 x2 ->
q x1 => r x2 => p x1 x2
\end{code}
%
that states that if two values @x1@ and @x2@ respectively satisfy
the (unary) properties @q x1@ and @r x2@ then they satisfy the
binary property @p x1 x2@. We can now use this to give append a
type that preserves the abstract binary relation @r@:
%
\begin{code}
(++) :: (Meet p q r) =>
List<p> a<q> -> List<p> a<r> -> List<p> a
[] ++ ys = ys
(x:xs) ++ ys = x : xs ++ ys
\end{code}
\paragraph{To verify \cc{qsort}} \toolname automatically instantiates the
refinements at the call to @(++)@ as:
%
\begin{code}
p |-> \hd v -> hd <= v -- inc
q |-> \v -> v <= x
r |-> \v -> x < v
\end{code}
%
This instantiation is permitted as upon instantiation, the bound
yields the VC:
%
\begin{code}
x1 <= x => x < x2 => x1 <= x2
\end{code}
%
which is easily validated by the SMT solver, thereby verifying that
the concatenation and hence @qsort@ produces increasingly ordered
lists of type @List<inc> a@.
\subsubsection*{Reversing Lists}
As a final example, consider the tail recursive list @reverse@ function:
%
\begin{code}
reverse [] = []
reverse (x:xs) = go x [] xs
where
go x acc [] = x : acc
go x acc (y:xs) = go y (x : acc) xs
\end{code}
As with append, we would like to assign @reverse@ a
refinement-generic type that does not bake order into the
signature. The natural specification is that if the input was a
@List<p> a@ then the output must be a @List<q> a@ where the
binary relation @q@ is the inverse of @p@.
\paragraph{We can specify inversion} via a bound:
%
\begin{code}
bound Inverse p q = \x y -> p x y => q y x
\end{code}
%
and use it to type
%
\begin{code}
reverse :: (Inverse p q)
=> List<p> a -> List<q> a
\end{code}
\paragraph{We can use \cc{reverse}} to specify and verify that @decsort@
returns lists sorted in decreasing order:
%
\begin{code}
decsort :: List a -> List<dec> a
decsort = reverse `compose` qsort
\end{code}
%
where @dec = \hd v -> hd >= v@. Verification proceeds by
by automatically instantiating @p@ and @q@ with the (valid)
concrete refinements:
%
\begin{code}
p |-> \hd v -> hd <= v
q |-> \hd v -> v <= hd
\end{code}
%% -- inferring
%% go :: x:a -> List<q> a<q x> -> List<p> a<p x>
%% -> List<q> a
%% \end{code}
|
Lemma NotnotP_andP : (forall (P : Prop), ~(~P /\ ~~P)).
Proof.
intros.
easy.
Qed.
Theorem modDeMorgan_imply_TE : (forall (P Q : Prop), ~(~P /\ ~Q) -> P \/ Q)
-> (forall (P : Prop), P \/ ~ P).
Proof.
intros.
apply H.
apply NotnotP_andP.
Qed.
Theorem TE_imply_modDN : (forall (P : Prop), P \/ ~P)
-> forall (P : Prop), (~P -> P) -> P.
Proof.
intros.
destruct (H P).
+ easy.
+ apply H0.
apply H1.
Qed.
<<<<<<< HEAD
(* En coq, not P = p -> false *)
=======
Theorem modDN_imply_Pierce : (forall (P : Prop), (~P -> P) -> P)
-> (forall (P Q : Prop), ((P -> Q) -> P) -> P).
Proof.
intros.
Qed.
>>>>>>> 00e85d079641e974cef87d45fe3b169c1e270f46
|
[GOAL]
𝕜 : Type u_1
inst✝¹ : NontriviallyNormedField 𝕜
inst✝ : CompleteSpace 𝕜
⊢ 𝔠 ≤ #𝕜
[PROOFSTEP]
suffices ∃ f : (ℕ → Bool) → 𝕜, range f ⊆ univ ∧ Continuous f ∧ Injective f
by
rcases this with ⟨f, -, -, f_inj⟩
simpa using lift_mk_le_lift_mk_of_injective f_inj
[GOAL]
𝕜 : Type u_1
inst✝¹ : NontriviallyNormedField 𝕜
inst✝ : CompleteSpace 𝕜
this : ∃ f, range f ⊆ Set.univ ∧ Continuous f ∧ Injective f
⊢ 𝔠 ≤ #𝕜
[PROOFSTEP]
rcases this with ⟨f, -, -, f_inj⟩
[GOAL]
case intro.intro.intro
𝕜 : Type u_1
inst✝¹ : NontriviallyNormedField 𝕜
inst✝ : CompleteSpace 𝕜
f : (ℕ → Bool) → 𝕜
f_inj : Injective f
⊢ 𝔠 ≤ #𝕜
[PROOFSTEP]
simpa using lift_mk_le_lift_mk_of_injective f_inj
[GOAL]
𝕜 : Type u_1
inst✝¹ : NontriviallyNormedField 𝕜
inst✝ : CompleteSpace 𝕜
⊢ ∃ f, range f ⊆ Set.univ ∧ Continuous f ∧ Injective f
[PROOFSTEP]
apply Perfect.exists_nat_bool_injection _ univ_nonempty
[GOAL]
𝕜 : Type u_1
inst✝¹ : NontriviallyNormedField 𝕜
inst✝ : CompleteSpace 𝕜
⊢ Perfect Set.univ
[PROOFSTEP]
refine ⟨isClosed_univ, preperfect_iff_nhds.2 (fun x _ U hU ↦ ?_)⟩
[GOAL]
𝕜 : Type u_1
inst✝¹ : NontriviallyNormedField 𝕜
inst✝ : CompleteSpace 𝕜
x : 𝕜
x✝ : x ∈ Set.univ
U : Set 𝕜
hU : U ∈ 𝓝 x
⊢ ∃ y, y ∈ U ∩ Set.univ ∧ y ≠ x
[PROOFSTEP]
rcases NormedField.exists_norm_lt_one 𝕜 with ⟨c, c_pos, hc⟩
[GOAL]
case intro.intro
𝕜 : Type u_1
inst✝¹ : NontriviallyNormedField 𝕜
inst✝ : CompleteSpace 𝕜
x : 𝕜
x✝ : x ∈ Set.univ
U : Set 𝕜
hU : U ∈ 𝓝 x
c : 𝕜
c_pos : 0 < ‖c‖
hc : ‖c‖ < 1
⊢ ∃ y, y ∈ U ∩ Set.univ ∧ y ≠ x
[PROOFSTEP]
have A : Tendsto (fun n ↦ x + c ^ n) atTop (𝓝 (x + 0)) :=
tendsto_const_nhds.add (tendsto_pow_atTop_nhds_0_of_norm_lt_1 hc)
[GOAL]
case intro.intro
𝕜 : Type u_1
inst✝¹ : NontriviallyNormedField 𝕜
inst✝ : CompleteSpace 𝕜
x : 𝕜
x✝ : x ∈ Set.univ
U : Set 𝕜
hU : U ∈ 𝓝 x
c : 𝕜
c_pos : 0 < ‖c‖
hc : ‖c‖ < 1
A : Tendsto (fun n => x + c ^ n) atTop (𝓝 (x + 0))
⊢ ∃ y, y ∈ U ∩ Set.univ ∧ y ≠ x
[PROOFSTEP]
rw [add_zero] at A
[GOAL]
case intro.intro
𝕜 : Type u_1
inst✝¹ : NontriviallyNormedField 𝕜
inst✝ : CompleteSpace 𝕜
x : 𝕜
x✝ : x ∈ Set.univ
U : Set 𝕜
hU : U ∈ 𝓝 x
c : 𝕜
c_pos : 0 < ‖c‖
hc : ‖c‖ < 1
A : Tendsto (fun n => x + c ^ n) atTop (𝓝 x)
⊢ ∃ y, y ∈ U ∩ Set.univ ∧ y ≠ x
[PROOFSTEP]
have B : ∀ᶠ n in atTop, x + c ^ n ∈ U := tendsto_def.1 A U hU
[GOAL]
case intro.intro
𝕜 : Type u_1
inst✝¹ : NontriviallyNormedField 𝕜
inst✝ : CompleteSpace 𝕜
x : 𝕜
x✝ : x ∈ Set.univ
U : Set 𝕜
hU : U ∈ 𝓝 x
c : 𝕜
c_pos : 0 < ‖c‖
hc : ‖c‖ < 1
A : Tendsto (fun n => x + c ^ n) atTop (𝓝 x)
B : ∀ᶠ (n : ℕ) in atTop, x + c ^ n ∈ U
⊢ ∃ y, y ∈ U ∩ Set.univ ∧ y ≠ x
[PROOFSTEP]
rcases B.exists with ⟨n, hn⟩
[GOAL]
case intro.intro.intro
𝕜 : Type u_1
inst✝¹ : NontriviallyNormedField 𝕜
inst✝ : CompleteSpace 𝕜
x : 𝕜
x✝ : x ∈ Set.univ
U : Set 𝕜
hU : U ∈ 𝓝 x
c : 𝕜
c_pos : 0 < ‖c‖
hc : ‖c‖ < 1
A : Tendsto (fun n => x + c ^ n) atTop (𝓝 x)
B : ∀ᶠ (n : ℕ) in atTop, x + c ^ n ∈ U
n : ℕ
hn : x + c ^ n ∈ U
⊢ ∃ y, y ∈ U ∩ Set.univ ∧ y ≠ x
[PROOFSTEP]
refine ⟨x + c ^ n, by simpa using hn, ?_⟩
[GOAL]
𝕜 : Type u_1
inst✝¹ : NontriviallyNormedField 𝕜
inst✝ : CompleteSpace 𝕜
x : 𝕜
x✝ : x ∈ Set.univ
U : Set 𝕜
hU : U ∈ 𝓝 x
c : 𝕜
c_pos : 0 < ‖c‖
hc : ‖c‖ < 1
A : Tendsto (fun n => x + c ^ n) atTop (𝓝 x)
B : ∀ᶠ (n : ℕ) in atTop, x + c ^ n ∈ U
n : ℕ
hn : x + c ^ n ∈ U
⊢ x + c ^ n ∈ U ∩ Set.univ
[PROOFSTEP]
simpa using hn
[GOAL]
case intro.intro.intro
𝕜 : Type u_1
inst✝¹ : NontriviallyNormedField 𝕜
inst✝ : CompleteSpace 𝕜
x : 𝕜
x✝ : x ∈ Set.univ
U : Set 𝕜
hU : U ∈ 𝓝 x
c : 𝕜
c_pos : 0 < ‖c‖
hc : ‖c‖ < 1
A : Tendsto (fun n => x + c ^ n) atTop (𝓝 x)
B : ∀ᶠ (n : ℕ) in atTop, x + c ^ n ∈ U
n : ℕ
hn : x + c ^ n ∈ U
⊢ x + c ^ n ≠ x
[PROOFSTEP]
simp only [ne_eq, add_right_eq_self]
[GOAL]
case intro.intro.intro
𝕜 : Type u_1
inst✝¹ : NontriviallyNormedField 𝕜
inst✝ : CompleteSpace 𝕜
x : 𝕜
x✝ : x ∈ Set.univ
U : Set 𝕜
hU : U ∈ 𝓝 x
c : 𝕜
c_pos : 0 < ‖c‖
hc : ‖c‖ < 1
A : Tendsto (fun n => x + c ^ n) atTop (𝓝 x)
B : ∀ᶠ (n : ℕ) in atTop, x + c ^ n ∈ U
n : ℕ
hn : x + c ^ n ∈ U
⊢ ¬c ^ n = 0
[PROOFSTEP]
apply pow_ne_zero
[GOAL]
case intro.intro.intro.h
𝕜 : Type u_1
inst✝¹ : NontriviallyNormedField 𝕜
inst✝ : CompleteSpace 𝕜
x : 𝕜
x✝ : x ∈ Set.univ
U : Set 𝕜
hU : U ∈ 𝓝 x
c : 𝕜
c_pos : 0 < ‖c‖
hc : ‖c‖ < 1
A : Tendsto (fun n => x + c ^ n) atTop (𝓝 x)
B : ∀ᶠ (n : ℕ) in atTop, x + c ^ n ∈ U
n : ℕ
hn : x + c ^ n ∈ U
⊢ c ≠ 0
[PROOFSTEP]
simpa using c_pos
[GOAL]
𝕜 : Type u
E : Type v
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : CompleteSpace 𝕜
inst✝² : AddCommGroup E
inst✝¹ : Module 𝕜 E
inst✝ : Nontrivial E
⊢ 𝔠 ≤ #E
[PROOFSTEP]
have A : lift.{v} (𝔠 : Cardinal.{u}) ≤ lift.{v} (#𝕜) := by
simpa using continuum_le_cardinal_of_nontriviallyNormedField 𝕜
[GOAL]
𝕜 : Type u
E : Type v
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : CompleteSpace 𝕜
inst✝² : AddCommGroup E
inst✝¹ : Module 𝕜 E
inst✝ : Nontrivial E
⊢ lift 𝔠 ≤ lift #𝕜
[PROOFSTEP]
simpa using continuum_le_cardinal_of_nontriviallyNormedField 𝕜
[GOAL]
𝕜 : Type u
E : Type v
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : CompleteSpace 𝕜
inst✝² : AddCommGroup E
inst✝¹ : Module 𝕜 E
inst✝ : Nontrivial E
A : lift 𝔠 ≤ lift #𝕜
⊢ 𝔠 ≤ #E
[PROOFSTEP]
simpa using A.trans (Cardinal.mk_le_of_module 𝕜 E)
[GOAL]
E : Type u_1
𝕜 : Type u_2
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : AddCommGroup E
inst✝² : Module 𝕜 E
inst✝¹ : TopologicalSpace E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : s ∈ 𝓝 0
⊢ #↑s = #E
[PROOFSTEP]
obtain ⟨c, hc⟩ : ∃ x : 𝕜, 1 < ‖x‖ := NormedField.exists_lt_norm 𝕜 1
[GOAL]
case intro
E : Type u_1
𝕜 : Type u_2
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : AddCommGroup E
inst✝² : Module 𝕜 E
inst✝¹ : TopologicalSpace E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : s ∈ 𝓝 0
c : 𝕜
hc : 1 < ‖c‖
⊢ #↑s = #E
[PROOFSTEP]
have cn_ne : ∀ n, c ^ n ≠ 0 := by
intro n
apply pow_ne_zero
rintro rfl
simp only [norm_zero] at hc
exact lt_irrefl _ (hc.trans zero_lt_one)
[GOAL]
E : Type u_1
𝕜 : Type u_2
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : AddCommGroup E
inst✝² : Module 𝕜 E
inst✝¹ : TopologicalSpace E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : s ∈ 𝓝 0
c : 𝕜
hc : 1 < ‖c‖
⊢ ∀ (n : ℕ), c ^ n ≠ 0
[PROOFSTEP]
intro n
[GOAL]
E : Type u_1
𝕜 : Type u_2
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : AddCommGroup E
inst✝² : Module 𝕜 E
inst✝¹ : TopologicalSpace E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : s ∈ 𝓝 0
c : 𝕜
hc : 1 < ‖c‖
n : ℕ
⊢ c ^ n ≠ 0
[PROOFSTEP]
apply pow_ne_zero
[GOAL]
case h
E : Type u_1
𝕜 : Type u_2
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : AddCommGroup E
inst✝² : Module 𝕜 E
inst✝¹ : TopologicalSpace E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : s ∈ 𝓝 0
c : 𝕜
hc : 1 < ‖c‖
n : ℕ
⊢ c ≠ 0
[PROOFSTEP]
rintro rfl
[GOAL]
case h
E : Type u_1
𝕜 : Type u_2
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : AddCommGroup E
inst✝² : Module 𝕜 E
inst✝¹ : TopologicalSpace E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : s ∈ 𝓝 0
n : ℕ
hc : 1 < ‖0‖
⊢ False
[PROOFSTEP]
simp only [norm_zero] at hc
[GOAL]
case h
E : Type u_1
𝕜 : Type u_2
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : AddCommGroup E
inst✝² : Module 𝕜 E
inst✝¹ : TopologicalSpace E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : s ∈ 𝓝 0
n : ℕ
hc : 1 < 0
⊢ False
[PROOFSTEP]
exact lt_irrefl _ (hc.trans zero_lt_one)
[GOAL]
case intro
E : Type u_1
𝕜 : Type u_2
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : AddCommGroup E
inst✝² : Module 𝕜 E
inst✝¹ : TopologicalSpace E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : s ∈ 𝓝 0
c : 𝕜
hc : 1 < ‖c‖
cn_ne : ∀ (n : ℕ), c ^ n ≠ 0
⊢ #↑s = #E
[PROOFSTEP]
have A : ∀ (x : E), ∀ᶠ n in (atTop : Filter ℕ), x ∈ c ^ n • s :=
by
intro x
have : Tendsto (fun n ↦ (c ^ n)⁻¹ • x) atTop (𝓝 ((0 : 𝕜) • x)) :=
by
have : Tendsto (fun n ↦ (c ^ n)⁻¹) atTop (𝓝 0) :=
by
simp_rw [← inv_pow]
apply tendsto_pow_atTop_nhds_0_of_norm_lt_1
rw [norm_inv]
exact inv_lt_one hc
exact Tendsto.smul_const this x
rw [zero_smul] at this
filter_upwards [this hs] with n (hn : (c ^ n)⁻¹ • x ∈ s)
exact (mem_smul_set_iff_inv_smul_mem₀ (cn_ne n) _ _).2 hn
[GOAL]
E : Type u_1
𝕜 : Type u_2
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : AddCommGroup E
inst✝² : Module 𝕜 E
inst✝¹ : TopologicalSpace E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : s ∈ 𝓝 0
c : 𝕜
hc : 1 < ‖c‖
cn_ne : ∀ (n : ℕ), c ^ n ≠ 0
⊢ ∀ (x : E), ∀ᶠ (n : ℕ) in atTop, x ∈ c ^ n • s
[PROOFSTEP]
intro x
[GOAL]
E : Type u_1
𝕜 : Type u_2
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : AddCommGroup E
inst✝² : Module 𝕜 E
inst✝¹ : TopologicalSpace E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : s ∈ 𝓝 0
c : 𝕜
hc : 1 < ‖c‖
cn_ne : ∀ (n : ℕ), c ^ n ≠ 0
x : E
⊢ ∀ᶠ (n : ℕ) in atTop, x ∈ c ^ n • s
[PROOFSTEP]
have : Tendsto (fun n ↦ (c ^ n)⁻¹ • x) atTop (𝓝 ((0 : 𝕜) • x)) :=
by
have : Tendsto (fun n ↦ (c ^ n)⁻¹) atTop (𝓝 0) :=
by
simp_rw [← inv_pow]
apply tendsto_pow_atTop_nhds_0_of_norm_lt_1
rw [norm_inv]
exact inv_lt_one hc
exact Tendsto.smul_const this x
[GOAL]
E : Type u_1
𝕜 : Type u_2
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : AddCommGroup E
inst✝² : Module 𝕜 E
inst✝¹ : TopologicalSpace E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : s ∈ 𝓝 0
c : 𝕜
hc : 1 < ‖c‖
cn_ne : ∀ (n : ℕ), c ^ n ≠ 0
x : E
⊢ Tendsto (fun n => (c ^ n)⁻¹ • x) atTop (𝓝 (0 • x))
[PROOFSTEP]
have : Tendsto (fun n ↦ (c ^ n)⁻¹) atTop (𝓝 0) := by
simp_rw [← inv_pow]
apply tendsto_pow_atTop_nhds_0_of_norm_lt_1
rw [norm_inv]
exact inv_lt_one hc
[GOAL]
E : Type u_1
𝕜 : Type u_2
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : AddCommGroup E
inst✝² : Module 𝕜 E
inst✝¹ : TopologicalSpace E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : s ∈ 𝓝 0
c : 𝕜
hc : 1 < ‖c‖
cn_ne : ∀ (n : ℕ), c ^ n ≠ 0
x : E
⊢ Tendsto (fun n => (c ^ n)⁻¹) atTop (𝓝 0)
[PROOFSTEP]
simp_rw [← inv_pow]
[GOAL]
E : Type u_1
𝕜 : Type u_2
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : AddCommGroup E
inst✝² : Module 𝕜 E
inst✝¹ : TopologicalSpace E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : s ∈ 𝓝 0
c : 𝕜
hc : 1 < ‖c‖
cn_ne : ∀ (n : ℕ), c ^ n ≠ 0
x : E
⊢ Tendsto (fun n => c⁻¹ ^ n) atTop (𝓝 0)
[PROOFSTEP]
apply tendsto_pow_atTop_nhds_0_of_norm_lt_1
[GOAL]
case h
E : Type u_1
𝕜 : Type u_2
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : AddCommGroup E
inst✝² : Module 𝕜 E
inst✝¹ : TopologicalSpace E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : s ∈ 𝓝 0
c : 𝕜
hc : 1 < ‖c‖
cn_ne : ∀ (n : ℕ), c ^ n ≠ 0
x : E
⊢ ‖c⁻¹‖ < 1
[PROOFSTEP]
rw [norm_inv]
[GOAL]
case h
E : Type u_1
𝕜 : Type u_2
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : AddCommGroup E
inst✝² : Module 𝕜 E
inst✝¹ : TopologicalSpace E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : s ∈ 𝓝 0
c : 𝕜
hc : 1 < ‖c‖
cn_ne : ∀ (n : ℕ), c ^ n ≠ 0
x : E
⊢ ‖c‖⁻¹ < 1
[PROOFSTEP]
exact inv_lt_one hc
[GOAL]
E : Type u_1
𝕜 : Type u_2
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : AddCommGroup E
inst✝² : Module 𝕜 E
inst✝¹ : TopologicalSpace E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : s ∈ 𝓝 0
c : 𝕜
hc : 1 < ‖c‖
cn_ne : ∀ (n : ℕ), c ^ n ≠ 0
x : E
this : Tendsto (fun n => (c ^ n)⁻¹) atTop (𝓝 0)
⊢ Tendsto (fun n => (c ^ n)⁻¹ • x) atTop (𝓝 (0 • x))
[PROOFSTEP]
exact Tendsto.smul_const this x
[GOAL]
E : Type u_1
𝕜 : Type u_2
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : AddCommGroup E
inst✝² : Module 𝕜 E
inst✝¹ : TopologicalSpace E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : s ∈ 𝓝 0
c : 𝕜
hc : 1 < ‖c‖
cn_ne : ∀ (n : ℕ), c ^ n ≠ 0
x : E
this : Tendsto (fun n => (c ^ n)⁻¹ • x) atTop (𝓝 (0 • x))
⊢ ∀ᶠ (n : ℕ) in atTop, x ∈ c ^ n • s
[PROOFSTEP]
rw [zero_smul] at this
[GOAL]
E : Type u_1
𝕜 : Type u_2
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : AddCommGroup E
inst✝² : Module 𝕜 E
inst✝¹ : TopologicalSpace E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : s ∈ 𝓝 0
c : 𝕜
hc : 1 < ‖c‖
cn_ne : ∀ (n : ℕ), c ^ n ≠ 0
x : E
this : Tendsto (fun n => (c ^ n)⁻¹ • x) atTop (𝓝 0)
⊢ ∀ᶠ (n : ℕ) in atTop, x ∈ c ^ n • s
[PROOFSTEP]
filter_upwards [this hs] with n (hn : (c ^ n)⁻¹ • x ∈ s)
[GOAL]
case h
E : Type u_1
𝕜 : Type u_2
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : AddCommGroup E
inst✝² : Module 𝕜 E
inst✝¹ : TopologicalSpace E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : s ∈ 𝓝 0
c : 𝕜
hc : 1 < ‖c‖
cn_ne : ∀ (n : ℕ), c ^ n ≠ 0
x : E
this : Tendsto (fun n => (c ^ n)⁻¹ • x) atTop (𝓝 0)
n : ℕ
hn : (c ^ n)⁻¹ • x ∈ s
⊢ x ∈ c ^ n • s
[PROOFSTEP]
exact (mem_smul_set_iff_inv_smul_mem₀ (cn_ne n) _ _).2 hn
[GOAL]
case intro
E : Type u_1
𝕜 : Type u_2
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : AddCommGroup E
inst✝² : Module 𝕜 E
inst✝¹ : TopologicalSpace E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : s ∈ 𝓝 0
c : 𝕜
hc : 1 < ‖c‖
cn_ne : ∀ (n : ℕ), c ^ n ≠ 0
A : ∀ (x : E), ∀ᶠ (n : ℕ) in atTop, x ∈ c ^ n • s
⊢ #↑s = #E
[PROOFSTEP]
have B : ∀ n, #(c ^ n • s) = #s := by
intro n
have : c ^ n • s ≃ s :=
{ toFun := fun x ↦ ⟨(c ^ n)⁻¹ • x.1, (mem_smul_set_iff_inv_smul_mem₀ (cn_ne n) _ _).1 x.2⟩
invFun := fun x ↦ ⟨(c ^ n) • x.1, smul_mem_smul_set x.2⟩
left_inv := fun x ↦ by simp [smul_smul, mul_inv_cancel (cn_ne n)]
right_inv := fun x ↦ by simp [smul_smul, inv_mul_cancel (cn_ne n)] }
exact Cardinal.mk_congr this
[GOAL]
E : Type u_1
𝕜 : Type u_2
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : AddCommGroup E
inst✝² : Module 𝕜 E
inst✝¹ : TopologicalSpace E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : s ∈ 𝓝 0
c : 𝕜
hc : 1 < ‖c‖
cn_ne : ∀ (n : ℕ), c ^ n ≠ 0
A : ∀ (x : E), ∀ᶠ (n : ℕ) in atTop, x ∈ c ^ n • s
⊢ ∀ (n : ℕ), #↑(c ^ n • s) = #↑s
[PROOFSTEP]
intro n
[GOAL]
E : Type u_1
𝕜 : Type u_2
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : AddCommGroup E
inst✝² : Module 𝕜 E
inst✝¹ : TopologicalSpace E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : s ∈ 𝓝 0
c : 𝕜
hc : 1 < ‖c‖
cn_ne : ∀ (n : ℕ), c ^ n ≠ 0
A : ∀ (x : E), ∀ᶠ (n : ℕ) in atTop, x ∈ c ^ n • s
n : ℕ
⊢ #↑(c ^ n • s) = #↑s
[PROOFSTEP]
have : c ^ n • s ≃ s :=
{ toFun := fun x ↦ ⟨(c ^ n)⁻¹ • x.1, (mem_smul_set_iff_inv_smul_mem₀ (cn_ne n) _ _).1 x.2⟩
invFun := fun x ↦ ⟨(c ^ n) • x.1, smul_mem_smul_set x.2⟩
left_inv := fun x ↦ by simp [smul_smul, mul_inv_cancel (cn_ne n)]
right_inv := fun x ↦ by simp [smul_smul, inv_mul_cancel (cn_ne n)] }
[GOAL]
E : Type u_1
𝕜 : Type u_2
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : AddCommGroup E
inst✝² : Module 𝕜 E
inst✝¹ : TopologicalSpace E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : s ∈ 𝓝 0
c : 𝕜
hc : 1 < ‖c‖
cn_ne : ∀ (n : ℕ), c ^ n ≠ 0
A : ∀ (x : E), ∀ᶠ (n : ℕ) in atTop, x ∈ c ^ n • s
n : ℕ
x : ↑(c ^ n • s)
⊢ (fun x => { val := c ^ n • ↑x, property := (_ : c ^ n • ↑x ∈ c ^ n • s) })
((fun x => { val := (c ^ n)⁻¹ • ↑x, property := (_ : (c ^ n)⁻¹ • ↑x ∈ s) }) x) =
x
[PROOFSTEP]
simp [smul_smul, mul_inv_cancel (cn_ne n)]
[GOAL]
E : Type u_1
𝕜 : Type u_2
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : AddCommGroup E
inst✝² : Module 𝕜 E
inst✝¹ : TopologicalSpace E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : s ∈ 𝓝 0
c : 𝕜
hc : 1 < ‖c‖
cn_ne : ∀ (n : ℕ), c ^ n ≠ 0
A : ∀ (x : E), ∀ᶠ (n : ℕ) in atTop, x ∈ c ^ n • s
n : ℕ
x : ↑s
⊢ (fun x => { val := (c ^ n)⁻¹ • ↑x, property := (_ : (c ^ n)⁻¹ • ↑x ∈ s) })
((fun x => { val := c ^ n • ↑x, property := (_ : c ^ n • ↑x ∈ c ^ n • s) }) x) =
x
[PROOFSTEP]
simp [smul_smul, inv_mul_cancel (cn_ne n)]
[GOAL]
E : Type u_1
𝕜 : Type u_2
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : AddCommGroup E
inst✝² : Module 𝕜 E
inst✝¹ : TopologicalSpace E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : s ∈ 𝓝 0
c : 𝕜
hc : 1 < ‖c‖
cn_ne : ∀ (n : ℕ), c ^ n ≠ 0
A : ∀ (x : E), ∀ᶠ (n : ℕ) in atTop, x ∈ c ^ n • s
n : ℕ
this : ↑(c ^ n • s) ≃ ↑s
⊢ #↑(c ^ n • s) = #↑s
[PROOFSTEP]
exact Cardinal.mk_congr this
[GOAL]
case intro
E : Type u_1
𝕜 : Type u_2
inst✝⁴ : NontriviallyNormedField 𝕜
inst✝³ : AddCommGroup E
inst✝² : Module 𝕜 E
inst✝¹ : TopologicalSpace E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : s ∈ 𝓝 0
c : 𝕜
hc : 1 < ‖c‖
cn_ne : ∀ (n : ℕ), c ^ n ≠ 0
A : ∀ (x : E), ∀ᶠ (n : ℕ) in atTop, x ∈ c ^ n • s
B : ∀ (n : ℕ), #↑(c ^ n • s) = #↑s
⊢ #↑s = #E
[PROOFSTEP]
apply (Cardinal.mk_of_countable_eventually_mem A B).symm
[GOAL]
E : Type u_1
𝕜 : Type u_2
inst✝⁵ : NontriviallyNormedField 𝕜
inst✝⁴ : AddCommGroup E
inst✝³ : Module 𝕜 E
inst✝² : TopologicalSpace E
inst✝¹ : ContinuousAdd E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
x : E
hs : s ∈ 𝓝 x
⊢ #↑s = #E
[PROOFSTEP]
let g := Homeomorph.addLeft x
[GOAL]
E : Type u_1
𝕜 : Type u_2
inst✝⁵ : NontriviallyNormedField 𝕜
inst✝⁴ : AddCommGroup E
inst✝³ : Module 𝕜 E
inst✝² : TopologicalSpace E
inst✝¹ : ContinuousAdd E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
x : E
hs : s ∈ 𝓝 x
g : E ≃ₜ E := Homeomorph.addLeft x
⊢ #↑s = #E
[PROOFSTEP]
let t := g ⁻¹' s
[GOAL]
E : Type u_1
𝕜 : Type u_2
inst✝⁵ : NontriviallyNormedField 𝕜
inst✝⁴ : AddCommGroup E
inst✝³ : Module 𝕜 E
inst✝² : TopologicalSpace E
inst✝¹ : ContinuousAdd E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
x : E
hs : s ∈ 𝓝 x
g : E ≃ₜ E := Homeomorph.addLeft x
t : Set E := ↑g ⁻¹' s
⊢ #↑s = #E
[PROOFSTEP]
have : t ∈ 𝓝 0 := g.continuous.continuousAt.preimage_mem_nhds (by simpa using hs)
[GOAL]
E : Type u_1
𝕜 : Type u_2
inst✝⁵ : NontriviallyNormedField 𝕜
inst✝⁴ : AddCommGroup E
inst✝³ : Module 𝕜 E
inst✝² : TopologicalSpace E
inst✝¹ : ContinuousAdd E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
x : E
hs : s ∈ 𝓝 x
g : E ≃ₜ E := Homeomorph.addLeft x
t : Set E := ↑g ⁻¹' s
⊢ s ∈ 𝓝 (↑g 0)
[PROOFSTEP]
simpa using hs
[GOAL]
E : Type u_1
𝕜 : Type u_2
inst✝⁵ : NontriviallyNormedField 𝕜
inst✝⁴ : AddCommGroup E
inst✝³ : Module 𝕜 E
inst✝² : TopologicalSpace E
inst✝¹ : ContinuousAdd E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
x : E
hs : s ∈ 𝓝 x
g : E ≃ₜ E := Homeomorph.addLeft x
t : Set E := ↑g ⁻¹' s
this : t ∈ 𝓝 0
⊢ #↑s = #E
[PROOFSTEP]
have A : #t = #E := cardinal_eq_of_mem_nhds_zero 𝕜 this
[GOAL]
E : Type u_1
𝕜 : Type u_2
inst✝⁵ : NontriviallyNormedField 𝕜
inst✝⁴ : AddCommGroup E
inst✝³ : Module 𝕜 E
inst✝² : TopologicalSpace E
inst✝¹ : ContinuousAdd E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
x : E
hs : s ∈ 𝓝 x
g : E ≃ₜ E := Homeomorph.addLeft x
t : Set E := ↑g ⁻¹' s
this : t ∈ 𝓝 0
A : #↑t = #E
⊢ #↑s = #E
[PROOFSTEP]
have B : #t = #s := Cardinal.mk_subtype_of_equiv s g.toEquiv
[GOAL]
E : Type u_1
𝕜 : Type u_2
inst✝⁵ : NontriviallyNormedField 𝕜
inst✝⁴ : AddCommGroup E
inst✝³ : Module 𝕜 E
inst✝² : TopologicalSpace E
inst✝¹ : ContinuousAdd E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
x : E
hs : s ∈ 𝓝 x
g : E ≃ₜ E := Homeomorph.addLeft x
t : Set E := ↑g ⁻¹' s
this : t ∈ 𝓝 0
A : #↑t = #E
B : #↑t = #↑s
⊢ #↑s = #E
[PROOFSTEP]
rwa [B] at A
[GOAL]
E : Type u_1
𝕜 : Type u_2
inst✝⁵ : NontriviallyNormedField 𝕜
inst✝⁴ : AddCommGroup E
inst✝³ : Module 𝕜 E
inst✝² : TopologicalSpace E
inst✝¹ : ContinuousAdd E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : IsOpen s
h's : Set.Nonempty s
⊢ #↑s = #E
[PROOFSTEP]
rcases h's with ⟨x, hx⟩
[GOAL]
case intro
E : Type u_1
𝕜 : Type u_2
inst✝⁵ : NontriviallyNormedField 𝕜
inst✝⁴ : AddCommGroup E
inst✝³ : Module 𝕜 E
inst✝² : TopologicalSpace E
inst✝¹ : ContinuousAdd E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : IsOpen s
x : E
hx : x ∈ s
⊢ #↑s = #E
[PROOFSTEP]
exact cardinal_eq_of_mem_nhds 𝕜 (hs.mem_nhds hx)
[GOAL]
E : Type u_1
𝕜 : Type u_2
inst✝⁷ : NontriviallyNormedField 𝕜
inst✝⁶ : CompleteSpace 𝕜
inst✝⁵ : AddCommGroup E
inst✝⁴ : Module 𝕜 E
inst✝³ : Nontrivial E
inst✝² : TopologicalSpace E
inst✝¹ : ContinuousAdd E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : IsOpen s
h's : Set.Nonempty s
⊢ 𝔠 ≤ #↑s
[PROOFSTEP]
simpa [cardinal_eq_of_is_open 𝕜 hs h's] using continuum_le_cardinal_of_module 𝕜 E
[GOAL]
E : Type u
𝕜 : Type u_1
inst✝⁷ : NontriviallyNormedField 𝕜
inst✝⁶ : CompleteSpace 𝕜
inst✝⁵ : AddCommGroup E
inst✝⁴ : Module 𝕜 E
inst✝³ : Nontrivial E
inst✝² : TopologicalSpace E
inst✝¹ : ContinuousAdd E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : Set.Countable s
⊢ Dense sᶜ
[PROOFSTEP]
rw [← interior_eq_empty_iff_dense_compl]
[GOAL]
E : Type u
𝕜 : Type u_1
inst✝⁷ : NontriviallyNormedField 𝕜
inst✝⁶ : CompleteSpace 𝕜
inst✝⁵ : AddCommGroup E
inst✝⁴ : Module 𝕜 E
inst✝³ : Nontrivial E
inst✝² : TopologicalSpace E
inst✝¹ : ContinuousAdd E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : Set.Countable s
⊢ interior s = ∅
[PROOFSTEP]
by_contra H
[GOAL]
E : Type u
𝕜 : Type u_1
inst✝⁷ : NontriviallyNormedField 𝕜
inst✝⁶ : CompleteSpace 𝕜
inst✝⁵ : AddCommGroup E
inst✝⁴ : Module 𝕜 E
inst✝³ : Nontrivial E
inst✝² : TopologicalSpace E
inst✝¹ : ContinuousAdd E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : Set.Countable s
H : ¬interior s = ∅
⊢ False
[PROOFSTEP]
apply lt_irrefl (ℵ₀ : Cardinal.{u})
[GOAL]
E : Type u
𝕜 : Type u_1
inst✝⁷ : NontriviallyNormedField 𝕜
inst✝⁶ : CompleteSpace 𝕜
inst✝⁵ : AddCommGroup E
inst✝⁴ : Module 𝕜 E
inst✝³ : Nontrivial E
inst✝² : TopologicalSpace E
inst✝¹ : ContinuousAdd E
inst✝ : ContinuousSMul 𝕜 E
s : Set E
hs : Set.Countable s
H : ¬interior s = ∅
⊢ ℵ₀ < ℵ₀
[PROOFSTEP]
calc
(ℵ₀ : Cardinal.{u}) < 𝔠 := aleph0_lt_continuum
_ ≤ #(interior s) := (continuum_le_cardinal_of_is_open 𝕜 isOpen_interior (nmem_singleton_empty.1 H))
_ ≤ #s := (mk_le_mk_of_subset interior_subset)
_ ≤ ℵ₀ := le_aleph0 hs
|
module packet_mod
use optical_properties_mod, only: nlayer
implicit none
save
!positional
real*8 xp,yp,zp !current position in grid
real*8 nxp,nyp,nzp !current direction of packet
integer xcell,ycell,zcell
!optical properties
real*8 ns,g,u_a(nlayer),u_s(nlayer)
real*8 sint,cost,sinp,cosp,phi
real*8 fi,fq,fu,fv
end module packet_mod
|
/-
Copyright (c) 2021 Jordan Brown, Thomas Browning, Patrick Lutz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jordan Brown, Thomas Browning, Patrick Lutz
! This file was ported from Lean 3 source module group_theory.commutator
! leanprover-community/mathlib commit 0a0ec35061ed9960bf0e7ffb0335f44447b58977
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathlib.Algebra.Group.Commutator
import Mathlib.Data.Bracket
import Mathlib.GroupTheory.Subgroup.Finite
import Mathlib.Tactic.Group
/-!
# Commutators of Subgroups
If `G` is a group and `H₁ H₂ : Subgroup G` then the commutator `⁅H₁, H₂⁆ : Subgroup G`
is the subgroup of `G` generated by the commutators `h₁ * h₂ * h₁⁻¹ * h₂⁻¹`.
## Main definitions
* `⁅g₁, g₂⁆` : the commutator of the elements `g₁` and `g₂`
(defined by `commutatorElement` elsewhere).
* `⁅H₁, H₂⁆` : the commutator of the subgroups `H₁` and `H₂`.
-/
variable {G G' F : Type _} [Group G] [Group G'] [MonoidHomClass F G G'] (f : F) {g₁ g₂ g₃ g : G}
theorem commutatorElement_eq_one_iff_mul_comm : ⁅g₁, g₂⁆ = 1 ↔ g₁ * g₂ = g₂ * g₁ := by
rw [commutatorElement_def, mul_inv_eq_one, mul_inv_eq_iff_eq_mul]
#align commutator_element_eq_one_iff_mul_comm commutatorElement_eq_one_iff_mul_comm
theorem commutatorElement_eq_one_iff_commute : ⁅g₁, g₂⁆ = 1 ↔ Commute g₁ g₂ :=
commutatorElement_eq_one_iff_mul_comm
#align commutator_element_eq_one_iff_commute commutatorElement_eq_one_iff_commute
theorem Commute.commutator_eq (h : Commute g₁ g₂) : ⁅g₁, g₂⁆ = 1 :=
commutatorElement_eq_one_iff_commute.mpr h
#align commute.commutator_eq Commute.commutator_eq
variable (g₁ g₂ g₃ g)
@[simp]
theorem commutatorElement_one_right : ⁅g, (1 : G)⁆ = 1 :=
(Commute.one_right g).commutator_eq
#align commutator_element_one_right commutatorElement_one_right
@[simp]
theorem commutatorElement_one_left : ⁅(1 : G), g⁆ = 1 :=
(Commute.one_left g).commutator_eq
#align commutator_element_one_left commutatorElement_one_left
@[simp]
theorem commutatorElement_self : ⁅g, g⁆ = 1 :=
(Commute.refl g).commutator_eq
#align commutator_element_self commutatorElement_self
@[simp]
theorem commutatorElement_inv : ⁅g₁, g₂⁆⁻¹ = ⁅g₂, g₁⁆ := by
simp_rw [commutatorElement_def, mul_inv_rev, inv_inv, mul_assoc]
#align commutator_element_inv commutatorElement_inv
theorem map_commutatorElement : (f ⁅g₁, g₂⁆ : G') = ⁅f g₁, f g₂⁆ := by
simp_rw [commutatorElement_def, map_mul f, map_inv f]
#align map_commutator_element map_commutatorElement
theorem conjugate_commutatorElement : g₃ * ⁅g₁, g₂⁆ * g₃⁻¹ = ⁅g₃ * g₁ * g₃⁻¹, g₃ * g₂ * g₃⁻¹⁆ :=
map_commutatorElement (MulAut.conj g₃).toMonoidHom g₁ g₂
#align conjugate_commutator_element conjugate_commutatorElement
namespace Subgroup
/-- The commutator of two subgroups `H₁` and `H₂`. -/
instance commutator : Bracket (Subgroup G) (Subgroup G) :=
⟨fun H₁ H₂ => closure { g | ∃ g₁ ∈ H₁, ∃ g₂ ∈ H₂, ⁅g₁, g₂⁆ = g }⟩
#align subgroup.commutator Subgroup.commutator
theorem commutator_def (H₁ H₂ : Subgroup G) :
⁅H₁, H₂⁆ = closure { g | ∃ g₁ ∈ H₁, ∃ g₂ ∈ H₂, ⁅g₁, g₂⁆ = g } :=
rfl
#align subgroup.commutator_def Subgroup.commutator_def
variable {g₁ g₂ g₃} {H₁ H₂ H₃ K₁ K₂ : Subgroup G}
theorem commutator_mem_commutator (h₁ : g₁ ∈ H₁) (h₂ : g₂ ∈ H₂) : ⁅g₁, g₂⁆ ∈ ⁅H₁, H₂⁆ :=
subset_closure ⟨g₁, h₁, g₂, h₂, rfl⟩
#align subgroup.commutator_mem_commutator Subgroup.commutator_mem_commutator
theorem commutator_le : ⁅H₁, H₂⁆ ≤ H₃ ↔ ∀ g₁ ∈ H₁, ∀ g₂ ∈ H₂, ⁅g₁, g₂⁆ ∈ H₃ :=
H₃.closure_le.trans
⟨fun h a b c d => h ⟨a, b, c, d, rfl⟩, fun h _g ⟨a, b, c, d, h_eq⟩ => h_eq ▸ h a b c d⟩
#align subgroup.commutator_le Subgroup.commutator_le
theorem commutator_mono (h₁ : H₁ ≤ K₁) (h₂ : H₂ ≤ K₂) : ⁅H₁, H₂⁆ ≤ ⁅K₁, K₂⁆ :=
commutator_le.mpr fun _g₁ hg₁ _g₂ hg₂ => commutator_mem_commutator (h₁ hg₁) (h₂ hg₂)
#align subgroup.commutator_mono Subgroup.commutator_mono
theorem commutator_eq_bot_iff_le_centralizer : ⁅H₁, H₂⁆ = ⊥ ↔ H₁ ≤ H₂.centralizer := by
rw [eq_bot_iff, commutator_le]
refine'
forall_congr' fun p => forall_congr' fun _hp => forall_congr' fun q => forall_congr' fun hq => _
rw [mem_bot, commutatorElement_eq_one_iff_mul_comm, eq_comm]
#align subgroup.commutator_eq_bot_iff_le_centralizer Subgroup.commutator_eq_bot_iff_le_centralizer
/-- **The Three Subgroups Lemma** (via the Hall-Witt identity) -/
theorem commutator_commutator_eq_bot_of_rotate (h1 : ⁅⁅H₂, H₃⁆, H₁⁆ = ⊥) (h2 : ⁅⁅H₃, H₁⁆, H₂⁆ = ⊥) :
⁅⁅H₁, H₂⁆, H₃⁆ = ⊥ := by
simp_rw [commutator_eq_bot_iff_le_centralizer, commutator_le,
mem_centralizer_iff_commutator_eq_one, ← commutatorElement_def] at h1 h2⊢
intro x hx y hy z hz
trans x * z * ⁅y, ⁅z⁻¹, x⁻¹⁆⁆⁻¹ * z⁻¹ * y * ⁅x⁻¹, ⁅y⁻¹, z⁆⁆⁻¹ * y⁻¹ * x⁻¹
· group
· rw [h1 _ (H₂.inv_mem hy) _ hz _ (H₁.inv_mem hx), h2 _ (H₃.inv_mem hz) _ (H₁.inv_mem hx) _ hy]
group
#align subgroup.commutator_commutator_eq_bot_of_rotate Subgroup.commutator_commutator_eq_bot_of_rotate
variable (H₁ H₂)
theorem commutator_comm_le : ⁅H₁, H₂⁆ ≤ ⁅H₂, H₁⁆ :=
commutator_le.mpr fun g₁ h₁ g₂ h₂ =>
commutatorElement_inv g₂ g₁ ▸ ⁅H₂, H₁⁆.inv_mem_iff.mpr (commutator_mem_commutator h₂ h₁)
#align subgroup.commutator_comm_le Subgroup.commutator_comm_le
theorem commutator_comm : ⁅H₁, H₂⁆ = ⁅H₂, H₁⁆ :=
le_antisymm (commutator_comm_le H₁ H₂) (commutator_comm_le H₂ H₁)
#align subgroup.commutator_comm Subgroup.commutator_comm
section Normal
instance commutator_normal [h₁ : H₁.Normal] [h₂ : H₂.Normal] : Normal ⁅H₁, H₂⁆ := by
let base : Set G := { x | ∃ g₁ ∈ H₁, ∃ g₂ ∈ H₂, ⁅g₁, g₂⁆ = x }
change (closure base).Normal
suffices h_base : base = Group.conjugatesOfSet base
· rw [h_base]
exact Subgroup.normalClosure_normal
refine' Set.Subset.antisymm Group.subset_conjugatesOfSet fun a h => _
simp_rw [Group.mem_conjugatesOfSet_iff, isConj_iff] at h
rcases h with ⟨b, ⟨c, hc, e, he, rfl⟩, d, rfl⟩
exact ⟨_, h₁.conj_mem c hc d, _, h₂.conj_mem e he d, (conjugate_commutatorElement c e d).symm⟩
#align subgroup.commutator_normal Subgroup.commutator_normal
theorem commutator_def' [H₁.Normal] [H₂.Normal] :
⁅H₁, H₂⁆ = normalClosure { g | ∃ g₁ ∈ H₁, ∃ g₂ ∈ H₂, ⁅g₁, g₂⁆ = g } :=
le_antisymm closure_le_normalClosure (normalClosure_le_normal subset_closure)
#align subgroup.commutator_def' Subgroup.commutator_def'
theorem commutator_le_right [h : H₂.Normal] : ⁅H₁, H₂⁆ ≤ H₂ :=
commutator_le.mpr fun g₁ _h₁ g₂ h₂ => H₂.mul_mem (h.conj_mem g₂ h₂ g₁) (H₂.inv_mem h₂)
#align subgroup.commutator_le_right Subgroup.commutator_le_right
theorem commutator_le_left [H₁.Normal] : ⁅H₁, H₂⁆ ≤ H₁ :=
commutator_comm H₂ H₁ ▸ commutator_le_right H₂ H₁
#align subgroup.commutator_le_left Subgroup.commutator_le_left
@[simp]
theorem commutator_bot_left : ⁅(⊥ : Subgroup G), H₁⁆ = ⊥ :=
le_bot_iff.mp (commutator_le_left ⊥ H₁)
#align subgroup.commutator_bot_left Subgroup.commutator_bot_left
@[simp]
theorem commutator_bot_right : ⁅H₁, ⊥⁆ = (⊥ : Subgroup G) :=
le_bot_iff.mp (commutator_le_right H₁ ⊥)
#align subgroup.commutator_bot_right Subgroup.commutator_bot_right
theorem commutator_le_inf [Normal H₁] [Normal H₂] : ⁅H₁, H₂⁆ ≤ H₁ ⊓ H₂ :=
le_inf (commutator_le_left H₁ H₂) (commutator_le_right H₁ H₂)
#align subgroup.commutator_le_inf Subgroup.commutator_le_inf
end Normal
theorem map_commutator (f : G →* G') : map f ⁅H₁, H₂⁆ = ⁅map f H₁, map f H₂⁆ := by
simp_rw [le_antisymm_iff, map_le_iff_le_comap, commutator_le, mem_comap, map_commutatorElement]
constructor
· intro p hp q hq
exact commutator_mem_commutator (mem_map_of_mem _ hp) (mem_map_of_mem _ hq)
· rintro _ ⟨p, hp, rfl⟩ _ ⟨q, hq, rfl⟩
rw [← map_commutatorElement]
exact mem_map_of_mem _ (commutator_mem_commutator hp hq)
#align subgroup.map_commutator Subgroup.map_commutator
variable {H₁ H₂}
theorem commutator_le_map_commutator {f : G →* G'} {K₁ K₂ : Subgroup G'} (h₁ : K₁ ≤ H₁.map f)
(h₂ : K₂ ≤ H₂.map f) : ⁅K₁, K₂⁆ ≤ ⁅H₁, H₂⁆.map f :=
(commutator_mono h₁ h₂).trans (ge_of_eq (map_commutator H₁ H₂ f))
#align subgroup.commutator_le_map_commutator Subgroup.commutator_le_map_commutator
variable (H₁ H₂)
instance commutator_characteristic [h₁ : Characteristic H₁] [h₂ : Characteristic H₂] :
Characteristic ⁅H₁, H₂⁆ :=
characteristic_iff_le_map.mpr fun ϕ =>
commutator_le_map_commutator (characteristic_iff_le_map.mp h₁ ϕ)
(characteristic_iff_le_map.mp h₂ ϕ)
#align subgroup.commutator_characteristic Subgroup.commutator_characteristic
theorem commutator_prod_prod (K₁ K₂ : Subgroup G') :
⁅H₁.prod K₁, H₂.prod K₂⁆ = ⁅H₁, H₂⁆.prod ⁅K₁, K₂⁆ := by
apply le_antisymm
· rw [commutator_le]
rintro ⟨p₁, p₂⟩ ⟨hp₁, hp₂⟩ ⟨q₁, q₂⟩ ⟨hq₁, hq₂⟩
exact ⟨commutator_mem_commutator hp₁ hq₁, commutator_mem_commutator hp₂ hq₂⟩
· rw [prod_le_iff]
constructor <;>
· rw [map_commutator]
apply commutator_mono <;>
simp [le_prod_iff, map_map, MonoidHom.fst_comp_inl, MonoidHom.snd_comp_inl,
MonoidHom.fst_comp_inr, MonoidHom.snd_comp_inr]
#align subgroup.commutator_prod_prod Subgroup.commutator_prod_prod
/-- The commutator of direct product is contained in the direct product of the commutators.
See `commutator_pi_pi_of_finite` for equality given `Fintype η`.
-/
theorem commutator_pi_pi_le {η : Type _} {Gs : η → Type _} [∀ i, Group (Gs i)]
(H K : ∀ i, Subgroup (Gs i)) :
⁅Subgroup.pi Set.univ H, Subgroup.pi Set.univ K⁆ ≤ Subgroup.pi Set.univ fun i => ⁅H i, K i⁆ :=
commutator_le.mpr fun _p hp _q hq i hi => commutator_mem_commutator (hp i hi) (hq i hi)
#align subgroup.commutator_pi_pi_le Subgroup.commutator_pi_pi_le
/-- The commutator of a finite direct product is contained in the direct product of the commutators.
-/
theorem commutator_pi_pi_of_finite {η : Type _} [Finite η] {Gs : η → Type _} [∀ i, Group (Gs i)]
(H K : ∀ i, Subgroup (Gs i)) :
⁅Subgroup.pi Set.univ H, Subgroup.pi Set.univ K⁆ = Subgroup.pi Set.univ fun i => ⁅H i, K i⁆ :=
by
classical
apply le_antisymm (commutator_pi_pi_le H K)
· rw [pi_le_iff]
intro i hi
rw [map_commutator]
apply commutator_mono <;>
· rw [le_pi_iff]
intro j _hj
rintro _ ⟨_, ⟨x, hx, rfl⟩, rfl⟩
by_cases h : j = i
· subst h
simpa using hx
· simp [h, one_mem]
#align subgroup.commutator_pi_pi_of_finite Subgroup.commutator_pi_pi_of_finite
end Subgroup
variable (G)
/-- The set of commutator elements `⁅g₁, g₂⁆` in `G`. -/
def commutatorSet : Set G :=
{ g | ∃ g₁ g₂ : G, ⁅g₁, g₂⁆ = g }
#align commutator_set commutatorSet
theorem commutatorSet_def : commutatorSet G = { g | ∃ g₁ g₂ : G, ⁅g₁, g₂⁆ = g } :=
rfl
#align commutator_set_def commutatorSet_def
theorem one_mem_commutatorSet : (1 : G) ∈ commutatorSet G :=
⟨1, 1, commutatorElement_self 1⟩
#align one_mem_commutator_set one_mem_commutatorSet
instance : Nonempty (commutatorSet G) :=
⟨⟨1, one_mem_commutatorSet G⟩⟩
variable {G g}
theorem mem_commutatorSet_iff : g ∈ commutatorSet G ↔ ∃ g₁ g₂ : G, ⁅g₁, g₂⁆ = g :=
Iff.rfl
#align mem_commutator_set_iff mem_commutatorSet_iff
theorem commutator_mem_commutatorSet : ⁅g₁, g₂⁆ ∈ commutatorSet G :=
⟨g₁, g₂, rfl⟩
#align commutator_mem_commutator_set commutator_mem_commutatorSet
|
data Unit : Set where
unit : Unit
F : Unit → Set₁
F {x = unit} = Set
|
[GOAL]
H : Type u
inst✝² : NormedAddCommGroup H
inst✝¹ : InnerProductSpace ℂ H
inst✝ : CompleteSpace H
S T : VonNeumannAlgebra H
h : (fun S => S.carrier) S = (fun S => S.carrier) T
⊢ S = T
[PROOFSTEP]
obtain ⟨⟨⟨⟨⟨⟨_, _⟩, _⟩, _⟩, _⟩, _⟩, _⟩ := S
[GOAL]
case mk.mk.mk.mk.mk.mk
H : Type u
inst✝² : NormedAddCommGroup H
inst✝¹ : InnerProductSpace ℂ H
inst✝ : CompleteSpace H
T : VonNeumannAlgebra H
carrier✝ : Set (H →L[ℂ] H)
mul_mem'✝ : ∀ {a b : H →L[ℂ] H}, a ∈ carrier✝ → b ∈ carrier✝ → a * b ∈ carrier✝
one_mem'✝ : 1 ∈ { carrier := carrier✝, mul_mem' := mul_mem'✝ }.carrier
add_mem'✝ :
∀ {a b : H →L[ℂ] H},
a ∈
{ toSubsemigroup := { carrier := carrier✝, mul_mem' := mul_mem'✝ },
one_mem' := one_mem'✝ }.toSubsemigroup.carrier →
b ∈
{ toSubsemigroup := { carrier := carrier✝, mul_mem' := mul_mem'✝ },
one_mem' := one_mem'✝ }.toSubsemigroup.carrier →
a + b ∈
{ toSubsemigroup := { carrier := carrier✝, mul_mem' := mul_mem'✝ },
one_mem' := one_mem'✝ }.toSubsemigroup.carrier
zero_mem'✝ :
0 ∈ { toSubsemigroup := { carrier := carrier✝, mul_mem' := mul_mem'✝ }, one_mem' := one_mem'✝ }.toSubsemigroup.carrier
algebraMap_mem'✝ :
∀ (r : ℂ),
↑(algebraMap ℂ (H →L[ℂ] H)) r ∈
{ toSubmonoid := { toSubsemigroup := { carrier := carrier✝, mul_mem' := mul_mem'✝ }, one_mem' := one_mem'✝ },
add_mem' := add_mem'✝, zero_mem' := zero_mem'✝ }.toSubmonoid.toSubsemigroup.carrier
star_mem'✝ :
∀ {a : H →L[ℂ] H},
a ∈
{
toSubsemiring :=
{
toSubmonoid :=
{ toSubsemigroup := { carrier := carrier✝, mul_mem' := mul_mem'✝ }, one_mem' := one_mem'✝ },
add_mem' := add_mem'✝, zero_mem' := zero_mem'✝ },
algebraMap_mem' := algebraMap_mem'✝ }.toSubsemiring.toSubmonoid.toSubsemigroup.carrier →
star a ∈
{
toSubsemiring :=
{
toSubmonoid :=
{ toSubsemigroup := { carrier := carrier✝, mul_mem' := mul_mem'✝ }, one_mem' := one_mem'✝ },
add_mem' := add_mem'✝, zero_mem' := zero_mem'✝ },
algebraMap_mem' := algebraMap_mem'✝ }.toSubsemiring.toSubmonoid.toSubsemigroup.carrier
centralizer_centralizer'✝ :
Set.centralizer
(Set.centralizer
{
toSubalgebra :=
{
toSubsemiring :=
{
toSubmonoid :=
{ toSubsemigroup := { carrier := carrier✝, mul_mem' := mul_mem'✝ },
one_mem' := one_mem'✝ },
add_mem' := add_mem'✝, zero_mem' := zero_mem'✝ },
algebraMap_mem' := algebraMap_mem'✝ },
star_mem' := star_mem'✝ }.toSubalgebra.toSubsemiring.toSubmonoid.toSubsemigroup.carrier) =
{
toSubalgebra :=
{
toSubsemiring :=
{
toSubmonoid :=
{ toSubsemigroup := { carrier := carrier✝, mul_mem' := mul_mem'✝ }, one_mem' := one_mem'✝ },
add_mem' := add_mem'✝, zero_mem' := zero_mem'✝ },
algebraMap_mem' := algebraMap_mem'✝ },
star_mem' := star_mem'✝ }.toSubalgebra.toSubsemiring.toSubmonoid.toSubsemigroup.carrier
h :
(fun S => S.carrier)
{
toStarSubalgebra :=
{
toSubalgebra :=
{
toSubsemiring :=
{
toSubmonoid :=
{ toSubsemigroup := { carrier := carrier✝, mul_mem' := mul_mem'✝ }, one_mem' := one_mem'✝ },
add_mem' := add_mem'✝, zero_mem' := zero_mem'✝ },
algebraMap_mem' := algebraMap_mem'✝ },
star_mem' := star_mem'✝ },
centralizer_centralizer' := centralizer_centralizer'✝ } =
(fun S => S.carrier) T
⊢ {
toStarSubalgebra :=
{
toSubalgebra :=
{
toSubsemiring :=
{
toSubmonoid :=
{ toSubsemigroup := { carrier := carrier✝, mul_mem' := mul_mem'✝ }, one_mem' := one_mem'✝ },
add_mem' := add_mem'✝, zero_mem' := zero_mem'✝ },
algebraMap_mem' := algebraMap_mem'✝ },
star_mem' := star_mem'✝ },
centralizer_centralizer' := centralizer_centralizer'✝ } =
T
[PROOFSTEP]
cases T
[GOAL]
case mk.mk.mk.mk.mk.mk.mk
H : Type u
inst✝² : NormedAddCommGroup H
inst✝¹ : InnerProductSpace ℂ H
inst✝ : CompleteSpace H
carrier✝ : Set (H →L[ℂ] H)
mul_mem'✝ : ∀ {a b : H →L[ℂ] H}, a ∈ carrier✝ → b ∈ carrier✝ → a * b ∈ carrier✝
one_mem'✝ : 1 ∈ { carrier := carrier✝, mul_mem' := mul_mem'✝ }.carrier
add_mem'✝ :
∀ {a b : H →L[ℂ] H},
a ∈
{ toSubsemigroup := { carrier := carrier✝, mul_mem' := mul_mem'✝ },
one_mem' := one_mem'✝ }.toSubsemigroup.carrier →
b ∈
{ toSubsemigroup := { carrier := carrier✝, mul_mem' := mul_mem'✝ },
one_mem' := one_mem'✝ }.toSubsemigroup.carrier →
a + b ∈
{ toSubsemigroup := { carrier := carrier✝, mul_mem' := mul_mem'✝ },
one_mem' := one_mem'✝ }.toSubsemigroup.carrier
zero_mem'✝ :
0 ∈ { toSubsemigroup := { carrier := carrier✝, mul_mem' := mul_mem'✝ }, one_mem' := one_mem'✝ }.toSubsemigroup.carrier
algebraMap_mem'✝ :
∀ (r : ℂ),
↑(algebraMap ℂ (H →L[ℂ] H)) r ∈
{ toSubmonoid := { toSubsemigroup := { carrier := carrier✝, mul_mem' := mul_mem'✝ }, one_mem' := one_mem'✝ },
add_mem' := add_mem'✝, zero_mem' := zero_mem'✝ }.toSubmonoid.toSubsemigroup.carrier
star_mem'✝ :
∀ {a : H →L[ℂ] H},
a ∈
{
toSubsemiring :=
{
toSubmonoid :=
{ toSubsemigroup := { carrier := carrier✝, mul_mem' := mul_mem'✝ }, one_mem' := one_mem'✝ },
add_mem' := add_mem'✝, zero_mem' := zero_mem'✝ },
algebraMap_mem' := algebraMap_mem'✝ }.toSubsemiring.toSubmonoid.toSubsemigroup.carrier →
star a ∈
{
toSubsemiring :=
{
toSubmonoid :=
{ toSubsemigroup := { carrier := carrier✝, mul_mem' := mul_mem'✝ }, one_mem' := one_mem'✝ },
add_mem' := add_mem'✝, zero_mem' := zero_mem'✝ },
algebraMap_mem' := algebraMap_mem'✝ }.toSubsemiring.toSubmonoid.toSubsemigroup.carrier
centralizer_centralizer'✝¹ :
Set.centralizer
(Set.centralizer
{
toSubalgebra :=
{
toSubsemiring :=
{
toSubmonoid :=
{ toSubsemigroup := { carrier := carrier✝, mul_mem' := mul_mem'✝ },
one_mem' := one_mem'✝ },
add_mem' := add_mem'✝, zero_mem' := zero_mem'✝ },
algebraMap_mem' := algebraMap_mem'✝ },
star_mem' := star_mem'✝ }.toSubalgebra.toSubsemiring.toSubmonoid.toSubsemigroup.carrier) =
{
toSubalgebra :=
{
toSubsemiring :=
{
toSubmonoid :=
{ toSubsemigroup := { carrier := carrier✝, mul_mem' := mul_mem'✝ }, one_mem' := one_mem'✝ },
add_mem' := add_mem'✝, zero_mem' := zero_mem'✝ },
algebraMap_mem' := algebraMap_mem'✝ },
star_mem' := star_mem'✝ }.toSubalgebra.toSubsemiring.toSubmonoid.toSubsemigroup.carrier
toStarSubalgebra✝ : StarSubalgebra ℂ (H →L[ℂ] H)
centralizer_centralizer'✝ : Set.centralizer (Set.centralizer toStarSubalgebra✝.carrier) = toStarSubalgebra✝.carrier
h :
(fun S => S.carrier)
{
toStarSubalgebra :=
{
toSubalgebra :=
{
toSubsemiring :=
{
toSubmonoid :=
{ toSubsemigroup := { carrier := carrier✝, mul_mem' := mul_mem'✝ }, one_mem' := one_mem'✝ },
add_mem' := add_mem'✝, zero_mem' := zero_mem'✝ },
algebraMap_mem' := algebraMap_mem'✝ },
star_mem' := star_mem'✝ },
centralizer_centralizer' := centralizer_centralizer'✝¹ } =
(fun S => S.carrier)
{ toStarSubalgebra := toStarSubalgebra✝, centralizer_centralizer' := centralizer_centralizer'✝ }
⊢ {
toStarSubalgebra :=
{
toSubalgebra :=
{
toSubsemiring :=
{
toSubmonoid :=
{ toSubsemigroup := { carrier := carrier✝, mul_mem' := mul_mem'✝ }, one_mem' := one_mem'✝ },
add_mem' := add_mem'✝, zero_mem' := zero_mem'✝ },
algebraMap_mem' := algebraMap_mem'✝ },
star_mem' := star_mem'✝ },
centralizer_centralizer' := centralizer_centralizer'✝¹ } =
{ toStarSubalgebra := toStarSubalgebra✝, centralizer_centralizer' := centralizer_centralizer'✝ }
[PROOFSTEP]
congr
-- porting note: `StarMemClass` should be in `Prop`?
[GOAL]
H : Type u
inst✝² : NormedAddCommGroup H
inst✝¹ : InnerProductSpace ℂ H
inst✝ : CompleteSpace H
S : VonNeumannAlgebra H
⊢ Set.centralizer
(Set.centralizer
(StarSubalgebra.centralizer ℂ ↑S).toSubalgebra.toSubsemiring.toSubmonoid.toSubsemigroup.carrier) =
(StarSubalgebra.centralizer ℂ ↑S).toSubalgebra.toSubsemiring.toSubmonoid.toSubsemigroup.carrier
[PROOFSTEP]
simp
[GOAL]
H : Type u
inst✝² : NormedAddCommGroup H
inst✝¹ : InnerProductSpace ℂ H
inst✝ : CompleteSpace H
S : VonNeumannAlgebra H
⊢ ↑(commutant S) = Set.centralizer ↑S
[PROOFSTEP]
simp [commutant]
[GOAL]
H : Type u
inst✝² : NormedAddCommGroup H
inst✝¹ : InnerProductSpace ℂ H
inst✝ : CompleteSpace H
S : VonNeumannAlgebra H
z : H →L[ℂ] H
⊢ z ∈ commutant S ↔ ∀ (g : H →L[ℂ] H), g ∈ S → g * z = z * g
[PROOFSTEP]
rw [← SetLike.mem_coe, coe_commutant]
[GOAL]
H : Type u
inst✝² : NormedAddCommGroup H
inst✝¹ : InnerProductSpace ℂ H
inst✝ : CompleteSpace H
S : VonNeumannAlgebra H
z : H →L[ℂ] H
⊢ z ∈ Set.centralizer ↑S ↔ ∀ (g : H →L[ℂ] H), g ∈ S → g * z = z * g
[PROOFSTEP]
rfl
[GOAL]
H : Type u
inst✝² : NormedAddCommGroup H
inst✝¹ : InnerProductSpace ℂ H
inst✝ : CompleteSpace H
S : VonNeumannAlgebra H
⊢ ↑(commutant (commutant S)) = ↑S
[PROOFSTEP]
simp
|
lemma lift_trans: assumes "f \<in> L F (g)" assumes "(\<lambda>x. t x (g x)) \<in> L F (h)" assumes "\<And>f g. f \<in> L F (g) \<Longrightarrow> (\<lambda>x. t x (f x)) \<in> L F (\<lambda>x. t x (g x))" shows "(\<lambda>x. t x (f x)) \<in> L F (h)" |
State Before: x : ℝ
h₁ : x ≠ -1
h₂ : x ≠ 1
⊢ HasStrictDerivAt arcsin (1 / sqrt (1 - x ^ 2)) x ∧ ContDiffAt ℝ ⊤ arcsin x State After: case inl
x : ℝ
h₁✝ : x ≠ -1
h₂ : x ≠ 1
h₁ : x < -1
⊢ HasStrictDerivAt arcsin (1 / sqrt (1 - x ^ 2)) x ∧ ContDiffAt ℝ ⊤ arcsin x
case inr
x : ℝ
h₁✝ : x ≠ -1
h₂ : x ≠ 1
h₁ : -1 < x
⊢ HasStrictDerivAt arcsin (1 / sqrt (1 - x ^ 2)) x ∧ ContDiffAt ℝ ⊤ arcsin x Tactic: cases' h₁.lt_or_lt with h₁ h₁ State Before: case inr
x : ℝ
h₁✝ : x ≠ -1
h₂ : x ≠ 1
h₁ : -1 < x
⊢ HasStrictDerivAt arcsin (1 / sqrt (1 - x ^ 2)) x ∧ ContDiffAt ℝ ⊤ arcsin x State After: case inr.inl
x : ℝ
h₁✝ : x ≠ -1
h₂✝ : x ≠ 1
h₁ : -1 < x
h₂ : x < 1
⊢ HasStrictDerivAt arcsin (1 / sqrt (1 - x ^ 2)) x ∧ ContDiffAt ℝ ⊤ arcsin x
case inr.inr
x : ℝ
h₁✝ : x ≠ -1
h₂✝ : x ≠ 1
h₁ : -1 < x
h₂ : 1 < x
⊢ HasStrictDerivAt arcsin (1 / sqrt (1 - x ^ 2)) x ∧ ContDiffAt ℝ ⊤ arcsin x Tactic: cases' h₂.lt_or_lt with h₂ h₂ State Before: case inl
x : ℝ
h₁✝ : x ≠ -1
h₂ : x ≠ 1
h₁ : x < -1
⊢ HasStrictDerivAt arcsin (1 / sqrt (1 - x ^ 2)) x ∧ ContDiffAt ℝ ⊤ arcsin x State After: case inl
x : ℝ
h₁✝ : x ≠ -1
h₂ : x ≠ 1
h₁ : x < -1
this : 1 - x ^ 2 < 0
⊢ HasStrictDerivAt arcsin (1 / sqrt (1 - x ^ 2)) x ∧ ContDiffAt ℝ ⊤ arcsin x Tactic: have : 1 - x ^ 2 < 0 := by nlinarith [h₁] State Before: case inl
x : ℝ
h₁✝ : x ≠ -1
h₂ : x ≠ 1
h₁ : x < -1
this : 1 - x ^ 2 < 0
⊢ HasStrictDerivAt arcsin (1 / sqrt (1 - x ^ 2)) x ∧ ContDiffAt ℝ ⊤ arcsin x State After: case inl
x : ℝ
h₁✝ : x ≠ -1
h₂ : x ≠ 1
h₁ : x < -1
this : 1 - x ^ 2 < 0
⊢ HasStrictDerivAt arcsin 0 x ∧ ContDiffAt ℝ ⊤ arcsin x Tactic: rw [sqrt_eq_zero'.2 this.le, div_zero] State Before: case inl
x : ℝ
h₁✝ : x ≠ -1
h₂ : x ≠ 1
h₁ : x < -1
this : 1 - x ^ 2 < 0
⊢ HasStrictDerivAt arcsin 0 x ∧ ContDiffAt ℝ ⊤ arcsin x State After: case inl
x : ℝ
h₁✝ : x ≠ -1
h₂ : x ≠ 1
h₁ : x < -1
this✝ : 1 - x ^ 2 < 0
this : arcsin =ᶠ[𝓝 x] fun x => -(π / 2)
⊢ HasStrictDerivAt arcsin 0 x ∧ ContDiffAt ℝ ⊤ arcsin x Tactic: have : arcsin =ᶠ[𝓝 x] fun _ => -(π / 2) :=
(gt_mem_nhds h₁).mono fun y hy => arcsin_of_le_neg_one hy.le State Before: case inl
x : ℝ
h₁✝ : x ≠ -1
h₂ : x ≠ 1
h₁ : x < -1
this✝ : 1 - x ^ 2 < 0
this : arcsin =ᶠ[𝓝 x] fun x => -(π / 2)
⊢ HasStrictDerivAt arcsin 0 x ∧ ContDiffAt ℝ ⊤ arcsin x State After: no goals Tactic: exact ⟨(hasStrictDerivAt_const _ _).congr_of_eventuallyEq this.symm,
contDiffAt_const.congr_of_eventuallyEq this⟩ State Before: x : ℝ
h₁✝ : x ≠ -1
h₂ : x ≠ 1
h₁ : x < -1
⊢ 1 - x ^ 2 < 0 State After: no goals Tactic: nlinarith [h₁] State Before: case inr.inl
x : ℝ
h₁✝ : x ≠ -1
h₂✝ : x ≠ 1
h₁ : -1 < x
h₂ : x < 1
⊢ HasStrictDerivAt arcsin (1 / sqrt (1 - x ^ 2)) x ∧ ContDiffAt ℝ ⊤ arcsin x State After: case inr.inl
x : ℝ
h₁✝ : x ≠ -1
h₂✝ : x ≠ 1
h₁ : -1 < x
h₂ : x < 1
this : 0 < sqrt (1 - x ^ 2)
⊢ HasStrictDerivAt arcsin (1 / sqrt (1 - x ^ 2)) x ∧ ContDiffAt ℝ ⊤ arcsin x Tactic: have : 0 < sqrt (1 - x ^ 2) := sqrt_pos.2 (by nlinarith [h₁, h₂]) State Before: case inr.inl
x : ℝ
h₁✝ : x ≠ -1
h₂✝ : x ≠ 1
h₁ : -1 < x
h₂ : x < 1
this : 0 < sqrt (1 - x ^ 2)
⊢ HasStrictDerivAt arcsin (1 / sqrt (1 - x ^ 2)) x ∧ ContDiffAt ℝ ⊤ arcsin x State After: case inr.inl
x : ℝ
h₁✝ : x ≠ -1
h₂✝ : x ≠ 1
h₁ : -1 < x
h₂ : x < 1
this : 0 < cos (arcsin x)
⊢ HasStrictDerivAt arcsin (cos (arcsin x))⁻¹ x ∧ ContDiffAt ℝ ⊤ arcsin x Tactic: simp only [← cos_arcsin, one_div] at this ⊢ State Before: case inr.inl
x : ℝ
h₁✝ : x ≠ -1
h₂✝ : x ≠ 1
h₁ : -1 < x
h₂ : x < 1
this : 0 < cos (arcsin x)
⊢ HasStrictDerivAt arcsin (cos (arcsin x))⁻¹ x ∧ ContDiffAt ℝ ⊤ arcsin x State After: no goals Tactic: exact ⟨sinLocalHomeomorph.hasStrictDerivAt_symm ⟨h₁, h₂⟩ this.ne' (hasStrictDerivAt_sin _),
sinLocalHomeomorph.contDiffAt_symm_deriv this.ne' ⟨h₁, h₂⟩ (hasDerivAt_sin _)
contDiff_sin.contDiffAt⟩ State Before: x : ℝ
h₁✝ : x ≠ -1
h₂✝ : x ≠ 1
h₁ : -1 < x
h₂ : x < 1
⊢ 0 < 1 - x ^ 2 State After: no goals Tactic: nlinarith [h₁, h₂] State Before: case inr.inr
x : ℝ
h₁✝ : x ≠ -1
h₂✝ : x ≠ 1
h₁ : -1 < x
h₂ : 1 < x
⊢ HasStrictDerivAt arcsin (1 / sqrt (1 - x ^ 2)) x ∧ ContDiffAt ℝ ⊤ arcsin x State After: case inr.inr
x : ℝ
h₁✝ : x ≠ -1
h₂✝ : x ≠ 1
h₁ : -1 < x
h₂ : 1 < x
this : 1 - x ^ 2 < 0
⊢ HasStrictDerivAt arcsin (1 / sqrt (1 - x ^ 2)) x ∧ ContDiffAt ℝ ⊤ arcsin x Tactic: have : 1 - x ^ 2 < 0 := by nlinarith [h₂] State Before: case inr.inr
x : ℝ
h₁✝ : x ≠ -1
h₂✝ : x ≠ 1
h₁ : -1 < x
h₂ : 1 < x
this : 1 - x ^ 2 < 0
⊢ HasStrictDerivAt arcsin (1 / sqrt (1 - x ^ 2)) x ∧ ContDiffAt ℝ ⊤ arcsin x State After: case inr.inr
x : ℝ
h₁✝ : x ≠ -1
h₂✝ : x ≠ 1
h₁ : -1 < x
h₂ : 1 < x
this : 1 - x ^ 2 < 0
⊢ HasStrictDerivAt arcsin 0 x ∧ ContDiffAt ℝ ⊤ arcsin x Tactic: rw [sqrt_eq_zero'.2 this.le, div_zero] State Before: case inr.inr
x : ℝ
h₁✝ : x ≠ -1
h₂✝ : x ≠ 1
h₁ : -1 < x
h₂ : 1 < x
this : 1 - x ^ 2 < 0
⊢ HasStrictDerivAt arcsin 0 x ∧ ContDiffAt ℝ ⊤ arcsin x State After: case inr.inr
x : ℝ
h₁✝ : x ≠ -1
h₂✝ : x ≠ 1
h₁ : -1 < x
h₂ : 1 < x
this✝ : 1 - x ^ 2 < 0
this : arcsin =ᶠ[𝓝 x] fun x => π / 2
⊢ HasStrictDerivAt arcsin 0 x ∧ ContDiffAt ℝ ⊤ arcsin x Tactic: have : arcsin =ᶠ[𝓝 x] fun _ => π / 2 := (lt_mem_nhds h₂).mono fun y hy => arcsin_of_one_le hy.le State Before: case inr.inr
x : ℝ
h₁✝ : x ≠ -1
h₂✝ : x ≠ 1
h₁ : -1 < x
h₂ : 1 < x
this✝ : 1 - x ^ 2 < 0
this : arcsin =ᶠ[𝓝 x] fun x => π / 2
⊢ HasStrictDerivAt arcsin 0 x ∧ ContDiffAt ℝ ⊤ arcsin x State After: no goals Tactic: exact ⟨(hasStrictDerivAt_const _ _).congr_of_eventuallyEq this.symm,
contDiffAt_const.congr_of_eventuallyEq this⟩ State Before: x : ℝ
h₁✝ : x ≠ -1
h₂✝ : x ≠ 1
h₁ : -1 < x
h₂ : 1 < x
⊢ 1 - x ^ 2 < 0 State After: no goals Tactic: nlinarith [h₂] |
```python
from sympy import *
from sympy.abc import *
import numpy as np
import matplotlib.pyplot as plt
def Kw_(C):
return ((4*C - 1)/(4*C - 4)) + 0.625/C
def Ks_(C):
return (0.5/C) + 1
def Fm_(Fmax, Fmin):
return (Fmax + Fmin)/2
def Fa_(Fmax, Fmin):
return (Fmax - Fmin)/2
Ks, Kw, Fmin, Fmax, Fm, Sf, Fa, nf, Ytrab = symbols("K_s K_w F_{min} F_{max} F_m S_f F_a n_f y_{trab}")
Y = ((d**(b+2))*0.67*np.pi*A)
Z = (Y/(8*C)) - Ks*Fmin
X = Ks*(Fm-Fmin) + (1.34*((A*d**b)/Sf)-1)*Kw*Fa
e = Z/X
e.evalf(3)
```
$\displaystyle \frac{\frac{0.263 A d^{b + 2.0}}{C} - F_{min} K_{s}}{F_{a} K_{w} \left(\frac{1.34 A d^{b}}{S_{f}} - 1.0\right) + K_{s} \left(F_{m} - F_{min}\right)}$
### Resumo de molas helicoidais - Segunda - Aula 10/01
Indice da mola $C$
$$K_s = 1 + \frac{0.5}{C}$$
$$K_w = \frac{4C - 1}{4C - 4} + \frac{0.625}{C}$$
Forças médias e alternadas
$$F_m = \frac{F_{max + F_{min}}}{2}$$
$$F_a = \frac{F_{max - F_{min}}}{2}$$
Determinando $d$ pela relação iterativa - Começar i com $d=1mm$
$$d = \left(\frac{11.9 C n_{f} \left(F_{a} K_{w} \left(\frac{1.34 A d^{b}}{S_{f}} - 1.0\right) + K_{s} \left(F_{m} - \frac{F_{min} \left(n_{f} - 1.0\right)}{n_{f}}\right)\right)}{A \pi}\right)^{\frac{1}{b + 2.0}}$$
Diâmetro médio $D$ e externo $D_0$
$$D = Cd$$
$$D_0 = D + d$$
Rigidez da mola $K$
$$K = \frac{F_{max - F_{min}}}{y_{trabalho}}$$
Número de espiras ativas $N_a$ e totais $N_t$
$$N_a = \frac{d^{4}G}{8D^3K}$$
$$N_t = N_a + 2$$
Rigidez da mola $K$ considerando $Na$ inteiro
$$K = \frac{d^{4}G}{8D^3N_a}$$
Deflexão inicial $y_{inicial}$
$$y_{inic} = \frac{F_{min}}{K}$$
Comprimento livre $L_f$
$$L_f = dN_t + 1.15 + y_{inic}$$
```python
#Equação iterativo de 'd'
U = Fm-((nf-1)/nf)*Fmin
U_ = 1.34*((A*d**b)/Sf) - 1
J = ((8*C*nf)/(0.67*pi*A))
d_ = (J*(Ks*U + U_*Kw*Fa))**(1/(b+2))
d_.evalf(3)
```
$\displaystyle \left(\frac{11.9 C n_{f} \left(F_{a} K_{w} \left(\frac{1.34 A d^{b}}{S_{f}} - 1.0\right) + K_{s} \left(F_{m} - \frac{F_{min} \left(n_{f} - 1.0\right)}{n_{f}}\right)\right)}{A \pi}\right)^{\frac{1}{b + 2.0}}$
```python
#Dados do problema
fmax, fmin, ytrab, c = 600, 300, 25E-3, 8
A_, b_, sf = 1909.9, -0.1453, 310
#Cálculo dos coeficientes
ks, kw = Ks_(c), Kw_(c)
#Cálculo das forças médias e alternadas
fm = Fm_(fmax, fmin)
fa = Fa_(fmax, fmin)
#Cálculo iterativo do diâmetro
solução = []
din = 1 #chute inicial
for i in range(10):
s = d_.subs({d:din, Kw:kw, Ks:ks, Fm:fm, Fa:fa, nf:1.5, Fmin:fmin, Fmax:fmax,
b:b_, A:A_, Sf:sf, C:c, pi:np.pi})
solução.append(s)
din = (s.evalf(5))
np.array(solução, dtype=float)
```
array([7.27672017, 6.35883075, 6.41626819, 6.41241659, 6.41267379,
6.41265647, 6.41265749, 6.41265749, 6.41265749, 6.41265749])
```python
#Diâmetro comercial e dados numéricos
C, G = c, 80.8E9
dc = 6.5E-3
#Diâmetro médio D
D = C*dc
#Diâmetro externo D0
D0 = D + dc
#Rigidez da mola
K = (fmax-fmin)/ytrab
K, D, D0
```
(12000.0, 0.052, 0.058499999999999996)
```python
#Qtd de espiras ativas
Na_ = (G*dc**4)/(8*K*(D)**3)
#aprox pra cima
Na = int(Na_) + 1
(Na_, Na)
```
(10.685221354166664, 11)
```python
#Rigidez da mola de novo
K_ = (G*dc**4)/(8*Na*(D)**3)
K_
```
11656.605113636362
```python
#Deflexão inicial
yinic = fmin/K_
yinic
```
0.02573648134044174
```python
#Comprimento livre
Nt = Na + 2
Lf = (dc)*Nt + 1.15*(ytrab) + yinic
Lf
```
0.13898648134044173
### Resumo de molas de compressão/tração - Terça - Aula 11/01
Comprimento livre $L_f$
$$L_f = L_b + 2L_g$$
$$L_f = N_t + 2L_g$$
Espiras ativas $N_a$
$$N_t = N_a + 1$$
Equação transcendental pra determinar o diâmetro do fio
$$d = \left(G \left(\frac{2.98507462686567 F_{a} n_{f} \left(0.38659 A d^{b} - 0.2885 S_{f}\right)}{S_{f}} + F_{m} n_{f} - F_{min} \left(n_{f} - 1\right)\right)\right)^{\frac{1}{b + 2}}$$
```python
from sympy import *
from sympy.abc import *
import numpy as np
import matplotlib.pyplot as plt
Ks, Kw, Fmin, Fmax, Fm, Sf, Fa, nf, Ytrab = symbols("K_s K_w F_{min} F_{max} F_m S_f F_a n_f y_{trab}")
Kb = symbols("K_b")
C=8
G_ = (4*(4*Kb*C+1))/(pi*A)
H_ = nf*Fm - (nf-1)*Fmin
T_ = (0.577*(-0.5*Sf + 0.67*A*d**b))/(0.5*0.67*Sf)
d_ = (G_*(H_ + nf*Fa*T_))**(1/(b+2))
d_.evalf(3)
```
$\displaystyle \left(\frac{\left(128.0 K_{b} + 4.0\right) \left(\frac{2.98 F_{a} n_{f} \left(0.387 A d^{b} - 0.289 S_{f}\right)}{S_{f}} + F_{m} n_{f} - F_{min} \left(n_{f} - 1.0\right)\right)}{A \pi}\right)^{\frac{1}{b + 2.0}}$
```python
#Dados dos materiais
dic = { 'A227':[-0.1822, 1753.3],
'A228':[-0.1625, 2153.5],
'A229':[-0.1833, 1831.2],
'A232':[-0.1453, 1909.9],
'A232':[-0.0934, 2059.2]}
material = 'A228'
fmax, fmin, C = 150, 50, 8
b_, A_, sf = dic[material][0], dic[material][1], 310
fm = Fm_(fmax, fmin)
fa = Fa_(fmax, fmin)
kb = (-1-C+4*C**2)/(4*C*(C-1))
#Cálculo iterativo do diâmetro
solução = []
din = 1 #chute inicial
for i in range(10):
s = d_.subs({d:din, Kb:kb, Fm:fm, Fa:fa, nf:2, Fmin:fmin, Fmax:fmax,
b:b_, A:A_, Sf:sf, C:8, pi:np.pi})
solução.append(s)
din = (s.evalf(5))
solução
#np.array(solução, dtype=float)
```
[4.90339015850936,
4.31041980252648,
4.35523200896826,
4.35161560058455,
4.35190591019958,
4.35188262669210,
4.35188446480197,
4.35188446480197,
4.35188446480197,
4.35188446480197]
```python
```
|
% template.tex, dated April 5 2013
% This is a template file for Annual Reviews 1 column Journals
%
% Compilation using ar-1col.cls' - version 1.0, Aptara Inc.
% (c) 2013 AR
%
% Steps to compile: latex latex latex
%
% For tracking purposes => this is v1.0 - Apr. 2013
\documentclass{ar-1col}
% Metadata Information
\jname{Xxxx. Xxx. Xxx. Xxx.}
\jvol{AA}
\jyear{YYYY}
\doi{10.1146/((please add article doi))}
% Document starts
\begin{document}
% Page header
\markboth{Insert_author_names}{Insert_a_shortened_title}
% Title
\title{Title}
%Authors, affiliations address.
\author{Author B. Authorone,$^1$ Firstname C. Authortwo,$^2$ and D. Name Authorthree$^3$
\affil{$^1$Department/Institute, University, City, Country, Postal code}
\affil{$^2$Department/Institute, University, City, Country, Postal code}
\affil{$^3$Department/Institute, University, City, Country, Postal code}}
%Abstract
\begin{abstract}
Abstract text. Abstract text. Abstract text. Abstract text. Abstract text. Abstract text. Abstract text. Abstract text.
\end{abstract}
%Keywords, etc.
\begin{keywords}
keywords; separated by comma; no full stop
\end{keywords}
\maketitle
%Table of Contents
\tableofcontents
% Heading 1
\section{INTRODUCTION}
Please begin the main text of your article here. This is a template file for AR Journals.
% Text Box
\begin{textbox}
\section{TEXT BOX HEAD}
Text box text. Text box text. Text box text. Text box text. Text box text. Text box text.
\subsection{Text Box Sub-head}
Text box text. Text box text. Text box text. Text box text. Text box text. Text box text.
\subsubsection{Text Box Subsub-head}
Text box text. Text box text. Text box text. Text box text. Text box text. Text box text.
\end{textbox}
\begin{textbox}
Text box text. Text box text. Text box text. Text box text. Text box text. Text box text.
Text box text. Text box text. Text box text. Text box text. Text box text. Text box text.
Text box text. Text box text. Text box text. Text box text. Text box text. Text box text.
\end{textbox}
%Heading 1
\section{FIRST-ORDER HEADING}
This is dummy text. This is dummy text. This is dummy text. This is dummy text. This is dummy text. This is dummy text. This is dummy text. This is dummy text. This is dummy text. This is dummy text. This is dummy text. This is dummy text.
% Heading 2
\subsection{Second-Order Heading}
This is dummy text. This is dummy text. This is dummy text. This is dummy text.
% Heading 3
\subsubsection{Third-Order Heading}
This is dummy text. This is dummy text. This is dummy text. This is dummy text.
% Heading 4
\paragraph{Fourth-Order Heading:} Fourth-order headings are placed as part of the paragraph.
% Margin Note
\begin{marginnote}[<skip value - optional>]
\entry{XXX}{xx xxx ....}
\entry{XXX}{xx xxx ....}
\entry{XXX}{xx xxx ....}
\end{marginnote}
% Example of a single-line equation
\begin{equation}
a = b \ {\rm ((Single\ Equation\ Numbered))}
\end{equation}
%Example of multiple-line equation
Equations can also be multiple lines as shown in Equation 2 and 3.
\begin{eqnarray}
c = 0 \ {\rm ((Multiple\ Lines, \ Numbered))}\\
ac = 0 \ {\rm ((Multiple \ Lines, \ Numbered))}
\end{eqnarray}
%Example of a Figure
{\itshape Figures:} Figures should be cited in the main text in chronological order. This is dummy text with a citation to the first figure (\textbf{Figure \ref{fig1}}). Only the first citation in the main text of Figure \ref{fig1}, or any other display item, should be bolded. Citations to Figure \ref{fig1} later in the text should not be bolded.
\begin{figure}
\includegraphics[width=3in]{fpo}
\caption{Figure Caption.}
\label{fig1}
\end{figure}
% Example of a Table
{\itshape Tables:} Tables should also be cited in the main text in chronological order (\textbf {Table \ref{tab1}}).
\begin{table}
\tabcolsep7.5pt
\caption{Table Caption.}
\label{tab1}
\begin{center}
\begin{tabular}{@{}l|c|c|c|c@{}}
\hline
Head 1 &&&&Head 5\\
{[}units]$^{\rm a)}$ &Head 2 &Head 3 &Head 4 &{[}units]\\
\hline
Column 1 &Column 2 &Column3$^{\rm b)}$ &Column4 &Column\\
Column 1 &Column 2 &Column3 &Column4 &Column\\
Column 1 &Column 2 &Column3 &Column4 &Column\\
Column 1 &Column 2 &Column3 &Column4 &Column\\
\hline
\end{tabular}
\end{center}
\begin{tabnote}
$^{\rm a)}$Table Footnote; $^{\rm b)}$ Second Table Footnote.
\end{tabnote}
\end{table}
% Example of lists
{\itshape Lists:} Here is an example of a numbered list.
\begin{enumerate}
\item et al.
\item e.g.,
\item i.e.,
\item in vivo
\item in vitro
\item in situ
\item via
\end{enumerate}
Here is an example of a extract.
\begin{extract}
This is an example text of quote or extract.
This is an example text of quote or extract.
\end{extract}
% Summary Points
\begin{summary}[SUMMARY POINTS]
\begin{enumerate}
\item Summary points text .........
\item Summary points text ..........
\item Summary points text ..........
\item Summary points text ..........
\end{enumerate}
\end{summary}
% Future Issues
\begin{issues}[FUTURE ISSUES]
\begin{enumerate}
\item Future issue text ...........
\item Future issue text ...........
\item Future issue text ...........
\item Future issue text ...........
\end{enumerate}
\end{issues}
%Disclosure
\section*{DISCLOSURE STATEMENT}
Disclosure statement will go here.
% Acknowledgements
\section*{ACKNOWLEDGMENTS}
Acknowledgements, general annotations, funding.
% References
%
% Margin notes within bibliography
\bibnote[<vertical skip value - optional>]{Bibliography margin text.}
%
\bibliography{<bibfilename>.bib}
\bibliographystyle{<bstfilename>.bst}
\end{document}
|
#include <boost/test/unit_test.hpp>
#include <ETAio/testing/tester.hpp>
#include <ETAio/chain/abi_serializer.hpp>
#include <ETAio/chain/wast_to_wasm.hpp>
#include <ETAio.msig/ETAio.msig.wast.hpp>
#include <ETAio.msig/ETAio.msig.abi.hpp>
#include <exchange/exchange.wast.hpp>
#include <exchange/exchange.abi.hpp>
#include <test_api/test_api.wast.hpp>
#include <ETAio.system/ETAio.system.wast.hpp>
#include <ETAio.system/ETAio.system.abi.hpp>
#include <ETAio.token/ETAio.token.wast.hpp>
#include <ETAio.token/ETAio.token.abi.hpp>
#include <Runtime/Runtime.h>
#include <fc/variant_object.hpp>
using namespace ETAio::testing;
using namespace ETAio;
using namespace ETAio::chain;
using namespace ETAio::testing;
using namespace fc;
using mvo = fc::mutable_variant_object;
class ETAio_msig_tester : public tester {
public:
ETAio_msig_tester() {
create_accounts( { N(ETAio.msig), N(ETAio.stake), N(ETAio.ram), N(ETAio.ramfee), N(alice), N(bob), N(carol) } );
produce_block();
auto trace = base_tester::push_action(config::system_account_name, N(setpriv),
config::system_account_name, mutable_variant_object()
("account", "ETAio.msig")
("is_priv", 1)
);
set_code( N(ETAio.msig), ETAio_msig_wast );
set_abi( N(ETAio.msig), ETAio_msig_abi );
produce_blocks();
const auto& accnt = control->db().get<account_object,by_name>( N(ETAio.msig) );
abi_def abi;
BOOST_REQUIRE_EQUAL(abi_serializer::to_abi(accnt.abi, abi), true);
abi_ser.set_abi(abi, abi_serializer_max_time);
}
transaction_trace_ptr create_account_with_resources( account_name a, account_name creator, asset ramfunds, bool multisig,
asset net = core_from_string("10.0000"), asset cpu = core_from_string("10.0000") ) {
signed_transaction trx;
set_transaction_headers(trx);
authority owner_auth;
if (multisig) {
// multisig between account's owner key and creators active permission
owner_auth = authority(2, {key_weight{get_public_key( a, "owner" ), 1}}, {permission_level_weight{{creator, config::active_name}, 1}});
} else {
owner_auth = authority( get_public_key( a, "owner" ) );
}
trx.actions.emplace_back( vector<permission_level>{{creator,config::active_name}},
newaccount{
.creator = creator,
.name = a,
.owner = owner_auth,
.active = authority( get_public_key( a, "active" ) )
});
trx.actions.emplace_back( get_action( config::system_account_name, N(buyram), vector<permission_level>{{creator,config::active_name}},
mvo()
("payer", creator)
("receiver", a)
("quant", ramfunds) )
);
trx.actions.emplace_back( get_action( config::system_account_name, N(delegatebw), vector<permission_level>{{creator,config::active_name}},
mvo()
("from", creator)
("receiver", a)
("stake_net_quantity", net )
("stake_cpu_quantity", cpu )
("transfer", 0 )
)
);
set_transaction_headers(trx);
trx.sign( get_private_key( creator, "active" ), control->get_chain_id() );
return push_transaction( trx );
}
void create_currency( name contract, name manager, asset maxsupply ) {
auto act = mutable_variant_object()
("issuer", manager )
("maximum_supply", maxsupply );
base_tester::push_action(contract, N(create), contract, act );
}
void issue( name to, const asset& amount, name manager = config::system_account_name ) {
base_tester::push_action( N(ETAio.token), N(issue), manager, mutable_variant_object()
("to", to )
("quantity", amount )
("memo", "")
);
}
void transfer( name from, name to, const string& amount, name manager = config::system_account_name ) {
base_tester::push_action( N(ETAio.token), N(transfer), manager, mutable_variant_object()
("from", from)
("to", to )
("quantity", asset::from_string(amount) )
("memo", "")
);
}
asset get_balance( const account_name& act ) {
//return get_currency_balance( config::system_account_name, symbol(CORE_SYMBOL), act );
//temporary code. current get_currency_balancy uses table name N(accounts) from currency.h
//generic_currency table name is N(account).
const auto& db = control->db();
const auto* tbl = db.find<table_id_object, by_code_scope_table>(boost::make_tuple(N(ETAio.token), act, N(accounts)));
share_type result = 0;
// the balance is implied to be 0 if either the table or row does not exist
if (tbl) {
const auto *obj = db.find<key_value_object, by_scope_primary>(boost::make_tuple(tbl->id, symbol(CORE_SYMBOL).to_symbol_code()));
if (obj) {
// balance is the first field in the serialization
fc::datastream<const char *> ds(obj->value.data(), obj->value.size());
fc::raw::unpack(ds, result);
}
}
return asset( result, symbol(CORE_SYMBOL) );
}
transaction_trace_ptr push_action( const account_name& signer, const action_name& name, const variant_object& data, bool auth = true ) {
vector<account_name> accounts;
if( auth )
accounts.push_back( signer );
auto trace = base_tester::push_action( N(ETAio.msig), name, accounts, data );
produce_block();
BOOST_REQUIRE_EQUAL( true, chain_has_transaction(trace->id) );
return trace;
}
transaction reqauth( account_name from, const vector<permission_level>& auths, const fc::microseconds& max_serialization_time );
abi_serializer abi_ser;
};
transaction ETAio_msig_tester::reqauth( account_name from, const vector<permission_level>& auths, const fc::microseconds& max_serialization_time ) {
fc::variants v;
for ( auto& level : auths ) {
v.push_back(fc::mutable_variant_object()
("actor", level.actor)
("permission", level.permission)
);
}
variant pretty_trx = fc::mutable_variant_object()
("expiration", "2020-01-01T00:30")
("ref_block_num", 2)
("ref_block_prefix", 3)
("max_net_usage_words", 0)
("max_cpu_usage_ms", 0)
("delay_sec", 0)
("actions", fc::variants({
fc::mutable_variant_object()
("account", name(config::system_account_name))
("name", "reqauth")
("authorization", v)
("data", fc::mutable_variant_object() ("from", from) )
})
);
transaction trx;
abi_serializer::from_variant(pretty_trx, trx, get_resolver(), max_serialization_time);
return trx;
}
BOOST_AUTO_TEST_SUITE(ETAio_msig_tests)
BOOST_FIXTURE_TEST_CASE( propose_approve_execute, ETAio_msig_tester ) try {
auto trx = reqauth("alice", {permission_level{N(alice), config::active_name}}, abi_serializer_max_time );
push_action( N(alice), N(propose), mvo()
("proposer", "alice")
("proposal_name", "first")
("trx", trx)
("requested", vector<permission_level>{{ N(alice), config::active_name }})
);
//fail to execute before approval
BOOST_REQUIRE_EXCEPTION( push_action( N(alice), N(exec), mvo()
("proposer", "alice")
("proposal_name", "first")
("executer", "alice")
),
ETAio_assert_message_exception,
ETAio_assert_message_is("transaction authorization failed")
);
//approve and execute
push_action( N(alice), N(approve), mvo()
("proposer", "alice")
("proposal_name", "first")
("level", permission_level{ N(alice), config::active_name })
);
transaction_trace_ptr trace;
control->applied_transaction.connect([&]( const transaction_trace_ptr& t) { if (t->scheduled) { trace = t; } } );
push_action( N(alice), N(exec), mvo()
("proposer", "alice")
("proposal_name", "first")
("executer", "alice")
);
BOOST_REQUIRE( bool(trace) );
BOOST_REQUIRE_EQUAL( 1, trace->action_traces.size() );
BOOST_REQUIRE_EQUAL( transaction_receipt::executed, trace->receipt->status );
} FC_LOG_AND_RETHROW()
BOOST_FIXTURE_TEST_CASE( propose_approve_unapprove, ETAio_msig_tester ) try {
auto trx = reqauth("alice", {permission_level{N(alice), config::active_name}}, abi_serializer_max_time );
push_action( N(alice), N(propose), mvo()
("proposer", "alice")
("proposal_name", "first")
("trx", trx)
("requested", vector<permission_level>{{ N(alice), config::active_name }})
);
push_action( N(alice), N(approve), mvo()
("proposer", "alice")
("proposal_name", "first")
("level", permission_level{ N(alice), config::active_name })
);
push_action( N(alice), N(unapprove), mvo()
("proposer", "alice")
("proposal_name", "first")
("level", permission_level{ N(alice), config::active_name })
);
BOOST_REQUIRE_EXCEPTION( push_action( N(alice), N(exec), mvo()
("proposer", "alice")
("proposal_name", "first")
("executer", "alice")
),
ETAio_assert_message_exception,
ETAio_assert_message_is("transaction authorization failed")
);
} FC_LOG_AND_RETHROW()
BOOST_FIXTURE_TEST_CASE( propose_approve_by_two, ETAio_msig_tester ) try {
auto trx = reqauth("alice", vector<permission_level>{ { N(alice), config::active_name }, { N(bob), config::active_name } }, abi_serializer_max_time );
push_action( N(alice), N(propose), mvo()
("proposer", "alice")
("proposal_name", "first")
("trx", trx)
("requested", vector<permission_level>{ { N(alice), config::active_name }, { N(bob), config::active_name } })
);
//approve by alice
push_action( N(alice), N(approve), mvo()
("proposer", "alice")
("proposal_name", "first")
("level", permission_level{ N(alice), config::active_name })
);
//fail because approval by bob is missing
BOOST_REQUIRE_EXCEPTION( push_action( N(alice), N(exec), mvo()
("proposer", "alice")
("proposal_name", "first")
("executer", "alice")
),
ETAio_assert_message_exception,
ETAio_assert_message_is("transaction authorization failed")
);
//approve by bob and execute
push_action( N(bob), N(approve), mvo()
("proposer", "alice")
("proposal_name", "first")
("level", permission_level{ N(bob), config::active_name })
);
transaction_trace_ptr trace;
control->applied_transaction.connect([&]( const transaction_trace_ptr& t) { if (t->scheduled) { trace = t; } } );
push_action( N(alice), N(exec), mvo()
("proposer", "alice")
("proposal_name", "first")
("executer", "alice")
);
BOOST_REQUIRE( bool(trace) );
BOOST_REQUIRE_EQUAL( 1, trace->action_traces.size() );
BOOST_REQUIRE_EQUAL( transaction_receipt::executed, trace->receipt->status );
} FC_LOG_AND_RETHROW()
BOOST_FIXTURE_TEST_CASE( propose_with_wrong_requested_auth, ETAio_msig_tester ) try {
auto trx = reqauth("alice", vector<permission_level>{ { N(alice), config::active_name }, { N(bob), config::active_name } }, abi_serializer_max_time );
//try with not enough requested auth
BOOST_REQUIRE_EXCEPTION( push_action( N(alice), N(propose), mvo()
("proposer", "alice")
("proposal_name", "third")
("trx", trx)
("requested", vector<permission_level>{ { N(alice), config::active_name } } )
),
ETAio_assert_message_exception,
ETAio_assert_message_is("transaction authorization failed")
);
} FC_LOG_AND_RETHROW()
BOOST_FIXTURE_TEST_CASE( big_transaction, ETAio_msig_tester ) try {
vector<permission_level> perm = { { N(alice), config::active_name }, { N(bob), config::active_name } };
auto wasm = wast_to_wasm( exchange_wast );
variant pretty_trx = fc::mutable_variant_object()
("expiration", "2020-01-01T00:30")
("ref_block_num", 2)
("ref_block_prefix", 3)
("max_net_usage_words", 0)
("max_cpu_usage_ms", 0)
("delay_sec", 0)
("actions", fc::variants({
fc::mutable_variant_object()
("account", name(config::system_account_name))
("name", "setcode")
("authorization", perm)
("data", fc::mutable_variant_object()
("account", "alice")
("vmtype", 0)
("vmversion", 0)
("code", bytes( wasm.begin(), wasm.end() ))
)
})
);
transaction trx;
abi_serializer::from_variant(pretty_trx, trx, get_resolver(), abi_serializer_max_time);
push_action( N(alice), N(propose), mvo()
("proposer", "alice")
("proposal_name", "first")
("trx", trx)
("requested", perm)
);
//approve by alice
push_action( N(alice), N(approve), mvo()
("proposer", "alice")
("proposal_name", "first")
("level", permission_level{ N(alice), config::active_name })
);
//approve by bob and execute
push_action( N(bob), N(approve), mvo()
("proposer", "alice")
("proposal_name", "first")
("level", permission_level{ N(bob), config::active_name })
);
transaction_trace_ptr trace;
control->applied_transaction.connect([&]( const transaction_trace_ptr& t) { if (t->scheduled) { trace = t; } } );
push_action( N(alice), N(exec), mvo()
("proposer", "alice")
("proposal_name", "first")
("executer", "alice")
);
BOOST_REQUIRE( bool(trace) );
BOOST_REQUIRE_EQUAL( 1, trace->action_traces.size() );
BOOST_REQUIRE_EQUAL( transaction_receipt::executed, trace->receipt->status );
} FC_LOG_AND_RETHROW()
BOOST_FIXTURE_TEST_CASE( update_system_contract_all_approve, ETAio_msig_tester ) try {
// required to set up the link between (ETAio active) and (ETAio.prods active)
//
// ETAio active
// |
// ETAio.prods active (2/3 threshold)
// / | \ <--- implicitly updated in onblock action
// alice active bob active carol active
set_authority(config::system_account_name, "active", authority(1,
vector<key_weight>{{get_private_key("ETAio", "active").get_public_key(), 1}},
vector<permission_level_weight>{{{N(ETAio.prods), config::active_name}, 1}}), "owner",
{ { config::system_account_name, "active" } }, { get_private_key( config::system_account_name, "active" ) });
set_producers( {N(alice),N(bob),N(carol)} );
produce_blocks(50);
create_accounts( { N(ETAio.token) } );
set_code( N(ETAio.token), ETAio_token_wast );
set_abi( N(ETAio.token), ETAio_token_abi );
create_currency( N(ETAio.token), config::system_account_name, core_from_string("10000000000.0000") );
issue(config::system_account_name, core_from_string("1000000000.0000"));
BOOST_REQUIRE_EQUAL( core_from_string("1000000000.0000"),
get_balance("ETAio") + get_balance("ETAio.ramfee") + get_balance("ETAio.stake") + get_balance("ETAio.ram") );
set_code( config::system_account_name, ETAio_system_wast );
set_abi( config::system_account_name, ETAio_system_abi );
produce_blocks();
create_account_with_resources( N(alice1111111), config::system_account_name, core_from_string("1.0000"), false );
create_account_with_resources( N(bob111111111), config::system_account_name, core_from_string("0.4500"), false );
create_account_with_resources( N(carol1111111), config::system_account_name, core_from_string("1.0000"), false );
BOOST_REQUIRE_EQUAL( core_from_string("1000000000.0000"),
get_balance("ETAio") + get_balance("ETAio.ramfee") + get_balance("ETAio.stake") + get_balance("ETAio.ram") );
vector<permission_level> perm = { { N(alice), config::active_name }, { N(bob), config::active_name },
{N(carol), config::active_name} };
vector<permission_level> action_perm = {{config::system_account_name, config::active_name}};
auto wasm = wast_to_wasm( test_api_wast );
variant pretty_trx = fc::mutable_variant_object()
("expiration", "2020-01-01T00:30")
("ref_block_num", 2)
("ref_block_prefix", 3)
("max_net_usage_words", 0)
("max_cpu_usage_ms", 0)
("delay_sec", 0)
("actions", fc::variants({
fc::mutable_variant_object()
("account", name(config::system_account_name))
("name", "setcode")
("authorization", action_perm)
("data", fc::mutable_variant_object()
("account", name(config::system_account_name))
("vmtype", 0)
("vmversion", 0)
("code", bytes( wasm.begin(), wasm.end() ))
)
})
);
transaction trx;
abi_serializer::from_variant(pretty_trx, trx, get_resolver(), abi_serializer_max_time);
// propose action
push_action( N(alice), N(propose), mvo()
("proposer", "alice")
("proposal_name", "first")
("trx", trx)
("requested", perm)
);
//approve by alice
push_action( N(alice), N(approve), mvo()
("proposer", "alice")
("proposal_name", "first")
("level", permission_level{ N(alice), config::active_name })
);
//approve by bob
push_action( N(bob), N(approve), mvo()
("proposer", "alice")
("proposal_name", "first")
("level", permission_level{ N(bob), config::active_name })
);
//approve by carol
push_action( N(carol), N(approve), mvo()
("proposer", "alice")
("proposal_name", "first")
("level", permission_level{ N(carol), config::active_name })
);
// execute by alice to replace the ETAio system contract
transaction_trace_ptr trace;
control->applied_transaction.connect([&]( const transaction_trace_ptr& t) { if (t->scheduled) { trace = t; } } );
push_action( N(alice), N(exec), mvo()
("proposer", "alice")
("proposal_name", "first")
("executer", "alice")
);
BOOST_REQUIRE( bool(trace) );
BOOST_REQUIRE_EQUAL( 1, trace->action_traces.size() );
BOOST_REQUIRE_EQUAL( transaction_receipt::executed, trace->receipt->status );
// can't create account because system contract was replace by the test_api contract
BOOST_REQUIRE_EXCEPTION( create_account_with_resources( N(alice1111112), config::system_account_name, core_from_string("1.0000"), false ),
ETAio_assert_message_exception, ETAio_assert_message_is("Unknown Test")
);
} FC_LOG_AND_RETHROW()
BOOST_FIXTURE_TEST_CASE( update_system_contract_major_approve, ETAio_msig_tester ) try {
// set up the link between (ETAio active) and (ETAio.prods active)
set_authority(config::system_account_name, "active", authority(1,
vector<key_weight>{{get_private_key("ETAio", "active").get_public_key(), 1}},
vector<permission_level_weight>{{{N(ETAio.prods), config::active_name}, 1}}), "owner",
{ { config::system_account_name, "active" } }, { get_private_key( config::system_account_name, "active" ) });
create_accounts( { N(apple) } );
set_producers( {N(alice),N(bob),N(carol), N(apple)} );
produce_blocks(50);
create_accounts( { N(ETAio.token) } );
set_code( N(ETAio.token), ETAio_token_wast );
set_abi( N(ETAio.token), ETAio_token_abi );
create_currency( N(ETAio.token), config::system_account_name, core_from_string("10000000000.0000") );
issue(config::system_account_name, core_from_string("1000000000.0000"));
BOOST_REQUIRE_EQUAL( core_from_string("1000000000.0000"), get_balance( "ETAio" ) );
set_code( config::system_account_name, ETAio_system_wast );
set_abi( config::system_account_name, ETAio_system_abi );
produce_blocks();
create_account_with_resources( N(alice1111111), config::system_account_name, core_from_string("1.0000"), false );
create_account_with_resources( N(bob111111111), config::system_account_name, core_from_string("0.4500"), false );
create_account_with_resources( N(carol1111111), config::system_account_name, core_from_string("1.0000"), false );
BOOST_REQUIRE_EQUAL( core_from_string("1000000000.0000"),
get_balance("ETAio") + get_balance("ETAio.ramfee") + get_balance("ETAio.stake") + get_balance("ETAio.ram") );
vector<permission_level> perm = { { N(alice), config::active_name }, { N(bob), config::active_name },
{N(carol), config::active_name}, {N(apple), config::active_name}};
vector<permission_level> action_perm = {{config::system_account_name, config::active_name}};
auto wasm = wast_to_wasm( test_api_wast );
variant pretty_trx = fc::mutable_variant_object()
("expiration", "2020-01-01T00:30")
("ref_block_num", 2)
("ref_block_prefix", 3)
("max_net_usage_words", 0)
("max_cpu_usage_ms", 0)
("delay_sec", 0)
("actions", fc::variants({
fc::mutable_variant_object()
("account", name(config::system_account_name))
("name", "setcode")
("authorization", action_perm)
("data", fc::mutable_variant_object()
("account", name(config::system_account_name))
("vmtype", 0)
("vmversion", 0)
("code", bytes( wasm.begin(), wasm.end() ))
)
})
);
transaction trx;
abi_serializer::from_variant(pretty_trx, trx, get_resolver(), abi_serializer_max_time);
// propose action
push_action( N(alice), N(propose), mvo()
("proposer", "alice")
("proposal_name", "first")
("trx", trx)
("requested", perm)
);
//approve by alice
push_action( N(alice), N(approve), mvo()
("proposer", "alice")
("proposal_name", "first")
("level", permission_level{ N(alice), config::active_name })
);
//approve by bob
push_action( N(bob), N(approve), mvo()
("proposer", "alice")
("proposal_name", "first")
("level", permission_level{ N(bob), config::active_name })
);
// not enough approvers
BOOST_REQUIRE_EXCEPTION(
push_action( N(alice), N(exec), mvo()
("proposer", "alice")
("proposal_name", "first")
("executer", "alice")
),
ETAio_assert_message_exception, ETAio_assert_message_is("transaction authorization failed")
);
//approve by apple
push_action( N(apple), N(approve), mvo()
("proposer", "alice")
("proposal_name", "first")
("level", permission_level{ N(apple), config::active_name })
);
// execute by alice to replace the ETAio system contract
transaction_trace_ptr trace;
control->applied_transaction.connect([&]( const transaction_trace_ptr& t) { if (t->scheduled) { trace = t; } } );
// execute by another producer different from proposer
push_action( N(apple), N(exec), mvo()
("proposer", "alice")
("proposal_name", "first")
("executer", "apple")
);
BOOST_REQUIRE( bool(trace) );
BOOST_REQUIRE_EQUAL( 1, trace->action_traces.size() );
BOOST_REQUIRE_EQUAL( transaction_receipt::executed, trace->receipt->status );
// can't create account because system contract was replace by the test_api contract
BOOST_REQUIRE_EXCEPTION( create_account_with_resources( N(alice1111112), config::system_account_name, core_from_string("1.0000"), false ),
ETAio_assert_message_exception, ETAio_assert_message_is("Unknown Test")
);
} FC_LOG_AND_RETHROW()
BOOST_AUTO_TEST_SUITE_END()
|
MODULE hfsgg_I
INTERFACE
!...Generated by Pacific-Sierra Research 77to90 4.3E 18:34:47 1/ 6/07
!...Modified by Charlotte Froese Fischer
! Gediminas Gaigalas 11/01/17
SUBROUTINE hfsgg
END SUBROUTINE
END INTERFACE
END MODULE
|
subroutine ksunsc (x,sx,scale,ndv)
implicit double precision (a-h,o-z)
dimension x(*),sx(*),scale(ndv,2)
c
c routine to un-scale design variables before returning
c to the real world
c
c author - Gregory A. Wrenn
c location - Lockheed Engineering and Sciences Co.
c 144 Research Drive
c Hampton, Va. 23666
c
c last modification - 17 July 1996
c
do 10 i = 1,ndv
ss = scale(i,1)
x(i) = sx(i) * ss
10 continue
c
return
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.