text
stringlengths 0
3.34M
|
---|
[STATEMENT]
lemma prio_add_abc:
assumes "(l::('e,'a::linorder)Prio) + a \<le> c"
and "\<not> l \<le> c"
shows "\<not> l \<le> a"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<not> l \<le> a
[PROOF STEP]
proof (rule ccontr)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<not> \<not> l \<le> a \<Longrightarrow> False
[PROOF STEP]
assume "\<not> \<not> l \<le> a"
[PROOF STATE]
proof (state)
this:
\<not> \<not> l \<le> a
goal (1 subgoal):
1. \<not> \<not> l \<le> a \<Longrightarrow> False
[PROOF STEP]
with assms
[PROOF STATE]
proof (chain)
picking this:
l + a \<le> c
\<not> l \<le> c
\<not> \<not> l \<le> a
[PROOF STEP]
have "l + a = l"
[PROOF STATE]
proof (prove)
using this:
l + a \<le> c
\<not> l \<le> c
\<not> \<not> l \<le> a
goal (1 subgoal):
1. l + a = l
[PROOF STEP]
apply (auto simp add: plus_def plesseq_def)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>p_less_eq (p_min l a) c; \<not> p_less_eq l c; p_less_eq l a\<rbrakk> \<Longrightarrow> p_min l a = l
[PROOF STEP]
apply (cases "(l,a)" rule: p_less_eq.cases)
[PROOF STATE]
proof (prove)
goal (3 subgoals):
1. \<And>e aa f b. \<lbrakk>p_less_eq (p_min l a) c; \<not> p_less_eq l c; p_less_eq l a; (l, a) = (Prio e aa, Prio f b)\<rbrakk> \<Longrightarrow> p_min l a = l
2. \<And>uu_. \<lbrakk>p_less_eq (p_min l a) c; \<not> p_less_eq l c; p_less_eq l a; (l, a) = (uu_, Infty)\<rbrakk> \<Longrightarrow> p_min l a = l
3. \<And>e aa. \<lbrakk>p_less_eq (p_min l a) c; \<not> p_less_eq l c; p_less_eq l a; (l, a) = (Infty, Prio e aa)\<rbrakk> \<Longrightarrow> p_min l a = l
[PROOF STEP]
apply auto
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done
[PROOF STATE]
proof (state)
this:
l + a = l
goal (1 subgoal):
1. \<not> \<not> l \<le> a \<Longrightarrow> False
[PROOF STEP]
with assms
[PROOF STATE]
proof (chain)
picking this:
l + a \<le> c
\<not> l \<le> c
l + a = l
[PROOF STEP]
show False
[PROOF STATE]
proof (prove)
using this:
l + a \<le> c
\<not> l \<le> c
l + a = l
goal (1 subgoal):
1. False
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
False
goal:
No subgoals!
[PROOF STEP]
qed |
-- Andreas, 2019-02-03, issue #3541:
-- Treat indices like parameters in positivity check.
data Works (A : Set) : Set where
nest : Works (Works A) → Works A
data Foo : Set → Set where
foo : ∀{A} → Foo (Foo A) → Foo A
-- Should pass.
|
/*
*
* A cross-platform way of providing access to gsl_ieee_env_setup
* from Fortran on any system MITgcm runs on currently.
*/
#ifdef USE_GSL_IEEE
#include <gsl/gsl_math.h>
#include <gsl/gsl_ieee_utils.h>
void fgsl_ieee_env_setup ()
{
gsl_ieee_env_setup ();
}
void fgsl_ieee_env_setup_ ()
{
gsl_ieee_env_setup ();
}
void fgsl_ieee_env_setup__ ()
{
gsl_ieee_env_setup ();
}
void FGSL_IEEE_ENV_SETUP ()
{
gsl_ieee_env_setup ();
}
#endif
|
[GOAL]
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁ π₂ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
⊢ Henstock ≤ Riemann
[PROOFSTEP]
trivial
[GOAL]
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁ π₂ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
⊢ Henstock ≤ McShane
[PROOFSTEP]
trivial
[GOAL]
ι✝ : Type u_1
inst✝ : Fintype ι✝
I J : Box ι✝
c c₁ c₂ : ℝ≥0
r✝ r₁ r₂ : (ι✝ → ℝ) → ↑(Set.Ioi 0)
π π₁ π₂ : TaggedPrepartition I
l✝ l₁ l₂ : IntegrationParams
ι : Type u_2
l : IntegrationParams
hl : l.bRiemann = false
r : (ι → ℝ) → ↑(Set.Ioi 0)
⊢ RCond l r
[PROOFSTEP]
simp [RCond, hl]
[GOAL]
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁ π₂ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
h₁ : MemBaseSet l I c₁ r₁ π₁
h₂ : MemBaseSet l I c₂ r₂ π₂
hU : TaggedPrepartition.iUnion π₁ = TaggedPrepartition.iUnion π₂
⊢ ∃ π,
Prepartition.iUnion π = ↑I \ TaggedPrepartition.iUnion π₁ ∧
(l.bDistortion = true → Prepartition.distortion π ≤ c₁) ∧ (l.bDistortion = true → Prepartition.distortion π ≤ c₂)
[PROOFSTEP]
wlog hc : c₁ ≤ c₂ with H
[GOAL]
case inr
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁ π₂ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
h₁ : MemBaseSet l I c₁ r₁ π₁
h₂ : MemBaseSet l I c₂ r₂ π₂
hU : TaggedPrepartition.iUnion π₁ = TaggedPrepartition.iUnion π₂
H :
∀ {ι : Type u_1} [inst : Fintype ι] {I : Box ι} {J : Box ι} {c : ℝ≥0} {c₁ c₂ : ℝ≥0} {r : (ι → ℝ) → ↑(Set.Ioi 0)}
{r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)} {π : TaggedPrepartition I} {π₁ π₂ : TaggedPrepartition I} {l : IntegrationParams}
{l₁ l₂ : IntegrationParams},
MemBaseSet l I c₁ r₁ π₁ →
MemBaseSet l I c₂ r₂ π₂ →
TaggedPrepartition.iUnion π₁ = TaggedPrepartition.iUnion π₂ →
c₁ ≤ c₂ →
∃ π,
Prepartition.iUnion π = ↑I \ TaggedPrepartition.iUnion π₁ ∧
(l.bDistortion = true → Prepartition.distortion π ≤ c₁) ∧
(l.bDistortion = true → Prepartition.distortion π ≤ c₂)
hc : ¬c₁ ≤ c₂
⊢ ∃ π,
Prepartition.iUnion π = ↑I \ TaggedPrepartition.iUnion π₁ ∧
(l.bDistortion = true → Prepartition.distortion π ≤ c₁) ∧ (l.bDistortion = true → Prepartition.distortion π ≤ c₂)
[PROOFSTEP]
simpa [hU, _root_.and_comm] using @H _ _ I J c c₂ c₁ r r₂ r₁ π π₂ π₁ _ l₂ l₁ h₂ h₁ hU.symm (le_of_not_le hc)
[GOAL]
ι✝ : Type u_1
inst✝¹ : Fintype ι✝
I✝ : Box ι✝
c₁✝ c₂✝ : ℝ≥0
r₁✝ r₂✝ : (ι✝ → ℝ) → ↑(Set.Ioi 0)
π₁✝ π₂✝ : TaggedPrepartition I✝
l✝ : IntegrationParams
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁ π₂ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
h₁ : MemBaseSet l I c₁ r₁ π₁
h₂ : MemBaseSet l I c₂ r₂ π₂
hU : TaggedPrepartition.iUnion π₁ = TaggedPrepartition.iUnion π₂
hc : c₁ ≤ c₂
⊢ ∃ π,
Prepartition.iUnion π = ↑I \ TaggedPrepartition.iUnion π₁ ∧
(l.bDistortion = true → Prepartition.distortion π ≤ c₁) ∧ (l.bDistortion = true → Prepartition.distortion π ≤ c₂)
[PROOFSTEP]
by_cases hD : (l.bDistortion : Prop)
[GOAL]
case pos
ι✝ : Type u_1
inst✝¹ : Fintype ι✝
I✝ : Box ι✝
c₁✝ c₂✝ : ℝ≥0
r₁✝ r₂✝ : (ι✝ → ℝ) → ↑(Set.Ioi 0)
π₁✝ π₂✝ : TaggedPrepartition I✝
l✝ : IntegrationParams
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁ π₂ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
h₁ : MemBaseSet l I c₁ r₁ π₁
h₂ : MemBaseSet l I c₂ r₂ π₂
hU : TaggedPrepartition.iUnion π₁ = TaggedPrepartition.iUnion π₂
hc : c₁ ≤ c₂
hD : l.bDistortion = true
⊢ ∃ π,
Prepartition.iUnion π = ↑I \ TaggedPrepartition.iUnion π₁ ∧
(l.bDistortion = true → Prepartition.distortion π ≤ c₁) ∧ (l.bDistortion = true → Prepartition.distortion π ≤ c₂)
[PROOFSTEP]
rcases h₁.4 hD with ⟨π, hπU, hπc⟩
[GOAL]
case pos.intro.intro
ι✝ : Type u_1
inst✝¹ : Fintype ι✝
I✝ : Box ι✝
c₁✝ c₂✝ : ℝ≥0
r₁✝ r₂✝ : (ι✝ → ℝ) → ↑(Set.Ioi 0)
π₁✝ π₂✝ : TaggedPrepartition I✝
l✝ : IntegrationParams
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π✝ π₁ π₂ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
h₁ : MemBaseSet l I c₁ r₁ π₁
h₂ : MemBaseSet l I c₂ r₂ π₂
hU : TaggedPrepartition.iUnion π₁ = TaggedPrepartition.iUnion π₂
hc : c₁ ≤ c₂
hD : l.bDistortion = true
π : Prepartition I
hπU : Prepartition.iUnion π = ↑I \ TaggedPrepartition.iUnion π₁
hπc : Prepartition.distortion π ≤ c₁
⊢ ∃ π,
Prepartition.iUnion π = ↑I \ TaggedPrepartition.iUnion π₁ ∧
(l.bDistortion = true → Prepartition.distortion π ≤ c₁) ∧ (l.bDistortion = true → Prepartition.distortion π ≤ c₂)
[PROOFSTEP]
exact ⟨π, hπU, fun _ => hπc, fun _ => hπc.trans hc⟩
[GOAL]
case neg
ι✝ : Type u_1
inst✝¹ : Fintype ι✝
I✝ : Box ι✝
c₁✝ c₂✝ : ℝ≥0
r₁✝ r₂✝ : (ι✝ → ℝ) → ↑(Set.Ioi 0)
π₁✝ π₂✝ : TaggedPrepartition I✝
l✝ : IntegrationParams
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁ π₂ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
h₁ : MemBaseSet l I c₁ r₁ π₁
h₂ : MemBaseSet l I c₂ r₂ π₂
hU : TaggedPrepartition.iUnion π₁ = TaggedPrepartition.iUnion π₂
hc : c₁ ≤ c₂
hD : ¬l.bDistortion = true
⊢ ∃ π,
Prepartition.iUnion π = ↑I \ TaggedPrepartition.iUnion π₁ ∧
(l.bDistortion = true → Prepartition.distortion π ≤ c₁) ∧ (l.bDistortion = true → Prepartition.distortion π ≤ c₂)
[PROOFSTEP]
exact ⟨π₁.toPrepartition.compl, π₁.toPrepartition.iUnion_compl, fun h => (hD h).elim, fun h => (hD h).elim⟩
[GOAL]
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁ π₂✝ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
hπ₁ : MemBaseSet l I c r₁ π₁
hle : ∀ (x : ι → ℝ), x ∈ ↑Box.Icc I → r₂ x ≤ r₁ x
π₂ : Prepartition I
hU : Prepartition.iUnion π₂ = ↑I \ TaggedPrepartition.iUnion π₁
hc : l.bDistortion = true → Prepartition.distortion π₂ ≤ c
x✝ : l.bDistortion = true
⊢ Prepartition.iUnion ⊥ = ↑I \ TaggedPrepartition.iUnion (unionComplToSubordinate π₁ π₂ hU r₂) ∧
Prepartition.distortion ⊥ ≤ c
[PROOFSTEP]
simp
[GOAL]
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁ π₂ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
hπ : MemBaseSet l I c r π
p : Box ι → Prop
⊢ MemBaseSet l I c r (TaggedPrepartition.filter π p)
[PROOFSTEP]
refine'
⟨fun J hJ => hπ.1 J (π.mem_filter.1 hJ).1, fun hH J hJ => hπ.2 hH J (π.mem_filter.1 hJ).1, fun hD =>
(distortion_filter_le _ _).trans (hπ.3 hD), fun hD => _⟩
[GOAL]
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁ π₂ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
hπ : MemBaseSet l I c r π
p : Box ι → Prop
hD : l.bDistortion = true
⊢ ∃ π',
Prepartition.iUnion π' = ↑I \ TaggedPrepartition.iUnion (TaggedPrepartition.filter π p) ∧
Prepartition.distortion π' ≤ c
[PROOFSTEP]
rcases hπ.4 hD with ⟨π₁, hπ₁U, hc⟩
[GOAL]
case intro.intro
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁✝ π₂ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
hπ : MemBaseSet l I c r π
p : Box ι → Prop
hD : l.bDistortion = true
π₁ : Prepartition I
hπ₁U : Prepartition.iUnion π₁ = ↑I \ TaggedPrepartition.iUnion π
hc : Prepartition.distortion π₁ ≤ c
⊢ ∃ π',
Prepartition.iUnion π' = ↑I \ TaggedPrepartition.iUnion (TaggedPrepartition.filter π p) ∧
Prepartition.distortion π' ≤ c
[PROOFSTEP]
set π₂ := π.filter fun J => ¬p J
[GOAL]
case intro.intro
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁✝ π₂✝ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
hπ : MemBaseSet l I c r π
p : Box ι → Prop
hD : l.bDistortion = true
π₁ : Prepartition I
hπ₁U : Prepartition.iUnion π₁ = ↑I \ TaggedPrepartition.iUnion π
hc : Prepartition.distortion π₁ ≤ c
π₂ : TaggedPrepartition I := TaggedPrepartition.filter π fun J => ¬p J
⊢ ∃ π',
Prepartition.iUnion π' = ↑I \ TaggedPrepartition.iUnion (TaggedPrepartition.filter π p) ∧
Prepartition.distortion π' ≤ c
[PROOFSTEP]
have : Disjoint π₁.iUnion π₂.iUnion := by simpa [hπ₁U] using disjoint_sdiff_self_left.mono_right sdiff_le
[GOAL]
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁✝ π₂✝ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
hπ : MemBaseSet l I c r π
p : Box ι → Prop
hD : l.bDistortion = true
π₁ : Prepartition I
hπ₁U : Prepartition.iUnion π₁ = ↑I \ TaggedPrepartition.iUnion π
hc : Prepartition.distortion π₁ ≤ c
π₂ : TaggedPrepartition I := TaggedPrepartition.filter π fun J => ¬p J
⊢ Disjoint (Prepartition.iUnion π₁) (TaggedPrepartition.iUnion π₂)
[PROOFSTEP]
simpa [hπ₁U] using disjoint_sdiff_self_left.mono_right sdiff_le
[GOAL]
case intro.intro
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁✝ π₂✝ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
hπ : MemBaseSet l I c r π
p : Box ι → Prop
hD : l.bDistortion = true
π₁ : Prepartition I
hπ₁U : Prepartition.iUnion π₁ = ↑I \ TaggedPrepartition.iUnion π
hc : Prepartition.distortion π₁ ≤ c
π₂ : TaggedPrepartition I := TaggedPrepartition.filter π fun J => ¬p J
this : Disjoint (Prepartition.iUnion π₁) (TaggedPrepartition.iUnion π₂)
⊢ ∃ π',
Prepartition.iUnion π' = ↑I \ TaggedPrepartition.iUnion (TaggedPrepartition.filter π p) ∧
Prepartition.distortion π' ≤ c
[PROOFSTEP]
refine' ⟨π₁.disjUnion π₂.toPrepartition this, _, _⟩
[GOAL]
case intro.intro.refine'_1
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁✝ π₂✝ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
hπ : MemBaseSet l I c r π
p : Box ι → Prop
hD : l.bDistortion = true
π₁ : Prepartition I
hπ₁U : Prepartition.iUnion π₁ = ↑I \ TaggedPrepartition.iUnion π
hc : Prepartition.distortion π₁ ≤ c
π₂ : TaggedPrepartition I := TaggedPrepartition.filter π fun J => ¬p J
this : Disjoint (Prepartition.iUnion π₁) (TaggedPrepartition.iUnion π₂)
⊢ Prepartition.iUnion (Prepartition.disjUnion π₁ π₂.toPrepartition this) =
↑I \ TaggedPrepartition.iUnion (TaggedPrepartition.filter π p)
[PROOFSTEP]
suffices ↑I \ π.iUnion ∪ π.iUnion \ (π.filter p).iUnion = ↑I \ (π.filter p).iUnion by simp [*]
[GOAL]
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁✝ π₂✝ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
hπ : MemBaseSet l I c r π
p : Box ι → Prop
hD : l.bDistortion = true
π₁ : Prepartition I
hπ₁U : Prepartition.iUnion π₁ = ↑I \ TaggedPrepartition.iUnion π
hc : Prepartition.distortion π₁ ≤ c
π₂ : TaggedPrepartition I := TaggedPrepartition.filter π fun J => ¬p J
this✝ : Disjoint (Prepartition.iUnion π₁) (TaggedPrepartition.iUnion π₂)
this :
↑I \ TaggedPrepartition.iUnion π ∪
TaggedPrepartition.iUnion π \ TaggedPrepartition.iUnion (TaggedPrepartition.filter π p) =
↑I \ TaggedPrepartition.iUnion (TaggedPrepartition.filter π p)
⊢ Prepartition.iUnion (Prepartition.disjUnion π₁ π₂.toPrepartition this✝) =
↑I \ TaggedPrepartition.iUnion (TaggedPrepartition.filter π p)
[PROOFSTEP]
simp [*]
[GOAL]
case intro.intro.refine'_1
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁✝ π₂✝ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
hπ : MemBaseSet l I c r π
p : Box ι → Prop
hD : l.bDistortion = true
π₁ : Prepartition I
hπ₁U : Prepartition.iUnion π₁ = ↑I \ TaggedPrepartition.iUnion π
hc : Prepartition.distortion π₁ ≤ c
π₂ : TaggedPrepartition I := TaggedPrepartition.filter π fun J => ¬p J
this : Disjoint (Prepartition.iUnion π₁) (TaggedPrepartition.iUnion π₂)
⊢ ↑I \ TaggedPrepartition.iUnion π ∪
TaggedPrepartition.iUnion π \ TaggedPrepartition.iUnion (TaggedPrepartition.filter π p) =
↑I \ TaggedPrepartition.iUnion (TaggedPrepartition.filter π p)
[PROOFSTEP]
have h : (π.filter p).iUnion ⊆ π.iUnion := biUnion_subset_biUnion_left (Finset.filter_subset _ _)
[GOAL]
case intro.intro.refine'_1
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁✝ π₂✝ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
hπ : MemBaseSet l I c r π
p : Box ι → Prop
hD : l.bDistortion = true
π₁ : Prepartition I
hπ₁U : Prepartition.iUnion π₁ = ↑I \ TaggedPrepartition.iUnion π
hc : Prepartition.distortion π₁ ≤ c
π₂ : TaggedPrepartition I := TaggedPrepartition.filter π fun J => ¬p J
this : Disjoint (Prepartition.iUnion π₁) (TaggedPrepartition.iUnion π₂)
h : TaggedPrepartition.iUnion (TaggedPrepartition.filter π p) ⊆ TaggedPrepartition.iUnion π
⊢ ↑I \ TaggedPrepartition.iUnion π ∪
TaggedPrepartition.iUnion π \ TaggedPrepartition.iUnion (TaggedPrepartition.filter π p) =
↑I \ TaggedPrepartition.iUnion (TaggedPrepartition.filter π p)
[PROOFSTEP]
ext x
[GOAL]
case intro.intro.refine'_1.h
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁✝ π₂✝ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
hπ : MemBaseSet l I c r π
p : Box ι → Prop
hD : l.bDistortion = true
π₁ : Prepartition I
hπ₁U : Prepartition.iUnion π₁ = ↑I \ TaggedPrepartition.iUnion π
hc : Prepartition.distortion π₁ ≤ c
π₂ : TaggedPrepartition I := TaggedPrepartition.filter π fun J => ¬p J
this : Disjoint (Prepartition.iUnion π₁) (TaggedPrepartition.iUnion π₂)
h : TaggedPrepartition.iUnion (TaggedPrepartition.filter π p) ⊆ TaggedPrepartition.iUnion π
x : ι → ℝ
⊢ x ∈
↑I \ TaggedPrepartition.iUnion π ∪
TaggedPrepartition.iUnion π \ TaggedPrepartition.iUnion (TaggedPrepartition.filter π p) ↔
x ∈ ↑I \ TaggedPrepartition.iUnion (TaggedPrepartition.filter π p)
[PROOFSTEP]
fconstructor
[GOAL]
case intro.intro.refine'_1.h.mp
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁✝ π₂✝ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
hπ : MemBaseSet l I c r π
p : Box ι → Prop
hD : l.bDistortion = true
π₁ : Prepartition I
hπ₁U : Prepartition.iUnion π₁ = ↑I \ TaggedPrepartition.iUnion π
hc : Prepartition.distortion π₁ ≤ c
π₂ : TaggedPrepartition I := TaggedPrepartition.filter π fun J => ¬p J
this : Disjoint (Prepartition.iUnion π₁) (TaggedPrepartition.iUnion π₂)
h : TaggedPrepartition.iUnion (TaggedPrepartition.filter π p) ⊆ TaggedPrepartition.iUnion π
x : ι → ℝ
⊢ x ∈
↑I \ TaggedPrepartition.iUnion π ∪
TaggedPrepartition.iUnion π \ TaggedPrepartition.iUnion (TaggedPrepartition.filter π p) →
x ∈ ↑I \ TaggedPrepartition.iUnion (TaggedPrepartition.filter π p)
[PROOFSTEP]
rintro (⟨hxI, hxπ⟩ | ⟨hxπ, hxp⟩)
[GOAL]
case intro.intro.refine'_1.h.mp.inl.intro
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁✝ π₂✝ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
hπ : MemBaseSet l I c r π
p : Box ι → Prop
hD : l.bDistortion = true
π₁ : Prepartition I
hπ₁U : Prepartition.iUnion π₁ = ↑I \ TaggedPrepartition.iUnion π
hc : Prepartition.distortion π₁ ≤ c
π₂ : TaggedPrepartition I := TaggedPrepartition.filter π fun J => ¬p J
this : Disjoint (Prepartition.iUnion π₁) (TaggedPrepartition.iUnion π₂)
h : TaggedPrepartition.iUnion (TaggedPrepartition.filter π p) ⊆ TaggedPrepartition.iUnion π
x : ι → ℝ
hxI : x ∈ ↑I
hxπ : ¬x ∈ TaggedPrepartition.iUnion π
⊢ x ∈ ↑I \ TaggedPrepartition.iUnion (TaggedPrepartition.filter π p)
case intro.intro.refine'_1.h.mp.inr.intro
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁✝ π₂✝ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
hπ : MemBaseSet l I c r π
p : Box ι → Prop
hD : l.bDistortion = true
π₁ : Prepartition I
hπ₁U : Prepartition.iUnion π₁ = ↑I \ TaggedPrepartition.iUnion π
hc : Prepartition.distortion π₁ ≤ c
π₂ : TaggedPrepartition I := TaggedPrepartition.filter π fun J => ¬p J
this : Disjoint (Prepartition.iUnion π₁) (TaggedPrepartition.iUnion π₂)
h : TaggedPrepartition.iUnion (TaggedPrepartition.filter π p) ⊆ TaggedPrepartition.iUnion π
x : ι → ℝ
hxπ : x ∈ TaggedPrepartition.iUnion π
hxp : ¬x ∈ TaggedPrepartition.iUnion (TaggedPrepartition.filter π p)
⊢ x ∈ ↑I \ TaggedPrepartition.iUnion (TaggedPrepartition.filter π p)
[PROOFSTEP]
exacts [⟨hxI, mt (@h x) hxπ⟩, ⟨π.iUnion_subset hxπ, hxp⟩]
[GOAL]
case intro.intro.refine'_1.h.mpr
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁✝ π₂✝ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
hπ : MemBaseSet l I c r π
p : Box ι → Prop
hD : l.bDistortion = true
π₁ : Prepartition I
hπ₁U : Prepartition.iUnion π₁ = ↑I \ TaggedPrepartition.iUnion π
hc : Prepartition.distortion π₁ ≤ c
π₂ : TaggedPrepartition I := TaggedPrepartition.filter π fun J => ¬p J
this : Disjoint (Prepartition.iUnion π₁) (TaggedPrepartition.iUnion π₂)
h : TaggedPrepartition.iUnion (TaggedPrepartition.filter π p) ⊆ TaggedPrepartition.iUnion π
x : ι → ℝ
⊢ x ∈ ↑I \ TaggedPrepartition.iUnion (TaggedPrepartition.filter π p) →
x ∈
↑I \ TaggedPrepartition.iUnion π ∪
TaggedPrepartition.iUnion π \ TaggedPrepartition.iUnion (TaggedPrepartition.filter π p)
[PROOFSTEP]
rintro ⟨hxI, hxp⟩
[GOAL]
case intro.intro.refine'_1.h.mpr.intro
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁✝ π₂✝ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
hπ : MemBaseSet l I c r π
p : Box ι → Prop
hD : l.bDistortion = true
π₁ : Prepartition I
hπ₁U : Prepartition.iUnion π₁ = ↑I \ TaggedPrepartition.iUnion π
hc : Prepartition.distortion π₁ ≤ c
π₂ : TaggedPrepartition I := TaggedPrepartition.filter π fun J => ¬p J
this : Disjoint (Prepartition.iUnion π₁) (TaggedPrepartition.iUnion π₂)
h : TaggedPrepartition.iUnion (TaggedPrepartition.filter π p) ⊆ TaggedPrepartition.iUnion π
x : ι → ℝ
hxI : x ∈ ↑I
hxp : ¬x ∈ TaggedPrepartition.iUnion (TaggedPrepartition.filter π p)
⊢ x ∈
↑I \ TaggedPrepartition.iUnion π ∪
TaggedPrepartition.iUnion π \ TaggedPrepartition.iUnion (TaggedPrepartition.filter π p)
[PROOFSTEP]
by_cases hxπ : x ∈ π.iUnion
[GOAL]
case pos
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁✝ π₂✝ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
hπ : MemBaseSet l I c r π
p : Box ι → Prop
hD : l.bDistortion = true
π₁ : Prepartition I
hπ₁U : Prepartition.iUnion π₁ = ↑I \ TaggedPrepartition.iUnion π
hc : Prepartition.distortion π₁ ≤ c
π₂ : TaggedPrepartition I := TaggedPrepartition.filter π fun J => ¬p J
this : Disjoint (Prepartition.iUnion π₁) (TaggedPrepartition.iUnion π₂)
h : TaggedPrepartition.iUnion (TaggedPrepartition.filter π p) ⊆ TaggedPrepartition.iUnion π
x : ι → ℝ
hxI : x ∈ ↑I
hxp : ¬x ∈ TaggedPrepartition.iUnion (TaggedPrepartition.filter π p)
hxπ : x ∈ TaggedPrepartition.iUnion π
⊢ x ∈
↑I \ TaggedPrepartition.iUnion π ∪
TaggedPrepartition.iUnion π \ TaggedPrepartition.iUnion (TaggedPrepartition.filter π p)
case neg
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁✝ π₂✝ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
hπ : MemBaseSet l I c r π
p : Box ι → Prop
hD : l.bDistortion = true
π₁ : Prepartition I
hπ₁U : Prepartition.iUnion π₁ = ↑I \ TaggedPrepartition.iUnion π
hc : Prepartition.distortion π₁ ≤ c
π₂ : TaggedPrepartition I := TaggedPrepartition.filter π fun J => ¬p J
this : Disjoint (Prepartition.iUnion π₁) (TaggedPrepartition.iUnion π₂)
h : TaggedPrepartition.iUnion (TaggedPrepartition.filter π p) ⊆ TaggedPrepartition.iUnion π
x : ι → ℝ
hxI : x ∈ ↑I
hxp : ¬x ∈ TaggedPrepartition.iUnion (TaggedPrepartition.filter π p)
hxπ : ¬x ∈ TaggedPrepartition.iUnion π
⊢ x ∈
↑I \ TaggedPrepartition.iUnion π ∪
TaggedPrepartition.iUnion π \ TaggedPrepartition.iUnion (TaggedPrepartition.filter π p)
[PROOFSTEP]
exacts [Or.inr ⟨hxπ, hxp⟩, Or.inl ⟨hxI, hxπ⟩]
[GOAL]
case intro.intro.refine'_2
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁✝ π₂✝ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
hπ : MemBaseSet l I c r π
p : Box ι → Prop
hD : l.bDistortion = true
π₁ : Prepartition I
hπ₁U : Prepartition.iUnion π₁ = ↑I \ TaggedPrepartition.iUnion π
hc : Prepartition.distortion π₁ ≤ c
π₂ : TaggedPrepartition I := TaggedPrepartition.filter π fun J => ¬p J
this : Disjoint (Prepartition.iUnion π₁) (TaggedPrepartition.iUnion π₂)
⊢ Prepartition.distortion (Prepartition.disjUnion π₁ π₂.toPrepartition this) ≤ c
[PROOFSTEP]
have : (π.filter fun J => ¬p J).distortion ≤ c := (distortion_filter_le _ _).trans (hπ.3 hD)
[GOAL]
case intro.intro.refine'_2
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁✝ π₂✝ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
hπ : MemBaseSet l I c r π
p : Box ι → Prop
hD : l.bDistortion = true
π₁ : Prepartition I
hπ₁U : Prepartition.iUnion π₁ = ↑I \ TaggedPrepartition.iUnion π
hc : Prepartition.distortion π₁ ≤ c
π₂ : TaggedPrepartition I := TaggedPrepartition.filter π fun J => ¬p J
this✝ : Disjoint (Prepartition.iUnion π₁) (TaggedPrepartition.iUnion π₂)
this : distortion (TaggedPrepartition.filter π fun J => ¬p J) ≤ c
⊢ Prepartition.distortion (Prepartition.disjUnion π₁ π₂.toPrepartition this✝) ≤ c
[PROOFSTEP]
simpa [hc]
[GOAL]
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π✝ π₁ π₂ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
π : Prepartition I
πi : (J : Box ι) → TaggedPrepartition J
h : ∀ (J : Box ι), J ∈ π → MemBaseSet l J c r (πi J)
hp : ∀ (J : Box ι), J ∈ π → IsPartition (πi J)
hc : l.bDistortion = true → Prepartition.distortion (Prepartition.compl π) ≤ c
⊢ MemBaseSet l I c r (Prepartition.biUnionTagged π πi)
[PROOFSTEP]
refine'
⟨TaggedPrepartition.isSubordinate_biUnionTagged.2 fun J hJ => (h J hJ).1, fun hH =>
TaggedPrepartition.isHenstock_biUnionTagged.2 fun J hJ => (h J hJ).2 hH, fun hD => _, fun hD => _⟩
[GOAL]
case refine'_1
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π✝ π₁ π₂ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
π : Prepartition I
πi : (J : Box ι) → TaggedPrepartition J
h : ∀ (J : Box ι), J ∈ π → MemBaseSet l J c r (πi J)
hp : ∀ (J : Box ι), J ∈ π → IsPartition (πi J)
hc : l.bDistortion = true → Prepartition.distortion (Prepartition.compl π) ≤ c
hD : l.bDistortion = true
⊢ distortion (Prepartition.biUnionTagged π πi) ≤ c
[PROOFSTEP]
rw [Prepartition.distortion_biUnionTagged, Finset.sup_le_iff]
[GOAL]
case refine'_1
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π✝ π₁ π₂ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
π : Prepartition I
πi : (J : Box ι) → TaggedPrepartition J
h : ∀ (J : Box ι), J ∈ π → MemBaseSet l J c r (πi J)
hp : ∀ (J : Box ι), J ∈ π → IsPartition (πi J)
hc : l.bDistortion = true → Prepartition.distortion (Prepartition.compl π) ≤ c
hD : l.bDistortion = true
⊢ ∀ (b : Box ι), b ∈ π.boxes → distortion (πi b) ≤ c
[PROOFSTEP]
exact fun J hJ => (h J hJ).3 hD
[GOAL]
case refine'_2
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π✝ π₁ π₂ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
π : Prepartition I
πi : (J : Box ι) → TaggedPrepartition J
h : ∀ (J : Box ι), J ∈ π → MemBaseSet l J c r (πi J)
hp : ∀ (J : Box ι), J ∈ π → IsPartition (πi J)
hc : l.bDistortion = true → Prepartition.distortion (Prepartition.compl π) ≤ c
hD : l.bDistortion = true
⊢ ∃ π',
Prepartition.iUnion π' = ↑I \ TaggedPrepartition.iUnion (Prepartition.biUnionTagged π πi) ∧
Prepartition.distortion π' ≤ c
[PROOFSTEP]
refine' ⟨_, _, hc hD⟩
[GOAL]
case refine'_2
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π✝ π₁ π₂ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
π : Prepartition I
πi : (J : Box ι) → TaggedPrepartition J
h : ∀ (J : Box ι), J ∈ π → MemBaseSet l J c r (πi J)
hp : ∀ (J : Box ι), J ∈ π → IsPartition (πi J)
hc : l.bDistortion = true → Prepartition.distortion (Prepartition.compl π) ≤ c
hD : l.bDistortion = true
⊢ Prepartition.iUnion (Prepartition.compl π) = ↑I \ TaggedPrepartition.iUnion (Prepartition.biUnionTagged π πi)
[PROOFSTEP]
rw [π.iUnion_compl, ← π.iUnion_biUnion_partition hp]
[GOAL]
case refine'_2
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π✝ π₁ π₂ : TaggedPrepartition I
l l₁ l₂ : IntegrationParams
π : Prepartition I
πi : (J : Box ι) → TaggedPrepartition J
h : ∀ (J : Box ι), J ∈ π → MemBaseSet l J c r (πi J)
hp : ∀ (J : Box ι), J ∈ π → IsPartition (πi J)
hc : l.bDistortion = true → Prepartition.distortion (Prepartition.compl π) ≤ c
hD : l.bDistortion = true
⊢ ↑I \ Prepartition.iUnion (Prepartition.biUnion π fun J => (πi J).toPrepartition) =
↑I \ TaggedPrepartition.iUnion (Prepartition.biUnionTagged π πi)
[PROOFSTEP]
rfl
[GOAL]
ι : Type u_1
inst✝ : Fintype ι
I✝ J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁✝ π₂✝ : TaggedPrepartition I✝
l✝ l₁ l₂ : IntegrationParams
I : Box ι
l : IntegrationParams
π₁ π₂ : Prepartition I
h : Prepartition.iUnion π₁ = Prepartition.iUnion π₂
⊢ toFilteriUnion l I π₁ = toFilteriUnion l I π₂
[PROOFSTEP]
simp only [toFilteriUnion, toFilterDistortioniUnion, h]
[GOAL]
ι : Type u_1
inst✝ : Fintype ι
I✝ J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁ π₂ : TaggedPrepartition I✝
l✝ l₁ l₂ l : IntegrationParams
I : Box ι
π₀ : Prepartition I
⊢ HasBasis (toFilteriUnion l I π₀) (fun r => ∀ (c : ℝ≥0), RCond l (r c)) fun r =>
{π | ∃ c, MemBaseSet l I c (r c) π ∧ TaggedPrepartition.iUnion π = Prepartition.iUnion π₀}
[PROOFSTEP]
have := fun c => l.hasBasis_toFilterDistortioniUnion I c π₀
[GOAL]
ι : Type u_1
inst✝ : Fintype ι
I✝ J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁ π₂ : TaggedPrepartition I✝
l✝ l₁ l₂ l : IntegrationParams
I : Box ι
π₀ : Prepartition I
this :
∀ (c : ℝ≥0),
HasBasis (toFilterDistortioniUnion l I c π₀) (RCond l) fun r =>
{π | MemBaseSet l I c r π ∧ TaggedPrepartition.iUnion π = Prepartition.iUnion π₀}
⊢ HasBasis (toFilteriUnion l I π₀) (fun r => ∀ (c : ℝ≥0), RCond l (r c)) fun r =>
{π | ∃ c, MemBaseSet l I c (r c) π ∧ TaggedPrepartition.iUnion π = Prepartition.iUnion π₀}
[PROOFSTEP]
simpa only [setOf_and, setOf_exists] using hasBasis_iSup this
[GOAL]
ι : Type u_1
inst✝ : Fintype ι
I✝ J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁ π₂ : TaggedPrepartition I✝
l✝ l₁ l₂ l : IntegrationParams
I : Box ι
⊢ HasBasis (toFilteriUnion l I ⊤) (fun r => ∀ (c : ℝ≥0), RCond l (r c)) fun r =>
{π | ∃ c, MemBaseSet l I c (r c) π ∧ IsPartition π}
[PROOFSTEP]
simpa only [TaggedPrepartition.isPartition_iff_iUnion_eq, Prepartition.iUnion_top] using l.hasBasis_toFilteriUnion I ⊤
[GOAL]
ι : Type u_1
inst✝ : Fintype ι
I✝ J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁ π₂ : TaggedPrepartition I✝
l✝ l₁ l₂ l : IntegrationParams
I : Box ι
⊢ HasBasis (toFilter l I) (fun r => ∀ (c : ℝ≥0), RCond l (r c)) fun r => {π | ∃ c, MemBaseSet l I c (r c) π}
[PROOFSTEP]
simpa only [setOf_exists] using hasBasis_iSup (l.hasBasis_toFilterDistortion I)
[GOAL]
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁ π₂ : TaggedPrepartition I
l✝ l₁ l₂ l : IntegrationParams
h : I ≤ J
⊢ Tendsto (↑(embedBox I J h)) (toFilteriUnion l I ⊤) (toFilteriUnion l J (Prepartition.single J I h))
[PROOFSTEP]
simp only [toFilteriUnion, tendsto_iSup]
[GOAL]
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁ π₂ : TaggedPrepartition I
l✝ l₁ l₂ l : IntegrationParams
h : I ≤ J
⊢ ∀ (i : ℝ≥0),
Tendsto (↑(embedBox I J h)) (toFilterDistortioniUnion l I i ⊤)
(⨆ (c : ℝ≥0), toFilterDistortioniUnion l J c (Prepartition.single J I h))
[PROOFSTEP]
intro c
[GOAL]
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c✝ c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁ π₂ : TaggedPrepartition I
l✝ l₁ l₂ l : IntegrationParams
h : I ≤ J
c : ℝ≥0
⊢ Tendsto (↑(embedBox I J h)) (toFilterDistortioniUnion l I c ⊤)
(⨆ (c : ℝ≥0), toFilterDistortioniUnion l J c (Prepartition.single J I h))
[PROOFSTEP]
set π₀ := Prepartition.single J I h
[GOAL]
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c✝ c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁ π₂ : TaggedPrepartition I
l✝ l₁ l₂ l : IntegrationParams
h : I ≤ J
c : ℝ≥0
π₀ : Prepartition J := Prepartition.single J I h
⊢ Tendsto (↑(embedBox I J h)) (toFilterDistortioniUnion l I c ⊤) (⨆ (c : ℝ≥0), toFilterDistortioniUnion l J c π₀)
[PROOFSTEP]
refine' le_iSup_of_le (max c π₀.compl.distortion) _
[GOAL]
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c✝ c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁ π₂ : TaggedPrepartition I
l✝ l₁ l₂ l : IntegrationParams
h : I ≤ J
c : ℝ≥0
π₀ : Prepartition J := Prepartition.single J I h
⊢ Filter.map (↑(embedBox I J h)) (toFilterDistortioniUnion l I c ⊤) ≤
toFilterDistortioniUnion l J (max c (Prepartition.distortion (Prepartition.compl π₀))) π₀
[PROOFSTEP]
refine'
((l.hasBasis_toFilterDistortioniUnion I c ⊤).tendsto_iff (l.hasBasis_toFilterDistortioniUnion J _ _)).2 fun r hr => _
[GOAL]
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c✝ c₁ c₂ : ℝ≥0
r✝ r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁ π₂ : TaggedPrepartition I
l✝ l₁ l₂ l : IntegrationParams
h : I ≤ J
c : ℝ≥0
π₀ : Prepartition J := Prepartition.single J I h
r : (ι → ℝ) → ↑(Set.Ioi 0)
hr : RCond l r
⊢ ∃ ia,
RCond l ia ∧
∀ (x : TaggedPrepartition I),
x ∈ {π | MemBaseSet l I c ia π ∧ TaggedPrepartition.iUnion π = Prepartition.iUnion ⊤} →
↑(embedBox I J h) x ∈
{π |
MemBaseSet l J (max c (Prepartition.distortion (Prepartition.compl π₀))) r π ∧
TaggedPrepartition.iUnion π = Prepartition.iUnion π₀}
[PROOFSTEP]
refine' ⟨r, hr, fun π hπ => _⟩
[GOAL]
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c✝ c₁ c₂ : ℝ≥0
r✝ r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π✝ π₁ π₂ : TaggedPrepartition I
l✝ l₁ l₂ l : IntegrationParams
h : I ≤ J
c : ℝ≥0
π₀ : Prepartition J := Prepartition.single J I h
r : (ι → ℝ) → ↑(Set.Ioi 0)
hr : RCond l r
π : TaggedPrepartition I
hπ : π ∈ {π | MemBaseSet l I c r π ∧ TaggedPrepartition.iUnion π = Prepartition.iUnion ⊤}
⊢ ↑(embedBox I J h) π ∈
{π |
MemBaseSet l J (max c (Prepartition.distortion (Prepartition.compl π₀))) r π ∧
TaggedPrepartition.iUnion π = Prepartition.iUnion π₀}
[PROOFSTEP]
rw [mem_setOf_eq, Prepartition.iUnion_top] at hπ
[GOAL]
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c✝ c₁ c₂ : ℝ≥0
r✝ r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π✝ π₁ π₂ : TaggedPrepartition I
l✝ l₁ l₂ l : IntegrationParams
h : I ≤ J
c : ℝ≥0
π₀ : Prepartition J := Prepartition.single J I h
r : (ι → ℝ) → ↑(Set.Ioi 0)
hr : RCond l r
π : TaggedPrepartition I
hπ : MemBaseSet l I c r π ∧ TaggedPrepartition.iUnion π = ↑I
⊢ ↑(embedBox I J h) π ∈
{π |
MemBaseSet l J (max c (Prepartition.distortion (Prepartition.compl π₀))) r π ∧
TaggedPrepartition.iUnion π = Prepartition.iUnion π₀}
[PROOFSTEP]
refine' ⟨⟨hπ.1.1, hπ.1.2, fun hD => le_trans (hπ.1.3 hD) (le_max_left _ _), fun _ => _⟩, _⟩
[GOAL]
case refine'_1
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c✝ c₁ c₂ : ℝ≥0
r✝ r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π✝ π₁ π₂ : TaggedPrepartition I
l✝ l₁ l₂ l : IntegrationParams
h : I ≤ J
c : ℝ≥0
π₀ : Prepartition J := Prepartition.single J I h
r : (ι → ℝ) → ↑(Set.Ioi 0)
hr : RCond l r
π : TaggedPrepartition I
hπ : MemBaseSet l I c r π ∧ TaggedPrepartition.iUnion π = ↑I
x✝ : l.bDistortion = true
⊢ ∃ π',
Prepartition.iUnion π' = ↑J \ TaggedPrepartition.iUnion (↑(embedBox I J h) π) ∧
Prepartition.distortion π' ≤ max c (Prepartition.distortion (Prepartition.compl π₀))
[PROOFSTEP]
refine' ⟨_, π₀.iUnion_compl.trans _, le_max_right _ _⟩
[GOAL]
case refine'_1
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c✝ c₁ c₂ : ℝ≥0
r✝ r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π✝ π₁ π₂ : TaggedPrepartition I
l✝ l₁ l₂ l : IntegrationParams
h : I ≤ J
c : ℝ≥0
π₀ : Prepartition J := Prepartition.single J I h
r : (ι → ℝ) → ↑(Set.Ioi 0)
hr : RCond l r
π : TaggedPrepartition I
hπ : MemBaseSet l I c r π ∧ TaggedPrepartition.iUnion π = ↑I
x✝ : l.bDistortion = true
⊢ ↑J \ Prepartition.iUnion π₀ = ↑J \ TaggedPrepartition.iUnion (↑(embedBox I J h) π)
[PROOFSTEP]
congr 1
[GOAL]
case refine'_1.e_a
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c✝ c₁ c₂ : ℝ≥0
r✝ r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π✝ π₁ π₂ : TaggedPrepartition I
l✝ l₁ l₂ l : IntegrationParams
h : I ≤ J
c : ℝ≥0
π₀ : Prepartition J := Prepartition.single J I h
r : (ι → ℝ) → ↑(Set.Ioi 0)
hr : RCond l r
π : TaggedPrepartition I
hπ : MemBaseSet l I c r π ∧ TaggedPrepartition.iUnion π = ↑I
x✝ : l.bDistortion = true
⊢ Prepartition.iUnion π₀ = TaggedPrepartition.iUnion (↑(embedBox I J h) π)
[PROOFSTEP]
exact (Prepartition.iUnion_single h).trans hπ.2.symm
[GOAL]
case refine'_2
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c✝ c₁ c₂ : ℝ≥0
r✝ r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π✝ π₁ π₂ : TaggedPrepartition I
l✝ l₁ l₂ l : IntegrationParams
h : I ≤ J
c : ℝ≥0
π₀ : Prepartition J := Prepartition.single J I h
r : (ι → ℝ) → ↑(Set.Ioi 0)
hr : RCond l r
π : TaggedPrepartition I
hπ : MemBaseSet l I c r π ∧ TaggedPrepartition.iUnion π = ↑I
⊢ TaggedPrepartition.iUnion (↑(embedBox I J h) π) = Prepartition.iUnion π₀
[PROOFSTEP]
exact hπ.2.trans (Prepartition.iUnion_single _).symm
[GOAL]
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r✝ r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁ π₂ : TaggedPrepartition I
l✝ l₁ l₂ l : IntegrationParams
π₀ : Prepartition I
hc₁ : Prepartition.distortion π₀ ≤ c
hc₂ : Prepartition.distortion (Prepartition.compl π₀) ≤ c
r : (ι → ℝ) → ↑(Set.Ioi 0)
⊢ ∃ π, MemBaseSet l I c r π ∧ π.toPrepartition ≤ π₀ ∧ TaggedPrepartition.iUnion π = Prepartition.iUnion π₀
[PROOFSTEP]
rcases π₀.exists_tagged_le_isHenstock_isSubordinate_iUnion_eq r with ⟨π, hle, hH, hr, hd, hU⟩
[GOAL]
case intro.intro.intro.intro.intro
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r✝ r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π✝ π₁ π₂ : TaggedPrepartition I
l✝ l₁ l₂ l : IntegrationParams
π₀ : Prepartition I
hc₁ : Prepartition.distortion π₀ ≤ c
hc₂ : Prepartition.distortion (Prepartition.compl π₀) ≤ c
r : (ι → ℝ) → ↑(Set.Ioi 0)
π : TaggedPrepartition I
hle : π.toPrepartition ≤ π₀
hH : IsHenstock π
hr : IsSubordinate π r
hd : distortion π = Prepartition.distortion π₀
hU : TaggedPrepartition.iUnion π = Prepartition.iUnion π₀
⊢ ∃ π, MemBaseSet l I c r π ∧ π.toPrepartition ≤ π₀ ∧ TaggedPrepartition.iUnion π = Prepartition.iUnion π₀
[PROOFSTEP]
refine' ⟨π, ⟨hr, fun _ => hH, fun _ => hd.trans_le hc₁, fun _ => ⟨π₀.compl, _, hc₂⟩⟩, ⟨hle, hU⟩⟩
[GOAL]
case intro.intro.intro.intro.intro
ι : Type u_1
inst✝ : Fintype ι
I J : Box ι
c c₁ c₂ : ℝ≥0
r✝ r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π✝ π₁ π₂ : TaggedPrepartition I
l✝ l₁ l₂ l : IntegrationParams
π₀ : Prepartition I
hc₁ : Prepartition.distortion π₀ ≤ c
hc₂ : Prepartition.distortion (Prepartition.compl π₀) ≤ c
r : (ι → ℝ) → ↑(Set.Ioi 0)
π : TaggedPrepartition I
hle : π.toPrepartition ≤ π₀
hH : IsHenstock π
hr : IsSubordinate π r
hd : distortion π = Prepartition.distortion π₀
hU : TaggedPrepartition.iUnion π = Prepartition.iUnion π₀
x✝ : l.bDistortion = true
⊢ Prepartition.iUnion (Prepartition.compl π₀) = ↑I \ TaggedPrepartition.iUnion π
[PROOFSTEP]
exact Prepartition.compl_congr hU ▸ π.toPrepartition.iUnion_compl
[GOAL]
ι : Type u_1
inst✝ : Fintype ι
I✝ J : Box ι
c c₁ c₂ : ℝ≥0
r✝ r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁ π₂ : TaggedPrepartition I✝
l✝ l₁ l₂ l : IntegrationParams
I : Box ι
hc : Box.distortion I ≤ c
r : (ι → ℝ) → ↑(Set.Ioi 0)
⊢ ∃ π, MemBaseSet l I c r π ∧ IsPartition π
[PROOFSTEP]
rw [← Prepartition.distortion_top] at hc
[GOAL]
ι : Type u_1
inst✝ : Fintype ι
I✝ J : Box ι
c c₁ c₂ : ℝ≥0
r✝ r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁ π₂ : TaggedPrepartition I✝
l✝ l₁ l₂ l : IntegrationParams
I : Box ι
hc : Prepartition.distortion ⊤ ≤ c
r : (ι → ℝ) → ↑(Set.Ioi 0)
⊢ ∃ π, MemBaseSet l I c r π ∧ IsPartition π
[PROOFSTEP]
have hc' : (⊤ : Prepartition I).compl.distortion ≤ c := by simp
[GOAL]
ι : Type u_1
inst✝ : Fintype ι
I✝ J : Box ι
c c₁ c₂ : ℝ≥0
r✝ r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁ π₂ : TaggedPrepartition I✝
l✝ l₁ l₂ l : IntegrationParams
I : Box ι
hc : Prepartition.distortion ⊤ ≤ c
r : (ι → ℝ) → ↑(Set.Ioi 0)
⊢ Prepartition.distortion (Prepartition.compl ⊤) ≤ c
[PROOFSTEP]
simp
[GOAL]
ι : Type u_1
inst✝ : Fintype ι
I✝ J : Box ι
c c₁ c₂ : ℝ≥0
r✝ r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁ π₂ : TaggedPrepartition I✝
l✝ l₁ l₂ l : IntegrationParams
I : Box ι
hc : Prepartition.distortion ⊤ ≤ c
r : (ι → ℝ) → ↑(Set.Ioi 0)
hc' : Prepartition.distortion (Prepartition.compl ⊤) ≤ c
⊢ ∃ π, MemBaseSet l I c r π ∧ IsPartition π
[PROOFSTEP]
simpa [isPartition_iff_iUnion_eq] using l.exists_memBaseSet_le_iUnion_eq ⊤ hc hc' r
[GOAL]
ι : Type u_1
inst✝ : Fintype ι
I✝ J : Box ι
c c₁ c₂ : ℝ≥0
r r₁ r₂ : (ι → ℝ) → ↑(Set.Ioi 0)
π π₁ π₂ : TaggedPrepartition I✝
l✝ l₁ l₂ l : IntegrationParams
I : Box ι
⊢ NeBot (toFilterDistortion l I (Box.distortion I))
[PROOFSTEP]
simpa using (l.toFilterDistortioniUnion_neBot' I ⊤).mono inf_le_left
|
Dict{String, Any}("~!@\$^&*()_+-`1234567890[]|/?><.,;:'" => Dict{String, Any}("value" => "1", "type" => "integer")) |
theory Renaming_Auto
imports
Renaming
ZF.Finite
ZF.List
keywords
"rename" :: thy_decl % "ML"
and
"simple_rename" :: thy_decl % "ML"
and
"src"
and
"tgt"
abbrevs
"simple_rename" = ""
begin
lemmas app_fun = apply_iff[THEN iffD1]
lemmas nat_succI = nat_succ_iff[THEN iffD2]
ML_file\<open>Utils.ml\<close>
ML_file\<open>Renaming_ML.ml\<close>
ML\<open>
open Renaming_ML
fun renaming_def mk_ren name from to ctxt =
let val to = to |> Syntax.read_term ctxt
val from = from |> Syntax.read_term ctxt
val (tc_lemma,action_lemma,fvs,r) = mk_ren from to ctxt
val (tc_lemma,action_lemma) = (fix_vars tc_lemma fvs ctxt , fix_vars action_lemma fvs ctxt)
val ren_fun_name = Binding.name (name ^ "_fn")
val ren_fun_def = Binding.name (name ^ "_fn_def")
val ren_thm = Binding.name (name ^ "_thm")
in
Local_Theory.note ((ren_thm, []), [tc_lemma,action_lemma]) ctxt |> snd |>
Local_Theory.define ((ren_fun_name, NoSyn), ((ren_fun_def, []), r)) |> snd
end;
\<close>
ML\<open>
local
val ren_parser = Parse.position (Parse.string --
(Parse.$$$ "src" |-- Parse.string --| Parse.$$$ "tgt" -- Parse.string));
val _ =
Outer_Syntax.local_theory \<^command_keyword>\<open>rename\<close> "ML setup for synthetic definitions"
(ren_parser >> (fn ((name,(from,to)),_) => renaming_def sum_rename name from to ))
val _ =
Outer_Syntax.local_theory \<^command_keyword>\<open>simple_rename\<close> "ML setup for synthetic definitions"
(ren_parser >> (fn ((name,(from,to)),_) => renaming_def ren_thm name from to ))
in
end
\<close>
end |
"""
# Author : GS Oh
# Experiment : PRECOG_Carla
# Note : Utility functions used to save & load & etc.
"""
# Import pytorch libraries
import torch
from torch.distributions import MultivariateNormal
# Import ETC
import numpy as np
def load_state(path):
print('Loading model_state_dict, optimizer_state_dict..')
state_dict = torch.load(path, map_location='cpu')
best_epoch = state_dict['best_epoch']
best_loss = state_dict['best_loss']
model_state = state_dict['model_state_dict']
best_model_state = state_dict['best_model_state_dict']
optimizer_state = state_dict['optimizer_state_dict']
scheduler_state = state_dict['scheduler_state_dict']
return best_epoch, best_loss, model_state, best_model_state, optimizer_state, scheduler_state
def save_state(best_epoch, best_loss, model_state, best_model_state, optimizer_state, scheduler_state, path):
print('Saving model_state_dict & optimizer_state_dict..')
print('best epoch: {}, loss: {}'.format(best_epoch, best_loss))
torch.save({
'best_epoch': best_epoch,
'best_loss': best_loss,
'model_state_dict': model_state,
'best_model_state_dict': best_model_state,
'optimizer_state_dict': optimizer_state,
'scheduler_state_dict': scheduler_state
}, path + '_BestEpoch' + str(best_epoch) + '_BestLoss' + str(best_loss) + '.pt')
def save_state_intermediate(iteration, model_state, path):
print('Saving intermediate model_state_dict ...')
print('Iteration: {}'.format(iteration))
torch.save({
'iteration': iteration,
'model_state_dict': model_state,
}, path + '_Iteration' + str(iteration) + '.pt')
def load_state_intermediate(path):
print('Loading intermediate model_state_dict ...')
state_dict = torch.load(path, map_location='cpu')
iteration = state_dict['iteration']
model_state = state_dict['model_state_dict']
return iteration, model_state
|
State Before: R : Type u_2
R₂ : Type u_3
K : Type ?u.336789
M : Type u_1
M₂ : Type u_4
V : Type ?u.336798
S : Type ?u.336801
inst✝⁵ : Semiring R
inst✝⁴ : AddCommMonoid M
inst✝³ : Module R M
inst✝² : Semiring R₂
inst✝¹ : AddCommMonoid M₂
inst✝ : Module R₂ M₂
σ₁₂ : R →+* R₂
s : Set M
f g : M →ₛₗ[σ₁₂] M₂
H : Set.EqOn (↑f) (↑g) s
x : M
h : x ∈ span R s
⊢ ↑f x = ↑g x State After: no goals Tactic: refine' span_induction h H _ _ _ <;> simp (config := { contextual := true }) |
/**
* \file ModellerFilter.h
*/
#ifndef ATK_MODELLING_MODELLERFILTER_H
#define ATK_MODELLING_MODELLERFILTER_H
#include <ATK/Modelling/config.h>
#include <ATK/Modelling/Types.h>
#include <ATK/Core/TypedBaseFilter.h>
#include <gsl/gsl>
#include <Eigen/Eigen>
#include <tuple>
#include <unordered_set>
#include <vector>
namespace ATK
{
/// The common class for ModellerFilter
template<typename DataType_>
class ATK_MODELLING_EXPORT ModellerFilter: public TypedBaseFilter<DataType_>
{
public:
using Parent = TypedBaseFilter<DataType_>;
using DataType = DataType_;
public:
/**
* The main ModellerFilter constructor
* @param nb_dynamic_pins is the number of dymanic pins (that have a voltage that may vary with time)
* @param nb_input_pins is the number of input pins (that will have varying voltage with time)
*/
ModellerFilter(gsl::index nb_dynamic_pins, gsl::index nb_input_pins);
virtual Eigen::Matrix<DataType, Eigen::Dynamic, 1> get_static_state() const = 0;
/// Returns the number of dynamic pins
virtual gsl::index get_nb_dynamic_pins() const = 0;
/// Returns the number of static pins
virtual gsl::index get_nb_static_pins() const = 0;
/// Returns the number of input pins
virtual gsl::index get_nb_input_pins() const = 0;
/// Returns the number of components
virtual gsl::index get_nb_components() const = 0;
/// Returns the name of a dynamic pin, usefull to set output
virtual std::string get_dynamic_pin_name(gsl::index identifier) const = 0;
/// Returns the name of a input pin, usefull to set input
virtual std::string
get_input_pin_name(gsl::index identifier) const = 0;
/// Returns the name of a static pin, usefull to set static
virtual std::string get_static_pin_name(gsl::index identifier) const = 0;
gsl::index find_dynamic_pin(const std::string& name);
gsl::index find_input_pin(const std::string& name);
gsl::index find_static_pin(const std::string& name);
/// Get number of parameters
virtual gsl::index get_number_parameters() const = 0;
/// Get the name of a parameter
virtual std::string get_parameter_name(gsl::index identifier) const = 0;
/// Get the value of a parameter
virtual DataType_ get_parameter(gsl::index identifier) const = 0;
/// Set the value of a parameter
virtual void set_parameter(gsl::index identifier, DataType_ value) = 0;
};
}
#endif
|
(*
Some experiments with equality.
1. About the definitionand the usual properties of equality.
2. The Axiom of Extensionality for equality.
*)
Print eq.
Eval simpl in (eq 2 2). (* 2=2:Prop *)
Eval simpl in 1=2 /\ 2=2.
(* Coq out-of-the-box example first *)
Lemma coq_equality_is_transitive : forall (T : Type) (x y z: T),
x = y /\ y = z -> x = z.
Proof.
intros T x y z H.
inversion H as [Hx Hy].
rewrite -> Hx.
rewrite -> Hy.
reflexivity.
Qed.
(* similarly, = is transitive *)
Module My_Equality. (* equality test kitchen *)
(* Print eql. *) (* not defined *)
Inductive eql {T : Type} (x : T) : T -> Prop :=
eql_refl : eql x x.
Print eq.
Print eql.
Lemma eql_is_transitive_trans : forall (T : Type) (x y z: T),
eql x y /\ eql y z -> eql x z.
Proof.
intros T x y z H.
inversion H as [Hx Hy].
(* rewrite -> Hx. NO! *)
induction Hx.
induction Hy.
(* reflexivity. NO! *)
apply eql_refl.
Qed.
Lemma eql_is_symmetric : forall (T : Type) (x y : T),
eql x y -> eql y x.
Proof.
intros X x y H. (* i.e. call T X *)
induction H.
(* reflexivity. NO! *)
apply eql_refl.
Qed.
Lemma eql_is_leibniz_equality : forall (T : Type) (x y: T),
eql x y -> forall P : T -> Prop, P x -> P y.
Proof. (* same as for builtin Coq = *)
intros X x y H.
induction H.
intros P H. apply H.
Qed.
(* eql has same definition as eq so, of course ... *)
Theorem eql_is_eq : forall (T: Type) (x y : T),
eql x y <-> x = y.
Proof.
intros T x y.
split.
(* -> *)
intros H. induction H. reflexivity.
(* <- *)
intros H. subst.
apply eql_refl.
Qed.
(* extensionality for our eql *)
Axiom eql_extensionality :
forall {X Y: Type} {f g : X -> Y},
(forall (x: X), f x = g x) -> eql f g.
Definition f (m : nat) : nat := m+1.
Definition g (n : nat) : nat := 1+n.
Definition h (o : nat) : nat := o+1.
Lemma plus_comm : forall n m : nat,
n + m = m + n.
Proof.
(* known *) Admitted.
Lemma a : eql f g.
Proof. apply eql_extensionality.
(* work from inside out *)
intros. unfold f. unfold g. apply plus_comm.
Qed.
Lemma b : f = h.
Proof. reflexivity. (* definitions of f and h unify *)
Qed.
Lemma c : f = g.
Proof. (* error reflexivity. *)
unfold f. unfold g. (* STUCK *)
Abort. (* because = has no extensionality axiom *)
End My_Equality.
|
import measure_theory.integral.bochner
import measure_theory.function.l2_space
import measure_theory.measure.measure_space
import measure_theory.function.l1_space
open measure_theory measure_theory.measure
open_locale big_operators measure_theory topological_space
variables {α : Type*} [fintype α]
instance sum_is_finite_measure {α ι : Type*} [measurable_space α] [fintype ι] {μ : ι → measure α}
[∀ i, is_finite_measure (μ i)] : is_finite_measure (sum μ) :=
begin
refine ⟨_⟩,
rw [measure.sum_apply _ measurable_set.univ, @tsum_eq_sum _ _ _ _ _ _ finset.univ],
{ simp only [ennreal.sum_lt_top, measure_ne_top, ne.def, not_false_iff, implies_true_iff] },
{ simp only [finset.mem_univ, not_true, forall_false_left, implies_true_iff] },
{ apply_instance },
{ apply_instance }
end
instance [measurable_space α] : is_finite_measure (count : measure α) :=
by apply sum_is_finite_measure
lemma lp (p : ennreal) (f : α → ℝ) :
mem_ℒp f p (@count α ⊤) :=
begin
refine mem_ℒp.mem_ℒp_of_exponent_le _ le_top,
suffices : ∃ b : nnreal, ∀ x : α, ∥f x∥₊ ≤ b,
{ obtain ⟨b, hb⟩ := this,
exact mem_ℒp_top_of_bound measurable_from_top.ae_strongly_measurable _ (@ae_of_all _ ⊤ _ _ hb) },
by_cases nonempty α,
{ obtain ⟨x, hx⟩ := by exactI fintype.exists_max (λ x, ∥f x∥₊),
exact ⟨_, hx⟩ },
{ exact ⟨0, λ x, false.rec _ (h ⟨x⟩)⟩ }
end
lemma integral_count {f : α → ℝ} :
∫ a, f a ∂(@count α ⊤) = ∑ a, f a :=
begin
simp [count],
rw integral_finset_sum_measure,
{ congr, funext i, apply integral_dirac', exact measurable_from_top.strongly_measurable },
{ refine λ i hi, ⟨measurable_from_top.ae_strongly_measurable, _⟩,
rw [has_finite_integral, lintegral_dirac' _ measurable_from_top],
simp only [ennreal.coe_lt_top] }
end
lemma lemma_2 {α : Type u_1} [fintype α] [measurable_space α] {μ : measure α} [is_finite_measure μ]
(f : (Lp ℝ 2 μ)) :
∥f∥ = (∫ (a : α), f a ^ 2 ∂μ) ^ (2⁻¹ : ℝ) :=
begin
simp only [norm, snorm, snorm', ennreal.bit0_eq_zero_iff, one_ne_zero, ennreal.bit0_eq_top_iff,
ennreal.one_ne_top, ennreal.to_real_bit0, ennreal.one_to_real, ennreal.rpow_two, one_div,
if_false],
have := lintegral_coe_eq_integral (λ x, ∥f x∥₊ ^ 2) _,
{ simp only [ennreal.coe_pow, nnreal.coe_pow, coe_nnnorm] at this,
rw [this, ennreal.of_real_rpow_of_nonneg, ennreal.to_real_of_real],
{ congr,
exact funext (λ _, sq_abs _) },
{ apply real.rpow_nonneg_of_nonneg,
apply integral_nonneg,
rw pi.le_def,
exact λ i, pow_two_nonneg _ },
{ apply integral_nonneg,
rw pi.le_def,
exact λ i, pow_two_nonneg _ },
{ norm_num } },
{ have := (Lp.mem_ℒp f).integrable_norm_rpow',
simpa [this] }
end
lemma cauchy_schwarz (f g : α → ℝ) :
(∑ x, f x * g x) ≤ (∑ x, f x ^ 2) ^ (2⁻¹ : ℝ) * (∑ x, g x ^ 2) ^ (2⁻¹ : ℝ) :=
begin
simp_rw [← integral_count, pow_two],
rw ← integral_congr_ae ((lp 2 f).coe_fn_to_Lp.mul (lp 2 g).coe_fn_to_Lp),
rw ← integral_congr_ae ((lp 2 f).coe_fn_to_Lp.mul (lp 2 f).coe_fn_to_Lp),
rw ← integral_congr_ae ((lp 2 g).coe_fn_to_Lp.mul (lp 2 g).coe_fn_to_Lp),
convert ← @real_inner_le_norm _ _ ((lp 2 f).to_Lp f) ((lp 2 g).to_Lp g) using 1,
simp only [← pow_two, lemma_2],
end
|
------------------------------------------------------------------------
-- Empty type (in Set₁)
------------------------------------------------------------------------
module Data.Empty1 where
data ⊥₁ : Set₁ where
|
lemma degree_reflect_poly_eq [simp]: "coeff p 0 \<noteq> 0 \<Longrightarrow> degree (reflect_poly p) = degree p" |
FUNCTION FFTAMP(CHANNEL,F)
C
C THIS IS THE GAIN OF A CIRCUIT JUST BEFORE THE FFT D/A CONVERTER
C
INTEGER*4 CHANNEL
COMPLEX Z1,Y2,GAIN
REAL RSW(6),C2MUF(6),F
COMMON /GAINBLK/ PHASE,GAIN
DATA RSW /50.,400.,400.,0.,0.,0./
DATA C2MUF /1.961,1.896,1.949,1.981,2.011,1.943/
DATA C1,R2,C2 /2.E-6,1.E4,1.E-9/
DATA TWOPI /6.2831853/
C
GAIN = CMPLX(1.,0.)
PHASE = 0.
FFTAMP = 1.
IF(CHANNEL.GT.6) RETURN
W = TWOPI*F
C1 = C2MUF(CHANNEL)*1.E-6
RSWT = RSW(CHANNEL)
Z1 = CMPLX(RSWT,-1./W/C1)
Y2 = CMPLX(1./R2,W*C2)
GAIN = 1./(1. + Y2*Z1)
C
GNIP = AIMAG(GAIN)
GNRP = GAIN
PHASE = ATAN2(GNIP,GNRP)
FFTAMP = CABS(GAIN)
RETURN
END
|
This is reported by me a while ago, just making sure it's on your radar.
When you decide to reset your profile and password due to a concern that the profile might have been leaked, by generating the new profile you are NOT blocking your old profile from being used.
This is a serious security issue. It is rather easy to fix.
I believe that security comes first in security products and you should probably agree.
Thanks for the great feedback. I totally agree.
This bug fix will be available in next patch. |
[STATEMENT]
lemma tiny_ntcfs_vsubset_Vset[simp]:
"set {\<NN>. \<exists>\<FF> \<GG>. \<NN> : \<FF> \<mapsto>\<^sub>C\<^sub>F\<^sub>.\<^sub>t\<^sub>i\<^sub>n\<^sub>y \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^sub>.\<^sub>t\<^sub>i\<^sub>n\<^sub>y\<^bsub>\<alpha>\<^esub> \<BB>} \<subseteq>\<^sub>\<circ> Vset \<alpha>"
(is \<open>set ?ntcfs \<subseteq>\<^sub>\<circ> _\<close>)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. tiny_ntcfs \<alpha> \<AA> \<BB> \<subseteq>\<^sub>\<circ> Vset \<alpha>
[PROOF STEP]
proof(cases \<open>tiny_category \<alpha> \<AA> \<and> tiny_category \<alpha> \<BB>\<close>)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. tiny_category \<alpha> \<AA> \<and> tiny_category \<alpha> \<BB> \<Longrightarrow> tiny_ntcfs \<alpha> \<AA> \<BB> \<subseteq>\<^sub>\<circ> Vset \<alpha>
2. \<not> (tiny_category \<alpha> \<AA> \<and> tiny_category \<alpha> \<BB>) \<Longrightarrow> tiny_ntcfs \<alpha> \<AA> \<BB> \<subseteq>\<^sub>\<circ> Vset \<alpha>
[PROOF STEP]
case True
[PROOF STATE]
proof (state)
this:
tiny_category \<alpha> \<AA> \<and> tiny_category \<alpha> \<BB>
goal (2 subgoals):
1. tiny_category \<alpha> \<AA> \<and> tiny_category \<alpha> \<BB> \<Longrightarrow> tiny_ntcfs \<alpha> \<AA> \<BB> \<subseteq>\<^sub>\<circ> Vset \<alpha>
2. \<not> (tiny_category \<alpha> \<AA> \<and> tiny_category \<alpha> \<BB>) \<Longrightarrow> tiny_ntcfs \<alpha> \<AA> \<BB> \<subseteq>\<^sub>\<circ> Vset \<alpha>
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
tiny_category \<alpha> \<AA> \<and> tiny_category \<alpha> \<BB>
[PROOF STEP]
have "tiny_category \<alpha> \<AA>" and "tiny_category \<alpha> \<BB>"
[PROOF STATE]
proof (prove)
using this:
tiny_category \<alpha> \<AA> \<and> tiny_category \<alpha> \<BB>
goal (1 subgoal):
1. tiny_category \<alpha> \<AA> &&& tiny_category \<alpha> \<BB>
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
tiny_category \<alpha> \<AA>
tiny_category \<alpha> \<BB>
goal (2 subgoals):
1. tiny_category \<alpha> \<AA> \<and> tiny_category \<alpha> \<BB> \<Longrightarrow> tiny_ntcfs \<alpha> \<AA> \<BB> \<subseteq>\<^sub>\<circ> Vset \<alpha>
2. \<not> (tiny_category \<alpha> \<AA> \<and> tiny_category \<alpha> \<BB>) \<Longrightarrow> tiny_ntcfs \<alpha> \<AA> \<BB> \<subseteq>\<^sub>\<circ> Vset \<alpha>
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. tiny_ntcfs \<alpha> \<AA> \<BB> \<subseteq>\<^sub>\<circ> Vset \<alpha>
[PROOF STEP]
proof(rule vsubsetI)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>x. x \<in>\<^sub>\<circ> tiny_ntcfs \<alpha> \<AA> \<BB> \<Longrightarrow> x \<in>\<^sub>\<circ> Vset \<alpha>
[PROOF STEP]
fix \<NN>
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>x. x \<in>\<^sub>\<circ> tiny_ntcfs \<alpha> \<AA> \<BB> \<Longrightarrow> x \<in>\<^sub>\<circ> Vset \<alpha>
[PROOF STEP]
assume "\<NN> \<in>\<^sub>\<circ> set ?ntcfs"
[PROOF STATE]
proof (state)
this:
\<NN> \<in>\<^sub>\<circ> tiny_ntcfs \<alpha> \<AA> \<BB>
goal (1 subgoal):
1. \<And>x. x \<in>\<^sub>\<circ> tiny_ntcfs \<alpha> \<AA> \<BB> \<Longrightarrow> x \<in>\<^sub>\<circ> Vset \<alpha>
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
\<NN> \<in>\<^sub>\<circ> tiny_ntcfs \<alpha> \<AA> \<BB>
[PROOF STEP]
obtain \<FF> \<GG> where "\<NN> : \<FF> \<mapsto>\<^sub>C\<^sub>F\<^sub>.\<^sub>t\<^sub>i\<^sub>n\<^sub>y \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^sub>.\<^sub>t\<^sub>i\<^sub>n\<^sub>y\<^bsub>\<alpha>\<^esub> \<BB>"
[PROOF STATE]
proof (prove)
using this:
\<NN> \<in>\<^sub>\<circ> tiny_ntcfs \<alpha> \<AA> \<BB>
goal (1 subgoal):
1. (\<And>\<FF> \<GG>. \<NN> : \<FF> \<mapsto>\<^sub>C\<^sub>F\<^sub>.\<^sub>t\<^sub>i\<^sub>n\<^sub>y \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^sub>.\<^sub>t\<^sub>i\<^sub>n\<^sub>y\<^bsub>\<alpha>\<^esub> \<BB> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
\<NN> : \<FF> \<mapsto>\<^sub>C\<^sub>F\<^sub>.\<^sub>t\<^sub>i\<^sub>n\<^sub>y \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^sub>.\<^sub>t\<^sub>i\<^sub>n\<^sub>y\<^bsub>\<alpha>\<^esub> \<BB>
goal (1 subgoal):
1. \<And>x. x \<in>\<^sub>\<circ> tiny_ntcfs \<alpha> \<AA> \<BB> \<Longrightarrow> x \<in>\<^sub>\<circ> Vset \<alpha>
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
\<NN> : \<FF> \<mapsto>\<^sub>C\<^sub>F\<^sub>.\<^sub>t\<^sub>i\<^sub>n\<^sub>y \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^sub>.\<^sub>t\<^sub>i\<^sub>n\<^sub>y\<^bsub>\<alpha>\<^esub> \<BB>
[PROOF STEP]
interpret is_tiny_ntcf \<alpha> \<AA> \<BB> \<FF> \<GG> \<NN>
[PROOF STATE]
proof (prove)
using this:
\<NN> : \<FF> \<mapsto>\<^sub>C\<^sub>F\<^sub>.\<^sub>t\<^sub>i\<^sub>n\<^sub>y \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^sub>.\<^sub>t\<^sub>i\<^sub>n\<^sub>y\<^bsub>\<alpha>\<^esub> \<BB>
goal (1 subgoal):
1. \<NN> : \<FF> \<mapsto>\<^sub>C\<^sub>F\<^sub>.\<^sub>t\<^sub>i\<^sub>n\<^sub>y \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^sub>.\<^sub>t\<^sub>i\<^sub>n\<^sub>y\<^bsub>\<alpha>\<^esub> \<BB>
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>x. x \<in>\<^sub>\<circ> tiny_ntcfs \<alpha> \<AA> \<BB> \<Longrightarrow> x \<in>\<^sub>\<circ> Vset \<alpha>
[PROOF STEP]
from tiny_ntcf_in_Vset
[PROOF STATE]
proof (chain)
picking this:
\<NN> \<in>\<^sub>\<circ> Vset \<alpha>
[PROOF STEP]
show "\<NN> \<in>\<^sub>\<circ> Vset \<alpha>"
[PROOF STATE]
proof (prove)
using this:
\<NN> \<in>\<^sub>\<circ> Vset \<alpha>
goal (1 subgoal):
1. \<NN> \<in>\<^sub>\<circ> Vset \<alpha>
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
\<NN> \<in>\<^sub>\<circ> Vset \<alpha>
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
tiny_ntcfs \<alpha> \<AA> \<BB> \<subseteq>\<^sub>\<circ> Vset \<alpha>
goal (1 subgoal):
1. \<not> (tiny_category \<alpha> \<AA> \<and> tiny_category \<alpha> \<BB>) \<Longrightarrow> tiny_ntcfs \<alpha> \<AA> \<BB> \<subseteq>\<^sub>\<circ> Vset \<alpha>
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<not> (tiny_category \<alpha> \<AA> \<and> tiny_category \<alpha> \<BB>) \<Longrightarrow> tiny_ntcfs \<alpha> \<AA> \<BB> \<subseteq>\<^sub>\<circ> Vset \<alpha>
[PROOF STEP]
case False
[PROOF STATE]
proof (state)
this:
\<not> (tiny_category \<alpha> \<AA> \<and> tiny_category \<alpha> \<BB>)
goal (1 subgoal):
1. \<not> (tiny_category \<alpha> \<AA> \<and> tiny_category \<alpha> \<BB>) \<Longrightarrow> tiny_ntcfs \<alpha> \<AA> \<BB> \<subseteq>\<^sub>\<circ> Vset \<alpha>
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
\<not> (tiny_category \<alpha> \<AA> \<and> tiny_category \<alpha> \<BB>)
[PROOF STEP]
have "set ?ntcfs = 0"
[PROOF STATE]
proof (prove)
using this:
\<not> (tiny_category \<alpha> \<AA> \<and> tiny_category \<alpha> \<BB>)
goal (1 subgoal):
1. tiny_ntcfs \<alpha> \<AA> \<BB> = []\<^sub>\<circ>
[PROOF STEP]
unfolding is_tiny_ntcf_iff is_tiny_functor_iff
[PROOF STATE]
proof (prove)
using this:
\<not> (tiny_category \<alpha> \<AA> \<and> tiny_category \<alpha> \<BB>)
goal (1 subgoal):
1. ZFC_in_HOL.set {\<NN>. \<exists>\<FF> \<GG>. \<NN> : \<FF> \<mapsto>\<^sub>C\<^sub>F \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<BB> \<and> (\<FF> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<BB> \<and> tiny_category \<alpha> \<AA> \<and> tiny_category \<alpha> \<BB>) \<and> \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<BB> \<and> tiny_category \<alpha> \<AA> \<and> tiny_category \<alpha> \<BB>} = []\<^sub>\<circ>
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
tiny_ntcfs \<alpha> \<AA> \<BB> = []\<^sub>\<circ>
goal (1 subgoal):
1. \<not> (tiny_category \<alpha> \<AA> \<and> tiny_category \<alpha> \<BB>) \<Longrightarrow> tiny_ntcfs \<alpha> \<AA> \<BB> \<subseteq>\<^sub>\<circ> Vset \<alpha>
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
tiny_ntcfs \<alpha> \<AA> \<BB> = []\<^sub>\<circ>
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
tiny_ntcfs \<alpha> \<AA> \<BB> = []\<^sub>\<circ>
goal (1 subgoal):
1. tiny_ntcfs \<alpha> \<AA> \<BB> \<subseteq>\<^sub>\<circ> Vset \<alpha>
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
tiny_ntcfs \<alpha> \<AA> \<BB> \<subseteq>\<^sub>\<circ> Vset \<alpha>
goal:
No subgoals!
[PROOF STEP]
qed |
[STATEMENT]
lemma A1'P: "\<lfloor>\<^bold>\<not>(\<P>(\<lambda>x.(x\<^bold>\<noteq>x)))\<rfloor>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lfloor>\<^bold>\<not>\<lambda>x. x\<^bold>\<noteq>x\<^bold>\<in>\<P>\<rfloor>
[PROOF STEP]
using Theorem9
[PROOF STATE]
proof (prove)
using this:
\<lfloor>\<lambda>w. \<forall>x. (x\<^bold>\<in>\<P> \<^bold>\<rightarrow> \<^bold>\<diamond>x\<^bold>\<in>q4) w\<rfloor>
goal (1 subgoal):
1. \<lfloor>\<^bold>\<not>\<lambda>x. x\<^bold>\<noteq>x\<^bold>\<in>\<P>\<rfloor>
[PROOF STEP]
by blast |
%CODEGENERATOR.GENGRAVLOAD Generate code for gravitational load
%
% G = cGen.gengravload() is a symbolic vector (1xN) of joint load
% forces/torques due to gravity.
%
% Notes::
% - Side effects of execution depends on the cGen flags:
% - saveresult: the symbolic expressions are saved to
% disk in the directory specified by cGen.sympath
% - genmfun: ready to use m-functions are generated and
% provided via a subclass of SerialLink stored in cGen.robjpath
% - genslblock: a Simulink block is generated and stored in a
% robot specific block library cGen.slib in the directory
% cGen.basepath
% - genccode: generates C-functions and -headers in the directory
% specified by the ccodepath property of the CodeGenerator object.
% - mex: generates robot specific MEX-functions as replacement for the
% m-functions mentioned above. Access is provided by the SerialLink
% subclass. The MEX files rely on the C code generated before.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also CodeGenerator, CodeGenerator.geninvdyn, CodeGenerator.genfdyn.
% Copyright (C) 2012-2014, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [G] = gengravload(CGen)
%% Derivation of symbolic expressions
CGen.logmsg([datestr(now),'\tDeriving gravitational load vector']);
q = CGen.rob.gencoords;
tmpRob = CGen.rob.nofriction;
G = tmpRob.gravload(q);
CGen.logmsg('\t%s\n',' done!');
%% Save symbolic expressions
if CGen.saveresult
CGen.logmsg([datestr(now),'\tSaving symbolic expression for gravitational load']);
CGen.savesym(G,'gravload','gravload.mat');
CGen.logmsg('\t%s\n',' done!');
end
% M-Functions
if CGen.genmfun
CGen.genmfungravload;
end
% Embedded Matlab Function Simulink blocks
if CGen.genslblock
CGen.genslblockgravload;
end
%% C-Code
if CGen.genccode
CGen.genccodegravload;
end
%% MEX
if CGen.genmex
CGen.genmexgravload;
end
end
|
library(readxl)
setwd ("c://R")
EmployeesSalary <- read_excel("employees.xlsx")
summary(EmployeesSalary)
EmployeesSalary$LevelOfEmployee <- as.factor(EmployeesSalary$LevelOfEmployee)
summary(EmployeesSalary)
pch.list <- as.numeric(EmployeesSalary$LevelOfEmployee)
plot(EmployeesSalary$YearsExperience, EmployeesSalary$Salary, pch=c(pch.list))
LMcat <- lm('Salary~YearsExperience*LevelOfEmployee',data=EmployeesSalary)
LMcat
LMcat.coef <- coef(LMcat)
LMcat.coef
LMcat.GeneralStaff <- c(LMcat.coef[1],LMcat.coef[2])
LMcat.GeneralStaff
LMcat.TechnicalStaff <- c(LMcat.coef[1]+LMcat.coef[4],LMcat.coef[2]+LMcat.coef[6])
LMcat.TechnicalStaff
LMcat.Management <- c(LMcat.coef[1]+LMcat.coef[3],LMcat.coef[2]+LMcat.coef[5])
LMcat.Management
pch.list <- as.numeric(EmployeesSalary$LevelOfEmployee)
plot(EmployeesSalary$YearsExperience, EmployeesSalary$Salary, pch=c(pch.list),cex.axis=0.6,cex.lab=0.6)
abline(coef=LMcat.GeneralStaff,lwd=2)
abline(coef=LMcat.TechnicalStaff,lwd=2)
abline(coef=LMcat.Management,lwd=2)
summary(LMcat)
|
module STLC.Semantics where
-- This file contains the definitional interpreter for STLC described
-- in Section 2 of the paper.
open import Data.Nat
open import Data.Integer
open import Data.List
open import Data.List.Membership.Propositional
open import Data.List.Relation.Unary.All as All
open import Data.Maybe.Base hiding (_>>=_)
------------
-- SYNTAX --
------------
-- These definitions correspond to Section 2.1, except we have
-- included numbers (integers) and integer operations in the language.
data Ty : Set where
unit : Ty
_⇒_ : (a b : Ty) → Ty
int : Ty
Ctx = List Ty
-- Below, `Expr` uses `_∈_` from `Relation.Binary` in the Agda
-- Standard Library to represent typed de Bruijn indices which witness
-- the existence of an entry in the type context.
data Expr (Γ : Ctx) : Ty → Set where
unit : Expr Γ unit
var : ∀ {t} → t ∈ Γ → Expr Γ t
ƛ : ∀ {a b} → Expr (a ∷ Γ) b → Expr Γ (a ⇒ b)
_·_ : ∀ {a b} → Expr Γ (a ⇒ b) → Expr Γ a → Expr Γ b
num : ℤ → Expr Γ int
iop : (ℤ → ℤ → ℤ) → (l r : Expr Γ int) → Expr Γ int
-----------------------------
-- VALUES AND ENVIRONMENTS --
-----------------------------
-- These definitions correspond to Section 2.2.
--
-- Note that the `All` type described in Section 2.2 of the paper (for
-- simplicity) does not mention universe levels, whereas the `All`
-- definition below refers to `Data.List.All` in the Agda Standard
-- Library which is defined in a universe polymorphic manner.
mutual
data Val : Ty → Set where
unit : Val unit
⟨_,_⟩ : ∀ {Γ a b} → Expr (a ∷ Γ) b → Env Γ → Val (a ⇒ b)
num : ℤ → Val int
Env : Ctx → Set
Env Γ = All Val Γ
-- The `lookup` function described in Section 2.2 of the paper is also
-- defined in `Data.List.All` in the Agda Standard Library.
-----------
-- MONAD --
-----------
-- These definitions correspond to Section 2.3.
M : Ctx → Set → Set
M Γ a = Env Γ → Maybe a
_>>=_ : ∀ {Γ a b} → M Γ a → (a → M Γ b) → M Γ b
(f >>= c) E with (f E)
... | just x = c x E
... | nothing = nothing
return : ∀ {Γ a} → a → M Γ a
return x E = just x
getEnv : ∀ {Γ} → M Γ (Env Γ)
getEnv E = return E E
usingEnv : ∀ {Γ Γ' a} → Env Γ → M Γ a → M Γ' a
usingEnv E f _ = f E
timeout : ∀ {Γ a} → M Γ a
timeout = λ _ → nothing
-----------------
-- INTERPRETER --
-----------------
-- These definitions correspond to Section 2.4.
eval : ℕ → ∀ {Γ t} → Expr Γ t → M Γ (Val t)
eval zero _ =
timeout
eval (suc k) unit =
return unit
eval (suc k) (var x) =
getEnv >>= λ E →
return (All.lookup E x)
eval (suc k) (ƛ b) =
getEnv >>= λ E →
return ⟨ b , E ⟩
eval (suc k) (l · r) =
eval k l >>= λ{ ⟨ e , E ⟩ →
eval k r >>= λ v →
usingEnv (v ∷ E) (eval k e) }
eval (suc k) (num x) =
return (num x)
eval (suc k) (iop f l r) =
eval k l >>= λ{ (num vₗ) →
eval k r >>= λ{ (num vᵣ) →
return (num (f vₗ vᵣ)) }}
|
# Declare a new `isfinite` function to avoid type piracy. This new function works with
# `Char` and `Period` as well as other types.
isfinite(x) = iszero(x - x)
isfinite(x::Real) = Base.isfinite(x)
isfinite(x::Union{Type{T}, T}) where T<:TimeType = Base.isfinite(x)
|
import data.real.basic
open rat
lemma mul_own_denom (q : ℚ) : q * q.denom = q.num :=
begin
rw [num_denom q],
ring,
have k₁ : (mk (q.num) ↑(q.denom)).denom = q.denom := by sorry,
rw [k₁],
have k₂ : ((mk (q.num) ↑(q.denom)).num) = q.num := by sorry,
rw [k₂],
sorry,
end
lemma div_2_of_sqr_div_2 (a : ℤ) (h : 2 ∣ a * a) : 2 ∣ a :=
begin
by_contradiction k,
dsimp [(∣)] at *,
simp at k,
cases h with c h,
sorry,
end
theorem sqrt2nonintegral : ∀ (z : ℤ), z^2 ≠ 2 :=
begin
intros z,
by_contradiction h,
rw [ne.def, not_not] at h,
sorry,
end
theorem sqrt2irrational : ∀ (q : ℚ), q^2 ≠ 2 :=
begin
intros q,
by_contradiction h,
rw [ne.def, not_not] at h,
have pos := q.pos,
have cop := q.cop,
rw [pow_two] at h,
have h₁ := congr_arg (λ (p : ℚ), p * q.denom * q.denom) h,
simp at h₁,
rw [mul_comm, mul_assoc, mul_own_denom, ←mul_assoc, mul_comm _ q,
mul_own_denom, mul_assoc] at h₁,
have w := dvd.intro (↑(q.denom) * ↑(q.denom)) h₁.symm,
dsimp [(∣)] at w,
sorry,
end |
# R - 3.4.1
test_that("Sample Tests", {
expect_equal(expand("hello"), c("h", "e", "l", "l", "o"))
expect_equal(expand(""), character(0))
})
|
lemma pderiv_0 [simp]: "pderiv 0 = 0" |
Formal statement is: lemma complex_Re_numeral [simp]: "Re (numeral v) = numeral v" Informal statement is: The real part of a numeral is the numeral itself. |
module Replica
import Data.List
import Data.Strings
import System
import System.Directory
import System.File
import System.Info
import Replica.TestConfig
import Replica.RunEnv
%default total
public export
data TestResult
= Success
| Failure (Maybe String) String
| NewGolden String
public export
data TestError
= CantLocateDir String
| CantReadOutput FileError
| CantParseTest (ParsingError BuildError)
| CantReadExpected FileError
| CantWriteNewGolden
| CommandFailed Int
expectedVsGiven : Maybe String -> String -> IO ()
expectedVsGiven exp out = do
case exp of
Nothing => putStrLn "Expected: Nothing Found"
Just str => do
putStrLn "Expected:"
putStrLn str
putStrLn "Given:"
putStrLn out
covering export
displayResult : Either TestError TestResult -> IO ()
displayResult (Left (CantLocateDir x)) = putStrLn $ "ERROR: Cannot find test directory"
displayResult (Left (CantReadOutput x)) = putStrLn $ "ERROR: Cannot read test output"
displayResult (Left (CantReadExpected x)) = putStrLn $ "ERROR: Cannot read expected output"
displayResult (Left (CantParseTest x)) = putStrLn $ "ERROR: Parsing failed: " ++ displayParsingError (const "something is missing") x
displayResult (Left CantWriteNewGolden) = putStrLn $ "ERROR: Cannot write file 'expected'"
displayResult (Left (CommandFailed x)) = putStrLn $ "ERROR: Cannot run command - Exit code: " ++ show x
displayResult (Right Success) = putStrLn "ok"
displayResult (Right (NewGolden str)) = putStrLn "new golden value" *> putStrLn str
displayResult (Right (Failure expected given)) = do
putStrLn "FAILURE"
expectedVsGiven expected given
displayPath : Path -> String
displayPath (MkDPair path snd) = foldr1 (\x, y => x <+> "." <+> y) path
covering export
displayTestResult : String -> Either TestError TestResult -> IO ()
displayTestResult testPath result = do
putStr $ testPath ++ ": "
displayResult result
-- on Windows, we just ignore backslashes and slashes when comparing,
-- similarity up to that is good enough. Leave errors that depend
-- on the confusion of slashes and backslashes to unix machines.
covering
normalize : String -> String
normalize str =
if isWindows
then pack $ filter (\ch => ch /= '/' && ch /= '\\') (unpack str)
else str
commandLine : TestConfig -> String
commandLine (MkTestConfig exec path params inputFile outputFile)
= exec ++ " " ++ params ++ (maybe "" (" < " ++) inputFile) ++ " > " ++ outputFile
covering
handleFailure : Maybe String -> String -> IO (Either TestError TestResult)
handleFailure exp out = do
expectedVsGiven exp out
putStrLn $ "Do you want to " ++ maybe "set" (const "replace") exp ++ " the golden value? [N/y]"
if !readAnswer
then do
Right _ <- writeFile "expected" out
| Left err => pure $ Left $ CantWriteNewGolden
putStrLn "New golden value saved"
pure $ Right $ NewGolden out
else do
putStrLn "Resuming..."
pure $ Right $ Failure exp out
where
covering
readAnswer : IO Bool
readAnswer = do
answer <- getLine
case answer of
"" => pure False
"n" => pure False
"N" => pure False
"y" => pure True
"Y" => pure True
_ => putStrLn "I didn't understand your answer. [N/y]" *> readAnswer
covering
testExecution : (interactive : Bool) -> TestConfig -> IO (Either TestError TestResult)
testExecution interactive opts = do
removeFile opts.outputFile
0 <- system $ commandLine opts
| n => pure $ Left $ CommandFailed 0
Right out <- readFile opts.outputFile
| Left err => pure $ Left $ CantReadOutput err
Right exp <- readFile "expected"
| Left err => if interactive
then handleFailure Nothing out
else pure $ Left $ CantReadExpected err
let result = normalize exp == normalize out
if result
then pure $ Right Success
else if interactive
then handleFailure (Just exp) out
else pure $ Right $ Failure (Just exp) out
asPath : DPair (List String) NonEmpty -> String
asPath (MkDPair path snd) = foldr1 (\x,y => x <+> "/" <+> y) path
covering export
runTest : RunEnv -> IO (Either TestError TestResult)
runTest env = do
Just cdir <- currentDir
| Nothing => pure $ Left $ CantLocateDir "Can't resolve currentDir"
True <- changeDir env.path
| False => pure $ Left $ CantLocateDir $ "Can't locate " ++ show env.path
Right cfg <- parseTestConfig "test.repl"
| Left err => pure $ Left $ CantParseTest err
result <- testExecution env.interactive cfg
changeDir cdir
pure $ result
|
[GOAL]
α : Type u_1
ι : Sort u_2
κ : ι → Sort u_3
A B : Set (Finset α)
r : ℕ
f : ι → Set (Finset α)
⊢ Sized r (⋃ (i : ι), f i) ↔ ∀ (i : ι), Sized r (f i)
[PROOFSTEP]
simp_rw [Set.Sized, Set.mem_iUnion, forall_exists_index]
[GOAL]
α : Type u_1
ι : Sort u_2
κ : ι → Sort u_3
A B : Set (Finset α)
r : ℕ
f : ι → Set (Finset α)
⊢ (∀ ⦃x : Finset α⦄ (x_1 : ι), x ∈ f x_1 → card x = r) ↔ ∀ (i : ι) ⦃x : Finset α⦄, x ∈ f i → card x = r
[PROOFSTEP]
exact forall_swap
[GOAL]
α : Type u_1
ι : Sort u_2
κ : ι → Sort u_3
A B : Set (Finset α)
r : ℕ
f : (i : ι) → κ i → Set (Finset α)
⊢ Sized r (⋃ (i : ι) (j : κ i), f i j) ↔ ∀ (i : ι) (j : κ i), Sized r (f i j)
[PROOFSTEP]
simp only [Set.sized_iUnion]
[GOAL]
α : Type u_1
ι : Sort u_2
κ : ι → Sort u_3
inst✝ : Fintype α
𝒜 : Finset (Finset α)
s : Finset α
r : ℕ
A : Finset α
⊢ A ∈ 𝒜 → A ∈ powersetLen r univ ↔ A ∈ ↑𝒜 → card A = r
[PROOFSTEP]
rw [mem_powerset_len_univ_iff, mem_coe]
[GOAL]
α : Type u_1
ι : Sort u_2
κ : ι → Sort u_3
inst✝ : Fintype α
𝒜 : Finset (Finset α)
s : Finset α
r : ℕ
h𝒜 : Set.Sized r ↑𝒜
⊢ card 𝒜 ≤ Nat.choose (Fintype.card α) r
[PROOFSTEP]
rw [Fintype.card, ← card_powersetLen]
[GOAL]
α : Type u_1
ι : Sort u_2
κ : ι → Sort u_3
inst✝ : Fintype α
𝒜 : Finset (Finset α)
s : Finset α
r : ℕ
h𝒜 : Set.Sized r ↑𝒜
⊢ card 𝒜 ≤ card (powersetLen r univ)
[PROOFSTEP]
exact card_le_of_subset (subset_powersetLen_univ_iff.mpr h𝒜)
[GOAL]
α : Type u_1
ι : Sort u_2
κ : ι → Sort u_3
𝒜 : Finset (Finset α)
A A₁ A₂ : Finset α
r r₁ r₂ : ℕ
inst✝ : Fintype α
⊢ ∑ r in Iic (Fintype.card α), card (𝒜 # r) = card 𝒜
[PROOFSTEP]
letI := Classical.decEq α
[GOAL]
α : Type u_1
ι : Sort u_2
κ : ι → Sort u_3
𝒜 : Finset (Finset α)
A A₁ A₂ : Finset α
r r₁ r₂ : ℕ
inst✝ : Fintype α
this : DecidableEq α := Classical.decEq α
⊢ ∑ r in Iic (Fintype.card α), card (𝒜 # r) = card 𝒜
[PROOFSTEP]
rw [← card_biUnion, biUnion_slice]
[GOAL]
α : Type u_1
ι : Sort u_2
κ : ι → Sort u_3
𝒜 : Finset (Finset α)
A A₁ A₂ : Finset α
r r₁ r₂ : ℕ
inst✝ : Fintype α
this : DecidableEq α := Classical.decEq α
⊢ ∀ (x : ℕ), x ∈ Iic (Fintype.card α) → ∀ (y : ℕ), y ∈ Iic (Fintype.card α) → x ≠ y → Disjoint (𝒜 # x) (𝒜 # y)
[PROOFSTEP]
exact Finset.pairwiseDisjoint_slice.subset (Set.subset_univ _)
|
import numpy as np
from types import SimpleNamespace as SN
from functools import reduce
import re
from copy import deepcopy
class FymNamespace(SN):
def __repr__(self, indent=0):
items = ["{"]
indent += 1
for key, val in self.__dict__.items():
item = " " * indent + str(key) + ": "
if isinstance(val, SN):
item += val.__repr__(indent)
elif isinstance(val, np.ndarray):
if val.ndim > 1 and val.shape[0] > 1:
item += np.array2string(
val, prefix=" " * len(item))
else:
item += str(val)
item += ","
items.append(item)
indent -= 1
items.append(" " * indent + "}")
return "\n".join(items)
def _make_clean(string):
"""From https://stackoverflow.com/a/3305731"""
return re.sub(r"\W+|^(?=\d)", "_", string)
def _put(a, b):
for k, v in b.items():
if k in a and isinstance(v, dict) and isinstance(a[k], dict):
_put(a[k], v)
else:
a[k] = v
def unwind_nested_dict(d):
result = {}
for k, v in d.items():
if isinstance(v, dict):
v = unwind_nested_dict(v)
d = reduce(lambda d, k: {k: d}, k.split(".")[::-1], v)
_put(result, d)
return result
def wind(d, base="", delimiter="."):
result = {}
d = decode(d)
for k, v in d.items():
k = delimiter.join([base, k]) if base else k
if isinstance(v, dict):
v = wind(v, base=k, delimiter=delimiter)
result = dict(result, **v)
else:
result[k] = v
return result
def encode(d):
"""Encode a dict to a SimpleNamespace"""
if isinstance(d, SN):
d = SN.__dict__
elif not isinstance(d, dict):
return d
out = FymNamespace()
for k, v in d.items():
if isinstance(v, dict):
setattr(out, _make_clean(k), encode(v))
else:
setattr(out, _make_clean(k), v)
return out
def decode(sn):
"""Decode a SimpleNamespace or a dict to a nested dict"""
if isinstance(sn, SN):
sn = sn.__dict__
elif not isinstance(sn, dict):
return sn
out = {}
for key, val in sn.items():
if isinstance(val, (SN, dict)):
val = decode(val)
out.update({key: val})
return unwind_nested_dict(out)
def parse(d={}):
"""Pars:e a dict-like object"""
return encode(decode(d))
# return encode(decode(d))
def update(sn, d, copy_second=True, prune=False):
"""Update a SimpleNamespace with a dict or a SimpleNamespace"""
if isinstance(sn, SN):
sn = vars(sn)
if copy_second:
d = copy(d)
d = decode(d)
dtype = (dict, SN)
if prune:
for k, v in list(sn.items()):
if k in d and isinstance(v, dtype) and isinstance(d[k], dtype):
update(v, d[k], prune=prune)
elif k not in d:
del sn[k]
for k, v in d.items():
if k in sn and isinstance(v, dtype) and isinstance(sn[k], dtype):
update(sn[k], v)
else:
sn[k] = encode(v)
def copy(d):
if isinstance(d, SN):
d = parse(d)
return deepcopy(d)
def merge(d1, d2, prune=False):
d = copy(d1)
update(d, copy(d2), prune=prune)
return d
if __name__ == "__main__":
# ``parser.parse``
import fym.utils.parser as parser
from fym.core import BaseEnv, BaseSystem
json_dict = {
"env.kwargs": dict(dt=0.01, max_t=10),
"multicopter.nrotor": 6,
"multicopter.m": 3.,
"multicopter.LQRGain": {
"Q": [1, 1, 1, 1],
"R": [1, 1],
},
"actuator.tau": 1e-1,
}
cfg = parser.parse(json_dict)
# # ``parser.update``
# cfg = parser.parse()
# def load_config():
# parser.update(cfg, {
# "env.kwargs": dict(dt=0.01, max_t=10),
# "agent.memory_size": 1000,
# "agent.minibatch_size": 32,
# })
# load_config()
# cfg.env.kwargs.dt = 0.001
# # ``parser.decode``
# cfg = parser.parse()
# parser.update(cfg, {"env.kwargs": dict(dt=0.01, max_t=10)})
# env = BaseEnv(**parser.decode(cfg.env.kwargs))
|
lemma GPicard5: assumes holf: "f holomorphic_on (ball 0 1 - {0})" and f01: "\<And>z. z \<in> ball 0 1 - {0} \<Longrightarrow> f z \<noteq> 0 \<and> f z \<noteq> 1" obtains e B where "0 < e" "e < 1" "0 < B" "(\<forall>z \<in> ball 0 e - {0}. norm(f z) \<le> B) \<or> (\<forall>z \<in> ball 0 e - {0}. norm(f z) \<ge> B)" |
!! https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82996
!!
!! The issue seems to be the elemental final procedure being applied to
!! to the B array component of the BAR object
!!
!! $ gfortran --version
!! GNU Fortran (GCC) 6.4.1 20170727 (Red Hat 6.4.1-1)
!!
!! $ gfortran -g gfortran-bug-20171114a.f90
!! $ ./a.out
!!
!! Program received signal SIGSEGV: Segmentation fault - invalid memory reference.
!!
!! Backtrace for this error:
!! #0 0x7f52f8890df7 in ???
!! #1 0x7f52f889002d in ???
!! #2 0x7f52f7d8494f in ???
!! #3 0x400fa7 in __mod_MOD_foo_destroy
!! at /home/nnc/Fortran/Bugs/gfortran/tmp/gfortran-bug-20171114a.f90:46
!! #4 0x400f0f in __mod_MOD___final_mod_Foo
!! at /home/nnc/Fortran/Bugs/gfortran/tmp/gfortran-bug-20171114a.f90:49
!! #5 0x400b29 in __mod_MOD___final_mod_Bar
!! at /home/nnc/Fortran/Bugs/gfortran/tmp/gfortran-bug-20171114a.f90:49
!! #6 0x401026 in sub
!! at /home/nnc/Fortran/Bugs/gfortran/tmp/gfortran-bug-20171114a.f90:59
!! #7 0x40104a in MAIN__
!! at /home/nnc/Fortran/Bugs/gfortran/tmp/gfortran-bug-20171114a.f90:55
!! #8 0x401080 in main
!! at /home/nnc/Fortran/Bugs/gfortran/tmp/gfortran-bug-20171114a.f90:53
!! Segmentation fault (core dumped)
module mod
type foo
integer, pointer :: f(:) => null()
contains
final :: foo_destroy
end type
type bar
type(foo) :: b(2)
end type
contains
elemental subroutine foo_destroy(this)
type(foo), intent(inout) :: this
if (associated(this%f)) deallocate(this%f)
end subroutine
end module
program main
use mod
type(bar) :: x
call sub(x)
contains
subroutine sub(x)
type(bar), intent(out) :: x
end subroutine
end program
|
If $A_i$ is a measurable set in the $i$th $\sigma$-algebra, and $f$ is a measurable function from $M$ to $N_i$, then the set $\{x \in M \mid f(x) \in A_i\}$ is measurable in $M$. |
\documentclass[12]{scrartcl}
\usepackage{amssymb,amsmath,gensymb,dsfont,calc,multicol,fullpage}
\makeatletter
\newcommand\Aboxed[1]{
\@Aboxed#1\ENDDNE}
\def\@Aboxed#1\ENDDNE{%
&
\settowidth\@tempdima{$\displaystyle#1{}$}
\setlength\@tempdima{\@tempdima+\fboxsep+\fboxrule}
\kern-\@tempdima
\boxed{#1#2}
}
\makeatother
\begin{document}
\title{Homework 26, Section 5.1: 2(c,d), 4, 7, 8, 12(b), 14(a,b,c), 15(a,c)}
\author{Alex Gordon}
\date{\today}
\maketitle
\section*{Homework}
\subsection*{2. C)}
\{aa, ab, ao, bb, bo, oo\}
\subsection*{2. D)}
\{aa, ab, ba, ao, oa, bb, bo, ob, oo\}
\subsection*{4. A)}
It would be best represented as a set because order is not important.
\subsection*{4. B)}
If the same person will not be holding both offices, then it is a permutation from the club members.
\subsection*{4. C)}
It could be represented as an unordered list just fine.
\subsection*{4. D)}
It is an unordered list taken from the \{Red, green, blue\} set.
\subsection*{4. E)}
I think this one can be represented as either an ordered set or an unordered list. The reason for this is whether or not you can order more than one topping, leading to duplicate items in the list.
\subsection*{4. F)}
This is a permutation.
\subsection*{7. A)}
8
\subsection*{7. B)}
3
\subsection*{7. C)}
7
\subsection*{7. D)}
3
\subsection*{8. A)}
4
\subsection*{8. B)}
There is not one that is more likely. They're all equally likely.
\subsection*{8. C)}
2
\subsection*{8. D)}
6
\subsection*{8. E)}
4
\subsection*{12. A)}
There are 6 possibilities.
\begin{table}
\begin{tabular}{|l|l|l|}
\hline
~ & White pants & Black pants \\ \hline
Red shirt & White, Red & Black, Red \\ \hline
Green shirt & White, Green & Black, Green \\ \hline
Yellow shirt & White, Yellow & Black, Yellow \\ \hline
\end{tabular}
\end{table}
\subsection*{12. B)}
There would be 18 entries in this table $(6 \cdot 3)$.
\subsection*{12. C)}
For each section, there are $3 \cdot 3 \cdot 3 \cdot 3 = 81$ possibilities.
\subsection*{12. D)}
\begin{table}
\begin{tabular}{|l|l|l|}
\hline
Starts with a & Starts with c & Starts with c \\ \hline
aaa & bbb & ooo \\ \hline
aab & bbo & Black, Green \\ \hline
aao & boo & Black, Yellow \\ \hline
abb & ~ & ~ \\ \hline
abo & ~ & ~ \\ \hline
aoo & ~ & ~ \\ \hline
\end{tabular}
\end{table}
\subsection*{12. E)}
\begin{table}
\begin{tabular}{|l|l|l|l|}
\hline
HEAR & RHEA & ARHE & EARH \\ \hline
HERA & RAHE & AHER & EHAR \\ \hline
HAER & HEAH & AEHR & EHRA \\ \hline
HARE & RHAE & ARHE & EAHR \\ \hline
HREA & REHA & AERH & ERHA \\ \hline
HRAE & RHEA & AREH & ERAH \\ \hline
\end{tabular}
\end{table}
\subsection*{12. F)}
There are $24 \cdot 5 = 120$ variations.
\subsection*{14. A)}
\ \\
\ \\
\ \\
\ \\
\ \\
\
\subsection*{14. B)}
If we add another branch then there are 16 options.
\subsection*{14. C)}
There are 6.
\subsection*{15. A)}
$(7\cdot 1), (7\cdot 2), (7\cdot 3),(7\cdot 4), \ .\ .\ . \ ,(7\cdot 14285)$
\subsection*{15. C)}
There are 316 entries on the list.
\end{document} |
/-
Copyright (c) 2022 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers
! This file was ported from Lean 3 source module geometry.euclidean.angle.oriented.right_angle
! leanprover-community/mathlib commit 46b633fd842bef9469441c0209906f6dddd2b4f5
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Geometry.Euclidean.Angle.Oriented.Affine
import Mathbin.Geometry.Euclidean.Angle.Unoriented.RightAngle
/-!
# Oriented angles in right-angled triangles.
This file proves basic geometrical results about distances and oriented angles in (possibly
degenerate) right-angled triangles in real inner product spaces and Euclidean affine spaces.
-/
noncomputable section
open EuclideanGeometry
open Real
open RealInnerProductSpace
namespace Orientation
open FiniteDimensional
variable {V : Type _} [NormedAddCommGroup V] [InnerProductSpace ℝ V]
variable [hd2 : Fact (finrank ℝ V = 2)] (o : Orientation ℝ V (Fin 2))
include hd2 o
/-- An angle in a right-angled triangle expressed using `arccos`. -/
theorem oangle_add_right_eq_arccos_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
o.oangle x (x + y) = Real.arccos (‖x‖ / ‖x + y‖) :=
by
have hs : (o.oangle x (x + y)).sign = 1 := by
rw [oangle_sign_add_right, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs,
InnerProductGeometry.angle_add_eq_arccos_of_inner_eq_zero
(o.inner_eq_zero_of_oangle_eq_pi_div_two h)]
#align orientation.oangle_add_right_eq_arccos_of_oangle_eq_pi_div_two Orientation.oangle_add_right_eq_arccos_of_oangle_eq_pi_div_two
/-- An angle in a right-angled triangle expressed using `arccos`. -/
theorem oangle_add_left_eq_arccos_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
o.oangle (x + y) y = Real.arccos (‖y‖ / ‖x + y‖) :=
by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h⊢
rw [add_comm]
exact (-o).oangle_add_right_eq_arccos_of_oangle_eq_pi_div_two h
#align orientation.oangle_add_left_eq_arccos_of_oangle_eq_pi_div_two Orientation.oangle_add_left_eq_arccos_of_oangle_eq_pi_div_two
/-- An angle in a right-angled triangle expressed using `arcsin`. -/
theorem oangle_add_right_eq_arcsin_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
o.oangle x (x + y) = Real.arcsin (‖y‖ / ‖x + y‖) :=
by
have hs : (o.oangle x (x + y)).sign = 1 := by
rw [oangle_sign_add_right, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs,
InnerProductGeometry.angle_add_eq_arcsin_of_inner_eq_zero
(o.inner_eq_zero_of_oangle_eq_pi_div_two h)
(Or.inl (o.left_ne_zero_of_oangle_eq_pi_div_two h))]
#align orientation.oangle_add_right_eq_arcsin_of_oangle_eq_pi_div_two Orientation.oangle_add_right_eq_arcsin_of_oangle_eq_pi_div_two
/-- An angle in a right-angled triangle expressed using `arcsin`. -/
theorem oangle_add_left_eq_arcsin_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
o.oangle (x + y) y = Real.arcsin (‖x‖ / ‖x + y‖) :=
by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h⊢
rw [add_comm]
exact (-o).oangle_add_right_eq_arcsin_of_oangle_eq_pi_div_two h
#align orientation.oangle_add_left_eq_arcsin_of_oangle_eq_pi_div_two Orientation.oangle_add_left_eq_arcsin_of_oangle_eq_pi_div_two
/-- An angle in a right-angled triangle expressed using `arctan`. -/
theorem oangle_add_right_eq_arctan_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
o.oangle x (x + y) = Real.arctan (‖y‖ / ‖x‖) :=
by
have hs : (o.oangle x (x + y)).sign = 1 := by
rw [oangle_sign_add_right, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs,
InnerProductGeometry.angle_add_eq_arctan_of_inner_eq_zero
(o.inner_eq_zero_of_oangle_eq_pi_div_two h) (o.left_ne_zero_of_oangle_eq_pi_div_two h)]
#align orientation.oangle_add_right_eq_arctan_of_oangle_eq_pi_div_two Orientation.oangle_add_right_eq_arctan_of_oangle_eq_pi_div_two
/-- An angle in a right-angled triangle expressed using `arctan`. -/
theorem oangle_add_left_eq_arctan_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
o.oangle (x + y) y = Real.arctan (‖x‖ / ‖y‖) :=
by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h⊢
rw [add_comm]
exact (-o).oangle_add_right_eq_arctan_of_oangle_eq_pi_div_two h
#align orientation.oangle_add_left_eq_arctan_of_oangle_eq_pi_div_two Orientation.oangle_add_left_eq_arctan_of_oangle_eq_pi_div_two
/-- The cosine of an angle in a right-angled triangle as a ratio of sides. -/
theorem cos_oangle_add_right_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
Real.Angle.cos (o.oangle x (x + y)) = ‖x‖ / ‖x + y‖ :=
by
have hs : (o.oangle x (x + y)).sign = 1 := by
rw [oangle_sign_add_right, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs, Real.Angle.cos_coe,
InnerProductGeometry.cos_angle_add_of_inner_eq_zero (o.inner_eq_zero_of_oangle_eq_pi_div_two h)]
#align orientation.cos_oangle_add_right_of_oangle_eq_pi_div_two Orientation.cos_oangle_add_right_of_oangle_eq_pi_div_two
/-- The cosine of an angle in a right-angled triangle as a ratio of sides. -/
theorem cos_oangle_add_left_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
Real.Angle.cos (o.oangle (x + y) y) = ‖y‖ / ‖x + y‖ :=
by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h⊢
rw [add_comm]
exact (-o).cos_oangle_add_right_of_oangle_eq_pi_div_two h
#align orientation.cos_oangle_add_left_of_oangle_eq_pi_div_two Orientation.cos_oangle_add_left_of_oangle_eq_pi_div_two
/-- The sine of an angle in a right-angled triangle as a ratio of sides. -/
theorem sin_oangle_add_right_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
Real.Angle.sin (o.oangle x (x + y)) = ‖y‖ / ‖x + y‖ :=
by
have hs : (o.oangle x (x + y)).sign = 1 := by
rw [oangle_sign_add_right, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs, Real.Angle.sin_coe,
InnerProductGeometry.sin_angle_add_of_inner_eq_zero (o.inner_eq_zero_of_oangle_eq_pi_div_two h)
(Or.inl (o.left_ne_zero_of_oangle_eq_pi_div_two h))]
#align orientation.sin_oangle_add_right_of_oangle_eq_pi_div_two Orientation.sin_oangle_add_right_of_oangle_eq_pi_div_two
/-- The sine of an angle in a right-angled triangle as a ratio of sides. -/
theorem sin_oangle_add_left_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
Real.Angle.sin (o.oangle (x + y) y) = ‖x‖ / ‖x + y‖ :=
by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h⊢
rw [add_comm]
exact (-o).sin_oangle_add_right_of_oangle_eq_pi_div_two h
#align orientation.sin_oangle_add_left_of_oangle_eq_pi_div_two Orientation.sin_oangle_add_left_of_oangle_eq_pi_div_two
/-- The tangent of an angle in a right-angled triangle as a ratio of sides. -/
theorem tan_oangle_add_right_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
Real.Angle.tan (o.oangle x (x + y)) = ‖y‖ / ‖x‖ :=
by
have hs : (o.oangle x (x + y)).sign = 1 := by
rw [oangle_sign_add_right, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs, Real.Angle.tan_coe,
InnerProductGeometry.tan_angle_add_of_inner_eq_zero (o.inner_eq_zero_of_oangle_eq_pi_div_two h)]
#align orientation.tan_oangle_add_right_of_oangle_eq_pi_div_two Orientation.tan_oangle_add_right_of_oangle_eq_pi_div_two
/-- The tangent of an angle in a right-angled triangle as a ratio of sides. -/
theorem tan_oangle_add_left_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
Real.Angle.tan (o.oangle (x + y) y) = ‖x‖ / ‖y‖ :=
by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h⊢
rw [add_comm]
exact (-o).tan_oangle_add_right_of_oangle_eq_pi_div_two h
#align orientation.tan_oangle_add_left_of_oangle_eq_pi_div_two Orientation.tan_oangle_add_left_of_oangle_eq_pi_div_two
/-- The cosine of an angle in a right-angled triangle multiplied by the hypotenuse equals the
adjacent side. -/
theorem cos_oangle_add_right_mul_norm_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : Real.Angle.cos (o.oangle x (x + y)) * ‖x + y‖ = ‖x‖ :=
by
have hs : (o.oangle x (x + y)).sign = 1 := by
rw [oangle_sign_add_right, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs, Real.Angle.cos_coe,
InnerProductGeometry.cos_angle_add_mul_norm_of_inner_eq_zero
(o.inner_eq_zero_of_oangle_eq_pi_div_two h)]
#align orientation.cos_oangle_add_right_mul_norm_of_oangle_eq_pi_div_two Orientation.cos_oangle_add_right_mul_norm_of_oangle_eq_pi_div_two
/-- The cosine of an angle in a right-angled triangle multiplied by the hypotenuse equals the
adjacent side. -/
theorem cos_oangle_add_left_mul_norm_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : Real.Angle.cos (o.oangle (x + y) y) * ‖x + y‖ = ‖y‖ :=
by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h⊢
rw [add_comm]
exact (-o).cos_oangle_add_right_mul_norm_of_oangle_eq_pi_div_two h
#align orientation.cos_oangle_add_left_mul_norm_of_oangle_eq_pi_div_two Orientation.cos_oangle_add_left_mul_norm_of_oangle_eq_pi_div_two
/-- The sine of an angle in a right-angled triangle multiplied by the hypotenuse equals the
opposite side. -/
theorem sin_oangle_add_right_mul_norm_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : Real.Angle.sin (o.oangle x (x + y)) * ‖x + y‖ = ‖y‖ :=
by
have hs : (o.oangle x (x + y)).sign = 1 := by
rw [oangle_sign_add_right, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs, Real.Angle.sin_coe,
InnerProductGeometry.sin_angle_add_mul_norm_of_inner_eq_zero
(o.inner_eq_zero_of_oangle_eq_pi_div_two h)]
#align orientation.sin_oangle_add_right_mul_norm_of_oangle_eq_pi_div_two Orientation.sin_oangle_add_right_mul_norm_of_oangle_eq_pi_div_two
/-- The sine of an angle in a right-angled triangle multiplied by the hypotenuse equals the
opposite side. -/
theorem sin_oangle_add_left_mul_norm_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : Real.Angle.sin (o.oangle (x + y) y) * ‖x + y‖ = ‖x‖ :=
by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h⊢
rw [add_comm]
exact (-o).sin_oangle_add_right_mul_norm_of_oangle_eq_pi_div_two h
#align orientation.sin_oangle_add_left_mul_norm_of_oangle_eq_pi_div_two Orientation.sin_oangle_add_left_mul_norm_of_oangle_eq_pi_div_two
/-- The tangent of an angle in a right-angled triangle multiplied by the adjacent side equals
the opposite side. -/
theorem tan_oangle_add_right_mul_norm_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : Real.Angle.tan (o.oangle x (x + y)) * ‖x‖ = ‖y‖ :=
by
have hs : (o.oangle x (x + y)).sign = 1 := by
rw [oangle_sign_add_right, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs, Real.Angle.tan_coe,
InnerProductGeometry.tan_angle_add_mul_norm_of_inner_eq_zero
(o.inner_eq_zero_of_oangle_eq_pi_div_two h)
(Or.inl (o.left_ne_zero_of_oangle_eq_pi_div_two h))]
#align orientation.tan_oangle_add_right_mul_norm_of_oangle_eq_pi_div_two Orientation.tan_oangle_add_right_mul_norm_of_oangle_eq_pi_div_two
/-- The tangent of an angle in a right-angled triangle multiplied by the adjacent side equals
the opposite side. -/
theorem tan_oangle_add_left_mul_norm_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : Real.Angle.tan (o.oangle (x + y) y) * ‖y‖ = ‖x‖ :=
by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h⊢
rw [add_comm]
exact (-o).tan_oangle_add_right_mul_norm_of_oangle_eq_pi_div_two h
#align orientation.tan_oangle_add_left_mul_norm_of_oangle_eq_pi_div_two Orientation.tan_oangle_add_left_mul_norm_of_oangle_eq_pi_div_two
/-- A side of a right-angled triangle divided by the cosine of the adjacent angle equals the
hypotenuse. -/
theorem norm_div_cos_oangle_add_right_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : ‖x‖ / Real.Angle.cos (o.oangle x (x + y)) = ‖x + y‖ :=
by
have hs : (o.oangle x (x + y)).sign = 1 := by
rw [oangle_sign_add_right, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs, Real.Angle.cos_coe,
InnerProductGeometry.norm_div_cos_angle_add_of_inner_eq_zero
(o.inner_eq_zero_of_oangle_eq_pi_div_two h)
(Or.inl (o.left_ne_zero_of_oangle_eq_pi_div_two h))]
#align orientation.norm_div_cos_oangle_add_right_of_oangle_eq_pi_div_two Orientation.norm_div_cos_oangle_add_right_of_oangle_eq_pi_div_two
/-- A side of a right-angled triangle divided by the cosine of the adjacent angle equals the
hypotenuse. -/
theorem norm_div_cos_oangle_add_left_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : ‖y‖ / Real.Angle.cos (o.oangle (x + y) y) = ‖x + y‖ :=
by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h⊢
rw [add_comm]
exact (-o).norm_div_cos_oangle_add_right_of_oangle_eq_pi_div_two h
#align orientation.norm_div_cos_oangle_add_left_of_oangle_eq_pi_div_two Orientation.norm_div_cos_oangle_add_left_of_oangle_eq_pi_div_two
/-- A side of a right-angled triangle divided by the sine of the opposite angle equals the
hypotenuse. -/
theorem norm_div_sin_oangle_add_right_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : ‖y‖ / Real.Angle.sin (o.oangle x (x + y)) = ‖x + y‖ :=
by
have hs : (o.oangle x (x + y)).sign = 1 := by
rw [oangle_sign_add_right, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs, Real.Angle.sin_coe,
InnerProductGeometry.norm_div_sin_angle_add_of_inner_eq_zero
(o.inner_eq_zero_of_oangle_eq_pi_div_two h)
(Or.inr (o.right_ne_zero_of_oangle_eq_pi_div_two h))]
#align orientation.norm_div_sin_oangle_add_right_of_oangle_eq_pi_div_two Orientation.norm_div_sin_oangle_add_right_of_oangle_eq_pi_div_two
/-- A side of a right-angled triangle divided by the sine of the opposite angle equals the
hypotenuse. -/
theorem norm_div_sin_oangle_add_left_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : ‖x‖ / Real.Angle.sin (o.oangle (x + y) y) = ‖x + y‖ :=
by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h⊢
rw [add_comm]
exact (-o).norm_div_sin_oangle_add_right_of_oangle_eq_pi_div_two h
#align orientation.norm_div_sin_oangle_add_left_of_oangle_eq_pi_div_two Orientation.norm_div_sin_oangle_add_left_of_oangle_eq_pi_div_two
/-- A side of a right-angled triangle divided by the tangent of the opposite angle equals the
adjacent side. -/
theorem norm_div_tan_oangle_add_right_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : ‖y‖ / Real.Angle.tan (o.oangle x (x + y)) = ‖x‖ :=
by
have hs : (o.oangle x (x + y)).sign = 1 := by
rw [oangle_sign_add_right, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs, Real.Angle.tan_coe,
InnerProductGeometry.norm_div_tan_angle_add_of_inner_eq_zero
(o.inner_eq_zero_of_oangle_eq_pi_div_two h)
(Or.inr (o.right_ne_zero_of_oangle_eq_pi_div_two h))]
#align orientation.norm_div_tan_oangle_add_right_of_oangle_eq_pi_div_two Orientation.norm_div_tan_oangle_add_right_of_oangle_eq_pi_div_two
/-- A side of a right-angled triangle divided by the tangent of the opposite angle equals the
adjacent side. -/
theorem norm_div_tan_oangle_add_left_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : ‖x‖ / Real.Angle.tan (o.oangle (x + y) y) = ‖y‖ :=
by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h⊢
rw [add_comm]
exact (-o).norm_div_tan_oangle_add_right_of_oangle_eq_pi_div_two h
#align orientation.norm_div_tan_oangle_add_left_of_oangle_eq_pi_div_two Orientation.norm_div_tan_oangle_add_left_of_oangle_eq_pi_div_two
/-- An angle in a right-angled triangle expressed using `arccos`, version subtracting vectors. -/
theorem oangle_sub_right_eq_arccos_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
o.oangle y (y - x) = Real.arccos (‖y‖ / ‖y - x‖) :=
by
have hs : (o.oangle y (y - x)).sign = 1 := by
rw [oangle_sign_sub_right_swap, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs,
InnerProductGeometry.angle_sub_eq_arccos_of_inner_eq_zero
(o.inner_rev_eq_zero_of_oangle_eq_pi_div_two h)]
#align orientation.oangle_sub_right_eq_arccos_of_oangle_eq_pi_div_two Orientation.oangle_sub_right_eq_arccos_of_oangle_eq_pi_div_two
/-- An angle in a right-angled triangle expressed using `arccos`, version subtracting vectors. -/
theorem oangle_sub_left_eq_arccos_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
o.oangle (x - y) x = Real.arccos (‖x‖ / ‖x - y‖) :=
by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h⊢
exact (-o).oangle_sub_right_eq_arccos_of_oangle_eq_pi_div_two h
#align orientation.oangle_sub_left_eq_arccos_of_oangle_eq_pi_div_two Orientation.oangle_sub_left_eq_arccos_of_oangle_eq_pi_div_two
/-- An angle in a right-angled triangle expressed using `arcsin`, version subtracting vectors. -/
theorem oangle_sub_right_eq_arcsin_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
o.oangle y (y - x) = Real.arcsin (‖x‖ / ‖y - x‖) :=
by
have hs : (o.oangle y (y - x)).sign = 1 := by
rw [oangle_sign_sub_right_swap, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs,
InnerProductGeometry.angle_sub_eq_arcsin_of_inner_eq_zero
(o.inner_rev_eq_zero_of_oangle_eq_pi_div_two h)
(Or.inl (o.right_ne_zero_of_oangle_eq_pi_div_two h))]
#align orientation.oangle_sub_right_eq_arcsin_of_oangle_eq_pi_div_two Orientation.oangle_sub_right_eq_arcsin_of_oangle_eq_pi_div_two
/-- An angle in a right-angled triangle expressed using `arcsin`, version subtracting vectors. -/
theorem oangle_sub_left_eq_arcsin_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
o.oangle (x - y) x = Real.arcsin (‖y‖ / ‖x - y‖) :=
by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h⊢
exact (-o).oangle_sub_right_eq_arcsin_of_oangle_eq_pi_div_two h
#align orientation.oangle_sub_left_eq_arcsin_of_oangle_eq_pi_div_two Orientation.oangle_sub_left_eq_arcsin_of_oangle_eq_pi_div_two
/-- An angle in a right-angled triangle expressed using `arctan`, version subtracting vectors. -/
theorem oangle_sub_right_eq_arctan_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
o.oangle y (y - x) = Real.arctan (‖x‖ / ‖y‖) :=
by
have hs : (o.oangle y (y - x)).sign = 1 := by
rw [oangle_sign_sub_right_swap, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs,
InnerProductGeometry.angle_sub_eq_arctan_of_inner_eq_zero
(o.inner_rev_eq_zero_of_oangle_eq_pi_div_two h) (o.right_ne_zero_of_oangle_eq_pi_div_two h)]
#align orientation.oangle_sub_right_eq_arctan_of_oangle_eq_pi_div_two Orientation.oangle_sub_right_eq_arctan_of_oangle_eq_pi_div_two
/-- An angle in a right-angled triangle expressed using `arctan`, version subtracting vectors. -/
theorem oangle_sub_left_eq_arctan_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
o.oangle (x - y) x = Real.arctan (‖y‖ / ‖x‖) :=
by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h⊢
exact (-o).oangle_sub_right_eq_arctan_of_oangle_eq_pi_div_two h
#align orientation.oangle_sub_left_eq_arctan_of_oangle_eq_pi_div_two Orientation.oangle_sub_left_eq_arctan_of_oangle_eq_pi_div_two
/-- The cosine of an angle in a right-angled triangle as a ratio of sides, version subtracting
vectors. -/
theorem cos_oangle_sub_right_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
Real.Angle.cos (o.oangle y (y - x)) = ‖y‖ / ‖y - x‖ :=
by
have hs : (o.oangle y (y - x)).sign = 1 := by
rw [oangle_sign_sub_right_swap, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs, Real.Angle.cos_coe,
InnerProductGeometry.cos_angle_sub_of_inner_eq_zero
(o.inner_rev_eq_zero_of_oangle_eq_pi_div_two h)]
#align orientation.cos_oangle_sub_right_of_oangle_eq_pi_div_two Orientation.cos_oangle_sub_right_of_oangle_eq_pi_div_two
/-- The cosine of an angle in a right-angled triangle as a ratio of sides, version subtracting
vectors. -/
theorem cos_oangle_sub_left_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
Real.Angle.cos (o.oangle (x - y) x) = ‖x‖ / ‖x - y‖ :=
by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h⊢
exact (-o).cos_oangle_sub_right_of_oangle_eq_pi_div_two h
#align orientation.cos_oangle_sub_left_of_oangle_eq_pi_div_two Orientation.cos_oangle_sub_left_of_oangle_eq_pi_div_two
/-- The sine of an angle in a right-angled triangle as a ratio of sides, version subtracting
vectors. -/
theorem sin_oangle_sub_right_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
Real.Angle.sin (o.oangle y (y - x)) = ‖x‖ / ‖y - x‖ :=
by
have hs : (o.oangle y (y - x)).sign = 1 := by
rw [oangle_sign_sub_right_swap, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs, Real.Angle.sin_coe,
InnerProductGeometry.sin_angle_sub_of_inner_eq_zero
(o.inner_rev_eq_zero_of_oangle_eq_pi_div_two h)
(Or.inl (o.right_ne_zero_of_oangle_eq_pi_div_two h))]
#align orientation.sin_oangle_sub_right_of_oangle_eq_pi_div_two Orientation.sin_oangle_sub_right_of_oangle_eq_pi_div_two
/-- The sine of an angle in a right-angled triangle as a ratio of sides, version subtracting
vectors. -/
theorem sin_oangle_sub_left_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
Real.Angle.sin (o.oangle (x - y) x) = ‖y‖ / ‖x - y‖ :=
by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h⊢
exact (-o).sin_oangle_sub_right_of_oangle_eq_pi_div_two h
#align orientation.sin_oangle_sub_left_of_oangle_eq_pi_div_two Orientation.sin_oangle_sub_left_of_oangle_eq_pi_div_two
/-- The tangent of an angle in a right-angled triangle as a ratio of sides, version subtracting
vectors. -/
theorem tan_oangle_sub_right_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
Real.Angle.tan (o.oangle y (y - x)) = ‖x‖ / ‖y‖ :=
by
have hs : (o.oangle y (y - x)).sign = 1 := by
rw [oangle_sign_sub_right_swap, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs, Real.Angle.tan_coe,
InnerProductGeometry.tan_angle_sub_of_inner_eq_zero
(o.inner_rev_eq_zero_of_oangle_eq_pi_div_two h)]
#align orientation.tan_oangle_sub_right_of_oangle_eq_pi_div_two Orientation.tan_oangle_sub_right_of_oangle_eq_pi_div_two
/-- The tangent of an angle in a right-angled triangle as a ratio of sides, version subtracting
vectors. -/
theorem tan_oangle_sub_left_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
Real.Angle.tan (o.oangle (x - y) x) = ‖y‖ / ‖x‖ :=
by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h⊢
exact (-o).tan_oangle_sub_right_of_oangle_eq_pi_div_two h
#align orientation.tan_oangle_sub_left_of_oangle_eq_pi_div_two Orientation.tan_oangle_sub_left_of_oangle_eq_pi_div_two
/-- The cosine of an angle in a right-angled triangle multiplied by the hypotenuse equals the
adjacent side, version subtracting vectors. -/
theorem cos_oangle_sub_right_mul_norm_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : Real.Angle.cos (o.oangle y (y - x)) * ‖y - x‖ = ‖y‖ :=
by
have hs : (o.oangle y (y - x)).sign = 1 := by
rw [oangle_sign_sub_right_swap, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs, Real.Angle.cos_coe,
InnerProductGeometry.cos_angle_sub_mul_norm_of_inner_eq_zero
(o.inner_rev_eq_zero_of_oangle_eq_pi_div_two h)]
#align orientation.cos_oangle_sub_right_mul_norm_of_oangle_eq_pi_div_two Orientation.cos_oangle_sub_right_mul_norm_of_oangle_eq_pi_div_two
/-- The cosine of an angle in a right-angled triangle multiplied by the hypotenuse equals the
adjacent side, version subtracting vectors. -/
theorem cos_oangle_sub_left_mul_norm_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : Real.Angle.cos (o.oangle (x - y) x) * ‖x - y‖ = ‖x‖ :=
by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h⊢
exact (-o).cos_oangle_sub_right_mul_norm_of_oangle_eq_pi_div_two h
#align orientation.cos_oangle_sub_left_mul_norm_of_oangle_eq_pi_div_two Orientation.cos_oangle_sub_left_mul_norm_of_oangle_eq_pi_div_two
/-- The sine of an angle in a right-angled triangle multiplied by the hypotenuse equals the
opposite side, version subtracting vectors. -/
theorem sin_oangle_sub_right_mul_norm_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : Real.Angle.sin (o.oangle y (y - x)) * ‖y - x‖ = ‖x‖ :=
by
have hs : (o.oangle y (y - x)).sign = 1 := by
rw [oangle_sign_sub_right_swap, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs, Real.Angle.sin_coe,
InnerProductGeometry.sin_angle_sub_mul_norm_of_inner_eq_zero
(o.inner_rev_eq_zero_of_oangle_eq_pi_div_two h)]
#align orientation.sin_oangle_sub_right_mul_norm_of_oangle_eq_pi_div_two Orientation.sin_oangle_sub_right_mul_norm_of_oangle_eq_pi_div_two
/-- The sine of an angle in a right-angled triangle multiplied by the hypotenuse equals the
opposite side, version subtracting vectors. -/
theorem sin_oangle_sub_left_mul_norm_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : Real.Angle.sin (o.oangle (x - y) x) * ‖x - y‖ = ‖y‖ :=
by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h⊢
exact (-o).sin_oangle_sub_right_mul_norm_of_oangle_eq_pi_div_two h
#align orientation.sin_oangle_sub_left_mul_norm_of_oangle_eq_pi_div_two Orientation.sin_oangle_sub_left_mul_norm_of_oangle_eq_pi_div_two
/-- The tangent of an angle in a right-angled triangle multiplied by the adjacent side equals
the opposite side, version subtracting vectors. -/
theorem tan_oangle_sub_right_mul_norm_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : Real.Angle.tan (o.oangle y (y - x)) * ‖y‖ = ‖x‖ :=
by
have hs : (o.oangle y (y - x)).sign = 1 := by
rw [oangle_sign_sub_right_swap, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs, Real.Angle.tan_coe,
InnerProductGeometry.tan_angle_sub_mul_norm_of_inner_eq_zero
(o.inner_rev_eq_zero_of_oangle_eq_pi_div_two h)
(Or.inl (o.right_ne_zero_of_oangle_eq_pi_div_two h))]
#align orientation.tan_oangle_sub_right_mul_norm_of_oangle_eq_pi_div_two Orientation.tan_oangle_sub_right_mul_norm_of_oangle_eq_pi_div_two
/-- The tangent of an angle in a right-angled triangle multiplied by the adjacent side equals
the opposite side, version subtracting vectors. -/
theorem tan_oangle_sub_left_mul_norm_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : Real.Angle.tan (o.oangle (x - y) x) * ‖x‖ = ‖y‖ :=
by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h⊢
exact (-o).tan_oangle_sub_right_mul_norm_of_oangle_eq_pi_div_two h
#align orientation.tan_oangle_sub_left_mul_norm_of_oangle_eq_pi_div_two Orientation.tan_oangle_sub_left_mul_norm_of_oangle_eq_pi_div_two
/-- A side of a right-angled triangle divided by the cosine of the adjacent angle equals the
hypotenuse, version subtracting vectors. -/
theorem norm_div_cos_oangle_sub_right_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : ‖y‖ / Real.Angle.cos (o.oangle y (y - x)) = ‖y - x‖ :=
by
have hs : (o.oangle y (y - x)).sign = 1 := by
rw [oangle_sign_sub_right_swap, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs, Real.Angle.cos_coe,
InnerProductGeometry.norm_div_cos_angle_sub_of_inner_eq_zero
(o.inner_rev_eq_zero_of_oangle_eq_pi_div_two h)
(Or.inl (o.right_ne_zero_of_oangle_eq_pi_div_two h))]
#align orientation.norm_div_cos_oangle_sub_right_of_oangle_eq_pi_div_two Orientation.norm_div_cos_oangle_sub_right_of_oangle_eq_pi_div_two
/-- A side of a right-angled triangle divided by the cosine of the adjacent angle equals the
hypotenuse, version subtracting vectors. -/
theorem norm_div_cos_oangle_sub_left_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : ‖x‖ / Real.Angle.cos (o.oangle (x - y) x) = ‖x - y‖ :=
by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h⊢
exact (-o).norm_div_cos_oangle_sub_right_of_oangle_eq_pi_div_two h
#align orientation.norm_div_cos_oangle_sub_left_of_oangle_eq_pi_div_two Orientation.norm_div_cos_oangle_sub_left_of_oangle_eq_pi_div_two
/-- A side of a right-angled triangle divided by the sine of the opposite angle equals the
hypotenuse, version subtracting vectors. -/
theorem norm_div_sin_oangle_sub_right_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : ‖x‖ / Real.Angle.sin (o.oangle y (y - x)) = ‖y - x‖ :=
by
have hs : (o.oangle y (y - x)).sign = 1 := by
rw [oangle_sign_sub_right_swap, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs, Real.Angle.sin_coe,
InnerProductGeometry.norm_div_sin_angle_sub_of_inner_eq_zero
(o.inner_rev_eq_zero_of_oangle_eq_pi_div_two h)
(Or.inr (o.left_ne_zero_of_oangle_eq_pi_div_two h))]
#align orientation.norm_div_sin_oangle_sub_right_of_oangle_eq_pi_div_two Orientation.norm_div_sin_oangle_sub_right_of_oangle_eq_pi_div_two
/-- A side of a right-angled triangle divided by the sine of the opposite angle equals the
hypotenuse, version subtracting vectors. -/
theorem norm_div_sin_oangle_sub_left_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : ‖y‖ / Real.Angle.sin (o.oangle (x - y) x) = ‖x - y‖ :=
by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h⊢
exact (-o).norm_div_sin_oangle_sub_right_of_oangle_eq_pi_div_two h
#align orientation.norm_div_sin_oangle_sub_left_of_oangle_eq_pi_div_two Orientation.norm_div_sin_oangle_sub_left_of_oangle_eq_pi_div_two
/-- A side of a right-angled triangle divided by the tangent of the opposite angle equals the
adjacent side, version subtracting vectors. -/
theorem norm_div_tan_oangle_sub_right_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : ‖x‖ / Real.Angle.tan (o.oangle y (y - x)) = ‖y‖ :=
by
have hs : (o.oangle y (y - x)).sign = 1 := by
rw [oangle_sign_sub_right_swap, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs, Real.Angle.tan_coe,
InnerProductGeometry.norm_div_tan_angle_sub_of_inner_eq_zero
(o.inner_rev_eq_zero_of_oangle_eq_pi_div_two h)
(Or.inr (o.left_ne_zero_of_oangle_eq_pi_div_two h))]
#align orientation.norm_div_tan_oangle_sub_right_of_oangle_eq_pi_div_two Orientation.norm_div_tan_oangle_sub_right_of_oangle_eq_pi_div_two
/-- A side of a right-angled triangle divided by the tangent of the opposite angle equals the
adjacent side, version subtracting vectors. -/
theorem norm_div_tan_oangle_sub_left_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : ‖y‖ / Real.Angle.tan (o.oangle (x - y) x) = ‖x‖ :=
by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h⊢
exact (-o).norm_div_tan_oangle_sub_right_of_oangle_eq_pi_div_two h
#align orientation.norm_div_tan_oangle_sub_left_of_oangle_eq_pi_div_two Orientation.norm_div_tan_oangle_sub_left_of_oangle_eq_pi_div_two
/-- An angle in a right-angled triangle expressed using `arctan`, where one side is a multiple
of a rotation of another by `π / 2`. -/
theorem oangle_add_right_smul_rotation_pi_div_two {x : V} (h : x ≠ 0) (r : ℝ) :
o.oangle x (x + r • o.rotation (π / 2 : ℝ) x) = Real.arctan r :=
by
rcases lt_trichotomy r 0 with (hr | rfl | hr)
· have ha : o.oangle x (r • o.rotation (π / 2 : ℝ) x) = -(π / 2 : ℝ) :=
by
rw [o.oangle_smul_right_of_neg _ _ hr, o.oangle_neg_right h, o.oangle_rotation_self_right h, ←
sub_eq_zero, add_comm, sub_neg_eq_add, ← Real.Angle.coe_add, ← Real.Angle.coe_add,
add_assoc, add_halves, ← two_mul, Real.Angle.coe_two_pi]
simpa using h
rw [← neg_inj, ← oangle_neg_orientation_eq_neg, neg_neg] at ha
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj, oangle_rev,
(-o).oangle_add_right_eq_arctan_of_oangle_eq_pi_div_two ha, norm_smul,
LinearIsometryEquiv.norm_map, mul_div_assoc, div_self (norm_ne_zero_iff.2 h), mul_one,
Real.norm_eq_abs, abs_of_neg hr, Real.arctan_neg, Real.Angle.coe_neg, neg_neg]
· rw [zero_smul, add_zero, oangle_self, Real.arctan_zero, Real.Angle.coe_zero]
· have ha : o.oangle x (r • o.rotation (π / 2 : ℝ) x) = (π / 2 : ℝ) := by
rw [o.oangle_smul_right_of_pos _ _ hr, o.oangle_rotation_self_right h]
rw [o.oangle_add_right_eq_arctan_of_oangle_eq_pi_div_two ha, norm_smul,
LinearIsometryEquiv.norm_map, mul_div_assoc, div_self (norm_ne_zero_iff.2 h), mul_one,
Real.norm_eq_abs, abs_of_pos hr]
#align orientation.oangle_add_right_smul_rotation_pi_div_two Orientation.oangle_add_right_smul_rotation_pi_div_two
/-- An angle in a right-angled triangle expressed using `arctan`, where one side is a multiple
of a rotation of another by `π / 2`. -/
theorem oangle_add_left_smul_rotation_pi_div_two {x : V} (h : x ≠ 0) (r : ℝ) :
o.oangle (x + r • o.rotation (π / 2 : ℝ) x) (r • o.rotation (π / 2 : ℝ) x) = Real.arctan r⁻¹ :=
by
by_cases hr : r = 0
· simp [hr]
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj, ←
neg_neg ((π / 2 : ℝ) : Real.Angle), ← rotation_neg_orientation_eq_neg, add_comm]
have hx : x = r⁻¹ • (-o).rotation (π / 2 : ℝ) (r • (-o).rotation (-(π / 2 : ℝ)) x) := by simp [hr]
nth_rw 3 [hx]
refine' (-o).oangle_add_right_smul_rotation_pi_div_two _ _
simp [hr, h]
#align orientation.oangle_add_left_smul_rotation_pi_div_two Orientation.oangle_add_left_smul_rotation_pi_div_two
/-- The tangent of an angle in a right-angled triangle, where one side is a multiple of a
rotation of another by `π / 2`. -/
theorem tan_oangle_add_right_smul_rotation_pi_div_two {x : V} (h : x ≠ 0) (r : ℝ) :
Real.Angle.tan (o.oangle x (x + r • o.rotation (π / 2 : ℝ) x)) = r := by
rw [o.oangle_add_right_smul_rotation_pi_div_two h, Real.Angle.tan_coe, Real.tan_arctan]
#align orientation.tan_oangle_add_right_smul_rotation_pi_div_two Orientation.tan_oangle_add_right_smul_rotation_pi_div_two
/-- The tangent of an angle in a right-angled triangle, where one side is a multiple of a
rotation of another by `π / 2`. -/
theorem tan_oangle_add_left_smul_rotation_pi_div_two {x : V} (h : x ≠ 0) (r : ℝ) :
Real.Angle.tan (o.oangle (x + r • o.rotation (π / 2 : ℝ) x) (r • o.rotation (π / 2 : ℝ) x)) =
r⁻¹ :=
by rw [o.oangle_add_left_smul_rotation_pi_div_two h, Real.Angle.tan_coe, Real.tan_arctan]
#align orientation.tan_oangle_add_left_smul_rotation_pi_div_two Orientation.tan_oangle_add_left_smul_rotation_pi_div_two
/-- An angle in a right-angled triangle expressed using `arctan`, where one side is a multiple
of a rotation of another by `π / 2`, version subtracting vectors. -/
theorem oangle_sub_right_smul_rotation_pi_div_two {x : V} (h : x ≠ 0) (r : ℝ) :
o.oangle (r • o.rotation (π / 2 : ℝ) x) (r • o.rotation (π / 2 : ℝ) x - x) = Real.arctan r⁻¹ :=
by
by_cases hr : r = 0
· simp [hr]
have hx : -x = r⁻¹ • o.rotation (π / 2 : ℝ) (r • o.rotation (π / 2 : ℝ) x) := by
simp [hr, ← Real.Angle.coe_add]
rw [sub_eq_add_neg, hx, o.oangle_add_right_smul_rotation_pi_div_two]
simpa [hr] using h
#align orientation.oangle_sub_right_smul_rotation_pi_div_two Orientation.oangle_sub_right_smul_rotation_pi_div_two
/-- An angle in a right-angled triangle expressed using `arctan`, where one side is a multiple
of a rotation of another by `π / 2`, version subtracting vectors. -/
theorem oangle_sub_left_smul_rotation_pi_div_two {x : V} (h : x ≠ 0) (r : ℝ) :
o.oangle (x - r • o.rotation (π / 2 : ℝ) x) x = Real.arctan r :=
by
by_cases hr : r = 0
· simp [hr]
have hx : x = r⁻¹ • o.rotation (π / 2 : ℝ) (-(r • o.rotation (π / 2 : ℝ) x)) := by
simp [hr, ← Real.Angle.coe_add]
rw [sub_eq_add_neg, add_comm]
nth_rw 3 [hx]
nth_rw 2 [hx]
rw [o.oangle_add_left_smul_rotation_pi_div_two, inv_inv]
simpa [hr] using h
#align orientation.oangle_sub_left_smul_rotation_pi_div_two Orientation.oangle_sub_left_smul_rotation_pi_div_two
end Orientation
namespace EuclideanGeometry
open FiniteDimensional
variable {V : Type _} {P : Type _} [NormedAddCommGroup V] [InnerProductSpace ℝ V] [MetricSpace P]
[NormedAddTorsor V P] [hd2 : Fact (finrank ℝ V = 2)] [Module.Oriented ℝ V (Fin 2)]
include hd2
/-- An angle in a right-angled triangle expressed using `arccos`. -/
theorem oangle_right_eq_arccos_of_oangle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∡ p₁ p₂ p₃ = ↑(π / 2)) :
∡ p₂ p₃ p₁ = Real.arccos (dist p₃ p₂ / dist p₁ p₃) :=
by
have hs : (∡ p₂ p₃ p₁).sign = 1 := by rw [oangle_rotate_sign, h, Real.Angle.sign_coe_pi_div_two]
rw [oangle_eq_angle_of_sign_eq_one hs,
angle_eq_arccos_of_angle_eq_pi_div_two (angle_eq_pi_div_two_of_oangle_eq_pi_div_two h)]
#align euclidean_geometry.oangle_right_eq_arccos_of_oangle_eq_pi_div_two EuclideanGeometry.oangle_right_eq_arccos_of_oangle_eq_pi_div_two
/-- An angle in a right-angled triangle expressed using `arccos`. -/
theorem oangle_left_eq_arccos_of_oangle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∡ p₁ p₂ p₃ = ↑(π / 2)) :
∡ p₃ p₁ p₂ = Real.arccos (dist p₁ p₂ / dist p₁ p₃) :=
by
have hs : (∡ p₃ p₁ p₂).sign = 1 := by rw [← oangle_rotate_sign, h, Real.Angle.sign_coe_pi_div_two]
rw [oangle_eq_angle_of_sign_eq_one hs, angle_comm,
angle_eq_arccos_of_angle_eq_pi_div_two (angle_rev_eq_pi_div_two_of_oangle_eq_pi_div_two h),
dist_comm p₁ p₃]
#align euclidean_geometry.oangle_left_eq_arccos_of_oangle_eq_pi_div_two EuclideanGeometry.oangle_left_eq_arccos_of_oangle_eq_pi_div_two
/-- An angle in a right-angled triangle expressed using `arcsin`. -/
theorem oangle_right_eq_arcsin_of_oangle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∡ p₁ p₂ p₃ = ↑(π / 2)) :
∡ p₂ p₃ p₁ = Real.arcsin (dist p₁ p₂ / dist p₁ p₃) :=
by
have hs : (∡ p₂ p₃ p₁).sign = 1 := by rw [oangle_rotate_sign, h, Real.Angle.sign_coe_pi_div_two]
rw [oangle_eq_angle_of_sign_eq_one hs,
angle_eq_arcsin_of_angle_eq_pi_div_two (angle_eq_pi_div_two_of_oangle_eq_pi_div_two h)
(Or.inl (left_ne_of_oangle_eq_pi_div_two h))]
#align euclidean_geometry.oangle_right_eq_arcsin_of_oangle_eq_pi_div_two EuclideanGeometry.oangle_right_eq_arcsin_of_oangle_eq_pi_div_two
/-- An angle in a right-angled triangle expressed using `arcsin`. -/
theorem oangle_left_eq_arcsin_of_oangle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∡ p₁ p₂ p₃ = ↑(π / 2)) :
∡ p₃ p₁ p₂ = Real.arcsin (dist p₃ p₂ / dist p₁ p₃) :=
by
have hs : (∡ p₃ p₁ p₂).sign = 1 := by rw [← oangle_rotate_sign, h, Real.Angle.sign_coe_pi_div_two]
rw [oangle_eq_angle_of_sign_eq_one hs, angle_comm,
angle_eq_arcsin_of_angle_eq_pi_div_two (angle_rev_eq_pi_div_two_of_oangle_eq_pi_div_two h)
(Or.inr (left_ne_of_oangle_eq_pi_div_two h)),
dist_comm p₁ p₃]
#align euclidean_geometry.oangle_left_eq_arcsin_of_oangle_eq_pi_div_two EuclideanGeometry.oangle_left_eq_arcsin_of_oangle_eq_pi_div_two
/-- An angle in a right-angled triangle expressed using `arctan`. -/
theorem oangle_right_eq_arctan_of_oangle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∡ p₁ p₂ p₃ = ↑(π / 2)) :
∡ p₂ p₃ p₁ = Real.arctan (dist p₁ p₂ / dist p₃ p₂) :=
by
have hs : (∡ p₂ p₃ p₁).sign = 1 := by rw [oangle_rotate_sign, h, Real.Angle.sign_coe_pi_div_two]
rw [oangle_eq_angle_of_sign_eq_one hs,
angle_eq_arctan_of_angle_eq_pi_div_two (angle_eq_pi_div_two_of_oangle_eq_pi_div_two h)
(right_ne_of_oangle_eq_pi_div_two h)]
#align euclidean_geometry.oangle_right_eq_arctan_of_oangle_eq_pi_div_two EuclideanGeometry.oangle_right_eq_arctan_of_oangle_eq_pi_div_two
/-- An angle in a right-angled triangle expressed using `arctan`. -/
theorem oangle_left_eq_arctan_of_oangle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∡ p₁ p₂ p₃ = ↑(π / 2)) :
∡ p₃ p₁ p₂ = Real.arctan (dist p₃ p₂ / dist p₁ p₂) :=
by
have hs : (∡ p₃ p₁ p₂).sign = 1 := by rw [← oangle_rotate_sign, h, Real.Angle.sign_coe_pi_div_two]
rw [oangle_eq_angle_of_sign_eq_one hs, angle_comm,
angle_eq_arctan_of_angle_eq_pi_div_two (angle_rev_eq_pi_div_two_of_oangle_eq_pi_div_two h)
(left_ne_of_oangle_eq_pi_div_two h)]
#align euclidean_geometry.oangle_left_eq_arctan_of_oangle_eq_pi_div_two EuclideanGeometry.oangle_left_eq_arctan_of_oangle_eq_pi_div_two
/-- The cosine of an angle in a right-angled triangle as a ratio of sides. -/
theorem cos_oangle_right_of_oangle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∡ p₁ p₂ p₃ = ↑(π / 2)) :
Real.Angle.cos (∡ p₂ p₃ p₁) = dist p₃ p₂ / dist p₁ p₃ :=
by
have hs : (∡ p₂ p₃ p₁).sign = 1 := by rw [oangle_rotate_sign, h, Real.Angle.sign_coe_pi_div_two]
rw [oangle_eq_angle_of_sign_eq_one hs, Real.Angle.cos_coe,
cos_angle_of_angle_eq_pi_div_two (angle_eq_pi_div_two_of_oangle_eq_pi_div_two h)]
#align euclidean_geometry.cos_oangle_right_of_oangle_eq_pi_div_two EuclideanGeometry.cos_oangle_right_of_oangle_eq_pi_div_two
/-- The cosine of an angle in a right-angled triangle as a ratio of sides. -/
theorem cos_oangle_left_of_oangle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∡ p₁ p₂ p₃ = ↑(π / 2)) :
Real.Angle.cos (∡ p₃ p₁ p₂) = dist p₁ p₂ / dist p₁ p₃ :=
by
have hs : (∡ p₃ p₁ p₂).sign = 1 := by rw [← oangle_rotate_sign, h, Real.Angle.sign_coe_pi_div_two]
rw [oangle_eq_angle_of_sign_eq_one hs, angle_comm, Real.Angle.cos_coe,
cos_angle_of_angle_eq_pi_div_two (angle_rev_eq_pi_div_two_of_oangle_eq_pi_div_two h),
dist_comm p₁ p₃]
#align euclidean_geometry.cos_oangle_left_of_oangle_eq_pi_div_two EuclideanGeometry.cos_oangle_left_of_oangle_eq_pi_div_two
/-- The sine of an angle in a right-angled triangle as a ratio of sides. -/
theorem sin_oangle_right_of_oangle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∡ p₁ p₂ p₃ = ↑(π / 2)) :
Real.Angle.sin (∡ p₂ p₃ p₁) = dist p₁ p₂ / dist p₁ p₃ :=
by
have hs : (∡ p₂ p₃ p₁).sign = 1 := by rw [oangle_rotate_sign, h, Real.Angle.sign_coe_pi_div_two]
rw [oangle_eq_angle_of_sign_eq_one hs, Real.Angle.sin_coe,
sin_angle_of_angle_eq_pi_div_two (angle_eq_pi_div_two_of_oangle_eq_pi_div_two h)
(Or.inl (left_ne_of_oangle_eq_pi_div_two h))]
#align euclidean_geometry.sin_oangle_right_of_oangle_eq_pi_div_two EuclideanGeometry.sin_oangle_right_of_oangle_eq_pi_div_two
/-- The sine of an angle in a right-angled triangle as a ratio of sides. -/
theorem sin_oangle_left_of_oangle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∡ p₁ p₂ p₃ = ↑(π / 2)) :
Real.Angle.sin (∡ p₃ p₁ p₂) = dist p₃ p₂ / dist p₁ p₃ :=
by
have hs : (∡ p₃ p₁ p₂).sign = 1 := by rw [← oangle_rotate_sign, h, Real.Angle.sign_coe_pi_div_two]
rw [oangle_eq_angle_of_sign_eq_one hs, angle_comm, Real.Angle.sin_coe,
sin_angle_of_angle_eq_pi_div_two (angle_rev_eq_pi_div_two_of_oangle_eq_pi_div_two h)
(Or.inr (left_ne_of_oangle_eq_pi_div_two h)),
dist_comm p₁ p₃]
#align euclidean_geometry.sin_oangle_left_of_oangle_eq_pi_div_two EuclideanGeometry.sin_oangle_left_of_oangle_eq_pi_div_two
/-- The tangent of an angle in a right-angled triangle as a ratio of sides. -/
theorem tan_oangle_right_of_oangle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∡ p₁ p₂ p₃ = ↑(π / 2)) :
Real.Angle.tan (∡ p₂ p₃ p₁) = dist p₁ p₂ / dist p₃ p₂ :=
by
have hs : (∡ p₂ p₃ p₁).sign = 1 := by rw [oangle_rotate_sign, h, Real.Angle.sign_coe_pi_div_two]
rw [oangle_eq_angle_of_sign_eq_one hs, Real.Angle.tan_coe,
tan_angle_of_angle_eq_pi_div_two (angle_eq_pi_div_two_of_oangle_eq_pi_div_two h)]
#align euclidean_geometry.tan_oangle_right_of_oangle_eq_pi_div_two EuclideanGeometry.tan_oangle_right_of_oangle_eq_pi_div_two
/-- The tangent of an angle in a right-angled triangle as a ratio of sides. -/
theorem tan_oangle_left_of_oangle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∡ p₁ p₂ p₃ = ↑(π / 2)) :
Real.Angle.tan (∡ p₃ p₁ p₂) = dist p₃ p₂ / dist p₁ p₂ :=
by
have hs : (∡ p₃ p₁ p₂).sign = 1 := by rw [← oangle_rotate_sign, h, Real.Angle.sign_coe_pi_div_two]
rw [oangle_eq_angle_of_sign_eq_one hs, angle_comm, Real.Angle.tan_coe,
tan_angle_of_angle_eq_pi_div_two (angle_rev_eq_pi_div_two_of_oangle_eq_pi_div_two h)]
#align euclidean_geometry.tan_oangle_left_of_oangle_eq_pi_div_two EuclideanGeometry.tan_oangle_left_of_oangle_eq_pi_div_two
/-- The cosine of an angle in a right-angled triangle multiplied by the hypotenuse equals the
adjacent side. -/
theorem cos_oangle_right_mul_dist_of_oangle_eq_pi_div_two {p₁ p₂ p₃ : P}
(h : ∡ p₁ p₂ p₃ = ↑(π / 2)) : Real.Angle.cos (∡ p₂ p₃ p₁) * dist p₁ p₃ = dist p₃ p₂ :=
by
have hs : (∡ p₂ p₃ p₁).sign = 1 := by rw [oangle_rotate_sign, h, Real.Angle.sign_coe_pi_div_two]
rw [oangle_eq_angle_of_sign_eq_one hs, Real.Angle.cos_coe,
cos_angle_mul_dist_of_angle_eq_pi_div_two (angle_eq_pi_div_two_of_oangle_eq_pi_div_two h)]
#align euclidean_geometry.cos_oangle_right_mul_dist_of_oangle_eq_pi_div_two EuclideanGeometry.cos_oangle_right_mul_dist_of_oangle_eq_pi_div_two
/-- The cosine of an angle in a right-angled triangle multiplied by the hypotenuse equals the
adjacent side. -/
theorem cos_oangle_left_mul_dist_of_oangle_eq_pi_div_two {p₁ p₂ p₃ : P}
(h : ∡ p₁ p₂ p₃ = ↑(π / 2)) : Real.Angle.cos (∡ p₃ p₁ p₂) * dist p₁ p₃ = dist p₁ p₂ :=
by
have hs : (∡ p₃ p₁ p₂).sign = 1 := by rw [← oangle_rotate_sign, h, Real.Angle.sign_coe_pi_div_two]
rw [oangle_eq_angle_of_sign_eq_one hs, angle_comm, Real.Angle.cos_coe, dist_comm p₁ p₃,
cos_angle_mul_dist_of_angle_eq_pi_div_two (angle_rev_eq_pi_div_two_of_oangle_eq_pi_div_two h)]
#align euclidean_geometry.cos_oangle_left_mul_dist_of_oangle_eq_pi_div_two EuclideanGeometry.cos_oangle_left_mul_dist_of_oangle_eq_pi_div_two
/-- The sine of an angle in a right-angled triangle multiplied by the hypotenuse equals the
opposite side. -/
theorem sin_oangle_right_mul_dist_of_oangle_eq_pi_div_two {p₁ p₂ p₃ : P}
(h : ∡ p₁ p₂ p₃ = ↑(π / 2)) : Real.Angle.sin (∡ p₂ p₃ p₁) * dist p₁ p₃ = dist p₁ p₂ :=
by
have hs : (∡ p₂ p₃ p₁).sign = 1 := by rw [oangle_rotate_sign, h, Real.Angle.sign_coe_pi_div_two]
rw [oangle_eq_angle_of_sign_eq_one hs, Real.Angle.sin_coe,
sin_angle_mul_dist_of_angle_eq_pi_div_two (angle_eq_pi_div_two_of_oangle_eq_pi_div_two h)]
#align euclidean_geometry.sin_oangle_right_mul_dist_of_oangle_eq_pi_div_two EuclideanGeometry.sin_oangle_right_mul_dist_of_oangle_eq_pi_div_two
/-- The sine of an angle in a right-angled triangle multiplied by the hypotenuse equals the
opposite side. -/
theorem sin_oangle_left_mul_dist_of_oangle_eq_pi_div_two {p₁ p₂ p₃ : P}
(h : ∡ p₁ p₂ p₃ = ↑(π / 2)) : Real.Angle.sin (∡ p₃ p₁ p₂) * dist p₁ p₃ = dist p₃ p₂ :=
by
have hs : (∡ p₃ p₁ p₂).sign = 1 := by rw [← oangle_rotate_sign, h, Real.Angle.sign_coe_pi_div_two]
rw [oangle_eq_angle_of_sign_eq_one hs, angle_comm, Real.Angle.sin_coe, dist_comm p₁ p₃,
sin_angle_mul_dist_of_angle_eq_pi_div_two (angle_rev_eq_pi_div_two_of_oangle_eq_pi_div_two h)]
#align euclidean_geometry.sin_oangle_left_mul_dist_of_oangle_eq_pi_div_two EuclideanGeometry.sin_oangle_left_mul_dist_of_oangle_eq_pi_div_two
/-- The tangent of an angle in a right-angled triangle multiplied by the adjacent side equals
the opposite side. -/
theorem tan_oangle_right_mul_dist_of_oangle_eq_pi_div_two {p₁ p₂ p₃ : P}
(h : ∡ p₁ p₂ p₃ = ↑(π / 2)) : Real.Angle.tan (∡ p₂ p₃ p₁) * dist p₃ p₂ = dist p₁ p₂ :=
by
have hs : (∡ p₂ p₃ p₁).sign = 1 := by rw [oangle_rotate_sign, h, Real.Angle.sign_coe_pi_div_two]
rw [oangle_eq_angle_of_sign_eq_one hs, Real.Angle.tan_coe,
tan_angle_mul_dist_of_angle_eq_pi_div_two (angle_eq_pi_div_two_of_oangle_eq_pi_div_two h)
(Or.inr (right_ne_of_oangle_eq_pi_div_two h))]
#align euclidean_geometry.tan_oangle_right_mul_dist_of_oangle_eq_pi_div_two EuclideanGeometry.tan_oangle_right_mul_dist_of_oangle_eq_pi_div_two
/-- The tangent of an angle in a right-angled triangle multiplied by the adjacent side equals
the opposite side. -/
theorem tan_oangle_left_mul_dist_of_oangle_eq_pi_div_two {p₁ p₂ p₃ : P}
(h : ∡ p₁ p₂ p₃ = ↑(π / 2)) : Real.Angle.tan (∡ p₃ p₁ p₂) * dist p₁ p₂ = dist p₃ p₂ :=
by
have hs : (∡ p₃ p₁ p₂).sign = 1 := by rw [← oangle_rotate_sign, h, Real.Angle.sign_coe_pi_div_two]
rw [oangle_eq_angle_of_sign_eq_one hs, angle_comm, Real.Angle.tan_coe,
tan_angle_mul_dist_of_angle_eq_pi_div_two (angle_rev_eq_pi_div_two_of_oangle_eq_pi_div_two h)
(Or.inr (left_ne_of_oangle_eq_pi_div_two h))]
#align euclidean_geometry.tan_oangle_left_mul_dist_of_oangle_eq_pi_div_two EuclideanGeometry.tan_oangle_left_mul_dist_of_oangle_eq_pi_div_two
/-- A side of a right-angled triangle divided by the cosine of the adjacent angle equals the
hypotenuse. -/
theorem dist_div_cos_oangle_right_of_oangle_eq_pi_div_two {p₁ p₂ p₃ : P}
(h : ∡ p₁ p₂ p₃ = ↑(π / 2)) : dist p₃ p₂ / Real.Angle.cos (∡ p₂ p₃ p₁) = dist p₁ p₃ :=
by
have hs : (∡ p₂ p₃ p₁).sign = 1 := by rw [oangle_rotate_sign, h, Real.Angle.sign_coe_pi_div_two]
rw [oangle_eq_angle_of_sign_eq_one hs, Real.Angle.cos_coe,
dist_div_cos_angle_of_angle_eq_pi_div_two (angle_eq_pi_div_two_of_oangle_eq_pi_div_two h)
(Or.inr (right_ne_of_oangle_eq_pi_div_two h))]
#align euclidean_geometry.dist_div_cos_oangle_right_of_oangle_eq_pi_div_two EuclideanGeometry.dist_div_cos_oangle_right_of_oangle_eq_pi_div_two
/-- A side of a right-angled triangle divided by the cosine of the adjacent angle equals the
hypotenuse. -/
theorem dist_div_cos_oangle_left_of_oangle_eq_pi_div_two {p₁ p₂ p₃ : P}
(h : ∡ p₁ p₂ p₃ = ↑(π / 2)) : dist p₁ p₂ / Real.Angle.cos (∡ p₃ p₁ p₂) = dist p₁ p₃ :=
by
have hs : (∡ p₃ p₁ p₂).sign = 1 := by rw [← oangle_rotate_sign, h, Real.Angle.sign_coe_pi_div_two]
rw [oangle_eq_angle_of_sign_eq_one hs, angle_comm, Real.Angle.cos_coe, dist_comm p₁ p₃,
dist_div_cos_angle_of_angle_eq_pi_div_two (angle_rev_eq_pi_div_two_of_oangle_eq_pi_div_two h)
(Or.inr (left_ne_of_oangle_eq_pi_div_two h))]
#align euclidean_geometry.dist_div_cos_oangle_left_of_oangle_eq_pi_div_two EuclideanGeometry.dist_div_cos_oangle_left_of_oangle_eq_pi_div_two
/-- A side of a right-angled triangle divided by the sine of the opposite angle equals the
hypotenuse. -/
theorem dist_div_sin_oangle_right_of_oangle_eq_pi_div_two {p₁ p₂ p₃ : P}
(h : ∡ p₁ p₂ p₃ = ↑(π / 2)) : dist p₁ p₂ / Real.Angle.sin (∡ p₂ p₃ p₁) = dist p₁ p₃ :=
by
have hs : (∡ p₂ p₃ p₁).sign = 1 := by rw [oangle_rotate_sign, h, Real.Angle.sign_coe_pi_div_two]
rw [oangle_eq_angle_of_sign_eq_one hs, Real.Angle.sin_coe,
dist_div_sin_angle_of_angle_eq_pi_div_two (angle_eq_pi_div_two_of_oangle_eq_pi_div_two h)
(Or.inl (left_ne_of_oangle_eq_pi_div_two h))]
#align euclidean_geometry.dist_div_sin_oangle_right_of_oangle_eq_pi_div_two EuclideanGeometry.dist_div_sin_oangle_right_of_oangle_eq_pi_div_two
/-- A side of a right-angled triangle divided by the sine of the opposite angle equals the
hypotenuse. -/
theorem dist_div_sin_oangle_left_of_oangle_eq_pi_div_two {p₁ p₂ p₃ : P}
(h : ∡ p₁ p₂ p₃ = ↑(π / 2)) : dist p₃ p₂ / Real.Angle.sin (∡ p₃ p₁ p₂) = dist p₁ p₃ :=
by
have hs : (∡ p₃ p₁ p₂).sign = 1 := by rw [← oangle_rotate_sign, h, Real.Angle.sign_coe_pi_div_two]
rw [oangle_eq_angle_of_sign_eq_one hs, angle_comm, Real.Angle.sin_coe, dist_comm p₁ p₃,
dist_div_sin_angle_of_angle_eq_pi_div_two (angle_rev_eq_pi_div_two_of_oangle_eq_pi_div_two h)
(Or.inl (right_ne_of_oangle_eq_pi_div_two h))]
#align euclidean_geometry.dist_div_sin_oangle_left_of_oangle_eq_pi_div_two EuclideanGeometry.dist_div_sin_oangle_left_of_oangle_eq_pi_div_two
/-- A side of a right-angled triangle divided by the tangent of the opposite angle equals the
adjacent side. -/
theorem dist_div_tan_oangle_right_of_oangle_eq_pi_div_two {p₁ p₂ p₃ : P}
(h : ∡ p₁ p₂ p₃ = ↑(π / 2)) : dist p₁ p₂ / Real.Angle.tan (∡ p₂ p₃ p₁) = dist p₃ p₂ :=
by
have hs : (∡ p₂ p₃ p₁).sign = 1 := by rw [oangle_rotate_sign, h, Real.Angle.sign_coe_pi_div_two]
rw [oangle_eq_angle_of_sign_eq_one hs, Real.Angle.tan_coe,
dist_div_tan_angle_of_angle_eq_pi_div_two (angle_eq_pi_div_two_of_oangle_eq_pi_div_two h)
(Or.inl (left_ne_of_oangle_eq_pi_div_two h))]
#align euclidean_geometry.dist_div_tan_oangle_right_of_oangle_eq_pi_div_two EuclideanGeometry.dist_div_tan_oangle_right_of_oangle_eq_pi_div_two
/-- A side of a right-angled triangle divided by the tangent of the opposite angle equals the
adjacent side. -/
theorem dist_div_tan_oangle_left_of_oangle_eq_pi_div_two {p₁ p₂ p₃ : P}
(h : ∡ p₁ p₂ p₃ = ↑(π / 2)) : dist p₃ p₂ / Real.Angle.tan (∡ p₃ p₁ p₂) = dist p₁ p₂ :=
by
have hs : (∡ p₃ p₁ p₂).sign = 1 := by rw [← oangle_rotate_sign, h, Real.Angle.sign_coe_pi_div_two]
rw [oangle_eq_angle_of_sign_eq_one hs, angle_comm, Real.Angle.tan_coe,
dist_div_tan_angle_of_angle_eq_pi_div_two (angle_rev_eq_pi_div_two_of_oangle_eq_pi_div_two h)
(Or.inl (right_ne_of_oangle_eq_pi_div_two h))]
#align euclidean_geometry.dist_div_tan_oangle_left_of_oangle_eq_pi_div_two EuclideanGeometry.dist_div_tan_oangle_left_of_oangle_eq_pi_div_two
end EuclideanGeometry
|
lemma snd_o_paired [simp]: "snd \<circ> (\<lambda>(x,y). (f x y, g x y)) = (\<lambda>(x,y). g x y)" |
/-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker
-/
import data.polynomial.reverse
import algebra.associated
import algebra.regular.smul
/-!
# Theory of monic polynomials
We give several tools for proving that polynomials are monic, e.g.
`monic_mul`, `monic_map`.
-/
noncomputable theory
open finset
open_locale big_operators classical
namespace polynomial
universes u v y
variables {R : Type u} {S : Type v} {a b : R} {m n : ℕ} {ι : Type y}
section semiring
variables [semiring R] {p q r : polynomial R}
lemma monic.as_sum {p : polynomial R} (hp : p.monic) :
p = X^(p.nat_degree) + (∑ i in range p.nat_degree, C (p.coeff i) * X^i) :=
begin
conv_lhs { rw [p.as_sum_range_C_mul_X_pow, sum_range_succ_comm] },
suffices : C (p.coeff p.nat_degree) = 1,
{ rw [this, one_mul] },
exact congr_arg C hp
end
lemma ne_zero_of_monic_of_zero_ne_one (hp : monic p) (h : (0 : R) ≠ 1) :
p ≠ 0 := mt (congr_arg leading_coeff) $ by rw [monic.def.1 hp, leading_coeff_zero]; cc
lemma ne_zero_of_ne_zero_of_monic (hp : p ≠ 0) (hq : monic q) : q ≠ 0 :=
begin
intro h, rw [h, monic.def, leading_coeff_zero] at hq,
rw [← mul_one p, ← C_1, ← hq, C_0, mul_zero] at hp,
exact hp rfl
end
lemma monic_map [semiring S] (f : R →+* S) (hp : monic p) : monic (p.map f) :=
if h : (0 : S) = 1 then
by haveI := subsingleton_of_zero_eq_one h;
exact subsingleton.elim _ _
else
have f (leading_coeff p) ≠ 0,
by rwa [show _ = _, from hp, f.map_one, ne.def, eq_comm],
by
begin
rw [monic, leading_coeff, coeff_map],
suffices : p.coeff (map f p).nat_degree = 1, simp [this],
suffices : (map f p).nat_degree = p.nat_degree, rw this, exact hp,
rwa nat_degree_eq_of_degree_eq (degree_map_eq_of_leading_coeff_ne_zero f _)
end
lemma monic_C_mul_of_mul_leading_coeff_eq_one [nontrivial R] {b : R}
(hp : b * p.leading_coeff = 1) : monic (C b * p) :=
by rw [monic, leading_coeff_mul' _]; simp [leading_coeff_C b, hp]
lemma monic_mul_C_of_leading_coeff_mul_eq_one [nontrivial R] {b : R}
(hp : p.leading_coeff * b = 1) : monic (p * C b) :=
by rw [monic, leading_coeff_mul' _]; simp [leading_coeff_C b, hp]
theorem monic_of_degree_le (n : ℕ) (H1 : degree p ≤ n) (H2 : coeff p n = 1) : monic p :=
decidable.by_cases
(assume H : degree p < n, eq_of_zero_eq_one
(H2 ▸ (coeff_eq_zero_of_degree_lt H).symm) _ _)
(assume H : ¬degree p < n,
by rwa [monic, leading_coeff, nat_degree, (lt_or_eq_of_le H1).resolve_left H])
theorem monic_X_pow_add {n : ℕ} (H : degree p ≤ n) : monic (X ^ (n+1) + p) :=
have H1 : degree p < n+1, from lt_of_le_of_lt H (with_bot.coe_lt_coe.2 (nat.lt_succ_self n)),
monic_of_degree_le (n+1)
(le_trans (degree_add_le _ _) (max_le (degree_X_pow_le _) (le_of_lt H1)))
(by rw [coeff_add, coeff_X_pow, if_pos rfl, coeff_eq_zero_of_degree_lt H1, add_zero])
theorem monic_X_add_C (x : R) : monic (X + C x) :=
pow_one (X : polynomial R) ▸ monic_X_pow_add degree_C_le
lemma monic_mul (hp : monic p) (hq : monic q) : monic (p * q) :=
if h0 : (0 : R) = 1 then by haveI := subsingleton_of_zero_eq_one h0;
exact subsingleton.elim _ _
else
have leading_coeff p * leading_coeff q ≠ 0, by simp [monic.def.1 hp, monic.def.1 hq, ne.symm h0],
by rw [monic.def, leading_coeff_mul' this, monic.def.1 hp, monic.def.1 hq, one_mul]
lemma monic_pow (hp : monic p) : ∀ (n : ℕ), monic (p ^ n)
| 0 := monic_one
| (n+1) := by { rw pow_succ, exact monic_mul hp (monic_pow n) }
lemma monic_add_of_left {p q : polynomial R} (hp : monic p) (hpq : degree q < degree p) :
monic (p + q) :=
by rwa [monic, add_comm, leading_coeff_add_of_degree_lt hpq]
lemma monic_add_of_right {p q : polynomial R} (hq : monic q) (hpq : degree p < degree q) :
monic (p + q) :=
by rwa [monic, leading_coeff_add_of_degree_lt hpq]
namespace monic
@[simp]
lemma nat_degree_eq_zero_iff_eq_one {p : polynomial R} (hp : p.monic) :
p.nat_degree = 0 ↔ p = 1 :=
begin
split; intro h,
swap, { rw h, exact nat_degree_one },
have : p = C (p.coeff 0),
{ rw ← polynomial.degree_le_zero_iff,
rwa polynomial.nat_degree_eq_zero_iff_degree_le_zero at h },
rw this, convert C_1, rw ← h, apply hp,
end
@[simp]
lemma degree_le_zero_iff_eq_one {p : polynomial R} (hp : p.monic) :
p.degree ≤ 0 ↔ p = 1 :=
by rw [←hp.nat_degree_eq_zero_iff_eq_one, nat_degree_eq_zero_iff_degree_le_zero]
lemma nat_degree_mul {p q : polynomial R} (hp : p.monic) (hq : q.monic) :
(p * q).nat_degree = p.nat_degree + q.nat_degree :=
begin
nontriviality R,
apply nat_degree_mul',
simp [hp.leading_coeff, hq.leading_coeff]
end
lemma degree_mul_comm {p : polynomial R} (hp : p.monic) (q : polynomial R) :
(p * q).degree = (q * p).degree :=
begin
by_cases h : q = 0,
{ simp [h] },
rw [degree_mul', hp.degree_mul],
{ exact add_comm _ _ },
{ rwa [hp.leading_coeff, one_mul, leading_coeff_ne_zero] }
end
lemma nat_degree_mul' {p q : polynomial R} (hp : p.monic) (hq : q ≠ 0) :
(p * q).nat_degree = p.nat_degree + q.nat_degree :=
begin
rw [nat_degree_mul', add_comm],
simpa [hp.leading_coeff, leading_coeff_ne_zero]
end
lemma nat_degree_mul_comm {p : polynomial R} (hp : p.monic) (q : polynomial R) :
(p * q).nat_degree = (q * p).nat_degree :=
begin
by_cases h : q = 0,
{ simp [h] },
rw [hp.nat_degree_mul' h, polynomial.nat_degree_mul', add_comm],
simpa [hp.leading_coeff, leading_coeff_ne_zero]
end
lemma next_coeff_mul {p q : polynomial R} (hp : monic p) (hq : monic q) :
next_coeff (p * q) = next_coeff p + next_coeff q :=
begin
nontriviality,
simp only [← coeff_one_reverse],
rw reverse_mul;
simp [coeff_mul, nat.antidiagonal, hp.leading_coeff, hq.leading_coeff, add_comm]
end
lemma eq_one_of_map_eq_one {S : Type*} [semiring S] [nontrivial S]
(f : R →+* S) (hp : p.monic) (map_eq : p.map f = 1) : p = 1 :=
begin
nontriviality R,
have hdeg : p.degree = 0,
{ rw [← degree_map_eq_of_leading_coeff_ne_zero f _, map_eq, degree_one],
{ rw [hp.leading_coeff, f.map_one],
exact one_ne_zero } },
have hndeg : p.nat_degree = 0 :=
with_bot.coe_eq_coe.mp ((degree_eq_nat_degree hp.ne_zero).symm.trans hdeg),
convert eq_C_of_degree_eq_zero hdeg,
rw [← hndeg, ← polynomial.leading_coeff, hp.leading_coeff, C.map_one]
end
end monic
end semiring
section comm_semiring
variables [comm_semiring R] {p : polynomial R}
lemma monic_multiset_prod_of_monic (t : multiset ι) (f : ι → polynomial R)
(ht : ∀ i ∈ t, monic (f i)) :
monic (t.map f).prod :=
begin
revert ht,
refine t.induction_on _ _, { simp },
intros a t ih ht,
rw [multiset.map_cons, multiset.prod_cons],
exact monic_mul
(ht _ (multiset.mem_cons_self _ _))
(ih (λ _ hi, ht _ (multiset.mem_cons_of_mem hi)))
end
lemma monic_prod_of_monic (s : finset ι) (f : ι → polynomial R) (hs : ∀ i ∈ s, monic (f i)) :
monic (∏ i in s, f i) :=
monic_multiset_prod_of_monic s.1 f hs
lemma is_unit_C {x : R} : is_unit (C x) ↔ is_unit x :=
begin
rw [is_unit_iff_dvd_one, is_unit_iff_dvd_one],
split,
{ rintros ⟨g, hg⟩,
replace hg := congr_arg (eval 0) hg,
rw [eval_one, eval_mul, eval_C] at hg,
exact ⟨g.eval 0, hg⟩ },
{ rintros ⟨y, hy⟩,
exact ⟨C y, by rw [← C_mul, ← hy, C_1]⟩ }
end
lemma eq_one_of_is_unit_of_monic (hm : monic p) (hpu : is_unit p) : p = 1 :=
have degree p ≤ 0,
from calc degree p ≤ degree (1 : polynomial R) :
let ⟨u, hu⟩ := is_unit_iff_dvd_one.1 hpu in
if hu0 : u = 0
then begin
rw [hu0, mul_zero] at hu,
rw [← mul_one p, hu, mul_zero],
simp
end
else have p.leading_coeff * u.leading_coeff ≠ 0,
by rw [hm.leading_coeff, one_mul, ne.def, leading_coeff_eq_zero];
exact hu0,
by rw [hu, degree_mul' this];
exact le_add_of_nonneg_right (degree_nonneg_iff_ne_zero.2 hu0)
... ≤ 0 : degree_one_le,
by rw [eq_C_of_degree_le_zero this, ← nat_degree_eq_zero_iff_degree_le_zero.2 this,
← leading_coeff, hm.leading_coeff, C_1]
lemma monic.next_coeff_multiset_prod (t : multiset ι) (f : ι → polynomial R)
(h : ∀ i ∈ t, monic (f i)) :
next_coeff (t.map f).prod = (t.map (λ i, next_coeff (f i))).sum :=
begin
revert h,
refine multiset.induction_on t _ (λ a t ih ht, _),
{ simp only [multiset.not_mem_zero, forall_prop_of_true, forall_prop_of_false, multiset.map_zero,
multiset.prod_zero, multiset.sum_zero, not_false_iff, forall_true_iff],
rw ← C_1, rw next_coeff_C_eq_zero },
{ rw [multiset.map_cons, multiset.prod_cons, multiset.map_cons, multiset.sum_cons,
monic.next_coeff_mul, ih],
exacts [λ i hi, ht i (multiset.mem_cons_of_mem hi), ht a (multiset.mem_cons_self _ _),
monic_multiset_prod_of_monic _ _ (λ b bs, ht _ (multiset.mem_cons_of_mem bs))] }
end
lemma monic.next_coeff_prod (s : finset ι) (f : ι → polynomial R) (h : ∀ i ∈ s, monic (f i)) :
next_coeff (∏ i in s, f i) = ∑ i in s, next_coeff (f i) :=
monic.next_coeff_multiset_prod s.1 f h
end comm_semiring
section ring
variables [ring R] {p : polynomial R}
theorem monic_X_sub_C (x : R) : monic (X - C x) :=
by simpa only [sub_eq_add_neg, C_neg] using monic_X_add_C (-x)
theorem monic_X_pow_sub {n : ℕ} (H : degree p ≤ n) : monic (X ^ (n+1) - p) :=
by simpa [sub_eq_add_neg] using monic_X_pow_add (show degree (-p) ≤ n, by rwa ←degree_neg p at H)
/-- `X ^ n - a` is monic. -/
lemma monic_X_pow_sub_C {R : Type u} [ring R] (a : R) {n : ℕ} (h : n ≠ 0) : (X ^ n - C a).monic :=
begin
obtain ⟨k, hk⟩ := nat.exists_eq_succ_of_ne_zero h,
convert monic_X_pow_sub _,
exact le_trans degree_C_le nat.with_bot.coe_nonneg,
end
lemma not_is_unit_X_pow_sub_one (R : Type*) [comm_ring R] [nontrivial R] (n : ℕ) :
¬ is_unit (X ^ n - 1 : polynomial R) :=
begin
intro h,
rcases eq_or_ne n 0 with rfl | hn,
{ simpa using h },
apply hn,
rwa [← @nat_degree_X_pow_sub_C _ _ _ n (1 : R),
eq_one_of_is_unit_of_monic (monic_X_pow_sub_C (1 : R) hn),
nat_degree_one]
end
lemma monic_sub_of_left {p q : polynomial R} (hp : monic p) (hpq : degree q < degree p) :
monic (p - q) :=
by { rw sub_eq_add_neg, apply monic_add_of_left hp, rwa degree_neg }
lemma monic_sub_of_right {p q : polynomial R}
(hq : q.leading_coeff = -1) (hpq : degree p < degree q) : monic (p - q) :=
have (-q).coeff (-q).nat_degree = 1 :=
by rw [nat_degree_neg, coeff_neg, show q.coeff q.nat_degree = -1, from hq, neg_neg],
by { rw sub_eq_add_neg, apply monic_add_of_right this, rwa degree_neg }
section injective
open function
variables [semiring S] {f : R →+* S} (hf : injective f)
include hf
lemma degree_map_eq_of_injective (p : polynomial R) : degree (p.map f) = degree p :=
if h : p = 0 then by simp [h]
else degree_map_eq_of_leading_coeff_ne_zero _
(by rw [← f.map_zero]; exact mt hf.eq_iff.1
(mt leading_coeff_eq_zero.1 h))
lemma degree_map' (p : polynomial R) :
degree (p.map f) = degree p :=
p.degree_map_eq_of_injective hf
lemma nat_degree_map' (p : polynomial R) :
nat_degree (p.map f) = nat_degree p :=
nat_degree_eq_of_degree_eq (degree_map' hf p)
lemma leading_coeff_map' (p : polynomial R) :
leading_coeff (p.map f) = f (leading_coeff p) :=
begin
unfold leading_coeff,
rw [coeff_map, nat_degree_map' hf p],
end
lemma next_coeff_map (p : polynomial R) :
(p.map f).next_coeff = f p.next_coeff :=
begin
unfold next_coeff,
rw nat_degree_map' hf,
split_ifs; simp
end
lemma leading_coeff_of_injective (p : polynomial R) :
leading_coeff (p.map f) = f (leading_coeff p) :=
begin
delta leading_coeff,
rw [coeff_map f, nat_degree_map' hf p]
end
lemma monic_of_injective {p : polynomial R} (hp : (p.map f).monic) : p.monic :=
begin
apply hf,
rw [← leading_coeff_of_injective hf, hp.leading_coeff, f.map_one]
end
end injective
end ring
section nonzero_semiring
variables [semiring R] [nontrivial R] {p q : polynomial R}
@[simp] lemma not_monic_zero : ¬monic (0 : polynomial R) :=
by simpa only [monic, leading_coeff_zero] using (zero_ne_one : (0 : R) ≠ 1)
lemma ne_zero_of_monic (h : monic p) : p ≠ 0 :=
λ h₁, @not_monic_zero R _ _ (h₁ ▸ h)
end nonzero_semiring
section not_zero_divisor
-- TODO: using gh-8537, rephrase lemmas that involve commutation around `*` using the op-ring
variables [semiring R] {p : polynomial R}
lemma monic.mul_left_ne_zero (hp : monic p) {q : polynomial R} (hq : q ≠ 0) :
q * p ≠ 0 :=
begin
by_cases h : p = 1,
{ simpa [h] },
rw [ne.def, ←degree_eq_bot, hp.degree_mul, with_bot.add_eq_bot, not_or_distrib, degree_eq_bot],
refine ⟨hq, _⟩,
rw [←hp.degree_le_zero_iff_eq_one, not_le] at h,
refine (lt_trans _ h).ne',
simp
end
lemma monic.mul_right_ne_zero (hp : monic p) {q : polynomial R} (hq : q ≠ 0) :
p * q ≠ 0 :=
begin
by_cases h : p = 1,
{ simpa [h] },
rw [ne.def, ←degree_eq_bot, hp.degree_mul_comm, hp.degree_mul, with_bot.add_eq_bot,
not_or_distrib, degree_eq_bot],
refine ⟨hq, _⟩,
rw [←hp.degree_le_zero_iff_eq_one, not_le] at h,
refine (lt_trans _ h).ne',
simp
end
lemma monic.mul_nat_degree_lt_iff (h : monic p) {q : polynomial R} :
(p * q).nat_degree < p.nat_degree ↔ p ≠ 1 ∧ q = 0 :=
begin
by_cases hq : q = 0,
{ suffices : 0 < p.nat_degree ↔ p.nat_degree ≠ 0,
{ simpa [hq, ←h.nat_degree_eq_zero_iff_eq_one] },
exact ⟨λ h, h.ne', λ h, lt_of_le_of_ne (nat.zero_le _) h.symm ⟩ },
{ simp [h.nat_degree_mul', hq] }
end
lemma monic.mul_right_eq_zero_iff (h : monic p) {q : polynomial R} :
p * q = 0 ↔ q = 0 :=
begin
by_cases hq : q = 0;
simp [h.mul_right_ne_zero, hq]
end
lemma monic.mul_left_eq_zero_iff (h : monic p) {q : polynomial R} :
q * p = 0 ↔ q = 0 :=
begin
by_cases hq : q = 0;
simp [h.mul_left_ne_zero, hq]
end
lemma monic.is_regular {R : Type*} [ring R] {p : polynomial R} (hp : monic p) : is_regular p :=
begin
split,
{ intros q r h,
rw [←sub_eq_zero, ←hp.mul_right_eq_zero_iff, mul_sub, h, sub_self] },
{ intros q r h,
simp only at h,
rw [←sub_eq_zero, ←hp.mul_left_eq_zero_iff, sub_mul, h, sub_self] }
end
lemma degree_smul_of_smul_regular {S : Type*} [monoid S] [distrib_mul_action S R]
{k : S} (p : polynomial R) (h : is_smul_regular R k) :
(k • p).degree = p.degree :=
begin
refine le_antisymm _ _,
{ rw degree_le_iff_coeff_zero,
intros m hm,
rw degree_lt_iff_coeff_zero at hm,
simp [hm m le_rfl] },
{ rw degree_le_iff_coeff_zero,
intros m hm,
rw degree_lt_iff_coeff_zero at hm,
refine h _,
simpa using hm m le_rfl },
end
lemma nat_degree_smul_of_smul_regular {S : Type*} [monoid S] [distrib_mul_action S R]
{k : S} (p : polynomial R) (h : is_smul_regular R k) :
(k • p).nat_degree = p.nat_degree :=
begin
by_cases hp : p = 0,
{ simp [hp] },
rw [←with_bot.coe_eq_coe, ←degree_eq_nat_degree hp, ←degree_eq_nat_degree,
degree_smul_of_smul_regular p h],
contrapose! hp,
rw ←smul_zero k at hp,
exact h.polynomial hp
end
lemma leading_coeff_smul_of_smul_regular {S : Type*} [monoid S] [distrib_mul_action S R]
{k : S} (p : polynomial R) (h : is_smul_regular R k) :
(k • p).leading_coeff = k • p.leading_coeff :=
by rw [leading_coeff, leading_coeff, coeff_smul, nat_degree_smul_of_smul_regular p h]
lemma monic_of_is_unit_leading_coeff_inv_smul (h : is_unit p.leading_coeff) :
monic (h.unit⁻¹ • p) :=
begin
rw [monic.def, leading_coeff_smul_of_smul_regular _ (is_smul_regular_of_group _), units.smul_def],
obtain ⟨k, hk⟩ := h,
simp only [←hk, smul_eq_mul, ←units.coe_mul, units.coe_eq_one, inv_mul_eq_iff_eq_mul],
simp [units.ext_iff, is_unit.unit_spec]
end
lemma is_unit_leading_coeff_mul_right_eq_zero_iff (h : is_unit p.leading_coeff) {q : polynomial R} :
p * q = 0 ↔ q = 0 :=
begin
split,
{ intro hp,
rw ←smul_eq_zero_iff_eq (h.unit)⁻¹ at hp,
have : (h.unit)⁻¹ • (p * q) = ((h.unit)⁻¹ • p) * q,
{ ext,
simp only [units.smul_def, coeff_smul, coeff_mul, smul_eq_mul, mul_sum],
refine sum_congr rfl (λ x hx, _),
rw ←mul_assoc },
rwa [this, monic.mul_right_eq_zero_iff] at hp,
exact monic_of_is_unit_leading_coeff_inv_smul _ },
{ rintro rfl,
simp }
end
end not_zero_divisor
end polynomial
|
From CAS Require Export
Execute.
From Extract Require Export
IO_Test.
Definition run_test : io_unit :=
IO.unsafe_run
(ORandom.self_init tt;;
multi_test test_cas).
Separate Extraction run_test.
|
Set Implicit Arguments.
From CFML Require Import WPLib Stdlib.
From Proofs Require Import Cascade_Spec.
From Proofs Require Import Cascade.
(* -------------------------------------------------------------------------- *)
(* -------------------------------------------------------------------------- *)
Theorem cons_spec A:
forall I seqs,
forall (x : A) c,
SPEC (Cascade.cons x c)
PRE (\[@PureCascade A I seqs c])
POST (fun c' => \[@PureCascade A I (List.cons x seqs) c']).
Proof.
(* This is viewed by CFML as a partial application. *)
intros. xpartial. intros xc. xpull. intros [ ? Hxc ].
(* There remains to prove that if [c] is a valid cascade
and if [xc] is the result of the application [cons x c]
then [xc] is a valid cascade. *)
xunfold Cascade. xpull. intros S Hdup Hpermitted Hspec.
(* This requires exhibiting the invariant of the new cascade,
which must be built on top of the invariant [S] of the
cascade [c]. Tricky. *)
xsimpl (fun xs c' =>
match xs with
| nil =>
\[ c' = xc ] \* S nil c
| y :: ys =>
\[ y = x ] \* S ys c'
end
).
{ intros [ | y ys ] c'.
{ xpull. intros. subst c'.
xdup (S nil c). (* TEMPORARY should not be necessary? *)
xapply~ Hxc.
xcf. xret.
xsimpl~. subst. xsimpl~. }
{ xpull. intros. subst y.
xapply~ Hspec. xsimpl~.
intros [ | ]; intros; xsimpl~.
{ eauto. }
{ unfold append. xsimpl. (* weird *) }
}
}
{ intros [ | y ys ] c'; xpull; intros; subst.
{ xsimpl~. unfold cons. simpl. eauto. }
{ xchange~ Hpermitted. xpull. intros. xsimpl~. unfold cons. simpl. eauto. }
}
{ intros [ | y ys ] c'; eauto with duplicable. }
{ eauto. }
Qed.
|
[STATEMENT]
lemma subcls1_induct_aux:
assumes "is_class P C" and wf: "wf_prog wf_md P" and QObj: "Q Object"
shows
"\<lbrakk> \<And>C D fs ms.
\<lbrakk> C \<noteq> Object; is_class P C; class P C = Some (D,fs,ms) \<and>
wf_cdecl wf_md P (C,D,fs,ms) \<and> P \<turnstile> C \<prec>\<^sup>1 D \<and> is_class P D \<and> Q D\<rbrakk> \<Longrightarrow> Q C \<rbrakk>
\<Longrightarrow> Q C"
(*<*)
(is "PROP ?P \<Longrightarrow> _")
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>C D fs ms. \<lbrakk>C \<noteq> Object; is_class P C; class P C = \<lfloor>(D, fs, ms)\<rfloor> \<and> wf_cdecl wf_md P (C, D, fs, ms) \<and> P \<turnstile> C \<prec>\<^sup>1 D \<and> is_class P D \<and> Q D\<rbrakk> \<Longrightarrow> Q C) \<Longrightarrow> Q C
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. (\<And>C D fs ms. \<lbrakk>C \<noteq> Object; is_class P C; class P C = \<lfloor>(D, fs, ms)\<rfloor> \<and> wf_cdecl wf_md P (C, D, fs, ms) \<and> P \<turnstile> C \<prec>\<^sup>1 D \<and> is_class P D \<and> Q D\<rbrakk> \<Longrightarrow> Q C) \<Longrightarrow> Q C
[PROOF STEP]
assume p: "PROP ?P"
[PROOF STATE]
proof (state)
this:
\<lbrakk>?C \<noteq> Object; is_class P ?C; class P ?C = \<lfloor>(?D, ?fs, ?ms)\<rfloor> \<and> wf_cdecl wf_md P (?C, ?D, ?fs, ?ms) \<and> P \<turnstile> ?C \<prec>\<^sup>1 ?D \<and> is_class P ?D \<and> Q ?D\<rbrakk> \<Longrightarrow> Q ?C
goal (1 subgoal):
1. (\<And>C D fs ms. \<lbrakk>C \<noteq> Object; is_class P C; class P C = \<lfloor>(D, fs, ms)\<rfloor> \<and> wf_cdecl wf_md P (C, D, fs, ms) \<and> P \<turnstile> C \<prec>\<^sup>1 D \<and> is_class P D \<and> Q D\<rbrakk> \<Longrightarrow> Q C) \<Longrightarrow> Q C
[PROOF STEP]
have "class P C \<noteq> None \<longrightarrow> Q C"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. class P C \<noteq> None \<longrightarrow> Q C
[PROOF STEP]
proof(induct rule: subcls_induct[OF wf])
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>C. \<forall>D. (C, D) \<in> (subcls1 P)\<^sup>+ \<longrightarrow> class P D \<noteq> None \<longrightarrow> Q D \<Longrightarrow> class P C \<noteq> None \<longrightarrow> Q C
[PROOF STEP]
case (1 C)
[PROOF STATE]
proof (state)
this:
\<forall>D. (C, D) \<in> (subcls1 P)\<^sup>+ \<longrightarrow> class P D \<noteq> None \<longrightarrow> Q D
goal (1 subgoal):
1. \<And>C. \<forall>D. (C, D) \<in> (subcls1 P)\<^sup>+ \<longrightarrow> class P D \<noteq> None \<longrightarrow> Q D \<Longrightarrow> class P C \<noteq> None \<longrightarrow> Q C
[PROOF STEP]
have "class P C \<noteq> None \<Longrightarrow> Q C"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. class P C \<noteq> None \<Longrightarrow> Q C
[PROOF STEP]
proof(cases "C = Object")
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<lbrakk>class P C \<noteq> None; C = Object\<rbrakk> \<Longrightarrow> Q C
2. \<lbrakk>class P C \<noteq> None; C \<noteq> Object\<rbrakk> \<Longrightarrow> Q C
[PROOF STEP]
case True
[PROOF STATE]
proof (state)
this:
C = Object
goal (2 subgoals):
1. \<lbrakk>class P C \<noteq> None; C = Object\<rbrakk> \<Longrightarrow> Q C
2. \<lbrakk>class P C \<noteq> None; C \<noteq> Object\<rbrakk> \<Longrightarrow> Q C
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
C = Object
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
C = Object
goal (1 subgoal):
1. Q C
[PROOF STEP]
using QObj
[PROOF STATE]
proof (prove)
using this:
C = Object
Q Object
goal (1 subgoal):
1. Q C
[PROOF STEP]
by fast
[PROOF STATE]
proof (state)
this:
Q C
goal (1 subgoal):
1. \<lbrakk>class P C \<noteq> None; C \<noteq> Object\<rbrakk> \<Longrightarrow> Q C
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<lbrakk>class P C \<noteq> None; C \<noteq> Object\<rbrakk> \<Longrightarrow> Q C
[PROOF STEP]
case False
[PROOF STATE]
proof (state)
this:
C \<noteq> Object
goal (1 subgoal):
1. \<lbrakk>class P C \<noteq> None; C \<noteq> Object\<rbrakk> \<Longrightarrow> Q C
[PROOF STEP]
assume nNone: "class P C \<noteq> None"
[PROOF STATE]
proof (state)
this:
class P C \<noteq> None
goal (1 subgoal):
1. \<lbrakk>class P C \<noteq> None; C \<noteq> Object\<rbrakk> \<Longrightarrow> Q C
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
class P C \<noteq> None
[PROOF STEP]
have is_cls: "is_class P C"
[PROOF STATE]
proof (prove)
using this:
class P C \<noteq> None
goal (1 subgoal):
1. is_class P C
[PROOF STEP]
by(simp add: is_class_def)
[PROOF STATE]
proof (state)
this:
is_class P C
goal (1 subgoal):
1. \<lbrakk>class P C \<noteq> None; C \<noteq> Object\<rbrakk> \<Longrightarrow> Q C
[PROOF STEP]
obtain D fs ms where cls: "class P C = \<lfloor>(D, fs, ms)\<rfloor>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>D fs ms. class P C = \<lfloor>(D, fs, ms)\<rfloor> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
using nNone
[PROOF STATE]
proof (prove)
using this:
class P C \<noteq> None
goal (1 subgoal):
1. (\<And>D fs ms. class P C = \<lfloor>(D, fs, ms)\<rfloor> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by safe
[PROOF STATE]
proof (state)
this:
class P C = \<lfloor>(D, fs, ms)\<rfloor>
goal (1 subgoal):
1. \<lbrakk>class P C \<noteq> None; C \<noteq> Object\<rbrakk> \<Longrightarrow> Q C
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
class P C = \<lfloor>(D, fs, ms)\<rfloor>
goal (1 subgoal):
1. \<lbrakk>class P C \<noteq> None; C \<noteq> Object\<rbrakk> \<Longrightarrow> Q C
[PROOF STEP]
have wfC: "wf_cdecl wf_md P (C, D, fs, ms)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. wf_cdecl wf_md P (C, D, fs, ms)
[PROOF STEP]
by(rule class_wf[OF cls wf])
[PROOF STATE]
proof (state)
this:
wf_cdecl wf_md P (C, D, fs, ms)
goal (1 subgoal):
1. \<lbrakk>class P C \<noteq> None; C \<noteq> Object\<rbrakk> \<Longrightarrow> Q C
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
wf_cdecl wf_md P (C, D, fs, ms)
goal (1 subgoal):
1. \<lbrakk>class P C \<noteq> None; C \<noteq> Object\<rbrakk> \<Longrightarrow> Q C
[PROOF STEP]
have D: "is_class P D"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. is_class P D
[PROOF STEP]
by(rule wf_cdecl_supD[OF wfC False])
[PROOF STATE]
proof (state)
this:
is_class P D
goal (1 subgoal):
1. \<lbrakk>class P C \<noteq> None; C \<noteq> Object\<rbrakk> \<Longrightarrow> Q C
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
is_class P D
goal (1 subgoal):
1. \<lbrakk>class P C \<noteq> None; C \<noteq> Object\<rbrakk> \<Longrightarrow> Q C
[PROOF STEP]
have "P \<turnstile> C \<prec>\<^sup>1 D"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. P \<turnstile> C \<prec>\<^sup>1 D
[PROOF STEP]
by(rule subcls1I[OF cls False])
[PROOF STATE]
proof (state)
this:
P \<turnstile> C \<prec>\<^sup>1 D
goal (1 subgoal):
1. \<lbrakk>class P C \<noteq> None; C \<noteq> Object\<rbrakk> \<Longrightarrow> Q C
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
P \<turnstile> C \<prec>\<^sup>1 D
goal (1 subgoal):
1. \<lbrakk>class P C \<noteq> None; C \<noteq> Object\<rbrakk> \<Longrightarrow> Q C
[PROOF STEP]
have "class P D \<noteq> None"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. class P D \<noteq> None
[PROOF STEP]
using D
[PROOF STATE]
proof (prove)
using this:
is_class P D
goal (1 subgoal):
1. class P D \<noteq> None
[PROOF STEP]
by(simp add: is_class_def)
[PROOF STATE]
proof (state)
this:
class P D \<noteq> None
goal (1 subgoal):
1. \<lbrakk>class P C \<noteq> None; C \<noteq> Object\<rbrakk> \<Longrightarrow> Q C
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
class P C = \<lfloor>(D, fs, ms)\<rfloor>
wf_cdecl wf_md P (C, D, fs, ms)
is_class P D
P \<turnstile> C \<prec>\<^sup>1 D
class P D \<noteq> None
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
class P C = \<lfloor>(D, fs, ms)\<rfloor>
wf_cdecl wf_md P (C, D, fs, ms)
is_class P D
P \<turnstile> C \<prec>\<^sup>1 D
class P D \<noteq> None
goal (1 subgoal):
1. Q C
[PROOF STEP]
using 1
[PROOF STATE]
proof (prove)
using this:
class P C = \<lfloor>(D, fs, ms)\<rfloor>
wf_cdecl wf_md P (C, D, fs, ms)
is_class P D
P \<turnstile> C \<prec>\<^sup>1 D
class P D \<noteq> None
\<forall>D. (C, D) \<in> (subcls1 P)\<^sup>+ \<longrightarrow> class P D \<noteq> None \<longrightarrow> Q D
goal (1 subgoal):
1. Q C
[PROOF STEP]
by (auto intro: p[OF False is_cls])
[PROOF STATE]
proof (state)
this:
Q C
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
class P C \<noteq> None \<Longrightarrow> Q C
goal (1 subgoal):
1. \<And>C. \<forall>D. (C, D) \<in> (subcls1 P)\<^sup>+ \<longrightarrow> class P D \<noteq> None \<longrightarrow> Q D \<Longrightarrow> class P C \<noteq> None \<longrightarrow> Q C
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
class P C \<noteq> None \<Longrightarrow> Q C
[PROOF STEP]
show "class P C \<noteq> None \<longrightarrow> Q C"
[PROOF STATE]
proof (prove)
using this:
class P C \<noteq> None \<Longrightarrow> Q C
goal (1 subgoal):
1. class P C \<noteq> None \<longrightarrow> Q C
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
class P C \<noteq> None \<longrightarrow> Q C
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
class P C \<noteq> None \<longrightarrow> Q C
goal (1 subgoal):
1. (\<And>C D fs ms. \<lbrakk>C \<noteq> Object; is_class P C; class P C = \<lfloor>(D, fs, ms)\<rfloor> \<and> wf_cdecl wf_md P (C, D, fs, ms) \<and> P \<turnstile> C \<prec>\<^sup>1 D \<and> is_class P D \<and> Q D\<rbrakk> \<Longrightarrow> Q C) \<Longrightarrow> Q C
[PROOF STEP]
thus ?thesis
[PROOF STATE]
proof (prove)
using this:
class P C \<noteq> None \<longrightarrow> Q C
goal (1 subgoal):
1. Q C
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
class P C \<noteq> None \<longrightarrow> Q C
is_class P C
wf_prog wf_md P
Q Object
goal (1 subgoal):
1. Q C
[PROOF STEP]
by(unfold is_class_def) simp
[PROOF STATE]
proof (state)
this:
Q C
goal:
No subgoals!
[PROOF STEP]
qed |
import data.matrix.notation
example (x : ℕ) (h : x = 3) : x + x + x = 9 :=
begin
set y := x with ←h_xy,
guard_hyp y : ℕ := x,
guard_hyp h_xy : x = y,
guard_hyp h : y = 3,
guard_target y + y + y = 9,
set! z : ℕ := y,
guard_target y + y + y = 9,
simp [h]
end
example : true :=
let X1 := (![![1, 0], ![0, 0]] : matrix (fin 2) (fin 2) ℕ), -- X1 : fin 1.succ → fin 2 → ℕ
X2 : matrix (fin 2) (fin 2) ℕ := ![![1, 0], ![0, 0]] in -- X2 : matrix (fin 2) (fin 2) ℕ
begin
set Y1 := (![![1, 0], ![0, 0]] : matrix (fin 2) (fin 2) ℕ),
set Y2 : matrix (fin 2) (fin 2) ℕ := ![![1, 0], ![0, 0]],
let Z1 := (![![1, 0], ![0, 0]] : matrix (fin 2) (fin 2) ℕ),
let Z2 : matrix (fin 2) (fin 2) ℕ := ![![1, 0], ![0, 0]],
guard_hyp Y2 : matrix (fin 2) (fin 2) ℕ := (![![1, 0], ![0, 0]] : matrix (fin 2) (fin 2) ℕ),
trivial
end
def T {α : Type} := ℕ
def v : @T ℕ := nat.zero
def S := @T ℕ
def u : S := nat.zero
def p : true :=
begin
set a : T := v,
set b : T := u, -- the type `T` can't be fully elaborated without the body but this is fine
trivial
end
section lean_555 -- https://github.com/leanprover-community/mathlib/pull/14488
inductive foo | bar
instance : has_coe_to_sort foo _ :=
⟨λ _, unit⟩
example : true :=
begin
set x : foo.bar := (),
trivial,
end
end lean_555
|
My editor’s note is this: I realize correlation isn’t causation. I realize correlations can change at any moment because every moment in the market is unique. I realize it isn’t always easy to determine which variable leads and which follows in a seeming correlation; it may be neither as both may be driven by some other narrative/variable/rationale, etc. But sometimes divergences in prior correlations which have stood for a while can represent nice setups for a winning trade.
Older PostClose to corrective high GBP/USD? |
Nicole and Geoff 's relationship became strained . Nicole decided to plan a return trip to the island , believing it would solve their problems and bring them closer together . James said that Geoff loved the surprise , but found Nicole " very sexy and tempting " . She added that everything about Nicole forced Geoff to question his religious beliefs and he felt he " needed to back away " . Their trip soon turned disastrous when a man named Derrick Quaid ( John Atkinson ) stole their food and intimidated the couple . He admitted he were a murderer and tried to attack Geoff with a knife . James said he " put himself in harms way " to save Nicole .
|
function foo(username)
@join begin
account = login(username)
last = getlastlogin(account)
dms = getdms(account)
who = getuser(account, dms[end])
followers = publicinfo(username)[:followers]
end
# Do something with followers, last, who etc.
end
followers = @fork publicinfo(username)[:followers]
account = @fork login(username)
last = @fork getlastlogin(fetch(account))
dms = getdms(fetch(account))
who = getuser(fetch(account), dms[end])
fetchall(last, who, followers)
|
%!TEX root = ../main.tex
\chapter{SPICE Modeling in KiCad}
\label{ch:spice}
\section{Getting SPICE working}
\section{Adding Sources}
\section{Simulating Analog Systems}
\section{Simulating Transmission Lines}
\section{Including Vendor Models} |
The function $f(t) = c + r e^{it}$ is differentiable at $x$ on the set $A$. |
\<^marker>\<open>creator "Kevin Kappelmann"\<close>
subsection \<open>Predicates\<close>
theory Predicates
imports
Functions_Base
Predicates_Order
Predicates_Lattice
begin
paragraph \<open>Summary\<close>
text \<open>Basic concepts on predicates.\<close>
definition "pred_map f (P :: 'a \<Rightarrow> bool) x \<equiv> P (f x)"
lemma pred_map_eq [simp]: "pred_map f P x = P (f x)"
unfolding pred_map_def by simp
lemma comp_eq_pred_map [simp]: "P \<circ> f = pred_map f P"
by (intro ext) simp
end |
theory "WMF_cert_auto"
imports
"../ESPLogic"
begin
(* section: Wide Mouthed Frog *)
(* text:
The protocol is modeled after the description in the SPORE library:
http://www.lsv.ens-cachan.fr/Software/spore/wideMouthedFrog.html
Note that we cannot reason about the timestamps in our current model.
Furthermore, our current calculus for backwards reasoning is too weak
to reason about the original protocol
1: I -> S: I, {TimeI, R, kIR}k(I,S)
2: R <- S: {TimeS, I, kIR}k(R,S)
because the server S could receive the message {TimeI, R, kIR}k(I,S)
arbitrarily many times from himself. Therefore, we added global constants
identifying the different steps.
*)
role I
where "I =
[ Send ''1'' <| sAV ''I'', sAV ''R'',
PEnc <| sC ''step1'', sN ''TimeI'', sAV ''R'', sN ''kIR'' |>
( sK ''I'' ''S'' )
|>
]"
role R
where "R =
[ Recv ''2'' <| sMV ''S'', sMV ''I'',
PEnc <| sC ''step2'', sMV ''TimeS'', sMV ''I'', sMV ''kIR'' |>
( PSymK ( sAV ''R'' ) ( sMV ''S'' ) )
|>
]"
role S
where "S =
[ Recv ''1'' <| sMV ''I'', sMV ''R'',
PEnc <| sC ''step1'', sMV ''TimeI'', sMV ''R'', sMV ''kIR'' |>
( PSymK ( sMV ''I'' ) ( sAV ''S'' ) )
|>
, Send ''2'' <| sAV ''S'', sMV ''I'',
PEnc <| sC ''step2'', sN ''TimeS'', sMV ''I'', sMV ''kIR'' |>
( PSymK ( sMV ''R'' ) ( sAV ''S'' ) )
|>
]"
protocol WMF
where "WMF = { I, R, S }"
locale restricted_WMF_state = WMF_state
type_invariant WMF_msc_typing for WMF
where "WMF_msc_typing = mk_typing
[ ((R, ''I''), (KnownT R_2))
, ((S, ''I''), (KnownT S_1))
, ((S, ''R''), (KnownT S_1))
, ((R, ''S''), (KnownT R_2))
, ((S, ''TimeI''), (SumT (KnownT S_1) (NonceT I ''TimeI'')))
, ((R, ''TimeS''), (SumT (KnownT R_2) (NonceT S ''TimeS'')))
, ((R, ''kIR''), (SumT (KnownT R_2) (NonceT I ''kIR'')))
, ((S, ''kIR''), (SumT (KnownT S_1) (NonceT I ''kIR'')))
]"
sublocale WMF_state < WMF_msc_typing_state
proof -
have "(t,r,s) : approx WMF_msc_typing"
proof(cases rule: reachable_in_approxI_ext
[OF WMF_msc_typing.monoTyp, completeness_cases_rule])
case (R_2_I t r s tid0) note facts = this
then interpret state: WMF_msc_typing_state t r s
by unfold_locales auto
show ?case using facts
by (fastsimp intro: event_predOrdI split: if_splits)
next
case (R_2_S t r s tid0) note facts = this
then interpret state: WMF_msc_typing_state t r s
by unfold_locales auto
show ?case using facts
by (fastsimp intro: event_predOrdI split: if_splits)
next
case (R_2_TimeS t r s tid0) note facts = this
then interpret state: WMF_msc_typing_state t r s
by unfold_locales auto
show ?case using facts
proof(sources! "
Enc {| LC ''step2'', s(MV ''TimeS'' tid0), s(MV ''I'' tid0),
s(MV ''kIR'' tid0)
|}
( K ( s(AV ''R'' tid0) ) ( s(MV ''S'' tid0) ) ) ")
qed (insert facts, ((fastsimp intro: event_predOrdI split: if_splits))+)?
next
case (R_2_kIR t r s tid0) note facts = this
then interpret state: WMF_msc_typing_state t r s
by unfold_locales auto
show ?case using facts
proof(sources! "
Enc {| LC ''step2'', s(MV ''TimeS'' tid0), s(MV ''I'' tid0),
s(MV ''kIR'' tid0)
|}
( K ( s(AV ''R'' tid0) ) ( s(MV ''S'' tid0) ) ) ")
case (S_2_enc tid1) note_unified facts = this facts
thus ?thesis proof(sources! "
Enc {| LC ''step1'', s(MV ''TimeI'' tid1), s(AV ''R'' tid0),
s(MV ''kIR'' tid0)
|}
( K ( s(MV ''I'' tid0) ) ( s(AV ''S'' tid1) ) ) ")
qed (insert facts, ((fastsimp intro: event_predOrdI split: if_splits))+)?
qed (insert facts, ((fastsimp intro: event_predOrdI split: if_splits))+)?
next
case (S_1_I t r s tid0) note facts = this
then interpret state: WMF_msc_typing_state t r s
by unfold_locales auto
show ?case using facts
by (fastsimp intro: event_predOrdI split: if_splits)
next
case (S_1_R t r s tid0) note facts = this
then interpret state: WMF_msc_typing_state t r s
by unfold_locales auto
show ?case using facts
by (fastsimp intro: event_predOrdI split: if_splits)
next
case (S_1_TimeI t r s tid0) note facts = this
then interpret state: WMF_msc_typing_state t r s
by unfold_locales auto
show ?case using facts
proof(sources! "
Enc {| LC ''step1'', s(MV ''TimeI'' tid0), s(MV ''R'' tid0),
s(MV ''kIR'' tid0)
|}
( K ( s(MV ''I'' tid0) ) ( s(AV ''S'' tid0) ) ) ")
qed (insert facts, ((fastsimp intro: event_predOrdI split: if_splits))+)?
next
case (S_1_kIR t r s tid0) note facts = this
then interpret state: WMF_msc_typing_state t r s
by unfold_locales auto
show ?case using facts
proof(sources! "
Enc {| LC ''step1'', s(MV ''TimeI'' tid0), s(MV ''R'' tid0),
s(MV ''kIR'' tid0)
|}
( K ( s(MV ''I'' tid0) ) ( s(AV ''S'' tid0) ) ) ")
qed (insert facts, ((fastsimp intro: event_predOrdI split: if_splits))+)?
qed
thus "WMF_msc_typing_state t r s" by unfold_locales auto
qed
text{* Prove secrecy of long-term keys. *}
context WMF_state begin
(* This rule is unsafe in general, but OK here,
as we are only reasoning about static compromise.
*)
lemma static_longterm_key_reveal[dest!]:
"predOrd t (LKR a) e ==> RLKR a : reveals t"
by (auto intro: compr_predOrdI)
lemma longterm_private_key_secrecy:
assumes facts:
"SK m : knows t"
"RLKR m ~: reveals t"
shows "False"
using facts by (sources "SK m")
lemma longterm_sym_ud_key_secrecy:
assumes facts:
"K m1 m2 : knows t"
"RLKR m1 ~: reveals t"
"RLKR m2 ~: reveals t"
shows "False"
using facts by (sources "K m1 m2")
lemma longterm_sym_bd_key_secrecy:
assumes facts:
"Kbd m1 m2 : knows t"
"RLKR m1 ~: reveals t"
"RLKR m2 ~: reveals t"
"m1 : Agent"
"m2 : Agent"
shows "False"
proof -
from facts
have "KShr (agents {m1, m2}) : knows t"
by (auto simp: Kbd_def)
thus ?thesis using facts
proof (sources "KShr (agents {m1, m2})")
qed (auto simp: agents_def Agent_def)
qed
lemmas ltk_secrecy =
longterm_sym_ud_key_secrecy
longterm_sym_ud_key_secrecy[OF in_knows_predOrd1]
longterm_sym_bd_key_secrecy
longterm_sym_bd_key_secrecy[OF in_knows_predOrd1]
longterm_private_key_secrecy
longterm_private_key_secrecy[OF in_knows_predOrd1]
end
(* subsection: Secrecy Properties *)
lemma (in restricted_WMF_state) I_kIR_sec:
assumes facts:
"roleMap r tid0 = Some I"
"RLKR(s(AV ''I'' tid0)) ~: reveals t"
"RLKR(s(AV ''R'' tid0)) ~: reveals t"
"RLKR(s(AV ''S'' tid0)) ~: reveals t"
"LN ''kIR'' tid0 : knows t"
shows "False"
using facts proof(sources! " LN ''kIR'' tid0 ")
case I_1_kIR note_unified facts = this facts
thus ?thesis by (fastsimp dest!: ltk_secrecy)
next
case (S_2_kIR tid1) note_unified facts = this facts
thus ?thesis proof(sources! "
Enc {| LC ''step1'', s(MV ''TimeI'' tid1), s(MV ''R'' tid1),
LN ''kIR'' tid0
|}
( K ( s(MV ''I'' tid1) ) ( s(AV ''S'' tid1) ) ) ")
case (I_1_enc tid2) note_unified facts = this facts
thus ?thesis by (fastsimp dest!: ltk_secrecy)
qed (insert facts, (((clarsimp, order?) | order))+)?
qed (insert facts, fastsimp+)?
lemma (in restricted_WMF_state) S_kIR_sec:
assumes facts:
"roleMap r tid0 = Some S"
"RLKR(s(AV ''S'' tid0)) ~: reveals t"
"RLKR(s(MV ''I'' tid0)) ~: reveals t"
"RLKR(s(MV ''R'' tid0)) ~: reveals t"
"( tid0, S_1 ) : steps t"
"s(MV ''kIR'' tid0) : knows t"
shows "False"
proof -
note_prefix_closed facts = facts
thus ?thesis proof(sources! "
Enc {| LC ''step1'', s(MV ''TimeI'' tid0), s(MV ''R'' tid0),
s(MV ''kIR'' tid0)
|}
( K ( s(MV ''I'' tid0) ) ( s(AV ''S'' tid0) ) ) ")
case fake note_unified facts = this facts
thus ?thesis by (fastsimp dest!: ltk_secrecy)
next
case (I_1_enc tid1) note_unified facts = this facts
thus ?thesis by (fastsimp dest: I_kIR_sec intro: event_predOrdI)
qed (insert facts, fastsimp+)?
qed
lemma (in restricted_WMF_state) R_kIR_sec:
assumes facts:
"roleMap r tid0 = Some R"
"RLKR(s(AV ''R'' tid0)) ~: reveals t"
"RLKR(s(MV ''I'' tid0)) ~: reveals t"
"RLKR(s(MV ''S'' tid0)) ~: reveals t"
"( tid0, R_2 ) : steps t"
"s(MV ''kIR'' tid0) : knows t"
shows "False"
proof -
note_prefix_closed facts = facts
thus ?thesis proof(sources! "
Enc {| LC ''step2'', s(MV ''TimeS'' tid0), s(MV ''I'' tid0),
s(MV ''kIR'' tid0)
|}
( K ( s(AV ''R'' tid0) ) ( s(MV ''S'' tid0) ) ) ")
case fake note_unified facts = this facts
thus ?thesis by (fastsimp dest!: ltk_secrecy)
next
case (S_2_enc tid1) note_unified facts = this facts
thus ?thesis by (fastsimp dest: S_kIR_sec intro: event_predOrdI)
qed (insert facts, fastsimp+)?
qed
(* subsection: Authentication Properties *)
(* text:
The authentication guarantee for the initiator is trivial because it does not
receive any confirmation that the responder received the new session-key.
*)
lemma (in restricted_WMF_state) S_ni_synch:
assumes facts:
"roleMap r tid3 = Some S"
"RLKR(s(AV ''S'' tid3)) ~: reveals t"
"RLKR(s(MV ''I'' tid3)) ~: reveals t"
"( tid3, S_1 ) : steps t"
shows
"(? tid1.
roleMap r tid1 = Some I &
s(AV ''I'' tid1) = s(MV ''I'' tid3) &
s(AV ''R'' tid1) = s(MV ''R'' tid3) &
s(AV ''S'' tid1) = s(AV ''S'' tid3) &
LN ''TimeI'' tid1 = s(MV ''TimeI'' tid3) &
LN ''kIR'' tid1 = s(MV ''kIR'' tid3) &
predOrd t (St( tid1, I_1 )) (St( tid3, S_1 )))"
proof -
note_prefix_closed facts = facts
thus ?thesis proof(sources! "
Enc {| LC ''step1'', s(MV ''TimeI'' tid3), s(MV ''R'' tid3),
s(MV ''kIR'' tid3)
|}
( K ( s(MV ''I'' tid3) ) ( s(AV ''S'' tid3) ) ) ")
case fake note_unified facts = this facts
thus ?thesis by (fastsimp dest!: ltk_secrecy)
next
case (I_1_enc tid4) note_unified facts = this facts
thus ?thesis by (fastsimp intro: event_predOrdI split: if_splits)
qed (insert facts, fastsimp+)?
qed
lemma (in restricted_WMF_state) R_ni_synch:
assumes facts:
"roleMap r tid2 = Some R"
"RLKR(s(AV ''R'' tid2)) ~: reveals t"
"RLKR(s(MV ''I'' tid2)) ~: reveals t"
"RLKR(s(MV ''S'' tid2)) ~: reveals t"
"( tid2, R_2 ) : steps t"
shows
"(? tid1.
(? tid3.
roleMap r tid1 = Some I &
roleMap r tid3 = Some S &
s(AV ''I'' tid1) = s(MV ''I'' tid2) &
s(MV ''I'' tid2) = s(MV ''I'' tid3) &
s(AV ''R'' tid1) = s(AV ''R'' tid2) &
s(AV ''R'' tid2) = s(MV ''R'' tid3) &
s(AV ''S'' tid1) = s(MV ''S'' tid2) &
s(MV ''S'' tid2) = s(AV ''S'' tid3) &
LN ''TimeI'' tid1 = s(MV ''TimeI'' tid3) &
s(MV ''TimeS'' tid2) = LN ''TimeS'' tid3 &
LN ''kIR'' tid1 = s(MV ''kIR'' tid2) &
s(MV ''kIR'' tid2) = s(MV ''kIR'' tid3) &
predOrd t (St( tid1, I_1 )) (St( tid3, S_1 )) &
predOrd t (St( tid3, S_1 )) (St( tid3, S_2 )) &
predOrd t (St( tid3, S_2 )) (St( tid2, R_2 ))))"
proof -
note_prefix_closed facts = facts
thus ?thesis proof(sources! "
Enc {| LC ''step2'', s(MV ''TimeS'' tid2), s(MV ''I'' tid2),
s(MV ''kIR'' tid2)
|}
( K ( s(AV ''R'' tid2) ) ( s(MV ''S'' tid2) ) ) ")
case fake note_unified facts = this facts
thus ?thesis by (fastsimp dest!: ltk_secrecy)
next
case (S_2_enc tid3) note_unified facts = this facts
thus ?thesis proof(sources! "
Enc {| LC ''step1'', s(MV ''TimeI'' tid3), s(AV ''R'' tid2),
s(MV ''kIR'' tid2)
|}
( K ( s(MV ''I'' tid2) ) ( s(AV ''S'' tid3) ) ) ")
case fake note_unified facts = this facts
thus ?thesis by (fastsimp dest!: ltk_secrecy)
next
case (I_1_enc tid4) note_unified facts = this facts
thus ?thesis by (fastsimp intro: event_predOrdI split: if_splits)
qed (insert facts, fastsimp+)?
qed (insert facts, fastsimp+)?
qed
end |
(* Title: CTT/ex/Equality.thy
Author: Lawrence C Paulson, Cambridge University Computer Laboratory
Copyright 1991 University of Cambridge
*)
section "Equality reasoning by rewriting"
theory Equality
imports "../CTT"
begin
lemma split_eq: "p : Sum(A,B) \<Longrightarrow> split(p,pair) = p : Sum(A,B)"
apply (rule EqE)
apply (rule elim_rls, assumption)
apply rew
done
lemma when_eq: "\<lbrakk>A type; B type; p : A+B\<rbrakk> \<Longrightarrow> when(p,inl,inr) = p : A + B"
apply (rule EqE)
apply (rule elim_rls, assumption)
apply rew
done
text \<open>in the "rec" formulation of addition, $0+n=n$\<close>
lemma "p:N \<Longrightarrow> rec(p,0, \<lambda>y z. succ(y)) = p : N"
apply (rule EqE)
apply (rule elim_rls, assumption)
apply rew
done
text \<open>the harder version, $n+0=n$: recursive, uses induction hypothesis\<close>
lemma "p:N \<Longrightarrow> rec(p,0, \<lambda>y z. succ(z)) = p : N"
apply (rule EqE)
apply (rule elim_rls, assumption)
apply hyp_rew
done
text \<open>Associativity of addition\<close>
lemma "\<lbrakk>a:N; b:N; c:N\<rbrakk>
\<Longrightarrow> rec(rec(a, b, \<lambda>x y. succ(y)), c, \<lambda>x y. succ(y)) =
rec(a, rec(b, c, \<lambda>x y. succ(y)), \<lambda>x y. succ(y)) : N"
apply (NE a)
apply hyp_rew
done
text \<open>Martin-Löf (1984) page 62: pairing is surjective\<close>
lemma "p : Sum(A,B) \<Longrightarrow> <split(p,\<lambda>x y. x), split(p,\<lambda>x y. y)> = p : Sum(A,B)"
apply (rule EqE)
apply (rule elim_rls, assumption)
apply (tactic \<open>DEPTH_SOLVE_1 (rew_tac \<^context> [])\<close>) (*!!!!!!!*)
done
lemma "\<lbrakk>a : A; b : B\<rbrakk> \<Longrightarrow> (\<^bold>\<lambda>u. split(u, \<lambda>v w.<w,v>)) ` <a,b> = <b,a> : \<Sum>x:B. A"
by rew
text \<open>a contrived, complicated simplication, requires sum-elimination also\<close>
lemma "(\<^bold>\<lambda>f. \<^bold>\<lambda>x. f`(f`x)) ` (\<^bold>\<lambda>u. split(u, \<lambda>v w.<w,v>)) =
\<^bold>\<lambda>x. x : \<Prod>x:(\<Sum>y:N. N). (\<Sum>y:N. N)"
apply (rule reduction_rls)
apply (rule_tac [3] intrL_rls)
apply (rule_tac [4] EqE)
apply (erule_tac [4] SumE)
(*order of unifiers is essential here*)
apply rew
done
end
|
theory AbstractSwapOrNotShuffle
imports
HOL.List
"HOL-Library.Permutation"
"HOL-Algebra.Ring"
begin
(* Swap or not primitive for shuffling a single element *)
definition (in abelian_group)
swap_or_not :: "'a \<Rightarrow> ('a \<times> ('a set \<Rightarrow> bool)) list \<Rightarrow> 'a"
where
"swap_or_not x kfs \<equiv>
fold
(\<lambda>(ki, fi) x. let
x' = ki \<ominus> x in
if fi {x, x'} then x' else x
)
kfs
x"
lemma (in abelian_group) swap_or_not_nil:
"swap_or_not x [] = x"
by (fastforce simp: swap_or_not_def)
lemma (in abelian_group) swap_or_not_rec:
"swap_or_not x ((ki, fi) # kfs) =
(if fi {x, ki \<ominus> x} then
swap_or_not (ki \<ominus> x) kfs
else
swap_or_not x kfs)"
by (fastforce simp: swap_or_not_def)
(* Swap or not shuffle on lists, parameterised by keys (k) and round functions (f) *)
(* The number of rounds is determined by the number of keys and round functions provided *)
definition (in abelian_group)
swap_or_not_shuffle :: "'a list \<Rightarrow> ('a \<times> ('a set \<Rightarrow> bool)) list \<Rightarrow> 'a list"
where
"swap_or_not_shuffle xs kfs \<equiv> [swap_or_not x kfs. x \<leftarrow> xs]"
lemma (in abelian_group) swap_or_not_shuffle_rec:
"swap_or_not_shuffle xs (kfs @ [(k, f)]) =
map (\<lambda>x. swap_or_not x [(k, f)]) (swap_or_not_shuffle xs kfs)"
by (fastforce simp: swap_or_not_shuffle_def swap_or_not_def)
(* Mapping a bijection over a permuted list yields another permutation *)
lemma map_perm:
"\<lbrakk>xs <~~> ys; bij_betw f (set ys) (set ys); distinct xs\<rbrakk>
\<Longrightarrow> xs <~~> map f ys"
apply (clarsimp simp: mset_eq_perm[symmetric])
apply (clarsimp simp: bij_betw_def dest!: mset_set_set[symmetric])
using image_mset_mset_set mset_eq_setD by fastforce
lemma (in abelian_group) plus_left_cancel:
"\<lbrakk>a \<oplus> b = a \<oplus> c; a \<in> carrier G; b \<in> carrier G; c \<in> carrier G\<rbrakk> \<Longrightarrow> b = c"
by fastforce
lemma (in abelian_group) minus_left_cancel:
"\<lbrakk>a \<ominus> b = a \<ominus> c; a \<in> carrier G; b \<in> carrier G; c \<in> carrier G\<rbrakk> \<Longrightarrow> b = c"
by (metis add.Units_eq add.Units_l_cancel add.inv_closed l_neg local.minus_eq)
lemma (in abelian_group) double_minus_eq:
"\<lbrakk>a \<in> carrier G; b \<in> carrier G\<rbrakk> \<Longrightarrow> a \<ominus> (a \<ominus> b) = b"
by (metis (no_types, lifting) abelian_group.minus_add abelian_group.minus_minus
abelian_group.r_neg1 abelian_group_axioms add.inv_closed local.minus_eq)
(* The swap or not function is a bijection *)
lemma (in abelian_group) swap_or_not_bij:
"k \<in> carrier G \<Longrightarrow>
set xs = carrier G \<Longrightarrow>
bij_betw (\<lambda>x. swap_or_not x [(k, f)]) (set xs) (set xs)"
apply (clarsimp simp: bij_betw_def)
apply (rule conjI)
apply (clarsimp simp: swap_or_not_def Let_def inj_on_def)
apply safe
apply (erule (1) minus_left_cancel)
apply ((fastforce simp: double_minus_eq insert_commute)+)[4]
apply (fastforce simp: swap_or_not_def Let_def)
apply (clarsimp simp: swap_or_not_def Let_def image_def)
apply (frule_tac x="k \<ominus> x" in bspec;
fastforce simp: double_minus_eq insert_commute)
done
(* Swap or not shuffle yields a permutation of the original list *)
lemma (in abelian_group) swap_or_not_shuffle_perm:
"\<lbrakk>distinct xs; set xs = carrier G; set (map fst kfs) \<subseteq> carrier G\<rbrakk>
\<Longrightarrow> xs <~~> swap_or_not_shuffle xs kfs"
apply (induct kfs arbitrary: xs rule: List.rev_induct)
apply (fastforce simp: swap_or_not_shuffle_def swap_or_not_nil)
apply (rename_tac kf kfs' xs')
apply (case_tac kf, rename_tac k f)
apply (clarsimp simp: swap_or_not_shuffle_rec)
apply (rule map_perm)
apply fastforce
apply (erule swap_or_not_bij)
using perm_set_eq by blast
end |
import algebra.group.basic
lemma right_inverse_eq_left_inverse {T : Type} [monoid T]
{a b c : T} (inv_right : a * b = 1) (inv_left : c * a = 1) :
b = c :=
calc b = 1 * b : (one_mul b).symm
... = (c * a) * b : by rw inv_left
... = c * (a * b) : mul_assoc c a b
... = c * 1 : by rw inv_right
... = c : mul_one c
lemma right_inverse_unique {T : Type} [group T]
{a b c : T} (inv_ab : a * b = 1) (inv_ac : a * c = 1) :
b = c :=
calc b = 1 * b : (one_mul b).symm
... = (a⁻¹ * a) * b : by rw mul_left_inv
... = a⁻¹ * (a * b) : mul_assoc a⁻¹ a b
... = a⁻¹ * 1 : by rw inv_ab
... = a⁻¹ * (a * c) : by rw inv_ac
... = (a⁻¹ * a) * c : (mul_assoc a⁻¹ a c).symm
... = 1 * c : by rw mul_left_inv
... = c : one_mul c
lemma right_inverse_unique_aux {T : Type} [group T]
{a b : T} (inv_ab : a * b = 1) :
b = a⁻¹ :=
calc b = 1 * b : (one_mul b).symm
... = (a⁻¹ * a) * b : by rw mul_left_inv
... = a⁻¹ * (a * b) : mul_assoc a⁻¹ a b
... = a⁻¹ * 1 : by rw inv_ab
... = a⁻¹ : mul_one a⁻¹
lemma right_inverse_unique' {T : Type} [group T]
{a b c : T} (inv_ab : a * b = 1) (inv_ac : a * c = 1) :
b = c :=
begin
rw right_inverse_unique_aux inv_ab,
rw right_inverse_unique_aux inv_ac,
end
|
A beautiful and delicate hanky, gracefully presented in a gift box, along with a printed verse written especially for this occasion. Express your heartfelt sentiments with this loving and thoughtful gift your loved one will treasure always.
"My daughter I'm so happy, yes My heart is filled with pride. A lovely woman you've become And soon to be a bride. This keepsake hanky is a gift A little something new, To carry down the aisle with you Along with something blue. Add something that is borrowed and Add something that is old, But also carry something that Cannot be bought or sold. It's a mother's love I speak of To carry in your heart, For though you'll be a fine man's wife, Our bond will never part." |
Require Export D.
(** **** Exercise: 1 star (update_eq) *)
Theorem update_eq : forall n x st,
(update st x n) x = n.
Proof.
intros. unfold update. apply eq_id.
Qed.
|
function [Y,W,SetupStruc] = Process_AuxIVA(s,Transfer,SetupStruc)
K = SetupStruc.AuxIVA.K;
hop = SetupStruc.AuxIVA.hop;
win = hanning(K,'periodic');
win = win/sqrt(sum(win(1:hop:K).^2));
SetupStruc.AuxIVA.win = win; % Preserve 'win' in 'SetupStruc'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
N = size(s,2);
for i = 1:N
X(:,:,i) = fft(enframe(s(:,i),win,hop)');
end
frame_N = size(X,2);
K_m = K/2+1;
Num = size(Transfer,3);
Y = zeros((frame_N-1)*hop+K,Num);
Y_f = zeros(Num,frame_N,K);
%%%%%%%%%%%%%%%%%%%%%%%%%% Obtain processing matrix 'W'
X_sp = zeros(Num,frame_N,K_m);
W_IVA = zeros(Num,Num,K_m);
V_sp = zeros(Num,N,K_m);
theta = 10^-6;
for i = 1:K_m
X_f = permute(X(i,:,:),[3 2 1]);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Initialize W by PCA
[E,D] = PCA(X_f,1,Num);
V = sqrt(D)\E';
V_sp(:,:,i) = V;
X_sp(:,:,i) = V*X_f;
%%%%%%%%%%%% Adjust amplitude of 'w'
W_o = eye(Num);
y_f = W_o*V*X_f;
% norm = max(abs(y_f),[],2);
% if(norm>10)
% norm = repmat(norm,1,Num);
% W_o = W_o./norm;
% y_f = W_o*V*X_f;
% end
W_IVA(:,:,i) = W_o;
Y_f(:,:,i) = y_f;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%% IVA iterations
max_iteration = 200;
Y_k = zeros(Num,frame_N);
epsi = 1e-6;
pObj = inf;
A = zeros(1001,2)-1; %%%% Show the decrease of non-linear correlation, IVA max iterations 1000
for iteration = 1:max_iteration
for i = 1:Num
y_temp = permute(Y_f(i,:,:),[3 2 1]);
Y_k(i,:) = sqrt(sum(abs(y_temp(1:K_m,:)).^2))+epsi;
end
dlw = 0;
for i = 1:K_m
W = W_IVA(:,:,i);
X_f = X_sp(:,:,i);
dlw = dlw +log(abs(det(W))+epsi);
for i_n = 1:Num
G_ = Y_k(i_n,:).^-1;
G_ = repmat(G_,Num,1);
Vk = (G_.*X_f)*X_f'/frame_N;
if rcond(Vk)<theta
Vk = Vk+eye(Num)*max(eig(Vk))*theta;
end
wk = inv(W*Vk);
wk = wk(:,i_n);
wk = wk/(sqrt(wk'*Vk*wk)+epsi);
W(i_n,:) = wk';
end
W_IVA(:,:,i) = W;
Y_f(:,:,i) = W*X_f;
end
Obj = (sum(sum(Y_k))/frame_N-2*dlw)/(Num*K_m);
dObj = pObj-Obj;
pObj = Obj;
A(iteration,:) = [Obj,abs(dObj)/abs(Obj)];
if(abs(dObj)/abs(Obj)<theta)
break;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%% Post processing
W = zeros(Num,N,K_m);
Y_f(:,:,1) = zeros(Num,frame_N);
for i = 2:K_m
W_inv = pinv(W_IVA(:,:,i)*V_sp(:,:,i));
for ii = 1:Num
Y_f(ii,:,i) = Y_f(ii,:,i)*W_inv(1,ii);
W_IVA(ii,:,i) = W_IVA(ii,:,i)*W_inv(1,ii);
end
W(:,:,i) = W_IVA(:,:,i)*V_sp(:,:,i);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if(i~=K_m)
Y_f(:,:,K+2-i) = conj(Y_f(:,:,i));
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Recover signals
if(K/hop==2)
win = ones(K,1);
end
for i = 1:Num
y_temp = permute(Y_f(i,:,:),[3 2 1]);
Y(:,i) = overlapadd(real(ifft(y_temp))',win,hop);
end
return; |
Require Import XR_Rmax.
Require Import XR_Rmin.
Require Import XR_Rle_dec.
Require Import XR_Rle_antisym.
Require Import XR_Ropp_le_contravar.
Require Import XR_Rnot_le_lt.
Local Open Scope R_scope.
Lemma Ropp_Rmin : forall x y, - Rmin x y = Rmax (-x) (-y).
Proof.
intros x y.
unfold Rmin, Rmax.
destruct (Rle_dec x y) as [ hmin | hmin ] ;
destruct (Rle_dec (-x) (-y) ) as [ hmax | hmax ].
{
apply Rle_antisym.
{ exact hmax. }
{
apply Ropp_le_contravar.
exact hmin.
}
}
{ reflexivity. }
{ reflexivity. }
{
apply Rle_antisym.
{
left.
apply Rnot_le_lt.
exact hmax.
}
{
left.
apply Ropp_lt_contravar.
apply Rnot_le_lt.
exact hmin.
}
}
Qed.
|
(* This code is copyrighted by its authors; it is distributed under *)
(* the terms of the LGPL license (see LICENSE and description files) *)
(****************************************************************************)
(* *)
(* *)
(* Solange Coupet-Grimal & Line Jakubiec-Jamet *)
(* *)
(* *)
(* Laboratoire d'Informatique Fondamentale de Marseille *)
(* CMI et Faculté des Sciences de Luminy *)
(* *)
(* e-mail:{Solange.Coupet,Line.Jakubiec}@lif.univ-mrs.fr *)
(* *)
(* *)
(* Developped in Coq v6 *)
(* Ported to Coq v7 *)
(* Translated to Coq v8 *)
(* *)
(* July 12nd 2005 *)
(* *)
(****************************************************************************)
(* Timing_Arbiter.v *)
(****************************************************************************)
Require Export Tools_Inf.
Require Export Behaviour_Struct_lemmas.
Set Implicit Arguments.
Unset Strict Implicit.
Section Timing_Arbiter_Proof.
Variable Fs : Stream bool.
Variable Act : Stream (d_list bool 4).
(** Hypothesis on the input signals fs and act **)
Hypothesis fs_0 : S_head Fs = false.
Hypothesis
fs_act_signals : EqS sig_false (S_map2 andb (S_tail Fs) (S_Ackor Act)).
Definition P_Timing (fs : bool) (st : label_t) :=
false = fs && Out_Timing st.
CoInductive Inv_P_Timing : Stream bool -> Stream label_t -> Prop :=
C_Inv_t :
forall (i : Stream bool) (s : Stream label_t),
P_Timing (S_head i) (S_head s) ->
Inv_P_Timing (S_tail i) (S_tail s) -> Inv_P_Timing i s.
Lemma eqS_Inv_P_Timing :
forall (i i' : Stream bool) (s s' : Stream label_t),
EqS i i' -> EqS s s' -> Inv_P_Timing i' s' -> Inv_P_Timing i s.
Proof.
cofix eqS_Inv_P_Timing.
intros i i' s s' H_i H_s H_P.
inversion_clear H_i.
inversion_clear H_s.
inversion_clear H_P.
apply C_Inv_t.
rewrite H; rewrite H1; try trivial.
apply eqS_Inv_P_Timing with (S_tail i') (S_tail s'); trivial.
Qed.
(** P_Timing is an invariant property **)
Lemma eq_fs_and_RouteE_false :
forall (e : bool * d_list bool 4) (s : label_t),
P_Timing (fst e) (Trans_Timing e s).
Proof.
unfold P_Timing in |- *.
intros e s; elim e; clear e; intros fs act.
elim (Lib_Bool.bool_dec fs); intros H_fs.
rewrite H_fs; simpl in |- *.
case s; case (Ackor act); simpl in |- *; auto.
rewrite H_fs; simpl in |- *; auto.
Qed.
Lemma Is_Inv_P_Timing :
forall s : label_t, Inv_P_Timing Fs (States_TIMING (Compact Fs Act) s).
Proof.
intro s.
apply C_Inv_t.
simpl in |- *; rewrite fs_0; unfold P_Timing in |- *; auto.
generalize Fs Act s fs_act_signals.
clear fs_act_signals fs_0 s Act Fs.
cofix Is_Inv_P_Timing.
intros fs act s H_sig.
inversion_clear H_sig.
apply C_Inv_t.
simpl in |- *.
generalize
(eq_fs_and_RouteE_false (S_head (S_tail fs), S_head (S_tail act))
(Trans_Timing (S_head fs, S_head act) s)); simpl in |- *;
auto.
simpl in H.
generalize H.
case (S_head (S_tail fs)); simpl in |- *.
intros h; elim h; simpl in |- *.
intros h'; clear h'.
case s; case (S_head fs); unfold P_Timing in |- *; simpl in |- *; auto.
unfold P_Timing in |- *; auto.
simpl in Is_Inv_P_Timing; simpl in |- *.
apply Is_Inv_P_Timing.
apply H0.
Qed.
(* Proof that the property P_a4 taken for the FOUR_ARBITERS proof holds *)
(* for the output of TIMING : we exhibit an invariant Inv_t_a4 *)
(* Proof that : sa=AT_LEAST_ONE_IS_ACTIVE_a4 \/ sa=WAIT_a4 -> RouteE=false *)
(* Avec RouteE=(Out_Timing st) *)
Definition Inv_t_a4 (s_a4 : STATE_a4) (st : label_t) :=
let (sa4, _) := s_a4 in
sa4 = START_a4 /\ st = START_t \/
sa4 = START_a4 /\ st = WAIT_t \/
sa4 = START_a4 /\ st = ROUTE_t \/
sa4 = AT_LEAST_ONE_IS_ACTIVE_a4 /\ st = START_t \/
sa4 = WAIT_a4 /\ st = START_t.
(** Inv_t_a4 is an invariant **)
Lemma Inv_Init_states_t_a4 :
forall (g : d_list (bool * bool) 4) (o : d_list bool 4),
Inv_t_a4 (WAIT_a4, (g, o)) START_t.
Proof.
unfold Inv_t_a4 in |- *; intros g o; do 3 right; auto.
Qed.
Lemma Inv_t_a4_Ok :
forall (sa4 : STATE_a4) (st : label_t) (fs : bool)
(act : d_list bool 4) (ltReq : d_list (d_list bool 4) 4),
P_Timing fs st ->
Inv_t_a4 sa4 st ->
Inv_t_a4 (Trans_Four_Arbiters (fs, (Out_Timing st, ltReq)) sa4)
(Trans_Timing (fs, act) st).
Proof.
unfold Inv_t_a4 at 1 in |- *.
intros sa4 st fs' act' ltReq'; elim sa4; clear sa4.
intros sa4 g P H.
elim g; clear g; intros g o.
elim H; clear H; intros H.
elim H; clear H; intros H1 H2; rewrite H1; rewrite H2; simpl in |- *.
case fs'; simpl in |- *; auto.
elim H; clear H; intros H.
elim H; clear H; intros H1 H2; rewrite H1; rewrite H2; simpl in |- *.
case (Ackor act'); simpl in |- *; auto.
case fs'; simpl in |- *; auto.
elim H; clear H; intros H.
generalize P; clear P.
elim H; clear H; intros H1 H2; rewrite H1; rewrite H2; simpl in |- *.
case fs'; simpl in |- *.
unfold P_Timing in |- *; simpl in |- *; intros Abs.
absurd (false = true); auto.
intro H0; clear H0.
case (Ackor (d_map (Ackor (n:=3)) ltReq')); simpl in |- *; auto.
right; right; right; auto.
elim H; clear H; intros H.
elim H; clear H; intros H1 H2; rewrite H1; rewrite H2; simpl in |- *.
case fs'; simpl in |- *; auto.
right; right; right; right; auto.
elim H; clear H; intros H1 H2; rewrite H1; rewrite H2; simpl in |- *.
case fs'; simpl in |- *; auto.
right; right; right; right; auto.
Qed.
Lemma P_a4_inv :
forall (sa4 : STATE_a4) (st : label_t) (fs : bool)
(ltReq : d_list (d_list bool 4) 4)
(old_a4 : d_list bool 2 * bool * (d_list bool 2 * bool) *
(d_list bool 2 * bool * (d_list bool 2 * bool))),
Inv_t_a4 sa4 st -> P_a4 (fs, (Out_Timing st, ltReq)) sa4 old_a4.
Proof.
unfold Inv_t_a4 in |- *; unfold P_a4 in |- *.
intros sa4 st fs' ltReq' old_a4; clear fs' ltReq' old_a4.
elim sa4; clear sa4; simpl in |- *.
intros sa4 g H.
elim g; clear g; intros g o.
elim H; clear H; intros H.
elim H; clear H; intros H1 H2; rewrite H1; rewrite H2; simpl in |- *; auto.
elim H; clear H; intros H.
elim H; clear H; intros H1 H2; rewrite H1; rewrite H2; simpl in |- *; auto.
elim H; clear H; intros H.
elim H; clear H; intros H1 H2; rewrite H1; rewrite H2; simpl in |- *; auto.
intro H; elim H; clear H; intro Abs.
absurd (START_a4 = AT_LEAST_ONE_IS_ACTIVE_a4); auto.
discriminate.
absurd (START_a4 = WAIT_a4); auto.
discriminate.
elim H; clear H; intros H.
elim H; clear H; intros H1 H2; rewrite H1; rewrite H2; simpl in |- *; auto.
elim H; clear H; intros H1 H2; rewrite H1; rewrite H2; simpl in |- *; auto.
Qed.
(* Proof that P_a4 is invariant *)
Lemma Inv_a4 :
forall (sa4 : STATE_a4) (st : label_t)
(old_a4 : d_list bool 2 * bool * (d_list bool 2 * bool) *
(d_list bool 2 * bool * (d_list bool 2 * bool)))
(ltReq : Stream (d_list (d_list bool 4) 4)),
Inv_t_a4 sa4 st ->
Inv P_a4 (Compact Fs (Compact (Behaviour_TIMING (Compact Fs Act) st) ltReq))
(States_FOUR_ARBITERS
(Compact Fs (Compact (Behaviour_TIMING (Compact Fs Act) st) ltReq)) sa4)
(Structure_States_FOUR_ARBITERS
(Compact Fs (Compact (Behaviour_TIMING (Compact Fs Act) st) ltReq))
old_a4).
Proof.
intros sa st old_a4 ltReq H_I.
generalize (Is_Inv_P_Timing st).
generalize sa st old_a4 Fs Act ltReq H_I.
cofix Inv_a4.
intros sa' st' old_a4' fs' act' ltReq' H_I' H_P'.
inversion_clear H_P'.
apply C_Inv.
simpl in H.
rewrite S_head_Compact.
rewrite S_head_Compact.
rewrite S_head_Behaviour_TIMING.
apply P_a4_inv; try trivial.
generalize
(Inv_a4
(Trans_Four_Arbiters
(S_head
(Compact fs'
(Compact (Behaviour_TIMING (Compact fs' act') st') ltReq'))) sa')
(Trans_Timing (S_head (Compact fs' act')) st')
(Trans_Struct_four_arbiters
(S_head
(Compact fs'
(Compact (Behaviour_TIMING (Compact fs' act') st') ltReq')))
old_a4') (S_tail fs') (S_tail act') (S_tail ltReq')).
clear Inv_a4.
intro a4_I; apply a4_I.
rewrite S_head_Compact.
rewrite S_head_Compact.
rewrite S_head_Behaviour_TIMING.
rewrite S_head_Compact.
apply Inv_t_a4_Ok; try trivial.
try trivial.
Qed.
End Timing_Arbiter_Proof.
Require Import Arbitration_beh_sc.
Lemma S_tail_Behaviour_TIMINGPDECODE_ID :
forall
(i : Stream
(bool *
(d_list bool 4 * (d_list bool 4 * d_list (d_list bool 2) 4))))
(s : state_id * (label_t * STATE_p)),
S_tail (Behaviour_TIMINGPDECODE_ID i s) =
Behaviour_TIMINGPDECODE_ID (S_tail i) (Trans_TimingPDecode_Id (S_head i) s).
Proof.
auto.
Qed.
Lemma Equiv_Behaviour_TIMINGPDECODE_ID :
forall
(i : Stream
(bool *
(d_list bool 4 * (d_list bool 4 * d_list (d_list bool 2) 4))))
(si : state_id) (st : label_t) (sp : STATE_p),
EqS (Behaviour_TIMINGPDECODE_ID i (si, (st, sp)))
(Compact (S_map fstS i)
(Compact
(Behaviour_TIMING
(Compact (S_map fstS i)
(S_map fstS (S_map sndS i))) st)
(Behaviour_PRIORITY_DECODE
(Compact (S_map fstS (S_map sndS i))
(Compact
(S_map fstS
(S_map sndS (S_map sndS i)))
(S_map sndS
(S_map sndS (S_map sndS i))))) sp))).
Proof.
cofix Equiv_Behaviour_TIMINGPDECODE_ID.
intros i si st sp.
apply eqS.
clear Equiv_Behaviour_TIMINGPDECODE_ID; simpl in |- *.
unfold Out_id in |- *; unfold Out_Timing_Mealy in |- *;
unfold Out_PriorityDecode_Mealy in |- *.
elim (S_head i); simpl in |- *.
intros y y0; elim y0; simpl in |- *.
intros y1 y2; elim y2; simpl in |- *; auto.
rewrite S_tail_Behaviour_TIMINGPDECODE_ID.
unfold Trans_TimingPDecode_Id in |- *.
unfold Trans_Timing_PDecode in |- *; unfold Trans_PC in |- *.
do 2 rewrite S_tail_Compact.
rewrite S_tail_Behaviour_TIMING; rewrite S_tail_Behaviour_PDECODE.
simpl in |- *.
elim (S_head i); intros y y0.
elim y0; intros y1 y2.
elim y2; intros y3 y4.
simpl in |- *.
generalize
(Equiv_Behaviour_TIMINGPDECODE_ID (S_tail i) (Trans_id y si)
(Trans_Timing (y, y1) st) (Trans_PriorityDecode (y1, (y3, y4)) sp)).
clear Equiv_Behaviour_TIMINGPDECODE_ID.
intro H; apply H.
Qed.
Section Verif_hyp.
Let Input_type :=
(bool * (d_list bool 4 * (d_list bool 4 * d_list (d_list bool 2) 4)))%type.
Variable i : Stream Input_type.
Let Fs := S_map fstS i.
Let Act := S_map fstS (S_map sndS i).
Let Pri := S_map fstS (S_map sndS (S_map sndS i)).
Let Route := S_map sndS (S_map sndS (S_map sndS i)).
(** Hypothesis on the input signals fs and act **)
Hypothesis fs_0 : S_head Fs = false.
Hypothesis
fs_act_signals : EqS sig_false (S_map2 andb (S_tail Fs) (S_Ackor Act)).
Lemma Inv_a4' :
forall (si : state_id) (st : label_t) (sp : STATE_p)
(sa4 : STATE_a4)
(ra4 : d_list bool 2 * bool * (d_list bool 2 * bool) *
(d_list bool 2 * bool * (d_list bool 2 * bool))),
Inv_t_a4 sa4 st ->
Inv P_a4 (Behaviour_TIMINGPDECODE_ID i (si, (st, sp)))
(States_FOUR_ARBITERS (Behaviour_TIMINGPDECODE_ID i (si, (st, sp))) sa4)
(Structure_States_FOUR_ARBITERS
(Behaviour_TIMINGPDECODE_ID i (si, (st, sp))) ra4).
Proof.
intros si st sp sa4 ra4 HI.
generalize
(Inv_a4 fs_0 fs_act_signals (sa4:=sa4) (st:=st) ra4
(Behaviour_PRIORITY_DECODE (Compact Act (Compact Pri Route)) sp)).
intro P.
apply
eqS_about_P
with
(i' := Compact Fs
(Compact (Behaviour_TIMING (Compact Fs Act) st)
(Behaviour_PRIORITY_DECODE (Compact Act (Compact Pri Route))
sp)))
(s1' := States_FOUR_ARBITERS
(Compact Fs
(Compact (Behaviour_TIMING (Compact Fs Act) st)
(Behaviour_PRIORITY_DECODE
(Compact Act (Compact Pri Route)) sp))) sa4)
(s2' := Structure_States_FOUR_ARBITERS
(Compact Fs
(Compact (Behaviour_TIMING (Compact Fs Act) st)
(Behaviour_PRIORITY_DECODE
(Compact Act (Compact Pri Route)) sp))) ra4).
unfold Fs in |- *; unfold Act in |- *; unfold Pri in |- *;
unfold Route in |- *; apply Equiv_Behaviour_TIMINGPDECODE_ID.
unfold States_FOUR_ARBITERS in |- *.
apply EqS_States_Mealy; auto.
unfold Fs in |- *; unfold Act in |- *; unfold Pri in |- *;
unfold Route in |- *; apply Equiv_Behaviour_TIMINGPDECODE_ID.
unfold Structure_States_FOUR_ARBITERS in |- *; unfold States_PC in |- *.
apply EqS_States_Mealy; auto.
unfold Fs in |- *; unfold Act in |- *; unfold Pri in |- *;
unfold Route in |- *; apply Equiv_Behaviour_TIMINGPDECODE_ID.
apply P.
try trivial.
Qed.
End Verif_hyp.
Section From_init_states.
Let Input_type :=
(bool * (d_list bool 4 * (d_list bool 4 * d_list (d_list bool 2) 4)))%type.
Variable i : Stream Input_type.
Let Fs := S_map fstS i.
Let Act := S_map fstS (S_map sndS i).
Let Pri := S_map fstS (S_map sndS (S_map sndS i)).
Let Route := S_map sndS (S_map sndS (S_map sndS i)).
(** Hypothesis on the input signals fs and act **)
Hypothesis fs_0 : S_head Fs = false.
Hypothesis
fs_act_signals : EqS sig_false (S_map2 andb (S_tail Fs) (S_Ackor Act)).
(* P_a4 is an invariant (from the initial states) *)
Variable g11_0 g12_0 g21_0 g22_0 : bool * bool. (* lasts *)
Variable p_0 : d_list (d_list bool 4) 4. (* ltReq *)
Lemma P_a4_Ok :
Inv P_a4
(Behaviour_TIMINGPDECODE_ID i (IDENTITY, (START_t, (START_p, p_0))))
(States_FOUR_ARBITERS
(Behaviour_TIMINGPDECODE_ID i (IDENTITY, (START_t, (START_p, p_0))))
(WAIT_a4, (List4 g11_0 g12_0 g21_0 g22_0, l4_ffff)))
(Structure_States_FOUR_ARBITERS
(Behaviour_TIMINGPDECODE_ID i (IDENTITY, (START_t, (START_p, p_0))))
(pdt_List2 g11_0, false, (pdt_List2 g12_0, false),
(pdt_List2 g21_0, false, (pdt_List2 g22_0, false)))).
Proof.
apply Inv_a4'; auto.
apply Inv_Init_states_t_a4.
Qed.
End From_init_states.
|
function [ T, W ] = rd_lin_spline ( w0, t_array, n, c_array )
%*****************************************************************************80
%
%% RD_LIN_SPLINE discretizes and solves a 1D reaction diffusion problem.
%
% Discussion:
%
% The problem includes homogeneous Neumann boundary conditions at both ends.
%
% The dynamics are given by the following reaction/diffusion equation
% for the function W(T,X):
%
% W_t = W_xx + NL(W,c),
%
% where NL(W,c) is a polynomial in W:
%
% NL(W,c) = c(1) + c(2) * W + c(3) * W^2 + c(4) * W^3
%
% with Neumann boundary conditions at X = 0.0 and X = 1.0:
%
% W_x(T,0.0) = 0.0
% W_x(T,1.0) = 0.0
%
% and initial condition at T = 0.0:
%
% W(0,X) = sin ( pi * X ).
%
% The problem is to be solved for 0.0 <= T <= 4.0, 0.0 <= X <= 1.0.
%
% We use a finite element approximation with piecewise linear "hat"
% functions. The resulting ODE model is:
%
% M * w-dot(t) = - K * w(t) + NL(w, c)
%
% where M is the mass matrix, K the stiffness matrix, and NL the nonlinear
% term.
%
% NL(w, c_array)=c_array(1)+ c_array(2)*w + c_array(3)*w^2 + c_array(4)*w^3
%
% Licensing:
%
% This code is distributed under the GNU LGPL license.
%
% Modified:
%
% 05 April 2011
%
% Author:
%
% Eugene Cliff
%
% Reference:
%
% Jeffrey Borggaard, John Burkardt, John Burns, Eugene Cliff,
% Working Notes on a Reaction Diffusion Model: a Finite Element Formulation.
%
% Parameters:
%
% w0 - handle to initial function (on [0, 1])
%
% t_array- array of times for output
%
% n - grid parameter ( > 2)
%
% c_array- coefficients in nonlinear term
%
%
% Assemble the mass matrix.
%
M = spdiags([ones(n+1,1) [2;4*ones(n-1,1);2] ones(n+1,1)], ...
[-1 0 1], n+1, n+1)/(6*n);
%
% Assemble the stiff matrix.
%
K = n*spdiags([-ones(n+1,1) [1;2*ones(n-1,1);1] -ones(n+1,1)], ...
[-1 0 1], n+1, n+1);
%
% Set the initial condition.
%
wr = zeros(n+1,1);
h_wr = @(x) w0(x).*basic_hat(n*x );
wr(1) = quad(h_wr, 0, 1/n); % < w_0, \phi_1 >
h_wr = @(x) w0(x).*basic_hat(n*x - n);
wr(n+1) = quad(h_wr, (n-1)/n, 1); % < w_0, \phi_n+1 >
for jj=2:n
h_wr = @(x) w0(x).*basic_hat(n*x + 1 - jj);
wr(jj) = quad(h_wr, (jj-2)/n, jj/n); % < w_0, \phi_i >
end
w_0 = M \ wr;
ODE_opt = odeset('Mass', M); % constant mass matrix
h_rhs = @(t, w) -K*w + NL(w, c_array, n, M); % handle for rhs function
[T, W] = ode15s(h_rhs, t_array, w_0, ODE_opt);% invoke ODE solver
return
end
function val = NL (w, c, n, M )
%*****************************************************************************80
%
%% NL evaluates the nonlinear term in the reaction-diffusion equation.
%
val = (c(1)/n)* [1; 2*ones(n-1,1); 1] ... % constant
+ c(2) * M * w ... % linear
+ c(3) * Nq(w, n) ... % quadratic
+ c(4) * Nc(w, n) ; % cubic
return
end
function val = Nq(w, n)
%*****************************************************************************80
%
%% NQ evaluates a quadratic nonlinear finite element function.
%
w2 = w(:).^2; wx = (w(1:end-1,1)+ w(2:end,1)).^2;
val = [2*w2(1)+wx(1); wx(1:end-1)+4*w2(2:end-1)+wx(2:end) ; ...
wx(end)+2*w2(end)]/(12*n);
return
end
function val = Nc(w, n)
%*****************************************************************************80
%
%% NC evaluates a cubiic nonlinear finite element function.
%
w2 = w(:).*w(:); w3 = w(:).*w2(:); wx = (w(1:end-1,1)+w(2:end,1)).^3;
val = [3*w3(1)+wx(1)-w(1)*w(2)^2;
wx(1:end-1)+6*w3(2:end-1)+wx(2:end)-w(2:end-1).*(w2(1:end-2)+w2(3:end));
wx(end)+3*w3(end)-w(end)*w(end-1)^2]/(20*n);
return
end
|
{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-unused-matches -fno-warn-name-shadowing -fno-warn-missing-signatures #-}
{-# LANGUAGE FlexibleInstances, ConstraintKinds, ExistentialQuantification, GADTs, RankNTypes, MultiParamTypeClasses, RankNTypes, UndecidableInstances, FlexibleContexts, TypeSynonymInstances #-}
---------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------
-- |
-- | Module : First attempt at approximate counting
-- | Creator: Xiao Ling
-- | Created: 12/08/2015
-- | TODO : test standard deviation of alpha, beta, and final version
-- |
---------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------
module Morris (
morris
, morris'
, morris1
, morris1'
) where
import Control.Monad.Random
import Control.Monad.Random.Class
import Data.Conduit
import Data.List.Split
import qualified Data.Conduit.List as Cl
import Core
import Statistics
{-----------------------------------------------------------------------------
I. Morris Algorithm list of counter
------------------------------------------------------------------------------}
---- * Count the number of items in `as` to within `eps` of actual
---- * with confidence `delta`
morris' :: EpsDelta -> Batch a IO Counter
morris' ed = morris ed `using` evalRandIO
morris :: MonadRandom m => EpsDelta -> Streaming a m Counter
morris (ED e d) = medianOfMeans $ go cs
where cs = replicate (t*m) 0
t = round $ 1/(e^2*d) :: Int
m = round . log $ 1/d
go cs = (\c -> 2^(round c) - 1) `ffmap` Cl.foldM (\cs _ -> traverse incr cs) cs
ffmap = fmap . fmap
medianOfMeans = fmap median' . (fmap . fmap) mean' . fmap (chunksOf t)
{-----------------------------------------------------------------------------
II. Morris Algorithm list of list of counter
------------------------------------------------------------------------------}
---- * Count the number of items in `as` to within `eps` of actual
---- * with confidence `delta`
morris1' :: EpsDelta -> Batch a IO Counter
morris1' ed = morris1 ed `using` evalRandIO
-- * Run on stream inputs `as` for t independent trials for `t = 1/eps^2 * d`,
-- * and `m` times in parallel, for `m = log(1/d)` and take the median
morris1 :: MonadRandom m => EpsDelta -> Streaming a m Counter
morris1 (ED e d) = medianOfMeans $ go ccs
where
medianOfMeans = fmap median' . (fmap . fmap) mean'
ccs = replicate m $ replicate t 0
t = round $ 1/(e^2*d)
m = round . log $ 1/d
go ccs = (\x -> 2^(round x) - 1) `fffmap` Cl.foldM (\xs _ -> incrs' xs) ccs
fffmap = fmap . fmap . fmap
-- * given a list of list of counters toss a coin for each counter and incr
-- * this can be flattened
incrs' :: MonadRandom m => [[Counter]] -> m [[Counter]]
incrs' = sequence . fmap (sequence . fmap incr)
{-----------------------------------------------------------------------------
III. Utils
------------------------------------------------------------------------------}
-- * Increment a counter `x` with probability 1/2^x
incr :: MonadRandom m => Counter -> m Counter
incr x = do
h <- toss . coin $ 0.5^(round x)
return $ if isHead h then (seq () succ x) else seq () x
mean', median' :: (Floating a, Ord a, RealFrac a) => [a] -> Float
mean' = fromIntegral . round . mean
median' = fromIntegral . round . median
|
function template(t::String)
"""
<!DOCTYPE html>
<html lang="en">
<head>
<title>BAWJ</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<style>
table, th, td {
border: 1px solid black;
padding: 0.5em;
border-collapse: collapse;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-md bg-dark navbar-dark">
<!-- Brand -->
<a class="navbar-brand" href="#">AppliGate</a>
<!-- Toggler/collapsibe Button -->
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
<span class="navbar-toggler-icon"></span>
</button>
<!-- Navbar links -->
<div class="collapse navbar-collapse" id="collapsibleNavbar">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="/">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/agingreport">Aging Report</a>
</li>
</ul>
</div>
</nav>
$(t)
</body>
</html>
"""
end
function index(c::WebController)
render(HTML, template("<h2>Hello World!</h2>"))
end
function aging_report(c::WebController)
r = @fetchfrom ar_pid report()
result =
"""
<h1>Aging Report</h1>
<table>
<th>Invoice</th><th>Customer</th><th>Date</th><th>Amount</th><th>Age</th>
"""
for n = 1:length(r)
result = result * """
<tr>
<td>$(r[n].id_inv)</td>
<td>$(r[n].csm)</td><td>$(r[n].inv_date)</td>
<td style='text-align:right'>$(r[n].amount)</td>
<td>$(r[n].days)</td>
</tr>"""
end
result * "</table>"
render(HTML, template("$(result)"))
end
|
Require Import Coq.ZArith.ZArith Coq.omega.Omega Coq.micromega.Lia.
Require Import Crypto.Util.ZUtil.Hints.Core.
Require Import Crypto.Util.ZUtil.Sgn.
Require Import Crypto.Util.ZUtil.Modulo.
Require Import Crypto.Util.ZUtil.Div.
Require Import Crypto.Util.ZUtil.Tactics.ReplaceNegWithPos.
Local Open Scope Z_scope.
Module Z.
Lemma quot_div_full a b : Z.quot a b = Z.sgn a * Z.sgn b * (Z.abs a / Z.abs b).
Proof.
destruct (Z_zerop b); [ subst | apply Z.quot_div; assumption ].
destruct a; simpl; reflexivity.
Qed.
Local Arguments Z.mul !_ !_.
Lemma quot_sgn_nonneg a b : 0 <= Z.sgn (Z.quot a b) * Z.sgn a * Z.sgn b.
Proof.
rewrite quot_div_full, !Z.sgn_mul, !Z.sgn_sgn.
set (d := Z.abs a / Z.abs b).
destruct a, b; simpl; try (subst d; simpl; omega);
try rewrite (Z.mul_opp_l 1);
do 2 try rewrite (Z.mul_opp_r _ 1);
rewrite ?Z.mul_1_l, ?Z.mul_1_r, ?Z.opp_involutive;
apply Z.div_abs_sgn_nonneg.
Qed.
Lemma quot_nonneg_same_sgn a b : Z.sgn a = Z.sgn b -> 0 <= Z.quot a b.
Proof.
intro H.
generalize (quot_sgn_nonneg a b); rewrite H.
rewrite <- Z.mul_assoc, <- Z.sgn_mul.
destruct (Z_zerop b); [ subst; destruct a; unfold Z.quot; simpl in *; congruence | ].
rewrite (Z.sgn_pos (_ * _)) by nia.
intro; apply Z.sgn_nonneg; omega.
Qed.
Lemma mul_quot_eq_full a m : m <> 0 -> m * (Z.quot a m) = a - a mod (Z.abs m * Z.sgn a).
Proof.
intro Hm.
assert (0 <> m * m) by (intro; apply Hm; nia).
assert (0 < m * m) by nia.
assert (0 <> Z.abs m) by (destruct m; simpl in *; try congruence).
rewrite quot_div_full.
rewrite <- (Z.abs_sgn m) at 1.
transitivity ((Z.sgn m * Z.sgn m) * Z.sgn a * (Z.abs m * (Z.abs a / Z.abs m))); [ nia | ].
rewrite <- Z.sgn_mul, Z.sgn_pos, Z.mul_1_l, Z.mul_div_eq_full by omega.
rewrite Z.mul_sub_distr_l.
rewrite Z.mul_comm, Z.abs_sgn.
destruct a; simpl Z.sgn; simpl Z.abs; autorewrite with zsimplify_const; [ reflexivity | reflexivity | ].
repeat match goal with |- context[-1 * ?x] => replace (-1 * x) with (-x) by omega end.
repeat match goal with |- context[?x * -1] => replace (x * -1) with (-x) by omega end.
rewrite <- Zmod_opp_opp; simpl Z.opp.
reflexivity.
Qed.
Lemma quot_sub_sgn a : Z.quot (a - Z.sgn a) a = 0.
Proof.
rewrite quot_div_full.
destruct (Z_zerop a); subst; [ lia | ].
rewrite Z.div_small; lia.
Qed.
Lemma quot_small_abs a b : 0 <= Z.abs a < Z.abs b -> Z.quot a b = 0.
Proof.
intros; rewrite Z.quot_small_iff by lia; lia.
Qed.
Lemma quot_add_sub_sgn_small a b : b <> 0 -> Z.sgn a = Z.sgn b -> Z.quot (a + b - Z.sgn b) b = Z.quot (a - Z.sgn b) b + 1.
Proof.
destruct (Z_zerop a), (Z_zerop b), (Z_lt_le_dec a 0), (Z_lt_le_dec b 0), (Z_lt_le_dec 1 (Z.abs a));
subst;
try lia;
rewrite !Z.quot_div_full;
try rewrite (Z.sgn_neg a) by omega;
try rewrite (Z.sgn_neg b) by omega;
repeat first [ reflexivity
| rewrite Z.sgn_neg by lia
| rewrite Z.sgn_pos by lia
| rewrite Z.abs_eq by lia
| rewrite Z.abs_neq by lia
| rewrite !Z.mul_opp_l
| rewrite Z.abs_opp in *
| rewrite Z.abs_eq in * by omega
| match goal with
| [ |- context[-1 * ?x] ]
=> replace (-1 * x) with (-x) by omega
| [ |- context[?x * -1] ]
=> replace (x * -1) with (-x) by omega
| [ |- context[-?x - ?y] ]
=> replace (-x - y) with (-(x + y)) by omega
| [ |- context[-?x + - ?y] ]
=> replace (-x + - y) with (-(x + y)) by omega
| [ |- context[(?a + ?b + ?c) / ?b] ]
=> replace (a + b + c) with (((a + c) + b * 1)) by lia; rewrite Z.div_add' by omega
| [ |- context[(?a + ?b - ?c) / ?b] ]
=> replace (a + b - c) with (((a - c) + b * 1)) by lia; rewrite Z.div_add' by omega
end
| progress intros
| progress Z.replace_all_neg_with_pos
| progress autorewrite with zsimplify ].
Qed.
End Z.
|
module Meh
import public Control.WellFounded
public export
interface Argh (rel : a -> a -> Type) where
argh : (x : a) -> Accessible rel x
data Meh : Nat -> Nat -> Type where
implementation Argh Meh where
argh x = ?foo
|
//////////////////////////////////////////////////////////////////////////////
/// Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand
/// Copyright 2009 and onward LRI UMR 8623 CNRS/Univ Paris Sud XI
///
/// Distributed under the Boost Software License, Version 1.0
/// See accompanying file LICENSE.txt or copy at
/// http://www.boost.org/LICENSE_1_0.txt
//////////////////////////////////////////////////////////////////////////////
#ifndef NT2_TOOLBOX_SWAR_FUNCTION_SIMD_SSE_AVX_SPLIT_HPP_INCLUDED
#define NT2_TOOLBOX_SWAR_FUNCTION_SIMD_SSE_AVX_SPLIT_HPP_INCLUDED
#include <nt2/sdk/meta/upgrade.hpp>
#include <nt2/sdk/meta/templatize.hpp>
#include <nt2/sdk/meta/adapted_traits.hpp>
#include <nt2/sdk/constant/digits.hpp>
#include <boost/fusion/tuple.hpp>
#include <nt2/sdk/meta/strip.hpp>
#include <nt2/include/functions/details/simd/sse/sse4_1/split.hpp>
/////////////////////////////////////////////////////////////////////////////
// Implementation when type is arithmetic_
/////////////////////////////////////////////////////////////////////////////
NT2_REGISTER_DISPATCH(tag::split_, tag::cpu_,
(A0),
((simd_<arithmetic_<A0>,tag::avx_>))
);
namespace nt2 { namespace ext
{
template<class Dummy>
struct call<tag::split_(tag::simd_<tag::arithmetic_, tag::avx_)),
tag::cpu_, Dummy> : callable
{
template<class Sig> struct result;
template<class This,class A0>
struct result<This(A0)>
{
typedef typename meta::scalar_of<A0>::type stype;
typedef typename meta::upgrade<stype>::type utype;
typedef simd::native<utype,simd::avx_> ttype;
typedef meta::is_floating_point<stype> rtag;
typedef simd::native<typename meta::double_<A0>::type,simd::avx_> dtype;
typedef typename boost::mpl::if_c < rtag::value
, dtype, ttype>::type rtype;
typedef boost::fusion::tuple<rtype,rtype> type;
};
NT2_FUNCTOR_CALL(1)
{
typedef typename meta::scalar_of<A0>::type stype;
typedef meta::is_floating_point<stype> rtag;
typedef typename meta::upgrade<stype>::type utype;
typedef simd::native<utype,simd::avx_> ttype;
typedef typename boost::mpl::if_c<rtag::value,
simd::native<double,simd::avx_>, ttype>::type rtype;
typename NT2_RETURN_TYPE(1)::type res;
typedef rtype tag;
eval( a0
, boost::fusion::at_c<0>(res)
, boost::fusion::at_c<1>(res)
, tag()
);
return res;
}
private:
// template<class A0,class R0,class R1> inline void
// eval(A0 const& a0, R0& r0, R1& r1, const simd::native<typename meta::int16_t_<A0>::type,simd::avx_>&)const
// {
// typedef simd::native<typename meta::int16_t_<A0>::type,simd::avx_> rtype;
// r1 = simd::native_cast<rtype>(_mm_unpackhi_epi8(a0, is_ltz(a0)));
// r0 = simd::native_cast<rtype>(_mm_unpacklo_epi8(a0, is_ltz(a0)));
// }
// template<class A0,class R0,class R1> inline void
// eval(A0 const& a0, R0& r0, R1& r1, const simd::native<typename meta::uint16_t_<A0>::type,simd::avx_ > &)const
// {
// typedef simd::native<typename meta::uint16_t_<A0>::type,simd::avx_> rtype;
// r1 = simd::native_cast<rtype>(_mm_unpackhi_epi8(a0, Zero<A0>()));
// r0 = simd::native_cast<rtype>(_mm_unpacklo_epi8(a0, Zero<A0>()));
// }
// template<class A0,class R0,class R1> inline void
// eval(A0 const& a0, R0& r0, R1& r1, const simd::native<typename meta::int32_t_<A0>::type,simd::avx_ > &)const
// {
// typedef simd::native<typename meta::int32_t_<A0>::type,simd::avx_> rtype;
// r1 = simd::native_cast<rtype>(_mm_unpackhi_epi16(a0, is_ltz(a0)));
// r0 = simd::native_cast<rtype>(_mm_unpacklo_epi16(a0, is_ltz(a0)));
// }
// template<class A0,class R0,class R1> inline void
// eval(A0 const& a0, R0& r0, R1& r1, const simd::native<typename meta::uint32_t_<A0>::type,simd::avx_ > &)const
// {
// typedef simd::native<typename meta::uint32_t_<A0>::type,simd::avx_> rtype;
// r1 = simd::native_cast<rtype>(_mm_unpackhi_epi16(a0, Zero<A0>()));
// r0 = simd::native_cast<rtype>(_mm_unpacklo_epi16(a0, Zero<A0>()));
// }
// template<class A0,class R0,class R1> inline void
// eval(A0 const& a0, R0& r0, R1& r1, const simd::native<typename meta::int64_t_<A0>::type,simd::avx_ > &)const
// {
// typedef simd::native<typename meta::int64_t_<A0>::type,simd::avx_> rtype;
// r1 = simd::native_cast<rtype>(_mm_unpackhi_epi32(a0, Zero<A0>()));
// r0 = simd::native_cast<rtype>(_mm_unpacklo_epi32(a0, Zero<A0>()));
// }
template<class A0,class R0,class R1> inline void
eval(A0 const& a0, R0& r0, R1& r1, const simd::native<typename meta::int64_t_<A0>::type,simd::avx_ > &)const
{
typedef simd::native<typename meta::int64_t_<A0>::type,simd::avx_> rtype;
typedef simd::native<typename meta::float_ <A0>::type,simd::avx_> ftype;
#define CAST(TYPE, CAT, A) simd::native_cast<simd::native<TYPE, simd::CAT> >(A)
ftype a00 = {CAST(float, avx_,_mm256_permute_pd(CAST(double, avx_,a0), 0xFF))};
r1 = simd::native_cast<rtype>(_mm256_unpackhi_ps(a00, Zero<ftype>()));
r0 = simd::native_cast<rtype>(_mm256_unpacklo_ps(a00, Zero<ftype>()));
#undef CAT
}
template<class A0,class R0,class R1> inline void
eval(A0 const& a0, R0& r0, R1& r1, const simd::native<typename meta::double_<A0>::type,simd::avx_> &)const
{
r0 = _mm256_cvtps_pd(_mm256_extractf128_ps(a0, 0)) ;
r1 = _mm256_cvtps_pd(_mm256_extractf128_ps(a0, 1)) ;
}
};
} }
#endif
// modified by jt the 05/01/2011 |
import game.modify.basic game.value
open game
open list
/-- the values of two games, that differ in exactly one component by at most d
d, differ by at most d-/
theorem MITM (G1 G2 : game 2) (d : ℤ) (p : game.modify G1 G2 d):
abs(G1.value - G2.value) ≤ d :=
begin
revert G1,
revert G2,
-- induction on size of G2 (using our recursor)
apply @game.rec_on_size2 (λ G2, ∀ G1, modify G1 G2 d →
abs (game.value G1 - game.value G2) ≤ d),
{ -- base case : G2 = zero 2
intros G1 p,
have hx : G1.size2 = (zero 2).size2 := eq_size_of_modify p, -- see game.modify.basic
rw size2_zero at hx, -- (zero 2).size2 = 0
have hy := eq_zero_of_size2_zero _ hx, -- hy is G1 = zero 2 (true by hx)
rw hy,
show 0 ≤ d, -- as by defintions of abs abd value, abs (value (zero 2) - value (zero 2)) = 0
exact abs_le_nonneg p.hl.bound,}, -- see misc_lemmas
{ -- inductive step : G2 has size n + 1
/- in the following we switched the names of G1 and G2, so now G1 is
initially assumed to have size n + 1-/
intros n H G1 h1 G2 p, -- H is the inductive hypothesis and h1 says G1.size2 = n + 1
have h2 := eq_size_of_modify p, -- h2 is size2 G2 = size2 G1 (see game.modify.basic)
rw h1 at h2, -- so now h2 is size2 G2 = n + 1, the parallel hypothesis to h1
/- now that we have h1 and h2, we can use our simplified value definition
(other arguments inferred)-/
rw game.value_def _ _ h2,
rw game.value_def _ _ h1,
apply list.min_change, -- se list.min.basic
/- necessary hypothesis for list.min : the lengths of the lists are the same
(whivh ia true because the sizes of the games are the same) -/
{ rw length_bind, dsimp,
rw [length_of_fn, length_of_fn],
rw length_bind, dsimp,
rw [length_of_fn, length_of_fn],
show G2.size = G1.size,
rw size_eq_size2,
rw size_eq_size2,
rw [h1, h2]},
/- because list.min takes as an argument, that the list we take the minimum
of is non-empty, these hypotheses for list.min_change are inferred from those
and need not be proved again-/
-- now we just need to prove hdist (see list.min.basic)
/- intuitively, we know this is true because G1 and G2 are modified games-/
intros i hiL hiM,
rw length_bind at hiL hiM,
dsimp at hiL hiM, /-because hiM and hiL are needed by nth_le, simplifying creates
new hypotheses -/
rw [length_of_fn, length_of_fn] at hiL_1 hiM_1,
rw sum_list2 at hiL_1,
rw sum_list2 at hiM_1,
/- now hiL_1 is : i < length (G2.f 0) + length (G2.f 1),
and hiM_1 is the similare statement for G1 -/
simp only [list.bind_fin2],
/- we just simplified a bit. Now as we viewed the lists of components
as the lists of chains and loops as bound together with list.bind we
need to consider two cases. Either the component considered is a chain
( ie. i < length (G2.f 0)) or it is a loop. That is important,
because we will case by case consider where G1 and G2 are modified-/
by_cases hi2 : i < length (G2.f 0),
{ -- hi2 : i < length (G2.f 0)
/- as the games are modified their chain and loop lists have the same lengths,
hence :-/
have lengthf0 : length (G2.f 0) = length (G1.f 0),
{apply eq_list_lengths_of_modify p},
have hi1 : i < length (G1.f 0),
{rw ←lengthf0, exact hi2},
/- so we can use this to show the elements we are comparing for hdist are both
chains and we can get rid of the appension of the list of values in case
we opened a loop-/
rw nth_le_append _ _,
swap,
{ rw length_of_fn,
exact hi2,
},
rw nth_le_append _ _,
swap,
{ rw length_of_fn,
exact hi1,
},
-- simplifying (see list.lemmas.simple)
rw nth_le_of_fn' _ _ hi2,
rw nth_le_of_fn' _ _ hi1,
/- now the goal is just
abs(nth_le (G2.f 0) (⟨i, hi2⟩.val) _ - (2 * ↑(0.val) + 2) +
abs (2 * ↑(0.val) + 2 - value (remove G2 0 ⟨i, hi2⟩)) -
(nth_le (G1.f 0) (⟨i, hi1⟩.val) _ - (2 * ↑(0.val) + 2) +
abs (2 * ↑(0.val) + 2 - value (remove G1 0 ⟨i, hi1⟩)))) ≤ d
Now we dive into the case by case consideration, of whether a chain
or a loop has been modified-/
by_cases hj : p.j = 0,
{ -- hj is p.j = 0 (ie. a chain has been modified)
set pl := p.hl with hpl,
set pn := pl.n with pln,
/- now either i stands for exacty the modified chain p.n (= pn)
or not-/
by_cases hni : pn = i,
{ -- hni : pn = i (i stands for the modified chain)
/- in that case removing component i makes the games exactly
the same, giving the following-/
have hG1G2 : game.remove G1 0 ⟨i, hi1⟩ = game.remove G2 0 ⟨i, hi2⟩,
{ apply game.ext, -- see game.basic
intros a ha,
cases a with a,
{ -- a = 0
unfold game.remove,
dsimp,
-- the if-condition in game.remove evaluates to true as ⟨0, ha⟩ = 0
rw dif_pos, swap, refl,
rw dif_pos, swap, refl,
rw ←hni,
rw pln,
convert pl.heq.symm; rw hj, -- this is then true by field heq of p.hl and hj
},
{ -- nat.succ a (a = 1, as a < 2 as it is a value of some object of type fin 2)
cases a with a,
swap,
{-- nat.succ (nat.succ a), which contradicts ha
cases ha,
cases ha_a,
cases ha_a_a}, -- do cases until Lean trivially sees the contradiction
-- a = 1
unfold game.remove,
dsimp,
-- the if-condition in game.remove is false, as we do not have ⟨1, ha⟩ = 0
rw dif_neg, swap, exact dec_trivial,
rw dif_neg, swap, exact dec_trivial,
/- so we just need to prove G1.f ⟨1, ha⟩ = G2.f ⟨1, ha⟩
as we are modifying a chain, this is true by field hj of p-/
convert (p.hj 1 _).symm using 1,
rw hj,
exact dec_trivial,
}
},
rw hG1G2,
/- with the resulting games after playing in component i being the same,
we just have to show the ith components differ by at most d.
That is basically what p.hl.bound says-/
convert pl.bound using 1,
apply congr_arg,
dsimp,
simp only [pln.symm, hni, hj],
ring
},
{ -- hni : ¬ (pn = i) (i does not stand for the modified chain)
/- in this case nth_le (G2.f 0) i _ = nth_le (G1.f 0) i _
and we can use the inductive hypothesis -/
have nth_le_eq : nth_le (G2.f 0) i hi2 = nth_le (G1.f 0) i hi1,
{apply list.modify_same _ i hi2 hi1 _, -- see list.modify.basic
-- an integer d
{exact d},
-- modify (G2.f 0) (G1.f 0) d
{simp only [hj] at pl,
exact pl},
/-(eq.mp _ pl).n ≠ i (basically just pl.n ≠ i, but we have a duplicate naming issue
for hypotheses which basically say the same (because of the simp only at pl, which
created a new pl, as the old one in that exact form was needed elsewhere))-/
convert hni,
rw eq_comm,
exact hj,
rw eq_comm,
exact hj,
-- prove eq.mp _ pl == pl, ie just the duplicate naming issue
-- one-line proof lean constructed by searchin through the library
exact cast_heq
((λ (A A_1 : list ℤ) (e_1 : A = A_1) (B B_1 : list ℤ) (e_2 : B = B_1) (d d_1 : ℤ) (e_3 : d = d_1),
congr (congr (congr_arg list.modify e_1) e_2) e_3)
(G2.f (p.j))
(G2.f 0)
((λ (c c_1 : game 2) (e_1 : c = c_1) (a a_1 : fin 2) (e_2 : a = a_1), congr (congr_arg f e_1) e_2) G2 G2
(eq.refl G2)
(p.j)
0
hj)
(G1.f (p.j))
(G1.f 0)
((λ (c c_1 : game 2) (e_1 : c = c_1) (a a_1 : fin 2) (e_2 : a = a_1), congr (congr_arg f e_1) e_2) G1 G1
(eq.refl G1)
(p.j)
0
hj)
d
d
(eq.refl d))
pl},--up to here by library_search
rw nth_le_eq,
/- so it suffices to prove the absolute value terms differ by at most d-/
suffices : abs
(abs (2 - game.value (game.remove G2 0 ⟨i, hi2⟩)) -
abs (2 - game.value (game.remove G1 0 ⟨i, hi1⟩))) ≤ d,
{ -- proof that this actually implies the result
convert this using 2,
rw [(show ((0 : fin 2).val : ℤ) = 0, by norm_cast), mul_zero, zero_add],
ring,
},
apply le_trans (abs_abs_sub_abs_le _ _), -- see misc_lemmas
/- now by using game.remove_of_modify we can prove the games with chain i
removed are also modified versions of each other, and then as they have sizen,
the inductive hypothesis and some term cancelling solve the goal-/
-- need the following as argument for game.remove_of_modify
have ho : 0 ≠ p.j ∨ (0 = p.j ∧ ((⟨i, hi2⟩ : fin (length (G2.f 0))).val) ≠ p.hl.n),
{right, -- the right side of the ∨ is true
split,
exact hj.symm, -- 0 = p.j
rw eq_comm at hni,
exact hni,}, /-((⟨i, hi2⟩ : fin (length (G2.f 0))).val) ≠ p.hl.n
which is what hni says-/
have hmod := (game.remove_of_modify_symm p 0 ⟨i, hi2⟩ ⟨i, hi1⟩ (by refl) ho), -- the reduced games are modified
have Hind := (H (game.remove G2 0 ⟨i, hi2⟩) _ (game.remove G1 0 ⟨i, hi1⟩) hmod), -- result of inductive hypothesis
swap,
-- proving size2 (remove G2 0 ⟨i, hi2⟩) = n (necessary hypothesis for H)
{rw game.size2_remove, -- size2 (remove G2 0 ⟨i, hi2⟩) = size2 G2 - 1
rw h2,
exact nat.add_sub_cancel n 1,
},
convert Hind using 2, -- goal is basically Hind (subject to terms cancelling)
ring, -- using that (ℤ,*,+) is a ring (commutativity and associativity, etc.)
},
},
/- This concludes the case where a chain has been modified. If a loop has been
modified, the chains are all exactly the same. So just as before,
nth_le (G2.f 0) i hi2 = nth_le (G1.f 0) i hi1 and we can use the inductive
hypothesis-/
{ -- hj is ¬ (p.j = 0) (ie. a loop has been modified)
have G1G2_1 : G2.f 0 = G1.f 0,
{rw eq_comm at hj,
exact p.hj 0 hj},
simp only [G1G2_1], -- simp only because of nth_le
{ have ho : 0 ≠ p.j ∨ (0 = p.j ∧ ((⟨i, hi2⟩ : fin (length (G2.f 0))).val) ≠ p.hl.n),
{left, -- the left side of ∨ is true
rw eq_comm at hj,
exact hj,},
have hmod := (game.remove_of_modify_symm p 0 ⟨i, hi2⟩ ⟨i, hi1⟩ (by refl) ho),
have Hind := (H (game.remove G2 0 ⟨i, hi2⟩) _ (game.remove G1 0 ⟨i, hi1⟩) hmod),
swap,
{rw game.size2_remove,
rw h2,
exact nat.add_sub_cancel n 1,
},
suffices : abs
(abs (2 - game.value (game.remove G2 0 ⟨i, hi2⟩)) -
abs (2 - game.value (game.remove G1 0 ⟨i, hi1⟩))) ≤ d,
{ convert this using 2,
rw [(show ((0 : fin 2).val : ℤ) = 0, by norm_cast), mul_zero, zero_add],
ring,
},
apply le_trans (abs_abs_sub_abs_le _ _),
convert Hind using 2,
ring,
},
},
},
/-This concludes the proof in the case that i represented a chain, now we consider
i to represent a loop -/
{ -- hi2 : ¬ (i < length (G2.f 0)) (we are considering a loop)
push_neg at hi2, -- hi2 is length (G2.f 0) ≤ i
/- similar to the other case, we can get rid of the lists of values
in case we opened a chain, which the other values are appended to in
the goal, by adjusting the index (subtracting the length of the first list)-/
rw nth_le_append_right _ _,
swap,
{ rw length_of_fn,
exact hi2,
},
rw nth_le_append_right _ _,
swap,
{ rw length_of_fn,
convert hi2 using 1,
symmetry,
apply eq_list_lengths_of_modify p,
},
-- through hiL_1, hi2 and the fact the games are modied, we have the following hypotheses
have hi_new2 : i - length (G2.f 0) < length (G2.f 1),
{ rwa [nat.sub_lt_right_iff_lt_add hi2, add_comm],},
have h1length : length (G2.f 1) = length (G1.f 1),
{apply eq_list_lengths_of_modify p},
have hi_new1 : i - length (G2.f 0) < length (G1.f 1),
{rw ←h1length,
exact hi_new2},
have hi_new1' : i - length (G1.f 0) < length (G1.f 1),
{convert hi_new1 using 2,
symmetry,
apply eq_list_lengths_of_modify p},
have h0length : length (G2.f 0) = length (G1.f 0),
{apply eq_list_lengths_of_modify p},
/- hi_new1, hi_new1' and h_new2 are what we will need instead of hi1 and
hi2 in this case, as the index has been shifted, when we got rid of the
pre-appended list -/
simp only [length_of_fn],
-- simplifying (see list.lemmas.simple)
rw nth_le_of_fn' _ _ hi_new2,
rw nth_le_of_fn' _ _ hi_new1',
/- now the goal is just
abs (nth_le (G2.f 1) (⟨i - length (G2.f 0), hi_new2⟩.val) _ - (2 * ↑(1.val) + 2) +
abs (2 * ↑(1.val) + 2 - value (remove G2 1 ⟨i - length (G2.f 0), hi_new2⟩)) -
(nth_le (G1.f 1) (⟨i - length (G1.f 0), hi_new1'⟩.val) _ - (2 * ↑(1.val) + 2) +
abs (2 * ↑(1.val) + 2 - value (remove G1 1 ⟨i - length (G1.f 0), hi_new1'⟩)))) ≤ d
Now, again, we dive into the case by case consideration, of whether a chain
or a loop has been modified-/
by_cases hj : p.j = 1,
{ -- hj is p.j = 1 (ie. a loop has been modified)
set pl := p.hl with hpl,
set pn := pl.n with pln,
/- now either i stands for exacty the modified loop p.n (= pn)
or not (i was the index in (chains ++ loops), so the index
is this time i - length (G2.f 0)-/
by_cases hni : pn = i - length (G2.f 0),
{ -- hni : pn = i - length (G2.f 0) (i stands for the modified loop)
/- in that case removing component i makes the games exactly
the same, giving the following-/
have hG1G2 : game.remove G1 1 ⟨i - length (G1.f 0), hi_new1'⟩ =
game.remove G2 1 ⟨i - length (G2.f 0), hi_new2⟩,
{ apply game.ext, -- see game.basic
intros a ha,
cases a with a,
{ -- a = 0
unfold game.remove,
dsimp,
/- the if-condition in game.remove evaluates to false as we do
not have ⟨0, ha⟩ = 1 -/
rw dif_neg, swap, exact dec_trivial,
rw dif_neg, swap, exact dec_trivial,
/- so we just need to prove G1.f ⟨0, ha⟩ = G2.f ⟨0, ha⟩
as we are modifying a chain, this is true by field hj of p-/
convert (p.hj 0 _).symm using 1,
rw hj,
exact dec_trivial,
},
{ -- nat.succ a (a = 1, as a < 2 as it is a value of some object of type fin 2)
cases a with a,
swap,
{ -- nat.succ (nat.succ a) , contradicts ha
cases ha,
cases ha_a,
cases ha_a_a}, -- do cases until Lean trivially sees the contradiction
unfold game.remove,
dsimp,
-- the if-condition in game.remove evaluates to true as ⟨1, ha⟩ = 1
rw dif_pos, swap, refl,
rw dif_pos, swap, refl,
rw ← eq_list_lengths_of_modify p 0,
rw ←hni,
rw pln,
convert pl.heq.symm; rw ← hj, -- this is then true by field heq of p.hl and hj
}
},
rw hG1G2,
/- with the resulting games after playing in component i being the same,
we just have to show the ith components differ by at most d.
That is basically what p.hl.bound says-/
convert pl.bound using 1,
apply congr_arg,
dsimp,
simp only [pln.symm, hni, hj],
simp only [eq_list_lengths_of_modify p 0],
ring,
},
{ -- hni : ¬ (pn = i) (i does not stand for the modified chain)
/- in this case nth_le (G2.f 1) (i - length (G2.f 0)) _ =
(G1.f 1) (i - length (G2.f 0)) _ ,
and we can use the inductive hypothesis -/
have nth_le_eq : nth_le (G2.f 1) (i - length (G2.f 0)) hi_new2
= nth_le (G1.f 1) (i - length (G2.f 0)) hi_new1,
{apply list.modify_same _ (i - length (G2.f 0)) hi_new2 hi_new1 _, -- see list.modify.basic
-- an integer d
{exact d},
-- modify (G2.f 1) (G1.f 1) d
{simp only [hj] at pl,
exact pl},
/-(eq.mp _ pl).n ≠ i - length (G2.f 0) (basically just pl.n ≠ i - length (G2.f 0),
but we have a duplicate naming issue for hypotheses which basically says the same
(because of the simp only at pl, which created a new pl, as the old one in that exact
form was needed elsewhere)-/
convert hni,
rw eq_comm,
exact hj,
rw eq_comm,
exact hj,
-- prove eq.mp _ pl == pl, ie just the duplicate naming issue
-- one-line proof lean constructed by searchin through the library
exact cast_heq
((λ (A A_1 : list ℤ) (e_1 : A = A_1) (B B_1 : list ℤ) (e_2 : B = B_1) (d d_1 : ℤ) (e_3 : d = d_1),
congr (congr (congr_arg list.modify e_1) e_2) e_3)
(G2.f (p.j))
(G2.f 1)
((λ (c c_1 : game 2) (e_1 : c = c_1) (a a_1 : fin 2) (e_2 : a = a_1), congr (congr_arg f e_1) e_2) G2 G2
(eq.refl G2)
(p.j)
1
hj)
(G1.f (p.j))
(G1.f 1)
((λ (c c_1 : game 2) (e_1 : c = c_1) (a a_1 : fin 2) (e_2 : a = a_1), congr (congr_arg f e_1) e_2) G1 G1
(eq.refl G1)
(p.j)
1
hj)
d
d
(eq.refl d))
pl},--up to here by library_search
rw nth_le_eq,
/- so it suffices to prove the absolute value terms differ by at most d-/
suffices : abs (
abs (4 - game.value (game.remove G2 1 ⟨i - length (G2.f 0), hi_new2⟩))
- abs (4 - game.value (game.remove G1 1 ⟨i - length (G1.f 0), hi_new1'⟩))
) ≤ d,
{ -- proof that this actually implies the result
convert this using 2,
rw (show (((1 : fin 2).val) : ℤ) = 1, by norm_cast),
simp only [h0length],
ring,
},
refine le_trans (abs_abs_sub_abs_le _ _) _, -- see misc_lemmas (le_trans is transitivity of ≤ )
/- now by using game.remove_of_modify we can prove the games with loop (i - length (G2.f 0))
removed are also modified versions of each other, and then as they have size n,
the inductive hypothesis and some term cancelling solve the goal-/
-- need the following as argument for game.remove_of_modify
have ho : 1 ≠ p.j ∨ (1 = p.j ∧ ((⟨i - length (G2.f 0), hi_new2⟩: fin (length (G2.f 1))).val) ≠ p.hl.n),
{right, -- the right side of the ∨ is true
split,
exact hj.symm, -- 1 = p.j
rw eq_comm at hni,
exact hni,}, /-((⟨i - length (G2.f 0), hi_new2⟩: fin (length (G2.f 1))).val) ≠ p.hl.n
which is what hni says-/
have hmod := (game.remove_of_modify_symm p 1 ⟨i - length (G2.f 0), hi_new2⟩ ⟨i - length (G1.f 0), hi_new1'⟩ _ ho), -- the reduced games are modified
swap,
{simp only [h0length],}, /- proving ⟨i - length (G2.f 0), hi_new2⟩.val = ⟨i - length (G1.f 0), hi_new1'⟩.val
(necessary hypothesis for game.remove_of_modify_symm)-/
have Hind := (H (game.remove G2 1 ⟨i - length (G2.f 0), hi_new2⟩) _ (game.remove G1 1 ⟨i - length (G1.f 0), hi_new1'⟩) hmod), -- result of inductive hypothesis
{ -- goal is basically Hind (subject to terms cancelling)
convert Hind using 2,
ring, -- using that (ℤ,*,+) is a ring (commutativity and associativity, etc.)
},
{ -- proving size2 (remove G2 1 ⟨i - length (G2.f 0), hi_new2⟩) = n (necessary hypothesis for H)
rw game.size2_remove, -- size2 (remove G2 1 ⟨i - length (G2.f 0), hi_new2⟩) = size2 G2 - 1
rw h2,
exact nat.add_sub_cancel n 1,
},
},
},
/- This concludes the case where a loop has been modified. If a chain has been
modified, the loops are all exactly the same. So just as before,
nth_le (G2.f 1) (i - length (G2.f 0)) hi_new2 = nth_le (G1.f 1) (i - length (G2.f 0)) hi_new1
and we can use the inductive hypothesis-/
{ -- hj is ¬ (p.j = 1) (ie. a chain has been modified)
have G1G2_1 : G2.f 1 = G1.f 1,
{rw eq_comm at hj,
exact p.hj 1 hj},
simp only [G1G2_1], --simp only because of nth_le
suffices : abs (
abs (4 - game.value (game.remove G2 1 ⟨i - length (G2.f 0), hi_new2⟩))
- abs (4 - game.value (game.remove G1 1 ⟨i - length (G1.f 0), hi_new1'⟩))
) ≤ d,
{ convert this using 2,
rw (show (((1 : fin 2).val) : ℤ) = 1, by norm_cast),
simp only [h0length],
ring,
},
refine le_trans (abs_abs_sub_abs_le _ _) _,
have ho : 1 ≠ p.j ∨ (1 = p.j ∧ ((⟨i - length (G2.f 0), hi_new2⟩: fin (length (G2.f 1))).val) ≠ p.hl.n),
{left, -- the left side of the ∨ is true
rw eq_comm at hj,
exact hj,},
have hmod := (game.remove_of_modify_symm p 1 ⟨i - length (G2.f 0), hi_new2⟩ ⟨i - length (G1.f 0), hi_new1'⟩ _ ho),
have Hind := (H (game.remove G2 1 ⟨i - length (G2.f 0), hi_new2⟩) _ (game.remove G1 1 ⟨i - length (G1.f 0), hi_new1'⟩) hmod),
{ convert Hind using 2,
ring,
},
{rw game.size2_remove,
rw h2,
exact nat.add_sub_cancel n 1,
},
{simp only [h0length],},
},
},
},
end |
According to jazz writer Francis Davis , " a modest commercial breakthrough seemed imminent " for Coleman , who appeared to be regaining his celebrity . German musicologist Peter Niklas Wilson said the album may have been the most tuneful and commercial @-@ sounding of his career at that point . The album 's clean mix and relatively short tracks were interpreted as an attempt for radio airplay by Mandel , who described its production as " the surface consistency that would put it in the pop sphere " . Of Human Feelings had no success on the American pop charts , only charting on the Top Jazz Albums , where it spent 26 weeks and peaked at number 15 . Because the record offered a middle ground between funk and jazz , McRae argued that it consequently appealed to neither demographic of listeners . Sound & Vision critic Brent Butterworth speculated that it was overlooked because it had electric instruments , rock and funk drumming , and did not conform to what he felt was the hokey image of jazz that many of the genre 's fans preferred . The album later went out of print .
|
{-# LANGUAGE BangPatterns #-}
-- file: Astro/Misc.hs
-- Miscellaneous utilities
module Astro.Misc where
import Data.List
import Debug.Trace
import Numeric.LinearAlgebra
import Numeric (showEFloat)
import Text.Printf
{-
- General math
-}
type Polynomial = [Double]
-- Evaluate real polynomial given as list of coefficients [a0,a1,...]
evalPoly :: Polynomial->Double->Double
evalPoly p x = sum $ zipWith (*) p $ map (x^) [0..]
-- Derivative of a (real) polynomial
diffPoly :: Polynomial->Polynomial
diffPoly [] = []
diffPoly (a0:[]) = []
diffPoly (a0:as) = zipWith (*) as [1..]
-- Degree of a polynomial
degPoly :: Polynomial->Int
degPoly [] = 0
degPoly (a:[]) = if a /= 0 then 1 else 0
degPoly p = if l == [] then 0 else last l
where
l = Data.List.findIndices (/= 0) p
-- Laguerre polynomial root finder
-- Returns Nothing if fails to converge to a real root within maxIt
rootLaguerre (tol,maxIt) p x0 = result
where
result = helper x0 0
p' = diffPoly p
p'' = diffPoly p'
deg = fromIntegral $ degPoly p
helper x n
| isNaN x = Nothing
| abs (evalPoly p x) <= tol = Just x
| n >= maxIt = Nothing -- `debug` ("maxit x,nx:"++show(x,nx))
| otherwise = helper nx (n+1)
{-
`debug` (printf ("g:n %g h: %g sqa: %g sq: %g x:"
++"%g y: %g") g h sqarg sq nx y)
-}
where
g = evalPoly p' x / evalPoly p x
h = g^2 - evalPoly p'' x / evalPoly p x
sqarg = (deg-1)*(deg*h-g^2)
sq = sqrt sqarg
denom = if g>0 then g+sq else g-sq
nx = x - deg/denom -- `debug` ("n,denom:"++show(n,denom))
y = evalPoly p nx
{-
- Vector Math
-}
-- Standard vector norms
norm :: Vector Double -> Double
--norm v = pnorm PNorm2 v
-- XXX: For 3-vectors this is quite a bit faster
norm !v = sqrt $ v@>0*v@>0 + v@>1*v@>1 + v@>2*v@>2
norm3D :: Vector Double -> Double
norm3D = sqrt . sqrNorm3D
sqrNorm3D :: Vector Double -> Double
sqrNorm3D v = v@>0*v@>0 + v@>1*v@>1 + v@>2*v@>2
-- Normalize vector
unitV v = scale (recip $ norm v) v
-- 3-vector cross product
cross :: Vector Double->Vector Double->Vector Double
cross !a !b = 3|>[a@>1 * b@>2 - a@>2 * b@>1
,-a@>0 * b@>2 + a@>2 * b@>0
,a@>0 * b@>1 - a@>1 * b@>0]
-- Rodrigues' rotation formula
rodr :: Vector Double->Double->Vector Double->Vector Double
rodr z th vec = scale (cos th) vec + scale (sin th) (cross z vec)
+ scale ((z<.>vec)*(1-cos th)) z
{-
- List and tuple manipulations
-}
thrd (_,_,a) = a
frth (_,_,_,a) = a
-- Give all pairings, excluding (p,p) and when (p1,p2) excluding (p2,p1)
-- Courtesy of Jussi Knuuttila
chooseTwo :: [a] -> [(a,a)]
chooseTwo as = concatMap pairs (tails as)
where pairs [] = []
pairs (a:as) = zip (repeat a) as
-- Take every nth of list
takenth 0 _ = []
takenth _ [] = []
takenth n list =
iter list []
where
iter [] acc = acc
iter list acc =
iter (tail newList) (acc ++ [head newList])
where newList = drop (n-1) list
-- Debugging and printing functions
debug = flip trace
showFloat f = showEFloat (Just 4) f ""
|
! =============================================================================
! Test the vorticity tendency
!
! This unit test checks the calculation of the vorticity tendency using the
! Beltrami flow:
! u(x, y, z) = (k^2 + l^2)^(-1) * [k*m*sin(mz) - l*alpha*cos(m*z) * sin(k*x + l*y)]
! v(x, y, z) = (k^2 + l^2)^(-1) * [l*m*sin(mz) + k*alpha*cos(m*z) * sin(k*x + l*y)]
! w(x, y, z) = cos(m*z) * cos(k*x + l*y)
! The vorticity of this flow is
! xi(x, y, z) = alpha * u(x, y, z)
! eta(x, y, z) = alpha * v(x, y, z)
! zeta(x, y, z) = alpha * w(x, y, z)
! For this setting the theoretical vorticity tendency is
! vtend(z, y, x, 1) = alpha*k*m**2 * (k^2+l^2)^(-1)*sin(k*x+l*y)*cos(k*x+l*y)
! vtend(z, y, x, 2) = alpha*l*m**2 * (k^2+l^2)^(-1)*sin(k*x+l*y)*cos(k*x+l*y)
! vtend(z, y, x, 3) = -alpha * m * sin(m*z) * cos(m*z)
! =============================================================================
program test_vtend
use unit_test
use constants, only : one, two, pi, f12, f34, three
use parameters, only : lower, update_parameters, dx, nx, ny, nz, extent
use fields, only : vortg, velog, vtend, tbuoyg, field_default
use inversion_utils, only : init_fft, fftxyp2s
use inversion_mod, only : vor2vel, vor2vel_timer, vorticity_tendency, vtend_timer
use timer
implicit none
double precision :: error
double precision, allocatable :: vtend_ref(:, :, :, :)
integer :: ix, iy, iz, ik, il, im
double precision :: x, y, z, alpha, fk2l2, k, l, m
double precision :: cosmz, sinmz, sinkxly, coskxly
call register_timer('vorticity', vor2vel_timer)
call register_timer('vtend', vtend_timer)
nx = 128
ny = 128
nz = 128
lower = -f12 * pi * (/one, one, one/)
extent = pi * (/one, one, one/)
allocate(vtend_ref(-1:nz+1, 0:ny-1, 0:nx-1, 3))
call update_parameters
call field_default
call init_fft
do ik = 1, 3
k = dble(ik)
do il = 1, 3
l = dble(il)
do im = 1, 3, 2
m = dble(im)
alpha = dsqrt(k ** 2 + l ** 2 + m ** 2)
fk2l2 = one / dble(k ** 2 + l ** 2)
do ix = 0, nx-1
x = lower(1) + ix * dx(1)
do iy = 0, ny-1
y = lower(2) + iy * dx(2)
do iz = -1, nz+1
z = lower(3) + iz * dx(3)
cosmz = dcos(m * z)
sinmz = dsin(m * z)
sinkxly = dsin(k * x + l * y)
coskxly = dcos(k * x + l * y)
! velocity
velog(iz, iy, ix, 1) = fk2l2 * (k * m * sinmz - l * alpha * cosmz) * sinkxly
velog(iz, iy, ix, 2) = fk2l2 * (l * m * sinmz + k * alpha * cosmz) * sinkxly
velog(iz, iy, ix, 3) = cosmz * coskxly
! vorticity
vortg(iz, iy, ix, 1) = alpha * velog(iz, iy, ix, 1)
vortg(iz, iy, ix, 2) = alpha * velog(iz, iy, ix, 2)
vortg(iz, iy, ix, 3) = alpha * velog(iz, iy, ix, 3)
! reference solution
vtend_ref(iz, iy, ix, 1) = alpha * k * m ** 2 * fk2l2 * sinkxly * coskxly
vtend_ref(iz, iy, ix, 2) = alpha * l * m ** 2 * fk2l2 * sinkxly * coskxly
vtend_ref(iz, iy, ix, 3) = -alpha * m * sinmz * cosmz
enddo
enddo
enddo
call vorticity_tendency(vortg, velog, tbuoyg, vtend)
error = max(error, maxval(dabs(vtend_ref(0:nz, :, :, :) - vtend(0:nz, :, :, :))))
enddo
enddo
enddo
call print_result_dp('Test vorticity tendency', error, atol=5.0e-2)
deallocate(vtend_ref)
end program test_vtend
|
Vans is hoping to prove its credentials as the skateboarder brand of choice with the opening of a new skateboard park and creative hub in London.
Located in the five Old Vic Tunnels under Waterloo Station, House of Vans plays host to the only indoor skate park in London, as well as a cinema, music venue, art gallery and bars and restaurants. There is also studio space that young artists can use for free to create a project then see it exhibited in the gallery.
Everything at House of Vans is free to attend, although available on a first come first served basis. The idea, marketing vice president Jeremy de Maillard tells Marketing Week, is to make the space feel like a “house where everyone is welcome”.
He highlights that this is not a short-term project, with Vans leasing the space for five years with the aim of integrating its brand into the local community. Vans will be supporting three local charities as part of the project and investing in the local skateboarding and creative scenes.
“We want this to be a stepping stone for artists and creatives in London. This is a way of showcasing the brand experience – we want to be synonymous with creativity,” de Maillard says.
There are no Vans products for sale at House of Vans, although there is a museum showcasing some of the brands iconic products. De Maillard says the aim is not to sell but to immerse people in the Vans brand and make them feel part of the “Vans family”.
He hopes that by making this investment the brand will experience a boost in brand equity, loyalty and increased purchase consideration and transactions.
It will be launching a membership programme that gives subscribers advantages such as priority for gig tickets and skateboarding sessions. For the most loyal, there are plans to offer “VIP” events such as a private session in the skate park with some of the big names in skateboarding.
Vans will not charge for the scheme itself but will require members to donate what they can afford to its charity partners.
It is also extending the project into the digital world with the aim of reaching a further 1 million people that might not be able to attend the space in person. The whole place is wired with HD cameras and Vans is planning live web casts of big events that will be shared on a dedicated House of Vans London website, as well as on social media.
There is also free Wi-Fi throughout the space so visitors can share their experiences on social media.
“We are trying to mix the digital and physical worlds. The consumer today is on their phone the whole time but we believe there is still a strong need for physical experiences and the more the world becomes digital the more meaningful and impactful those true authentic physical experiences become,” says de Maillard.
London is the second House of Vans project to go live, with the first opening in Brooklyn in 2010. It opens to the public tomorrow (9 August) and will be open five days a week.
A new report on omnichannel commerce shows that UK retailers are lagging behind their American counterparts in digital and in-store offerings, despite serving the world’s most mature ecommerce market. But even the US still hasn’t worked out the conundrum of linking up stock data.
Being the summer, I have had more time to chat with my teenage kids. As they have got older, they have become (a little) more interested in what I do for a living – perhaps as it starts to dawn on them that one day they too will have to enter the deep dark world of employment, and it would be wise to avoid the jobs that their parents do, as it seems like hard work.
Twitter is revamping its pricing model for campaigns, allowing advertisers to purchase ads based on what it claims are “objective-based” goals designed to inject variety into its cost-per-engagement model. |
/-
Copyright (c) 2021 OpenAI. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kunhao Zheng, Stanislas Polu, David Renshaw, OpenAI GPT-f
-/
import mathzoo.imports.miniF2F
open_locale nat rat real big_operators topological_space
theorem mathd_algebra_192
(q e d : ℂ)
(h₀ : q = 11 - (5 * complex.I))
(h₁ : e = 11 + (5 * complex.I))
(h₂ : d = 2 * complex.I) :
q * e * d = 292 * complex.I :=
begin
rw [h₀, h₁, h₂],
ring_nf,
rw [pow_two, complex.I_mul_I],
ring,
end |
SUBROUTINE SC_IFSP ( rimnem, cimnem, iret )
C************************************************************************
C* SC_IFSP *
C* *
C* This subroutine initializes the interface mnemonic arrays and sets *
C* the pointers within COMMON / RINTFP / and COMMON / CINTFP /. *
C* *
C* SC_IFSP ( RIMNEM, CIMNEM, IRET ) *
C* *
C* Output parameters: *
C* RIMNEM (*) CHAR* Interface mnemonics for reals *
C* CIMNEM (*) CHAR* Interface mnemonics for chars *
C* IRET INTEGER Return code *
C* 0 = normal return *
C* -1 = one or more pointers *
C* could not be set *
C* *
C** *
C* Log: *
C* A. Hardy/GSC 12/97 Based on AF_IFSP *
C* D. Kidwell/NCEP 6/98 Store NPWX with multi-level vals *
C* D. Kidwell/NCEP 10/98 Added init of interface mnemonics; *
C* added intf mnemonics to calling sequence*
C************************************************************************
INCLUDE 'GEMPRM.PRM'
INCLUDE 'sccmn.cmn'
C*
CHARACTER*(*) rimnem (*), cimnem (*)
C*
LOGICAL allok
INTEGER iploc ( NRSIMN )
CHARACTER rifmn ( NRIMN )*8, cifmn ( NCIMN )*8
C*
C* Establish equivalence between iploc ( ) and COMMON / RINTFP /
C*
EQUIVALENCE ( iploc (1), irtdxc )
C*
DATA ( rifmn (i), i = 1, NRIMN )
+ / 'TDXC' , 'TDNC' , 'P06I' , 'P24I' , 'SNOW' , 'SNEW' ,
+ 'WEQS' , 'MSUN' , 'CTYL' , 'CTYM' , 'CTYH' , 'CFRT' ,
+ 'CFRL' , 'CBAS' , 'SLAT' , 'SLON' , 'SELV' , 'CORN' ,
+ 'NPWX' /
C* Real interface mnemonics
C*
DATA ( cifmn (i), i = 1, NCIMN )
+ / 'STID' , 'WCOD' , ' ' , ' ' /
C* Character interface mnemonics
C*
C-----------------------------------------------------------------------
iret = 0
C
C* Initialize the interface mnemonics.
C
DO i = 1,NRIMN
rimnem ( i ) = rifmn ( i )
END DO
DO i = 1, NCIMN
cimnem ( i ) = cifmn ( i )
END DO
C
C* The logical variable "allok" is initially set to .true. but will
C* be reset to .false. if any of the pointers cannot be set.
C
allok = .true.
C
C* Set the pointers for the single-level interface mnemonics.
C
DO ii = 1, NRSIMN
CALL DC_IFFP ( rimnem (ii), rimnem, NRIMN, allok,
+ iploc (ii), ier )
END DO
C
CALL DC_IFFP ( 'STID', cimnem, NCIMN, allok, icstid, ier )
C
C* Set the pointers for multiple character weather groups.
C
CALL DC_IFFP ( 'NPWX', rimnem, NRIMN, allok, irnpwx, ier)
CALL DC_IFFP ( 'WCOD', cimnem, NCIMN, allok, icwcod (1), ier)
CALL DC_IFMP ( 1, MXWLYR, icwcod, ier )
C
C* Check that all of the pointers were set correctly.
C
IF ( .not. allok ) THEN
iret = -1
END IF
C*
RETURN
END
|
open import Everything
module Test.Class where
record ℭlass
{ℓ}
{𝔢}
{CONSTRAINTS : Ø 𝔢}
(constraints : CONSTRAINTS)
: Ø ↑̂ ℓ
where
constructor ∁
field
type : Ø ℓ
private
record SET-CLASS
⦃ _ : Constraint constraints ⦄
: Ø ℓ
where
constructor ∁
field ⋆ : type
open SET-CLASS public
class : Ø _
class = SET-CLASS
method : ⦃ _ : class ⦄ → type
method ⦃ ⌶ ⦄ = SET-CLASS.⋆ ⌶
mkClass : ∀
{ℓ}
{𝔢}
{CONSTRAINTS : Ø 𝔢}
(constraints : CONSTRAINTS)
→ Ø ℓ
→ ℭlass constraints
mkClass constraints set-method = ∁ set-method
module Unit-Unit/Unit/Unit
{𝔬} (𝔒 : Ø 𝔬)
= ℭlass (mkClass 𝔒 𝔒)
module PropSingle-Unit/Unit/Unit
{𝔬} {𝔒 : Ø 𝔬}
{𝔭} (𝔓 : 𝔒 → Ø 𝔭)
(x : 𝔒)
= Unit-Unit/Unit/Unit (𝔓 x)
module Prop-Unit/Unit/Unit
{𝔬} {𝔒 : Ø 𝔬}
{𝔭} (𝔓 : 𝔒 → Ø 𝔭)
where
private module M = PropSingle-Unit/Unit/Unit 𝔓
class = ∀ {x} → M.class x
type = ∀ x → M.type x
method = λ ⦃ _ : class ⦄ x → M.method x
module RelSingle-Unit/Unit/Unit
{𝔬} {𝔒 : Ø 𝔬}
{𝔯} (ℜ : 𝔒 → 𝔒 → Ø 𝔯)
(x : 𝔒)
= Unit-Unit/Unit/Unit (ℜ x x)
module Rel-Unit/Unit/Unit
{𝔬} {𝔒 : Ø 𝔬}
{𝔯} (ℜ : 𝔒 → 𝔒 → Ø 𝔯)
where
private module M = RelSingle-Unit/Unit/Unit ℜ
class = ∀ {x} → M.class x
type = ∀ x → M.type x
method = λ ⦃ _ : class ⦄ x → M.method x
module Prop-Rel-Unit/Unit/Unit
{𝔬} {𝔒 : Ø 𝔬}
{𝔭} (𝔓 : 𝔒 → Ø 𝔭)
= Rel-Unit/Unit/Unit (Extension 𝔓)
module UnitLevel-Unit/Unit/Unit
{𝔬} (𝔒 : Ø 𝔬) (𝔯 : Ł)
where
private module M = Rel-Unit/Unit/Unit {𝔒 = 𝔒} {𝔯 = 𝔯}
class = ∀ {ℜ} → M.class ℜ
type = ∀ {ℜ} → M.type ℜ
method : ⦃ _ : class ⦄ → type
method ⦃ ⌶ ⦄ {ℜ = ℜ} = M.method ℜ ⦃ ⌶ {ℜ} ⦄ -- FIXME
module RelSingle-RelSingle/Rel/RelSingle
{𝔬} {𝔒 : Ø 𝔬}
{𝔯} (ℜ : 𝔒 → 𝔒 → Ø 𝔯)
(x : 𝔒)
= ℭlass (mkClass ℜ (ℜ x x))
module Rel-RelSingle/Rel/RelSingle
{𝔬} {𝔒 : Ø 𝔬}
{𝔯} (ℜ : 𝔒 → 𝔒 → Ø 𝔯)
where
private module M = RelSingle-RelSingle/Rel/RelSingle ℜ
class = ∀ {x} → M.class x
type = ∀ {x} → M.type x
method = λ ⦃ _ : class ⦄ {x} → M.method x
module Prop-Rel-RelSingle/Rel/RelSingle
{𝔬} {𝔒 : Ø 𝔬}
{𝔭} (𝔓 : 𝔒 → Ø 𝔭)
= Rel-RelSingle/Rel/RelSingle (Extension 𝔓)
module All-Prop-Rel-RelSingle/Rel/RelSingle (𝔬 𝔭 : Ł) where
private module M = Prop-Rel-RelSingle/Rel/RelSingle
class = ∀ {𝔒 : Ø 𝔬} {𝔓 : 𝔒 → Ø 𝔭} → M.class 𝔓
type = ∀ {𝔒 : Ø 𝔬} {𝔓 : 𝔒 → Ø 𝔭} → M.type 𝔓
method : ⦃ _ : class ⦄ → type
method {𝔓 = 𝔓} = M.method 𝔓
module UnitLevel-RelSingle/Rel/RelSingle
{𝔬} (𝔒 : Ø 𝔬) (𝔯 : Ł)
where
private module M = Rel-RelSingle/Rel/RelSingle {𝔒 = 𝔒} {𝔯 = 𝔯}
class = ∀ {ℜ} → M.class ℜ
type = ∀ {ℜ} → M.type ℜ
method : ⦃ _ : class ⦄ → type
method {ℜ = ℜ} = M.method ℜ
module PropSingle-PropSingle/Prop/PropSingle
{𝔬} {𝔒 : Ø 𝔬}
{𝔭} (𝔓 : 𝔒 → Ø 𝔭)
(x : 𝔒)
where
open ℭlass (mkClass 𝔓 (𝔓 x)) public
module Prop-PropSingle/Prop/PropSingle
{𝔬} {𝔒 : Ø 𝔬}
{𝔭} (𝔓 : 𝔒 → Ø 𝔭)
where
private module M = PropSingle-PropSingle/Prop/PropSingle 𝔓
class = ∀ {x} → M.class x
type = ∀ x → M.type x
method = λ ⦃ _ : class ⦄ x → M.method x
module Asymmetric
ℓ
(𝔓' : ∀ {𝔬} {𝔒 : Ø 𝔬} {𝔭} (𝔓 : 𝔒 → Ø 𝔭) (x : 𝔒) → 𝔓 x → Ø ℓ)
where
module U = Unit-Unit/Unit/Unit
test-class' : ⦃ _ : ∀ {𝔬} {𝔒 : Ø 𝔬} {𝔭} {𝔓 : 𝔒 → Ø 𝔭} {x : 𝔒} {y : 𝔓 x} → U.class (𝔓' 𝔓 x y) ⦄ → ∀ {𝔬} {𝔒 : Ø 𝔬} {𝔭} {𝔓 : 𝔒 → Ø 𝔭} {x : 𝔒} {y : 𝔓 x} → U.class (𝔓' 𝔓 x y)
test-class' = !
module Symmetric
ℓ
(𝔓' : ∀ {𝔬} {𝔒 : Ø 𝔬} {𝔭} (𝔓 : 𝔒 → Ø 𝔭) (x : 𝔒) → 𝔓 x → 𝔓 x → Ø ℓ)
where
module U = Unit-Unit/Unit/Unit
test-class' : ⦃ _ : ∀ {𝔬} {𝔒 : Ø 𝔬} {𝔭} {𝔓 : 𝔒 → Ø 𝔭} {x : 𝔒} {y z : 𝔓 x} → U.class (𝔓' 𝔓 x y z → 𝔓' 𝔓 x y z) ⦄ → ∀ {𝔬} {𝔒 : Ø 𝔬} {𝔭} {𝔓 : 𝔒 → Ø 𝔭} {x : 𝔒} {y z : 𝔓 x} → U.class (𝔓' 𝔓 x y z → 𝔓' 𝔓 x y z)
test-class' ⦃ ⌶ ⦄ = !
module V {𝔬} (𝔒 : Ø 𝔬) = ℭlass (mkClass 𝔒 (𝔒 → 𝔒))
test-classV : ⦃ _ : ∀ {𝔬} {𝔒 : Ø 𝔬} {𝔭} {𝔓 : 𝔒 → Ø 𝔭} {x : 𝔒} {y z : 𝔓 x} → V.class (𝔓' 𝔓 x y z) ⦄ → ∀ {𝔬} {𝔒 : Ø 𝔬} {𝔭} {𝔓 : 𝔒 → Ø 𝔭} {x : 𝔒} {y z : 𝔓 x} → V.class (𝔓' 𝔓 x y z)
test-classV ⦃ ⌶ ⦄ = !
test-methodV : ⦃ _ : ∀ {𝔬} {𝔒 : Ø 𝔬} {𝔭} {𝔓 : 𝔒 → Ø 𝔭} {x : 𝔒} {y z : 𝔓 x} → V.class (𝔓' 𝔓 x y z) ⦄ → ∀ {𝔬} {𝔒 : Ø 𝔬} {𝔭} {𝔓 : 𝔒 → Ø 𝔭} {x : 𝔒} {y z : 𝔓 x} → V.type (𝔓' 𝔓 x y z)
test-methodV ⦃ ⌶ ⦄ = V.method _
module W {𝔬} {𝔒 : Ø 𝔬} (p : 𝔒) = ℭlass (mkClass p 𝔒)
test-classW : ⦃ _ : ∀ {𝔬} {𝔒 : Ø 𝔬} {𝔭} {𝔓 : 𝔒 → Ø 𝔭} {x : 𝔒} {y z : 𝔓 x} {p : 𝔓' 𝔓 x y z} → W.class p ⦄ → ∀ {𝔬} {𝔒 : Ø 𝔬} {𝔭} {𝔓 : 𝔒 → Ø 𝔭} {x : 𝔒} {y z : 𝔓 x} {p : 𝔓' 𝔓 x y z} → W.class p
test-classW ⦃ ⌶ ⦄ = magic
test-methodW : ⦃ _ : ∀ {𝔬} {𝔒 : Ø 𝔬} {𝔭} {𝔓 : 𝔒 → Ø 𝔭} {x : 𝔒} {y z : 𝔓 x} {p : 𝔓' 𝔓 x y z} → W.class p ⦄ → ∀ {𝔬} {𝔒 : Ø 𝔬} {𝔭} {𝔓 : 𝔒 → Ø 𝔭} {x : 𝔒} {y z : 𝔓 x} {p : 𝔓' 𝔓 x y z} → W.type p
test-methodW {p = p} = W.method p
module Prop-
{𝔬} {𝔒 : Ø 𝔬}
{𝔭} (𝔓 : 𝔒 → Ø 𝔭)
where
module -Unit/Unit/Unit where
module V = Prop-Unit/Unit/Unit 𝔓
module H = Prop-Unit/Unit/Unit
module X = Unit-Unit/Unit/Unit
test-class' : ⦃ _ : {𝔓 : 𝔒 → Ø 𝔭} → H.class 𝔓 ⦄ → {𝔓 : 𝔒 → Ø 𝔭} → H.class 𝔓
test-class' ⦃ ⌶ ⦄ {𝔓 = 𝔓} = magic -- ⌶ {𝔓 = 𝔓} -- FIXME
test-class : ⦃ _ : V.class ⦄ → V.class
test-class = !
test-method-V : ⦃ _ : V.class ⦄ → V.type
test-method-V = V.method
test-method-H : ⦃ _ : V.class ⦄ → V.type
test-method-H = H.method _
test-method-X : ⦃ _ : V.class ⦄ → V.type
test-method-X _ = X.method _ -- FIXME
module -PropSingle/Prop/PropSingle where
module V = Prop-PropSingle/Prop/PropSingle 𝔓
module H = Prop-PropSingle/Prop/PropSingle
module X = PropSingle-PropSingle/Prop/PropSingle
test-class' : ⦃ _ : {𝔓 : 𝔒 → Ø 𝔭} → H.class 𝔓 ⦄ → {𝔓 : 𝔒 → Ø 𝔭} → H.class 𝔓
test-class' ⦃ ⌶ ⦄ = magic
test-class : ⦃ _ : V.class ⦄ → V.class
test-class = !
test-method-V : ⦃ _ : V.class ⦄ → V.type
test-method-V = V.method
test-method-H : ⦃ _ : V.class ⦄ → V.type
test-method-H = H.method _
test-method-X : ⦃ _ : V.class ⦄ → V.type
test-method-X _ = X.method _ _ -- FIXME
module Rel-
{𝔬} {𝔒 : Ø 𝔬}
{𝔯} (ℜ : 𝔒 → 𝔒 → Ø 𝔯)
where
module -Unit/Unit/Unit where
module V = Rel-Unit/Unit/Unit ℜ
module H = Rel-Unit/Unit/Unit
module X = Unit-Unit/Unit/Unit
test-class : ⦃ _ : V.class ⦄ → V.class
test-class = !
test-method-V : ⦃ _ : V.class ⦄ → V.type
test-method-V = V.method
test-method-H : ⦃ _ : V.class ⦄ → V.type
test-method-H = H.method ℜ -- FIXME
test-method-X : ⦃ _ : V.class ⦄ → V.type
test-method-X _ = X.method _ -- FIXME
module -RelSingle/Rel/RelSingle where
module V = Rel-RelSingle/Rel/RelSingle ℜ
module H = Rel-RelSingle/Rel/RelSingle
module X = RelSingle-RelSingle/Rel/RelSingle
test-class : ⦃ _ : V.class ⦄ → V.class
test-class = !
test-method-V : ⦃ _ : V.class ⦄ → V.type
test-method-V = V.method
test-method-H : ⦃ _ : V.class ⦄ → V.type
test-method-H = H.method _
test-method-X : ⦃ _ : V.class ⦄ → V.type
test-method-X = X.method _ _
module Prop-Rel-
{𝔬} {𝔒 : Ø 𝔬}
{𝔭} (𝔓 : 𝔒 → Ø 𝔭)
where
module -Unit/Unit/Unit where
module V = Prop-Rel-Unit/Unit/Unit 𝔓
module H = Prop-Rel-Unit/Unit/Unit
module X = RelSingle-Unit/Unit/Unit
test-class' : ⦃ _ : ∀ {𝔬} {𝔒 : Ø 𝔬} {𝔭} {𝔓 : 𝔒 → Ø 𝔭} → H.class 𝔓 ⦄ → ∀ {𝔬} {𝔒 : Ø 𝔬} {𝔭} {𝔓 : 𝔒 → Ø 𝔭} → H.class 𝔓
test-class' ⦃ ⌶ ⦄ {ℜ} = magic -- ! -- FIXME
test-class : ⦃ _ : V.class ⦄ → V.class
test-class = !
test-method-V : ⦃ _ : V.class ⦄ → V.type
test-method-V ⦃ ⌶ ⦄ = magic
test-method-H : ⦃ _ : V.class ⦄ → V.type
test-method-H ⦃ ⌶ ⦄ = magic -- H.method _
test-method-X : ⦃ _ : V.class ⦄ → V.type
test-method-X ⦃ ⌶ ⦄ = magic -- X.method _ _
module -RelSingle/Rel/RelSingle where
module V = Prop-Rel-RelSingle/Rel/RelSingle 𝔓
module H = Prop-Rel-RelSingle/Rel/RelSingle
module X = RelSingle-RelSingle/Rel/RelSingle
test-class' : ⦃ _ : ∀ {𝔬} {𝔒 : Ø 𝔬} {𝔭} {𝔓 : 𝔒 → Ø 𝔭} → H.class 𝔓 ⦄ → ∀ {𝔬} {𝔒 : Ø 𝔬} {𝔭} (𝔓 : 𝔒 → Ø 𝔭) → H.class 𝔓
test-class' ⦃ ⌶ ⦄ = !
test-class : ⦃ _ : V.class ⦄ → V.class
test-class = !
test-method-V : ⦃ _ : V.class ⦄ → V.type
test-method-V ⦃ ⌶ ⦄ = magic -- V.method
test-method-H : ⦃ _ : V.class ⦄ → V.type
test-method-H ⦃ ⌶ ⦄ = magic -- H.method _
test-method-X : ⦃ _ : V.class ⦄ → V.type
test-method-X ⦃ ⌶ ⦄ = magic -- FIXME
module UnitLevel-
{𝔬} (𝔒 : Ø 𝔬) ℓ
where
module -Unit/Unit/Unit where
module V = UnitLevel-Unit/Unit/Unit 𝔒 ℓ
module H = UnitLevel-Unit/Unit/Unit
module X = RelSingle-Unit/Unit/Unit
test-class : ⦃ _ : V.class ⦄ → V.class
test-class ⦃ ⌶ ⦄ {ℜ} = ⌶ {ℜ} -- FIXME
test-method-V : ⦃ _ : V.class ⦄ → V.type
test-method-V ⦃ ⌶ ⦄ {ℜ} = magic
test-method-H : ⦃ _ : V.class ⦄ → V.type
test-method-H ⦃ ⌶ ⦄ {ℜ} = magic -- H.method _
test-method-X : ⦃ _ : V.class ⦄ → V.type
test-method-X ⦃ ⌶ ⦄ {ℜ} x = magic -- X.method _ _
module -RelSingle/Rel/RelSingle where
module V = UnitLevel-RelSingle/Rel/RelSingle 𝔒 ℓ
module H = UnitLevel-RelSingle/Rel/RelSingle
module X = RelSingle-RelSingle/Rel/RelSingle
test-class : ⦃ _ : V.class ⦄ → V.class
test-class = !
test-method-V : ⦃ _ : V.class ⦄ → V.type
test-method-V ⦃ ⌶ ⦄ {ℜ} = magic -- V.method
test-method-H : ⦃ _ : V.class ⦄ → V.type
test-method-H ⦃ ⌶ ⦄ {ℜ} = magic -- H.method _
test-method-X : ⦃ _ : V.class ⦄ → V.type
test-method-X ⦃ ⌶ ⦄ {ℜ} = X.method ℜ _ -- FIXME
module Rel-Extension
{𝔬} {𝔒 : Ø 𝔬}
{𝔭} (𝔓 : 𝔒 → Ø 𝔭)
(let ℜ = Extension 𝔓)
where
module -Unit/Unit/Unit where
module V = Rel-Unit/Unit/Unit ℜ
module H = Rel-Unit/Unit/Unit
module X = Unit-Unit/Unit/Unit
test-class' : ⦃ _ : ∀ {𝔬} {𝔒 : Ø 𝔬} {𝔭} {𝔓 : 𝔒 → Ø 𝔭} (let ℜ = Extension 𝔓) → H.class ℜ ⦄ → ∀ {𝔬} {𝔒 : Ø 𝔬} {𝔭} {𝔓 : 𝔒 → Ø 𝔭} (let ℜ = Extension 𝔓) → H.class ℜ
test-class' ⦃ ⌶ ⦄ {𝔓 = 𝔓} = magic -- ⌶ {𝔓 = 𝔓} -- FIXME
test-class : ⦃ _ : V.class ⦄ → V.class
test-class = !
test-method-V : ⦃ _ : V.class ⦄ → V.type
test-method-V = V.method
test-method-H : ⦃ _ : V.class ⦄ → V.type
test-method-H = H.method ℜ -- FIXME
test-method-X : ⦃ _ : V.class ⦄ → V.type
test-method-X _ = X.method _ -- FIXME
module -RelSingle/Rel/RelSingle where
module V = Rel-RelSingle/Rel/RelSingle ℜ
module H = Rel-RelSingle/Rel/RelSingle
module X = RelSingle-RelSingle/Rel/RelSingle
test-class' : ⦃ _ : ∀ {𝔬} {𝔒 : Ø 𝔬} {𝔭} {𝔓 : 𝔒 → Ø 𝔭} (let ℜ = Extension 𝔓) → H.class ℜ ⦄ → ∀ {𝔬} {𝔒 : Ø 𝔬} {𝔭} {𝔓 : 𝔒 → Ø 𝔭} (let ℜ = Extension 𝔓) → H.class ℜ
test-class' ⦃ ⌶ ⦄ = ! -- !
test-class'' : ⦃ _ : ∀ {𝔬} {𝔒 : Ø 𝔬} {𝔭} {𝔓 : 𝔒 → Ø 𝔭} (let ℜ = λ x _ → 𝔓 x) → H.class ℜ ⦄ → ∀ {𝔬} {𝔒 : Ø 𝔬} {𝔭} {𝔓 : 𝔒 → Ø 𝔭} (let ℜ = λ x _ → 𝔓 x) → H.class ℜ
test-class'' ⦃ ⌶ ⦄ = ! -- !
test-class : ⦃ _ : V.class ⦄ → V.class
test-class = !
test-method-V : ⦃ _ : V.class ⦄ → V.type
test-method-V = V.method
test-method-H : ⦃ _ : V.class ⦄ → V.type
test-method-H = H.method _
test-method-X : ⦃ _ : V.class ⦄ → V.type
test-method-X = X.method _ _
module AllUnitTest where
test : ⦃ I : ∀ {𝔬} {𝔒 : Ø 𝔬} → Unit-Unit/Unit/Unit.class 𝔒 ⦄ → ∀ {𝔬} {𝔒 : Ø 𝔬} → Unit-Unit/Unit/Unit.class 𝔒
test = !
module AllTest
{𝔬} {𝔒 : Ø 𝔬}
{𝔭}
where
testProp : ⦃ I : {𝔓 : 𝔒 → Ø 𝔭} → Prop-PropSingle/Prop/PropSingle.class 𝔓 ⦄ → {𝔓 : 𝔒 → Ø 𝔭} → Prop-PropSingle/Prop/PropSingle.class 𝔓
testProp = !
testUnitProp : ⦃ I : {𝔓 : 𝔒 → Ø 𝔭} → Prop-Unit/Unit/Unit.class 𝔓 ⦄ → {𝔓 : 𝔒 → Ø 𝔭} → Prop-Unit/Unit/Unit.class 𝔓
testUnitProp ⦃ I ⦄ {𝔓} = I {𝔓}
module SinglePropTest
{𝔬} {𝔒 : Ø 𝔬}
{𝔭} (𝔓 : 𝔒 → Ø 𝔭)
where
testProp : ⦃ _ : Prop-PropSingle/Prop/PropSingle.class 𝔓 ⦄ → Prop-PropSingle/Prop/PropSingle.class 𝔓
testProp = !
testUnitProp : ⦃ _ : Prop-Unit/Unit/Unit.class 𝔓 ⦄ → Prop-Unit/Unit/Unit.class 𝔓
testUnitProp = !
module SingleRelTest
{𝔬} {𝔒 : Ø 𝔬}
{𝔯} (ℜ : 𝔒 → 𝔒 → Ø 𝔯)
where
testProp : ⦃ _ : Rel-RelSingle/Rel/RelSingle.class ℜ ⦄ → Rel-RelSingle/Rel/RelSingle.class ℜ
testProp = !
testUnit : ⦃ _ : Rel-Unit/Unit/Unit.class ℜ ⦄ → Rel-Unit/Unit/Unit.class ℜ
testUnit = !
|
section \<open>Matrices\<close>
theory Matrices_Typed
imports Nat
begin
\<comment> \<open>I want the following -- is this safe?\<close>
\<comment> \<open>declare [[coercion_enabled]] [[coercion Element]] [[coercion "apply"]]\<close>
definition upto ("{0..< _}") where "{0..< n} = {i \<in> \<nat> | i < n}"
\<comment> \<open>Note Kevin: Having both, HOL and set functions is pain.\<close>
definition [typedef]:
"Matrix A m n \<equiv> Element {0..<m} \<Rightarrow> Element {0..<n} \<Rightarrow> Element A"
definition "matrix A m n \<equiv> {0..<m} \<rightarrow> {0..<n} \<rightarrow> A"
definition "Matrix_to_matrix m n M \<equiv> \<lambda>i \<in> {0..<m}. \<lambda>j \<in> {0..<n}. M i j"
lemma Matrix_to_matrix_type [type]:
"Matrix_to_matrix : (m : Nat) \<Rightarrow> (n : Nat) \<Rightarrow> Matrix A m n \<Rightarrow>
Element (matrix A m n)"
unfolding matrix_def Matrix_def Matrix_to_matrix_def
by discharge_types
definition "matrix_to_Matrix M \<equiv> \<lambda>i j. M `i `j"
lemma matrix_to_Matrix_type [type]:
"matrix_to_Matrix : Element (matrix A m n) \<Rightarrow> Matrix A m n"
unfolding matrix_to_Matrix_def Matrix_def matrix_def by discharge_types
subsection \<open>Addition\<close>
definition "Matrix_add A M N i j = add A (M i j) (N i j)"
lemma Matrix_add_type [type]: "Matrix_add: Add A \<Rightarrow> Matrix A m n \<Rightarrow>
Matrix A m n \<Rightarrow> Matrix A m n"
unfolding Matrix_def Matrix_add_def by discharge_types
definition "matrix_Add C A m n \<equiv> object {
\<langle>@add, \<lambda>M N \<in> matrix C m n. Matrix_to_matrix m n
(Matrix_add A (matrix_to_Matrix M) (matrix_to_Matrix N))\<rangle>
}"
lemma assumes "A: Add C" "m: Nat" "n: Nat"
shows "matrix_Add C A m n: Add (matrix C m n)"
unfolding matrix_Add_def by (rule Add_typeI) auto
\<comment> \<open>Note Kevin: Now, given "M N \<in> matrix A m n", I could write "M + N" but given
"M N: Matrix A m n", I could not write "M + N" but need to write
"matrix_to_Matrix (Matrix_to_matrix m n M + Matrix_to_matrix m n N).\<close>
lemma Matrix_add_assoc: assumes "M : Monoid A" "N : Matrix A m n"
"O : Matrix A m n" "P : Matrix A m n"
"i : Element {0..<m}" "j : Element {0..<n}"
shows "Matrix_add M (Matrix_add M N O) P i j =
Matrix_add M N (Matrix_add M O P) i j"
unfolding Matrix_add_def
using assms add_assoc by (auto simp: Matrix_def)
definition "matrix_add A m n M N \<equiv> Matrix_to_matrix m n
(Matrix_add A (matrix_to_Matrix M) (matrix_to_Matrix N))"
lemma matrix_add_assoc: assumes "M : Monoid A" "N : Element (matrix A m n)"
"O : Element (matrix A m n)" "P : Element (matrix A m n)"
shows "matrix_add M m n (matrix_add M m n N O) P =
matrix_add M m n N (matrix_add M m n O P)"
oops
end |
Formal statement is: lemma of_real_power_int [simp]: "of_real (power_int x n) = power_int (of_real x :: 'a :: {real_div_algebra,division_ring}) n" Informal statement is: For any real number $x$ and any integer $n$, the real number $x^n$ is equal to the complex number $(x + 0i)^n$. |
#pragma once
#include <gsl/gsl_assert>
#include <src/util/Logging.h>
#ifndef NDEBUG
//#define MI_EXPECTS(x) Expects(x)
//#define MI_ENSURES(x) Ensures(x)
#define MI_EXPECTS(x) \
do { \
if (!(x)) { \
LOG(ERROR) << "assertion failed: " << #x; \
std::terminate(); \
} \
} while (0)
#define MI_ENSURES(x) \
do { \
if (!(x)) { \
LOG(ERROR) << "assertion failed: " << #x; \
std::terminate(); \
} \
} while (0)
#else
#define MI_EXPECTS(x)
#define MI_ENSURES(x)
#endif |
(****************************************************************************)
(* Copyright 2021 The Project Oak Authors *)
(* *)
(* 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. *)
(****************************************************************************)
Require Import Coq.NArith.NArith.
Lemma apply_if {A B} (f : A -> B) (b : bool) x y : f (if b then x else y) = if b then f x else f y.
Proof. destruct b; reflexivity. Qed.
Lemma fst_if {A B} (b : bool) (x y : A * B) : fst (if b then x else y) = if b then fst x else fst y.
Proof. apply apply_if. Qed.
Lemma snd_if {A B} (b : bool) (x y : A * B) : snd (if b then x else y) = if b then snd x else snd y.
Proof. apply apply_if. Qed.
Hint Rewrite @fst_if @snd_if using solve [eauto] : tuple_if.
Lemma tup_if {A B} (b : bool) (x y: A) (z w: B) : (if b then x else y, if b then z else w) = if b then (x,z) else (y, w).
Proof. destruct b; reflexivity. Qed.
Hint Rewrite @tup_if using solve [eauto] : tuple_if.
Lemma apply_if_ext_1 {A B C} (f : A -> B -> C) (b : bool) x y z : f (if b then x else y) z = if b then f x z else f y z.
Proof. destruct b; reflexivity. Qed.
Lemma if_true_rew {A} (x: bool) (z: A) P Q: (x = true -> P = Q) ->
(if x then P else z) = (if x then Q else z).
Proof. intros; destruct x; [ apply H | ]; reflexivity. Qed.
Lemma to_nat_if (b: bool) x y : N.to_nat (if b then x else y) = if b then (N.to_nat x) else (N.to_nat y).
Proof. now destruct b. Qed.
Hint Rewrite to_nat_if : Nnat.
|
module Language.LSP.DocumentSymbol
import Core.Context
import Core.Core
import Core.Env
import Core.Metadata
import Data.List
import Language.LSP.Message
import Server.Configuration
import Server.Utils
import Server.Log
-- NOTE: Structured information should be rendereded from the actual Term of the expressions
-- in a file, that would give a better high-level overview. For now this is more like a placeholder
-- rather than a useful functionality.
||| Renders all the local names and type declarations from the Metadata of the active file.
export
documentSymbol : Ref MD Metadata
=> Ref LSPConf LSPConfiguration
=> DocumentSymbolParams -> Core (List DocumentSymbol)
documentSymbol params = do
Just (uri, _) <- gets LSPConf openFile
| Nothing => do
logString Debug "documentSymbol: openFile returned Nothing. Weird."
pure []
let True = uri == params.textDocument.uri
| False => do
logString Debug "documentSymbol: different URI than expected \{show (uri, params.textDocument.uri)}"
pure []
meta <- get MD
let localDocSymbols
= map (\((_, (sline,scol), (eline, ecol)), (n,_,_)) =>
let range = MkRange (MkPosition sline scol) (MkPosition eline ecol)
name = show $ dropNS n
in ( name
, MkDocumentSymbol
{ name = name
, detail = Nothing
, kind = Variable
, tags = Nothing
, deprecated = Nothing
, range = range
, selectionRange = range
, children = Nothing
}
))
meta.names
let localTypeDecSymbols
= map (\((_,(sline,scol),(eline,ecol)), (n,_,_)) =>
let range = MkRange (MkPosition sline scol) (MkPosition eline ecol)
name = show $ dropNS n
in ( name
, MkDocumentSymbol
{ name = name
, detail = Nothing
, kind = Function
, tags = Nothing
, deprecated = Nothing
, range = range
, selectionRange = range
, children = Nothing
}
))
meta.tydecls
pure
$ map snd
$ sortBy (\(n1, _), (n2, _) => compare n1 n2)
$ localDocSymbols ++ localTypeDecSymbols
|
[STATEMENT]
lemma normalize_condCatch [simp]:
"normalize (condCatch c1 b c2) = condCatch (normalize c1) b (normalize c2)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Language.normalize (condCatch c1 b c2) = condCatch (Language.normalize c1) b (Language.normalize c2)
[PROOF STEP]
by (simp add: condCatch_def) |
/**
* Copyright (C) 2018-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include <boost/optional.hpp>
#include "mongo/base/status_with.h"
#include "mongo/bson/bsonobj.h"
#include "mongo/bson/bsonobjbuilder.h"
#include "mongo/db/catalog/collection.h"
#include "mongo/db/catalog/document_validation.h"
#include "mongo/db/client.h"
#include "mongo/db/commands.h"
#include "mongo/db/commands/update_metrics.h"
#include "mongo/db/concurrency/exception_util.h"
#include "mongo/db/curop_failpoint_helpers.h"
#include "mongo/db/db_raii.h"
#include "mongo/db/exec/update_stage.h"
#include "mongo/db/exec/working_set_common.h"
#include "mongo/db/fle_crud.h"
#include "mongo/db/matcher/extensions_callback_real.h"
#include "mongo/db/namespace_string.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/ops/delete_request_gen.h"
#include "mongo/db/ops/insert.h"
#include "mongo/db/ops/parsed_delete.h"
#include "mongo/db/ops/parsed_update.h"
#include "mongo/db/ops/update_request.h"
#include "mongo/db/ops/write_ops_exec.h"
#include "mongo/db/ops/write_ops_retryability.h"
#include "mongo/db/query/collection_query_info.h"
#include "mongo/db/query/explain.h"
#include "mongo/db/query/get_executor.h"
#include "mongo/db/query/plan_executor.h"
#include "mongo/db/query/plan_summary_stats.h"
#include "mongo/db/repl/repl_client_info.h"
#include "mongo/db/repl/replication_coordinator.h"
#include "mongo/db/retryable_writes_stats.h"
#include "mongo/db/s/collection_sharding_state.h"
#include "mongo/db/s/operation_sharding_state.h"
#include "mongo/db/server_options.h"
#include "mongo/db/stats/counters.h"
#include "mongo/db/stats/resource_consumption_metrics.h"
#include "mongo/db/stats/top.h"
#include "mongo/db/storage/duplicate_key_error_info.h"
#include "mongo/db/transaction_participant.h"
#include "mongo/db/write_concern.h"
#include "mongo/logv2/log.h"
#include "mongo/util/log_and_backoff.h"
#include "mongo/util/scopeguard.h"
#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kCommand
namespace mongo {
namespace {
MONGO_FAIL_POINT_DEFINE(hangBeforeFindAndModifyPerformsUpdate);
/**
* If the operation succeeded, then returns either a document to return to the client, or
* boost::none if no matching document to update/remove was found. If the operation failed, throws.
*/
boost::optional<BSONObj> advanceExecutor(OperationContext* opCtx,
const write_ops::FindAndModifyCommandRequest& request,
PlanExecutor* exec,
bool isRemove) {
BSONObj value;
PlanExecutor::ExecState state;
try {
state = exec->getNext(&value, nullptr);
} catch (DBException& exception) {
auto&& explainer = exec->getPlanExplainer();
auto&& [stats, _] = explainer.getWinningPlanStats(ExplainOptions::Verbosity::kExecStats);
LOGV2_WARNING(
23802,
"Plan executor error during findAndModify: {error}, stats: {stats}, cmd: {cmd}",
"Plan executor error during findAndModify",
"error"_attr = exception.toStatus(),
"stats"_attr = redact(stats),
"cmd"_attr = request.toBSON(BSONObj() /* commandPassthroughFields */));
exception.addContext("Plan executor error during findAndModify");
throw;
}
if (PlanExecutor::ADVANCED == state) {
return {std::move(value)};
}
invariant(state == PlanExecutor::IS_EOF);
return boost::none;
}
void validate(const write_ops::FindAndModifyCommandRequest& request) {
uassert(ErrorCodes::FailedToParse,
"Either an update or remove=true must be specified",
request.getRemove().value_or(false) || request.getUpdate());
if (request.getRemove().value_or(false)) {
uassert(ErrorCodes::FailedToParse,
"Cannot specify both an update and remove=true",
!request.getUpdate());
uassert(ErrorCodes::FailedToParse,
"Cannot specify both upsert=true and remove=true ",
!request.getUpsert() || !*request.getUpsert());
uassert(ErrorCodes::FailedToParse,
"Cannot specify both new=true and remove=true; 'remove' always returns the deleted "
"document",
!request.getNew() || !*request.getNew());
uassert(ErrorCodes::FailedToParse,
"Cannot specify arrayFilters and remove=true",
!request.getArrayFilters());
}
if (request.getUpdate() &&
request.getUpdate()->type() == write_ops::UpdateModification::Type::kPipeline &&
request.getArrayFilters()) {
uasserted(ErrorCodes::FailedToParse, "Cannot specify arrayFilters and a pipeline update");
}
}
void makeUpdateRequest(OperationContext* opCtx,
const write_ops::FindAndModifyCommandRequest& request,
boost::optional<ExplainOptions::Verbosity> explain,
UpdateRequest* requestOut) {
requestOut->setQuery(request.getQuery());
requestOut->setProj(request.getFields().value_or(BSONObj()));
invariant(request.getUpdate());
requestOut->setUpdateModification(*request.getUpdate());
requestOut->setLegacyRuntimeConstants(
request.getLegacyRuntimeConstants().value_or(Variables::generateRuntimeConstants(opCtx)));
requestOut->setLetParameters(request.getLet());
requestOut->setSort(request.getSort().value_or(BSONObj()));
requestOut->setHint(request.getHint());
requestOut->setCollation(request.getCollation().value_or(BSONObj()));
requestOut->setArrayFilters(request.getArrayFilters().value_or(std::vector<BSONObj>()));
requestOut->setUpsert(request.getUpsert().value_or(false));
requestOut->setReturnDocs((request.getNew().value_or(false)) ? UpdateRequest::RETURN_NEW
: UpdateRequest::RETURN_OLD);
requestOut->setMulti(false);
requestOut->setExplain(explain);
requestOut->setYieldPolicy(opCtx->inMultiDocumentTransaction()
? PlanYieldPolicy::YieldPolicy::INTERRUPT_ONLY
: PlanYieldPolicy::YieldPolicy::YIELD_AUTO);
}
void makeDeleteRequest(OperationContext* opCtx,
const write_ops::FindAndModifyCommandRequest& request,
bool explain,
DeleteRequest* requestOut) {
requestOut->setQuery(request.getQuery());
requestOut->setProj(request.getFields().value_or(BSONObj()));
requestOut->setLegacyRuntimeConstants(
request.getLegacyRuntimeConstants().value_or(Variables::generateRuntimeConstants(opCtx)));
requestOut->setLet(request.getLet());
requestOut->setSort(request.getSort().value_or(BSONObj()));
requestOut->setHint(request.getHint());
requestOut->setCollation(request.getCollation().value_or(BSONObj()));
requestOut->setMulti(false);
requestOut->setReturnDeleted(true); // Always return the old value.
requestOut->setIsExplain(explain);
requestOut->setYieldPolicy(opCtx->inMultiDocumentTransaction()
? PlanYieldPolicy::YieldPolicy::INTERRUPT_ONLY
: PlanYieldPolicy::YieldPolicy::YIELD_AUTO);
}
write_ops::FindAndModifyCommandReply buildResponse(const PlanExecutor* exec,
bool isRemove,
const boost::optional<BSONObj>& value) {
write_ops::FindAndModifyLastError lastError;
if (isRemove) {
lastError.setNumDocs(value ? 1 : 0);
} else {
const auto updateResult = exec->getUpdateResult();
lastError.setNumDocs(!updateResult.upsertedId.isEmpty() ? 1 : updateResult.numMatched);
lastError.setUpdatedExisting(updateResult.numMatched > 0);
// Note we have to use the upsertedId from the update result here, rather than 'value'
// because the _id field could have been excluded by a projection.
if (!updateResult.upsertedId.isEmpty()) {
lastError.setUpserted(IDLAnyTypeOwned(updateResult.upsertedId.firstElement()));
}
}
write_ops::FindAndModifyCommandReply result;
result.setLastErrorObject(std::move(lastError));
result.setValue(value);
return result;
}
void assertCanWrite_inlock(OperationContext* opCtx, const NamespaceString& nsString) {
uassert(ErrorCodes::NotWritablePrimary,
str::stream() << "Not primary while running findAndModify command on collection "
<< nsString.ns(),
repl::ReplicationCoordinator::get(opCtx)->canAcceptWritesFor(opCtx, nsString));
CollectionShardingState::get(opCtx, nsString)->checkShardVersionOrThrow(opCtx);
}
void recordStatsForTopCommand(OperationContext* opCtx) {
auto curOp = CurOp::get(opCtx);
Top::get(opCtx->getClient()->getServiceContext())
.record(opCtx,
curOp->getNS(),
curOp->getLogicalOp(),
Top::LockType::WriteLocked,
durationCount<Microseconds>(curOp->elapsedTimeExcludingPauses()),
curOp->isCommand(),
curOp->getReadWriteType());
}
void checkIfTransactionOnCappedColl(const CollectionPtr& coll, bool inTransaction) {
if (coll && coll->isCapped()) {
uassert(
ErrorCodes::OperationNotSupportedInTransaction,
str::stream() << "Collection '" << coll->ns()
<< "' is a capped collection. Writes in transactions are not allowed on "
"capped collections.",
!inTransaction);
}
}
class CmdFindAndModify : public write_ops::FindAndModifyCmdVersion1Gen<CmdFindAndModify> {
public:
std::string help() const final {
return "{ findAndModify: \"collection\", query: {processed:false}, update: {$set: "
"{processed:true}}, new: true}\n"
"{ findAndModify: \"collection\", query: {processed:false}, remove: true, sort: "
"{priority:-1}}\n"
"Either update or remove is required, all other fields have default values.\n"
"Output is in the \"value\" field\n";
}
Command::AllowedOnSecondary secondaryAllowed(ServiceContext* srvContext) const final {
return Command::AllowedOnSecondary::kNever;
}
Command::ReadWriteType getReadWriteType() const final {
return Command::ReadWriteType::kWrite;
}
bool collectsResourceConsumptionMetrics() const final {
return true;
}
static void collectMetrics(const Request& request) {
CmdFindAndModify::_updateMetrics.collectMetrics(request);
}
class Invocation final : public InvocationBaseGen {
public:
using InvocationBaseGen::InvocationBaseGen;
bool supportsWriteConcern() const final {
return true;
}
bool supportsReadMirroring() const final {
return true;
}
NamespaceString ns() const final {
return this->request().getNamespace();
}
void doCheckAuthorization(OperationContext* opCtx) const final;
void explain(OperationContext* opCtx,
ExplainOptions::Verbosity verbosity,
rpc::ReplyBuilderInterface* result) final;
Reply typedRun(OperationContext* opCtx) final;
void appendMirrorableRequest(BSONObjBuilder* bob) const final;
private:
static write_ops::FindAndModifyCommandReply writeConflictRetryRemove(
OperationContext* opCtx,
const NamespaceString& nsString,
const write_ops::FindAndModifyCommandRequest& request,
int stmtId,
CurOp* curOp,
OpDebug* opDebug,
bool inTransaction);
static write_ops::FindAndModifyCommandReply writeConflictRetryUpsert(
OperationContext* opCtx,
const NamespaceString& nsString,
const write_ops::FindAndModifyCommandRequest& request,
CurOp* curOp,
OpDebug* opDebug,
bool inTransaction,
ParsedUpdate* parsedUpdate);
};
private:
// Update related command execution metrics.
static UpdateMetrics _updateMetrics;
} cmdFindAndModify;
UpdateMetrics CmdFindAndModify::_updateMetrics{"findAndModify"};
write_ops::FindAndModifyCommandReply CmdFindAndModify::Invocation::writeConflictRetryRemove(
OperationContext* opCtx,
const NamespaceString& nsString,
const write_ops::FindAndModifyCommandRequest& request,
int stmtId,
CurOp* curOp,
OpDebug* const opDebug,
bool inTransaction) {
auto deleteRequest = DeleteRequest{};
deleteRequest.setNsString(nsString);
const bool isExplain = false;
makeDeleteRequest(opCtx, request, isExplain, &deleteRequest);
if (opCtx->getTxnNumber()) {
deleteRequest.setStmtId(stmtId);
}
ParsedDelete parsedDelete(opCtx, &deleteRequest);
uassertStatusOK(parsedDelete.parseRequest());
AutoGetCollection collection(opCtx, nsString, MODE_IX);
{
stdx::lock_guard<Client> lk(*opCtx->getClient());
CurOp::get(opCtx)->enter_inlock(
nsString.ns().c_str(),
CollectionCatalog::get(opCtx)->getDatabaseProfileLevel(nsString.db()));
}
assertCanWrite_inlock(opCtx, nsString);
checkIfTransactionOnCappedColl(collection.getCollection(), inTransaction);
const auto exec = uassertStatusOK(getExecutorDelete(
opDebug, &collection.getCollection(), &parsedDelete, boost::none /* verbosity */));
{
stdx::lock_guard<Client> lk(*opCtx->getClient());
CurOp::get(opCtx)->setPlanSummary_inlock(exec->getPlanExplainer().getPlanSummary());
}
auto docFound =
advanceExecutor(opCtx, request, exec.get(), request.getRemove().value_or(false));
// Nothing after advancing the plan executor should throw a WriteConflictException,
// so the following bookkeeping with execution stats won't end up being done
// multiple times.
PlanSummaryStats summaryStats;
exec->getPlanExplainer().getSummaryStats(&summaryStats);
if (const auto& coll = collection.getCollection()) {
CollectionQueryInfo::get(coll).notifyOfQuery(opCtx, coll, summaryStats);
}
opDebug->setPlanSummaryMetrics(summaryStats);
// Fill out OpDebug with the number of deleted docs.
opDebug->additiveMetrics.ndeleted = docFound ? 1 : 0;
if (curOp->shouldDBProfile(opCtx)) {
auto&& explainer = exec->getPlanExplainer();
auto&& [stats, _] = explainer.getWinningPlanStats(ExplainOptions::Verbosity::kExecStats);
curOp->debug().execStats = std::move(stats);
}
recordStatsForTopCommand(opCtx);
if (docFound) {
ResourceConsumption::DocumentUnitCounter docUnitsReturned;
docUnitsReturned.observeOne(docFound->objsize());
auto& metricsCollector = ResourceConsumption::MetricsCollector::get(opCtx);
metricsCollector.incrementDocUnitsReturned(docUnitsReturned);
}
return buildResponse(exec.get(), request.getRemove().value_or(false), docFound);
}
write_ops::FindAndModifyCommandReply CmdFindAndModify::Invocation::writeConflictRetryUpsert(
OperationContext* opCtx,
const NamespaceString& nsString,
const write_ops::FindAndModifyCommandRequest& request,
CurOp* curOp,
OpDebug* opDebug,
bool inTransaction,
ParsedUpdate* parsedUpdate) {
AutoGetCollection autoColl(opCtx, nsString, MODE_IX);
Database* db = autoColl.ensureDbExists(opCtx);
{
stdx::lock_guard<Client> lk(*opCtx->getClient());
CurOp::get(opCtx)->enter_inlock(
nsString.ns().c_str(),
CollectionCatalog::get(opCtx)->getDatabaseProfileLevel(nsString.db()));
}
assertCanWrite_inlock(opCtx, nsString);
CollectionPtr createdCollection;
const CollectionPtr* collectionPtr = &autoColl.getCollection();
// TODO SERVER-50983: Create abstraction for creating collection when using
// AutoGetCollection Create the collection if it does not exist when performing an upsert
// because the update stage does not create its own collection
if (!*collectionPtr && request.getUpsert() && *request.getUpsert()) {
assertCanWrite_inlock(opCtx, nsString);
createdCollection =
CollectionCatalog::get(opCtx)->lookupCollectionByNamespace(opCtx, nsString);
// If someone else beat us to creating the collection, do nothing
if (!createdCollection) {
uassertStatusOK(userAllowedCreateNS(opCtx, nsString));
OperationShardingState::ScopedAllowImplicitCollectionCreate_UNSAFE
unsafeCreateCollection(opCtx);
WriteUnitOfWork wuow(opCtx);
CollectionOptions defaultCollectionOptions;
uassertStatusOK(db->userCreateNS(opCtx, nsString, defaultCollectionOptions));
wuow.commit();
createdCollection =
CollectionCatalog::get(opCtx)->lookupCollectionByNamespace(opCtx, nsString);
}
invariant(createdCollection);
collectionPtr = &createdCollection;
}
const auto& collection = *collectionPtr;
checkIfTransactionOnCappedColl(collection, inTransaction);
const auto exec = uassertStatusOK(
getExecutorUpdate(opDebug, &collection, parsedUpdate, boost::none /* verbosity */));
{
stdx::lock_guard<Client> lk(*opCtx->getClient());
CurOp::get(opCtx)->setPlanSummary_inlock(exec->getPlanExplainer().getPlanSummary());
}
auto docFound =
advanceExecutor(opCtx, request, exec.get(), request.getRemove().value_or(false));
// Nothing after advancing the plan executor should throw a WriteConflictException,
// so the following bookkeeping with execution stats won't end up being done
// multiple times.
PlanSummaryStats summaryStats;
auto&& explainer = exec->getPlanExplainer();
explainer.getSummaryStats(&summaryStats);
if (collection) {
CollectionQueryInfo::get(collection).notifyOfQuery(opCtx, collection, summaryStats);
}
auto updateResult = exec->getUpdateResult();
write_ops_exec::recordUpdateResultInOpDebug(updateResult, opDebug);
opDebug->setPlanSummaryMetrics(summaryStats);
if (updateResult.containsDotsAndDollarsField &&
serverGlobalParams.featureCompatibility.isVersionInitialized() &&
serverGlobalParams.featureCompatibility.isGreaterThanOrEqualTo(
multiversion::FeatureCompatibilityVersion::kFullyDowngradedTo_5_0)) {
// If it's an upsert, increment 'inserts' metric, otherwise increment 'updates'.
dotsAndDollarsFieldsCounters.incrementForUpsert(!updateResult.upsertedId.isEmpty());
}
if (curOp->shouldDBProfile(opCtx)) {
auto&& [stats, _] = explainer.getWinningPlanStats(ExplainOptions::Verbosity::kExecStats);
curOp->debug().execStats = std::move(stats);
}
recordStatsForTopCommand(opCtx);
if (docFound) {
ResourceConsumption::DocumentUnitCounter docUnitsReturned;
docUnitsReturned.observeOne(docFound->objsize());
auto& metricsCollector = ResourceConsumption::MetricsCollector::get(opCtx);
metricsCollector.incrementDocUnitsReturned(docUnitsReturned);
}
return buildResponse(exec.get(), request.getRemove().value_or(false), docFound);
}
void CmdFindAndModify::Invocation::doCheckAuthorization(OperationContext* opCtx) const {
std::vector<Privilege> privileges;
const auto& request = this->request();
ActionSet actions;
actions.addAction(ActionType::find);
if (request.getUpdate()) {
actions.addAction(ActionType::update);
}
if (request.getUpsert().value_or(false)) {
actions.addAction(ActionType::insert);
}
if (request.getRemove().value_or(false)) {
actions.addAction(ActionType::remove);
}
if (request.getBypassDocumentValidation().value_or(false)) {
actions.addAction(ActionType::bypassDocumentValidation);
}
ResourcePattern resource(
CommandHelpers::resourcePatternForNamespace(request.getNamespace().toString()));
uassert(17138,
"Invalid target namespace " + resource.toString(),
resource.isExactNamespacePattern());
privileges.push_back(Privilege(resource, actions));
uassert(ErrorCodes::Unauthorized,
str::stream() << "Not authorized to find and modify on database'"
<< this->request().getDbName() << "'",
AuthorizationSession::get(opCtx->getClient())->isAuthorizedForPrivileges(privileges));
}
void CmdFindAndModify::Invocation::explain(OperationContext* opCtx,
ExplainOptions::Verbosity verbosity,
rpc::ReplyBuilderInterface* result) {
const BSONObj& cmdObj = this->request().toBSON(BSONObj() /* commandPassthroughFields */);
validate(this->request());
auto requestAndMsg = [&]() {
if (this->request().getEncryptionInformation().has_value() &&
!this->request().getEncryptionInformation()->getCrudProcessed().get_value_or(false)) {
return processFLEFindAndModifyExplainMongod(opCtx, this->request());
} else {
return std::pair{this->request(), OpMsgRequest()};
}
}();
auto request = requestAndMsg.first;
const NamespaceString& nsString = request.getNamespace();
uassertStatusOK(userAllowedWriteNS(opCtx, nsString));
auto const curOp = CurOp::get(opCtx);
OpDebug* const opDebug = &curOp->debug();
const std::string dbName = request.getDbName().toString();
if (request.getRemove().value_or(false)) {
auto deleteRequest = DeleteRequest{};
deleteRequest.setNsString(nsString);
const bool isExplain = true;
makeDeleteRequest(opCtx, request, isExplain, &deleteRequest);
ParsedDelete parsedDelete(opCtx, &deleteRequest);
uassertStatusOK(parsedDelete.parseRequest());
// Explain calls of the findAndModify command are read-only, but we take write
// locks so that the timing information is more accurate.
AutoGetCollection collection(opCtx, nsString, MODE_IX);
uassert(ErrorCodes::NamespaceNotFound,
str::stream() << "database " << dbName << " does not exist",
collection.getDb());
CollectionShardingState::get(opCtx, nsString)->checkShardVersionOrThrow(opCtx);
const auto exec = uassertStatusOK(
getExecutorDelete(opDebug, &collection.getCollection(), &parsedDelete, verbosity));
auto bodyBuilder = result->getBodyBuilder();
Explain::explainStages(
exec.get(), collection.getCollection(), verbosity, BSONObj(), cmdObj, &bodyBuilder);
} else {
auto updateRequest = UpdateRequest();
updateRequest.setNamespaceString(nsString);
makeUpdateRequest(opCtx, request, verbosity, &updateRequest);
const ExtensionsCallbackReal extensionsCallback(opCtx, &updateRequest.getNamespaceString());
ParsedUpdate parsedUpdate(opCtx, &updateRequest, extensionsCallback);
uassertStatusOK(parsedUpdate.parseRequest());
// Explain calls of the findAndModify command are read-only, but we take write
// locks so that the timing information is more accurate.
AutoGetCollection collection(opCtx, nsString, MODE_IX);
uassert(ErrorCodes::NamespaceNotFound,
str::stream() << "database " << dbName << " does not exist",
collection.getDb());
CollectionShardingState::get(opCtx, nsString)->checkShardVersionOrThrow(opCtx);
const auto exec = uassertStatusOK(
getExecutorUpdate(opDebug, &collection.getCollection(), &parsedUpdate, verbosity));
auto bodyBuilder = result->getBodyBuilder();
Explain::explainStages(
exec.get(), collection.getCollection(), verbosity, BSONObj(), cmdObj, &bodyBuilder);
}
}
write_ops::FindAndModifyCommandReply CmdFindAndModify::Invocation::typedRun(
OperationContext* opCtx) {
const auto& req = request();
validate(req);
if (req.getEncryptionInformation().has_value() &&
!req.getEncryptionInformation()->getCrudProcessed().get_value_or(false)) {
return processFLEFindAndModify(opCtx, req);
}
const NamespaceString& nsString = req.getNamespace();
uassertStatusOK(userAllowedWriteNS(opCtx, nsString));
auto const curOp = CurOp::get(opCtx);
OpDebug* const opDebug = &curOp->debug();
// Collect metrics.
CmdFindAndModify::collectMetrics(req);
boost::optional<DisableDocumentValidation> maybeDisableValidation;
if (req.getBypassDocumentValidation().value_or(false)) {
maybeDisableValidation.emplace(opCtx);
}
const auto inTransaction = opCtx->inMultiDocumentTransaction();
uassert(50781,
str::stream() << "Cannot write to system collection " << nsString.ns()
<< " within a transaction.",
!(inTransaction && nsString.isSystem()));
const auto replCoord = repl::ReplicationCoordinator::get(opCtx->getServiceContext());
uassert(50777,
str::stream() << "Cannot write to unreplicated collection " << nsString.ns()
<< " within a transaction.",
!(inTransaction && replCoord->isOplogDisabledFor(opCtx, nsString)));
const auto stmtId = req.getStmtId().value_or(0);
if (opCtx->isRetryableWrite()) {
const auto txnParticipant = TransactionParticipant::get(opCtx);
if (auto entry = txnParticipant.checkStatementExecuted(opCtx, stmtId)) {
RetryableWritesStats::get(opCtx)->incrementRetriedCommandsCount();
RetryableWritesStats::get(opCtx)->incrementRetriedStatementsCount();
// Use a SideTransactionBlock since 'parseOplogEntryForFindAndModify' might need to
// fetch a pre/post image from the oplog and if this is a retry inside an in-progress
// retryable internal transaction, this 'opCtx' would have an active WriteUnitOfWork
// and it is illegal to read the the oplog when there is an active WriteUnitOfWork.
TransactionParticipant::SideTransactionBlock sideTxn(opCtx);
auto findAndModifyReply = parseOplogEntryForFindAndModify(opCtx, req, *entry);
findAndModifyReply.setRetriedStmtId(stmtId);
// Make sure to wait for writeConcern on the opTime that will include this
// write. Needs to set to the system last opTime to get the latest term in an
// event when an election happened after the actual write.
auto& replClient = repl::ReplClientInfo::forClient(opCtx->getClient());
replClient.setLastOpToSystemLastOpTime(opCtx);
return findAndModifyReply;
}
}
// Although usually the PlanExecutor handles WCE internally, it will throw WCEs when it
// is executing a findAndModify. This is done to ensure that we can always match,
// modify, and return the document under concurrency, if a matching document exists.
return writeConflictRetry(opCtx, "findAndModify", nsString.ns(), [&] {
if (req.getRemove().value_or(false)) {
return CmdFindAndModify::Invocation::writeConflictRetryRemove(
opCtx, nsString, req, stmtId, curOp, opDebug, inTransaction);
} else {
if (MONGO_unlikely(hangBeforeFindAndModifyPerformsUpdate.shouldFail())) {
CurOpFailpointHelpers::waitWhileFailPointEnabled(
&hangBeforeFindAndModifyPerformsUpdate,
opCtx,
"hangBeforeFindAndModifyPerformsUpdate");
}
// Nested retry loop to handle concurrent conflicting upserts with equality
// match.
int retryAttempts = 0;
for (;;) {
auto updateRequest = UpdateRequest();
updateRequest.setNamespaceString(nsString);
const auto verbosity = boost::none;
makeUpdateRequest(opCtx, req, verbosity, &updateRequest);
if (opCtx->getTxnNumber()) {
updateRequest.setStmtIds({stmtId});
}
const ExtensionsCallbackReal extensionsCallback(
opCtx, &updateRequest.getNamespaceString());
ParsedUpdate parsedUpdate(opCtx, &updateRequest, extensionsCallback);
uassertStatusOK(parsedUpdate.parseRequest());
try {
return CmdFindAndModify::Invocation::writeConflictRetryUpsert(
opCtx, nsString, req, curOp, opDebug, inTransaction, &parsedUpdate);
} catch (const ExceptionFor<ErrorCodes::DuplicateKey>& ex) {
if (!parsedUpdate.hasParsedQuery()) {
uassertStatusOK(parsedUpdate.parseQueryToCQ());
}
if (!write_ops_exec::shouldRetryDuplicateKeyException(
parsedUpdate, *ex.extraInfo<DuplicateKeyErrorInfo>())) {
throw;
}
++retryAttempts;
logAndBackoff(4721200,
::mongo::logv2::LogComponent::kWrite,
logv2::LogSeverity::Debug(1),
retryAttempts,
"Caught DuplicateKey exception during findAndModify upsert",
"namespace"_attr = nsString.ns());
}
}
}
});
}
void CmdFindAndModify::Invocation::appendMirrorableRequest(BSONObjBuilder* bob) const {
const auto& req = request();
bob->append(FindCommandRequest::kCommandName, req.getNamespace().coll());
if (!req.getQuery().isEmpty()) {
bob->append(FindCommandRequest::kFilterFieldName, req.getQuery());
}
if (req.getSort()) {
bob->append(write_ops::FindAndModifyCommandRequest::kSortFieldName, *req.getSort());
}
if (req.getCollation()) {
bob->append(write_ops::FindAndModifyCommandRequest::kCollationFieldName,
*req.getCollation());
}
const auto& rawCmd = unparsedRequest().body;
if (const auto& shardVersion = rawCmd.getField("shardVersion"); !shardVersion.eoo()) {
bob->append(shardVersion);
}
// Prevent the find from returning multiple documents since we can
bob->append("batchSize", 1);
bob->append("singleBatch", true);
}
} // namespace
} // namespace mongo
|
Require Import Coq.Logic.FunctionalExtensionality Coq.Arith.EqNat Coq.Vectors.Vector Coq.MSets.MSets Names Sets Fun.
Inductive config : Set :=
| nil : config
| create : name -> name -> config -> config
| send : name -> name -> config
| restrict : name -> config -> config
| compose : config -> config -> config
| caseof : name -> list (name * config) -> config
| instantiate_1 : forall n, name -> Vector.t name n ->
name -> config ->
name -> Vector.t name n -> config
| instantiate_2 : forall n, name -> name -> Vector.t name n ->
name -> config ->
name -> name -> Vector.t name n -> config.
Inductive ConfigName (x : name) : config -> Prop :=
| send_name_1 : forall y, ConfigName x (send x y)
| send_name_2 : forall y, ConfigName x (send y x)
| create_name_1 : forall y p, ConfigName x (create x y p)
| create_name_2 : forall y p, ConfigName x (create y x p)
| create_name_p : forall y z p, ConfigName x p -> ConfigName x (create y z p)
| compose_name_l : forall pl pr, ConfigName x pl -> ConfigName x (compose pl pr)
| compose_name_r : forall pl pr, ConfigName x pr -> ConfigName x (compose pl pr)
| restrict_name : forall p, ConfigName x (restrict x p)
| restrict_name_p : forall y p, ConfigName x p -> ConfigName x (restrict y p)
| caseof_name : forall l, ConfigName x (caseof x l)
| caseof_name_h_fst : forall y c l, ConfigName x (caseof y ((x, c) :: l))
| caseof_name_h_snd : forall y n c l, ConfigName x c -> ConfigName x (caseof y ((n, c) :: l))
| caseof_name_t : forall y nc l, ConfigName x (caseof y l) -> ConfigName x (caseof y (nc :: l)).
Hint Constructors ConfigName.
Inductive ConfigBoundedName (x : name) : config -> Prop :=
| create_bounded : forall y p, x <> y -> ConfigBoundedName x (create y x p)
| create_bounded_p : forall y z p, ConfigBoundedName x p -> x <> y ->
ConfigBoundedName x (create y z p)
| compose_bounded_b : forall pl pr, ConfigBoundedName x pl ->
ConfigBoundedName x pr ->
ConfigBoundedName x (compose pl pr)
| compose_bounded_l : forall pl pr, ConfigBoundedName x pl ->
~ ConfigName x pr ->
ConfigBoundedName x (compose pl pr)
| compose_bounded_r : forall pl pr, ConfigBoundedName x pr ->
~ ConfigName x pl ->
ConfigBoundedName x (compose pl pr)
| restrict_bounded : forall p, ConfigBoundedName x (restrict x p)
| restrict_bounded_p : forall y p, ConfigBoundedName x p ->
ConfigBoundedName x (restrict y p)
| caseof_bounded_s : forall y n c l, ConfigBoundedName x c ->
~ ConfigName x (caseof y l) ->
x <> n ->
ConfigBoundedName x (caseof y ((n, c) :: l))
| caseof_bounded_h : forall y n c l, ConfigBoundedName x c ->
ConfigBoundedName x (caseof y l) ->
x <> n ->
ConfigBoundedName x (caseof y ((n, c) :: l))
| caseof_bounded_t : forall y n c l, ConfigBoundedName x (caseof y l) ->
~ ConfigName x c ->
x <> n ->
ConfigBoundedName x (caseof y ((n, c) :: l)).
(* | caseof_bounded_s : forall y n c, ConfigBoundedName x c -> *)
(* x <> y -> *)
(* x <> n -> *)
(* ConfigBoundedName x (caseof y ((n, c) :: List.nil)) *)
(* | caseof_bounded_h : forall y n c l, ConfigBoundedName x c -> *)
(* ~ ConfigBoundedName x (caseof y l) -> *)
(* | caseof_bounded_t : forall y n c l, ConfigBoundedName x (caseof y l) -> *)
(* x <> n -> *)
(* ConfigBoundedName x (caseof y ((n, c) :: l)) *)
(* | caseof_bounded : forall y l, Forall (fun nc => ConfigBoundedName x (snd nc)) l -> *)
(* ConfigBoundedName x (caseof y l). *)
Hint Constructors ConfigBoundedName.
Inductive ConfigFreeName (x : name) : config -> Prop :=
| send_free_1 : forall y, ConfigFreeName x (send x y)
| send_free_2 : forall y, ConfigFreeName x (send y x)
| create_free : forall y p, ConfigFreeName x (create x y p)
| create_free_p : forall y z p, ConfigFreeName x p -> x <> z -> ConfigFreeName x (create y z p)
| compose_free_l : forall pl pr, ConfigFreeName x pl -> ConfigFreeName x (compose pl pr)
| compose_free_r : forall pl pr, ConfigFreeName x pr -> ConfigFreeName x (compose pl pr)
| restrict_free : forall r p, ConfigFreeName x p -> x <> r -> ConfigFreeName x (restrict r p)
| caseof_free : forall l, ConfigFreeName x (caseof x l)
| caseof_free_h_fst : forall y c l, ConfigFreeName x (caseof y ((x, c) :: l))
| caseof_free_h_snd : forall y n c l, ConfigFreeName x c -> ConfigFreeName x (caseof y ((n, c) :: l))
| caseof_free_t : forall y nc l, ConfigFreeName x (caseof y l) -> ConfigFreeName x (caseof y (nc :: l))
| instantiate_1_free_x : forall n u v z p y,
ConfigFreeName x (instantiate_1 n u v z p x y)
| instantiate_1_free_y : forall n u v z p x' y,
Vector.In x y ->
ConfigFreeName x (instantiate_1 n u v z p x' y)
| instantiate_1_free_p : forall n u v z p x' y,
ConfigFreeName x p ->
x <> u ->
~ Vector.In x v ->
x <> z ->
ConfigFreeName x (instantiate_1 n u v z p x' y)
| instantiate_2_free_x_1 : forall n u1 u2 v z p x2 y,
ConfigFreeName x (instantiate_2 n u1 u2 v z p x x2 y)
| instantiate_2_free_x_2 : forall n u1 u2 v z p x1 y,
ConfigFreeName x (instantiate_2 n u1 u2 v z p x1 x y)
| instantiate_2_free_y : forall n u1 u2 v z p x1 x2 y,
Vector.In x y ->
ConfigFreeName x (instantiate_2 n u1 u2 v z p x1 x2 y)
| instantiate_2_free_p : forall n u1 u2 v z p x1 x2 y,
ConfigFreeName x p ->
x <> u1 ->
x <> u2 ->
~ Vector.In x v ->
x <> z ->
ConfigFreeName x (instantiate_2 n u1 u2 v z p x1 x2 y).
Hint Constructors ConfigFreeName.
(* Lemma config_name_dec : forall x p, {ConfigName x p} + {~ ConfigName x p}. *)
(* Proof. *)
(* intros. *)
(* induction p. *)
(* right; intro. *)
(* inversion H. *)
(* inversion IHp. *)
(* left; auto. *)
(* destruct (name_dec x n). *)
(* rewrite e; left; auto. *)
(* destruct (name_dec x n0). *)
(* rewrite e; left; auto. *)
(* right; intro. *)
(* inversion H0; auto. *)
(* destruct (name_dec x n). *)
(* rewrite e; left; auto. *)
(* destruct (name_dec x n0). *)
(* rewrite e; left; auto. *)
(* right; intro. *)
(* inversion H; auto. *)
(* destruct (name_dec x n). *)
(* rewrite e; left; auto. *)
(* inversion IHp. *)
(* left; auto. *)
(* right; intro. *)
(* inversion H0; auto. *)
(* inversion IHp1; inversion IHp2. *)
(* left; auto. *)
(* left; auto. *)
(* left; auto. *)
(* right; intro. *)
(* inversion H1; auto. *)
(* destruct (name_dec x n). *)
(* rewrite e; left; auto. *)
(* induction l. *)
(* right; intro. *)
(* inversion H. *)
(* apply n0; auto. *)
(* inversion IHl. *)
(* left. *)
(* inversion H; subst. *)
(* auto. *)
(* apply caseof_name_t; auto. *)
(* apply caseof_name_t; auto. *)
(* apply caseof_name_t; auto. *)
(* destruct a. *)
(* destruct (name_dec x n1). *)
(* left; rewrite e; auto. *)
(* destruct (config_name_dec x c). *)
(* Qed. *)
(* Lemma config_free_dec : forall x p, {ConfigFreeName x p} + {~ ConfigFreeName x p}. *)
(* Proof. *)
(* intros. *)
(* induction p. *)
(* right; intro; inversion H. *)
(* destruct (name_dec x n). *)
(* rewrite e; left; auto. *)
(* destruct (name_dec x n0). *)
(* rewrite e; right; intro; inversion H; subst; auto. *)
(* inversion IHp. *)
(* left; auto. *)
(* right; intro; inversion H0; subst; auto. *)
(* destruct (name_dec x n); destruct (name_dec x n0). *)
(* rewrite e; auto. *)
(* rewrite e; auto. *)
(* rewrite e; auto. *)
(* right; intro; inversion H; subst; auto. *)
(* destruct (name_dec x n). *)
(* rewrite e; right; intro; inversion H; subst; auto. *)
(* inversion IHp. *)
(* left; auto. *)
(* right; intro; inversion H0; subst; auto. *)
(* inversion_clear IHp1; inversion_clear IHp2. *)
(* left; auto. *)
(* left; auto. *)
(* left; auto. *)
(* right; intro; inversion H1; subst; auto. *)
(* Qed. *)
(* Lemma config_bounded_prop : forall x p, ConfigBoundedName x p -> ConfigName x p. *)
(* Proof. *)
(* intros. *)
(* induction p; inversion H; subst; auto. *)
(* Qed. *)
(* Lemma config_free_prop : forall x p, ConfigFreeName x p -> ConfigName x p. *)
(* Proof. *)
(* intros. *)
(* induction p; inversion H; subst; auto. *)
(* Qed. *)
(* Lemma config_name_prop : forall x p, ConfigName x p -> *)
(* (ConfigBoundedName x p <-> ~ ConfigFreeName x p) /\ *)
(* (ConfigFreeName x p <-> ~ ConfigBoundedName x p). *)
(* Proof. *)
(* intros. *)
(* induction p. *)
(* inversion H. *)
(* inversion H; subst. *)
(* split; split; intros; try intro. *)
(* inversion H0; subst; auto. *)
(* absurd (ConfigFreeName n (create n n0 p)); auto. *)
(* inversion H1; subst; auto. *)
(* auto. *)
(* split; split; intros; try intro. *)
(* inversion H0; subst; inversion H1; subst; auto. *)
(* apply create_bounded. *)
(* intro; subst; apply H0; auto. *)
(* inversion H0; subst; inversion H1; subst; auto. *)
(* assert (n <> n0 -> False). *)
(* intro. *)
(* apply H0. *)
(* auto. *)
(* apply eq_name_double_neg in H1. *)
(* rewrite H1; auto. *)
(* apply IHp in H1. *)
(* inversion_clear H1. *)
(* split; split; intros; try intro. *)
(* inversion H1; subst; inversion H3; subst; auto. *)
(* apply H0 in H6; auto. *)
(* assert (x <> n). *)
(* intro; apply H1. *)
(* rewrite H3; auto. *)
(* destruct (beq_name x n0) eqn:?. *)
(* apply beq_name_true_iff in Heqb. *)
(* rewrite <- Heqb. *)
(* apply create_bounded; auto. *)
(* apply beq_name_false_iff in Heqb. *)
(* apply create_bounded_p. *)
(* apply H0. *)
(* intro. *)
(* apply H1. *)
(* apply create_free_p; auto. *)
(* auto. *)
(* inversion H1; subst; inversion H3; subst; auto. *)
(* apply H0 in H6; auto. *)
(* destruct (beq_name x n) eqn:?. *)
(* apply beq_name_true_iff in Heqb. *)
(* rewrite Heqb; auto. *)
(* apply beq_name_false_iff in Heqb. *)
(* assert (x <> n0). *)
(* intro. *)
(* rewrite <- H3 in H1. *)
(* apply H1. *)
(* auto. *)
(* apply create_free_p; auto. *)
(* apply H2. *)
(* intro. *)
(* apply H1. *)
(* auto. *)
(* inversion_clear H; subst. *)
(* split; split; intros; try intro. *)
(* inversion H. *)
(* exfalso; apply H; auto. *)
(* inversion H0. *)
(* auto. *)
(* split; split; intros; try intro. *)
(* inversion H. *)
(* exfalso; apply H; auto. *)
(* inversion H0. *)
(* auto. *)
(* inversion_clear H; subst. *)
(* split; split; intros; try intro. *)
(* inversion H0; auto. *)
(* auto. *)
(* inversion H; auto. *)
(* exfalso; apply H; auto. *)
(* apply IHp in H0. *)
(* clear IHp. *)
(* inversion_clear H0. *)
(* split; split; intros; try intro. *)
(* inversion H0; subst; inversion H2; subst; auto. *)
(* apply H in H4; auto. *)
(* destruct (beq_name x n) eqn:?. *)
(* apply beq_name_true_iff in Heqb. *)
(* rewrite Heqb; auto. *)
(* apply beq_name_false_iff in Heqb. *)
(* apply restrict_bounded_p. *)
(* apply H; intro. *)
(* apply H0; apply restrict_free; auto. *)
(* inversion H0; subst; inversion H2; subst; auto. *)
(* apply H in H4; auto. *)
(* destruct (beq_name x n) eqn:?. *)
(* apply beq_name_true_iff in Heqb. *)
(* rewrite Heqb in H0. *)
(* exfalso; apply H0; auto. *)
(* apply beq_name_false_iff in Heqb. *)
(* apply restrict_free; auto. *)
(* apply H1. *)
(* intro. *)
(* apply H0; auto. *)
(* inversion_clear H; subst. *)
(* assert (ConfigName x p1); auto. *)
(* apply IHp1 in H0. *)
(* inversion_clear H0. *)
(* split; split; intros; try intro. *)
(* inversion_clear H0; subst; inversion_clear H3; subst; auto. *)
(* apply H1 in H4; auto. *)
(* assert (ConfigBoundedName x p2); auto. *)
(* apply config_bounded_prop in H3. *)
(* apply IHp2 in H3. *)
(* inversion_clear H3. *)
(* apply H6 in H5; auto. *)
(* apply H1 in H0; auto. *)
(* apply config_free_prop in H0; auto. *)
(* assert (~ ConfigFreeName x p1 /\ ~ ConfigFreeName x p2). *)
(* split. *)
(* intro; apply H0; auto. *)
(* intro; apply H0; auto. *)
(* inversion_clear H3. *)
(* apply H1 in H4. *)
(* destruct (config_name_dec x p2). *)
(* apply IHp2 in c. *)
(* inversion_clear c. *)
(* apply H3 in H5. *)
(* auto. *)
(* auto. *)
(* inversion H0; subst; inversion H3; subst; auto. *)
(* apply H1 in H7; auto. *)
(* apply H1 in H7; auto. *)
(* assert (ConfigBoundedName x p2); auto. *)
(* apply config_bounded_prop in H4; apply IHp2 in H4. *)
(* inversion_clear H4. *)
(* apply H6 in H8; auto. *)
(* apply config_free_prop in H5; auto. *)
(* destruct (config_name_dec x p2). *)
(* apply IHp2 in c. *)
(* inversion_clear c. *)
(* destruct (config_free_dec x p1); auto. *)
(* destruct (config_free_dec x p2); auto. *)
(* apply H1 in n. *)
(* apply H3 in n0. *)
(* exfalso; apply H0; auto. *)
(* apply compose_free_l. *)
(* apply H2. *)
(* intro. *)
(* apply H0. *)
(* auto. *)
(* assert (ConfigName x p2); auto. *)
(* apply IHp2 in H0. *)
(* inversion_clear H0. *)
(* clear IHp2. *)
(* split; split; intros; try intro. *)
(* inversion H0; subst; inversion H3; subst; auto. *)
(* assert (ConfigBoundedName x p1); auto. *)
(* apply config_bounded_prop in H4. *)
(* apply IHp1 in H4. *)
(* inversion_clear H4. *)
(* apply H8 in H6; auto. *)
(* apply H1 in H7; auto. *)
(* apply config_free_prop in H5; auto. *)
(* apply H1 in H5; auto. *)
(* assert (~ ConfigFreeName x p1 /\ ~ ConfigFreeName x p2). *)
(* split. *)
(* intro; apply H0; auto. *)
(* intro; apply H0; auto. *)
(* inversion_clear H3. *)
(* apply H1 in H5. *)
(* destruct (config_name_dec x p1). *)
(* apply IHp1 in c; inversion_clear c. *)
(* apply H3 in H4. *)
(* auto. *)
(* auto. *)
(* inversion H0; subst; inversion H3; subst; auto. *)
(* assert (ConfigBoundedName x p1); auto. *)
(* apply config_bounded_prop in H4; apply IHp1 in H4; inversion_clear H4. *)
(* apply H6 in H7; auto. *)
(* apply config_free_prop in H5; auto. *)
(* apply H1 in H8; auto. *)
(* apply H1 in H7; auto. *)
(* destruct (config_free_dec x p1); auto. *)
(* destruct (config_free_dec x p2); auto. *)
(* destruct (config_name_dec x p1). *)
(* apply IHp1 in c; inversion_clear c. *)
(* apply H3 in n. *)
(* apply H1 in n0. *)
(* exfalso; apply H0; auto. *)
(* apply compose_free_r. *)
(* apply H2. *)
(* intro. *)
(* apply H0. *)
(* auto. *)
(* Qed. *)
|
# This script uses matR to generate 2 or 3 dimmensional pcoas
# table_in is the abundance array as tab text -- columns are samples(metagenomes) rows are taxa or functions
# color_table and pch_table are tab tables, with each row as a metagenome, each column as a metadata
# grouping/coloring. These tables are used to define colors and point shapes for the plot
# It is assumed that the order of samples (left to right) in table_in is the same
# as the order (top to bottom) in color_table and pch_table
# basic operation is to produce a color-less pcoa of the input data
# user can also input a table to specify colors
# This table can contain colors (as hex or nominal) or can contain metadata
# that is automatically interpreted to produce coloring (identical values or text receive the same color
#
# The user can also input a pch table -- this is more advanced R plotting that allows them to
# select the shape of the plotted points
#
# example invocations are below - going from simplest to most elaborate
# create a 3d plot, minimum input arguments:
# plot_mg_pcoa(table_in="test_data.txt")
# create a 2d plot, minimum input arguments:
# plot_mg_pcoa(table_in="test_data.txt", plot_pcs = c(1,2))
# create a 3d plot with colors specified by a color_table file
# (by default, first column of color table is used) and the script expecpts
# entries to be literal or hex colors:
# plot_mg_pcoa(table_in="test_data.txt", color_table="test_colors.txt")
# create a 3d plot with colors generated from the color_table, using second column in color table
# specify option to generate colors from the table (any metadata will work)
# specify that the second column is used:
# plot_mg_pcoa(table_in="test_data.txt", color_table="test_colors.txt", auto_colors=TRUE, color_column=2)
# create a plot where every input argument is explicitly addressed:
# plot_mg_pcoa(table_in="test_data.txt", image_out = "wacky_pcoa", plot_pcs = c(1,3,5), label_points=NA, color_table="test_colors.txt", auto_colors=TRUE, color_column=3, pch_table="test_pch.txt", pch_column=3, image_width_in=10, image_height_in=10, image_res_dpi=250)
plot_mg_pcoa <<- function(
table_in="", # annotation abundance table (raw or normalized values)
image_out="default",
plot_pcs=c(1,2,3), # R formated string telling which coordinates to plot, and how many (2 or 3 coordinates)
dist_metric="euclidean", # distance metric to use one of (bray-curtis, euclidean, maximum, manhattan, canberra, minkowski, difference)
label_points=FALSE, # default is off
color_list=NA, # a list of colors for data points
color_table=NA, # matrix that contains colors or metadata that can be used to generate colors
color_column=1, # column of the color matrix to color the pcoa (colors for the points in the matrix) -- rows = samples, columns = colorings
auto_colors=FALSE, # automatically generate colors from metadata tables (identical values/text get the same color)
pch_list=NA, # a list of shapes for data points
pch_table=NA, # additional matrix that allows users to specify the shape of the data points
pch_column=1,
image_width_in=11,
image_height_in=8.5,
image_res_dpi=300
)
{
require(matR)
###################################################################################################################################
# MAIN
###################################################################################################################################
# generate filename for the image output
if ( identical(image_out, "default") ){
image_out = paste(table_in, ".pcoa.png", sep="", collapse="")
}else{
image_out = paste(image_out, ".png", sep="", collapse="")
}
###################################################################################################################################
###################################################################################################################################
######## import/parse all inputs
# import DATA the data (from tab text)
data_matrix <- data.matrix(read.table(table_in, row.names=1, header=TRUE, sep="\t", comment.char="", quote="", check.names=FALSE))
# convert data to a matR collection
data_collection <- suppressWarnings(as(data_matrix, "collection")) # take the input data and create a matR object with it
# import colors if the option is selected - generate colors from metadata table if that option is selected
if ( identical( is.na(color_table), FALSE ) ){
color_matrix <- as.matrix(read.table(file=color_table, row.names=1, header=TRUE, sep="\t", colClasses = "character", check.names=FALSE, comment.char = "", quote="", fill=TRUE, blank.lines.skip=FALSE))
# generate auto colors if the color matrix contains metadata and not colors
# this needs more work -- to get legend that maps colors to groups
if ( identical(auto_colors, TRUE) ){
pcoa_colors <- create_colors(color_matrix, color_mode="auto")
# generate figure legend (for auto-coloring only)
png(
filename = paste(image_out, ".legend.png", sep="", collapse=""),
width = 3,
height = 8,
res = 300,
units = 'in'
)
# this bit is a repeat of the code in the sub below - clean up later
column_factors <- as.factor(color_matrix[,color_column])
column_levels <- levels(as.factor(color_matrix[,color_column]))
num_levels <- length(column_levels)
color_levels <- col.wheel(num_levels)
#levels(column_factors) <- color_levels
#my_data.color[,color_column]<-as.character(column_factors)
par( mai = c(0,0,0,0) )
par( oma = c(0,0,0,0) )
plot.new()
par_legend <- par_fetch()
par_legend.test <<- par_legend
par_legend_cex <- calculate_cex(column_levels, par_legend$my_pin, par_legend$my_mai, reduce_by=0.40)
par_legend_cex.test <<- par_legend_cex
## legend_len <- length(color_levels)
## cex_val <- 1.0
## if (legend_len > 5) {
## cex_val <- 0.7
## }
## if (legend_len > 20) {
## cex_val <- 0.5
## }
## if (legend_len > 50) {
## cex_val <- 0.3
## }
legend( x="center", legend=column_levels, pch=16, col=color_levels, cex=par_legend_cex )
dev.off()
}else{
pcoa_colors <- color_matrix
}
plot_colors <- pcoa_colors[,color_column]
#plot_colors <- pcoa_colors[,color_column,drop=FALSE]
#plot_colors <- plot_colors[ colnames(data_matrix),,drop=FALSE ]
plot_colors.test <<- plot_colors
}else{
# use color list if the option is selected
if ( identical( is.na(color_list), FALSE ) ){
plot_colors <- color_list
}else{
plot_colors <- "black"
}
}
# load pch matrix if one is specified
if ( identical( is.na(pch_table), FALSE ) ){
pch_matrix <- data.matrix(read.table(file=pch_table, row.names=1, header=TRUE, sep="\t", comment.char="", quote="", check.names=FALSE))
plot_pch <- pch_matrix[,pch_column]
}else{
# use pch list if the option is selected
if ( identical( is.na(pch_list), FALSE ) ){
plot_pch <- pch_list
}else{
plot_pch = 16
}
}
###################################################################################################################################
###################################################################################################################################
# GENERATE THE PLOT - A SCOND LEGEND FIGURE IS PRODUCED IF AU
# Have matR calculate the pco and generate an image generate the image (2d)
png(
filename = image_out,
width = image_width_in,
height = image_height_in,
res = image_res_dpi,
units = 'in'
)
# 2d (color variable in matR is called "col")
if( length(plot_pcs)==2 ){
# with labels
if( identical(label_points, TRUE) ){
matR::pco(data_collection, comp = plot_pcs, method = dist_metric, col = plot_colors, pch = plot_pch)
}else{
# without labels
matR::pco(data_collection, comp = plot_pcs, method = dist_metric, col = plot_colors, pch = plot_pch, labels=NA)
}
}
# 3d (color variable in matR is called "color"
if( length(plot_pcs)==3 ){
# with labels
if( identical(label_points, TRUE) ){
pco(data_collection, comp = plot_pcs, method = dist_metric, color = plot_colors, pch = plot_pch)
}else{
# without labels
pco(data_collection, comp = plot_pcs, method = dist_metric, color = plot_colors, pch = plot_pch, labels=NA)
}
}
dev.off()
}
###################################################################################################################################
###################################################################################################################################
###################################################################################################################################
######## SUBS
############################################################################
### Color methods adapted from https://stat.ethz.ch/pipermail/r-help/2002-May/022037.html
############################################################################
# create optimal contrast color selection using a color wheel
col.wheel <- function(num_col, my_cex=0.75) {
cols <- rainbow(num_col)
col_names <- vector(mode="list", length=num_col)
for (i in 1:num_col){
col_names[i] <- getColorTable(cols[i])
}
cols
}
# $ # The inverse function to col2rgb()
rgb2col <- function(rgb) {
rgb <- as.integer(rgb)
class(rgb) <- "hexmode"
rgb <- as.character(rgb)
rgb <- matrix(rgb, nrow=3)
paste("#", apply(rgb, MARGIN=2, FUN=paste, collapse=""), sep="")
}
# $ # Convert all colors into format "#rrggbb"
getColorTable <- function(col) {
rgb <- col2rgb(col);
col <- rgb2col(rgb);
sort(unique(col))
}
############################################################################
create_colors <- function(color_matrix, color_mode = "auto"){ # function to automtically generate colors from metadata with identical text or values
my_data.color <- data.frame(color_matrix)
ids <- rownames(color_matrix)
color_categories <- colnames(color_matrix)
for ( i in 1:dim(color_matrix)[2] ){
column_factors <- as.factor(color_matrix[,i])
column_levels <- levels(as.factor(color_matrix[,i]))
num_levels <- length(column_levels)
color_levels <- col.wheel(num_levels)
levels(column_factors) <- color_levels
my_data.color[,i]<-as.character(column_factors)
}
return(my_data.color)
}
############################################################################
############################################################################
############################################################################
### SUB: Sub to provide scaling for title and legened cex
############################################################################
calculate_cex <- function(my_labels, my_pin, my_mai, reduce_by=0.30, debug){
# get figure width and height from pin
my_width <- my_pin[1]
my_height <- my_pin[2]
# get margine from mai
my_margin_bottom <- my_mai[1]
my_margin_left <- my_mai[2]
my_margin_top <- my_mai[3]
my_margin_right <- my_mai[4]
#if(debug==TRUE){
# print(paste("my_pin: ", my_pin, sep=""))
# print(paste("my_mai: ", my_mai, sep=""))
#}
# find the longest label (in inches), and figure out the maximum amount of length scaling that is possible
label_width_max <- 0
for (i in 1:length(my_labels)){
label_width <- strwidth(my_labels[i],'inches')
if ( label_width > label_width_max){ label_width_max<-label_width }
}
label_width_scale_max <- ( my_width - ( my_margin_right + my_margin_left ) )/label_width_max
## if(debug==TRUE){
## cat(paste("\n", "my_width: ", my_width, "\n",
## "label_width_max: ", label_width_max, "\n",
## "label_width_scale_max: ", label_width_scale_max, "\n",
## sep=""))
## }
# find the number of labels, and figure out the maximum height scaling that is possible
label_height_max <- 0
for (i in 1:length(my_labels)){
label_height <- strheight(my_labels[i],'inches')
if ( label_height > label_height_max){ label_height_max<-label_height }
}
adjusted.label_height_max <- ( label_height_max + label_height_max*0.4 ) # fudge factor for vertical space between legend entries
label_height_scale_max <- ( my_height - ( my_margin_top + my_margin_bottom ) ) / ( adjusted.label_height_max*length(my_labels) )
## if(debug==TRUE){
## cat(paste("\n", "my_height: ", my_height, "\n",
## "label_height_max: ", label_height_max, "\n",
## "length(my_labels): ", length(my_labels), "\n",
## "label_height_scale_max: ", label_height_scale_max, "\n",
## sep="" ))
## }
# max possible scale is the smaller of the two
scale_max <- min(label_width_scale_max, label_height_scale_max)
# adjust by buffer
#scale_max <- scale_max*(100-buffer/100)
adjusted_scale_max <- ( scale_max * (1-reduce_by) )
#if(debug==TRUE){ print(cat("\n", "adjusted_scale_max: ", adjusted_scale_max, "\n", sep="")) }
return(adjusted_scale_max)
}
##################################################################
##################################################################
##################################################################
### SUB(3): Fetch par values of the current frame - use to scale cex
##################################################################
par_fetch <- function(){
my_pin<-par('pin')
my_mai<-par('mai')
my_mar<-par('mar')
return(list("my_pin"=my_pin, "my_mai"=my_mai, "my_mar"=my_mar))
}
##################################################################
##################################################################
|
Formal statement is: lemma fract_poly_1 [simp]: "fract_poly 1 = 1" Informal statement is: The fractional polynomial $1$ is equal to $1$. |
c*****************************************************************************
c
c Subroutine RFT2
c
c Brute force utilization of sri's fft and realtr packages
c to get a real, 2-d, in-main transform.
c
c M and N are considered to be the line and sample dimensions
c of the given real array, respectively. Samples are adjacent
c in main store so N is the first fortran dimension.
c
c The real transform is taken in the line direction. This has
c the advantage that the extra space required for the transform
c due to the represented, but zero, sine coefficients of dc
c and the highest frequency is tacked on at the end of the array
c rather than at the end of each line. Thus the dimensions can
c be more or less consistant everywhere. It has the disadvantage
c that the real and imaginary parts of each complex number of the
c transform are not adjacent, but are separated by one line.
c
c 2 june 93 M. O'Shaughnessy ported to UNIX
c 22 sept 83 ...cca... convert to vax
c 15 june 77 ..jek.. initial release
c*****************************************************************************
subroutine rft2(a,m,n,isn,status)
integer*4 m,n,isn,status,m2,mp2,n2
real*4 a(n,m)
c a - the matrix to be transformed. Dimensions: a(n,m+2)
c m - number of lines
c n - number of samples
c isn - flag to do inverse transform.
c status - new parm to replace old calculated label statements
c m2 - half the value of m
c mp2 - m + 2
c n2 - double the value of n
status = 1 !default status = success
m2 = m/2
c If the dimension isn't even in the real transform direction, return an error.
if (2*m2 .ne. m) then
call xvmessage(
+ 'RFT2> dimension of the input matrix is not even!',' ')
status = -3
return
endif
mp2 = m + 2
n2 = 2*n
if (isn .lt. 0) go to 200
c********************
c forward transform..
c********************
do 120 i=1,n
call dfft(a(i,1),a(i,2),m2,m2,m2,n2,*950,*960)
call realtr(a(i,1),a(i,2),m2,n2)
120 continue
do 140 i=2,mp2,2
call dfft(a(1,i-1),a(1,i),n,n,n,1,*950,*960)
140 continue
return
c************************
c the inverse transform..
c************************
200 continue
do 220 i=2,mp2,2
call dfft(a(1,i-1),a(1,i),n,n,n,-1,*950,*960)
220 continue
do 240 i=1,n
call realtr(a(i,1),a(i,2),m2,-n2)
call dfft(a(i,1),a(i,2),m2,m2,m2,-n2,*950,*960)
240 continue
return
c************ Returns *******************************************************
c return (1) if m or n has too large a prime factor..
950 call xvmessage(
+ 'RFT2> a dimension of the input matrix has too large a ' //
+ 'prime factor!',' ')
status = -1
return
c
c return (2) if the product of the square-free factors of m or n is too large..
960 call xvmessage(
+ 'RFT2> product of one of the square-free factors of matrix ' //
+ 'dimensions is too large!',' ')
status = -2
return
end
c***end module***************************************************************
|
interface Natty (n : Nat) where
fromNatty : Type -> Nat
fromNatty (Natty Z) = Z
fromNatty (Natty (S n)) = S (fromNatty (Natty n))
fromNatty _ = Z
main : IO ()
main = ignore $ traverse printLn
[ fromNatty (Natty 3)
, fromNatty (Natty (2 + 6))
, fromNatty (List (Natty 1))
]
|
```python
%load_ext autoreload
%autoreload 2
import os
os.chdir("..")
```
```python
from particlezoo import TemplateParser
tp = TemplateParser("standard.json")
```
```python
model = {
"name": "Standard Model",
"gauges": [
{
"name": "U(1)_Y",
"group_type": "abelian",
"coupling": "g_Y"
},
{
"name": "SU(2)_L",
"group_type": ["SU", "2"],
"coupling": "g_L"
},
{
"name": "SU(2)_R",
"group_type": ["SU", "2"],
"coupling": "g_R"
}
],
"fields": [
{
"name": "L",
"description": "Left handed lepton",
"spin": "1/2",
"mass": "m_L",
"representations": [
{"name": "U(1)_Y", "charge": "1/6"},
{"name": "SU(2)_L", "charge": "2", },
{"name": "SU(2)_R", "representation": [2]}
]
}
]
}
t = TemplateParser()
t.template = model
result = t.parse().build()
```
```python
result
```
{'name': 'Standard Model', 'fields': [{'name': L, 'spin': 1/2, 'mass': <particlezoo.modeltemplates._models.NumericSymbol object at 0x7f5652057100>, 'representations': {'U(1)_Y': {'charge': '1/6', 'representation': 1/6}, 'SU(2)_L': {'charge': '2', 'representation': Matrix([[1]])}, 'SU(2)_R': {'representation': Matrix([[2]]), 'charge': 3}}}], 'gauges': [{'name': U(1)_Y, 'coupling': g_Y}, {'name': SU(2)_L, 'coupling': g_L}, {'name': SU(2)_R, 'coupling': g_R}]}
```python
from liesym import D
from sympy import *
```
```python
a = D(5)
a.get_irrep_by_dim(10, max_dd=5, with_symbols=True)
```
[(Matrix([[1, 0, 0, 0, 0]]), 10)]
```python
a.tensor_product_decomposition([Matrix([[1, 0, 0, 0, 0]]),Matrix([[1, 0, 0, 0, 0]])])
```
[Matrix([[0, 0, 0, 0, 0]]),
Matrix([[0, 1, 0, 0, 0]]),
Matrix([[2, 0, 0, 0, 0]])]
```python
```
|
From iris.proofmode Require Import tactics.
From iris_named_props Require Import named_props.
Section demo.
Context {PROP: bi} `{Haff: BiAffine PROP}.
Context (P Q: PROP).
Definition foo_rep :=
("HP" ∷ P ∗
"HR" ∷ Q)%I.
Theorem foo_rep_read_P : foo_rep -∗ P.
Proof using Haff.
iIntros "H".
iNamed "H".
(* at this point we have a context of
"HP" : P
"HR" : Q
--------------------------------------∗
P
*)
iExact "HP".
Qed.
End demo.
|
function [ objectIndex ] = GetScenario_waypointCurve(varargin)
% This scenario is designed to present a waypoint following exercise.
fprintf('[SCENARIO]\tGetting the waypoint following exercise.\n');
% DEFAULT CONFIGURATION
defaultConfig = struct('file','scenario.mat',...
'agents',[],...
'agentVelocity',0,...
'noiseFactor',0,...
'waypoints',3,...
'waypointRadius',0.1,...
'plot',0);
% Instanciate the scenario builder
SBinstance = scenarioBuilder();
% PARSE THE USER OVERRIDES USING THE SCENARIO BUILDER
[inputConfig] = SBinstance.configurationParser(defaultConfig,varargin);
% AGENT CONDITIONS
agentIndex = inputConfig.agents;
agentNumber = numel(agentIndex); % Declare the number of agents
%% DEFINE THE AGENT CONFIGURATION
% MOVE THROUGH THE AGENTS AND INITIALISE WITH GLOBAL PROPERTIES
fprintf('[SCENARIO]\tAssigning agent definition...\n');
for i=1:agentNumber
agentIndex{i}.SetGLOBAL('position',[0;0;0] + inputConfig.noiseFactor*randn(3,1));
agentIndex{i}.SetGLOBAL('velocity',[inputConfig.agentVelocity;0;0] + inputConfig.noiseFactor*randn(3,1));
agentIndex{i}.SetGLOBAL('quaternion',[1;0;0;0]);
end
%% DEFINE THE WAYPOINT CONFIGURATION
fprintf('[SCENARIO]\tBuilding the new scenario...\n');
waypointDefiningRadius = 20;
angleOffset = -pi/2; % Align the first waypoint to be directly infront of the agent
waypointConfig = SBinstance.planarAngle(...
'objects',agentNumber,...
'radius',waypointDefiningRadius,...
'pointA',[waypointDefiningRadius;-waypointDefiningRadius;-1],...
'pointB',[waypointDefiningRadius;-waypointDefiningRadius;0],...
'velocities',0,...
'zeroAngle',angleOffset);
% MOVE THROUGH THE WAYPOINTS AND INITIALISE WITH GLOBAL PROPERTIES
fprintf('[SCENARIO]\tAssigning waypoint definitions:\n');
for index = 1:inputConfig.waypoints
nameString = sprintf('WP-%s',agentIndex{1}.name);
waypointIndex{index} = waypoint('radius',inputConfig.waypointRadius,'name',nameString);
% APPLY GLOBAL STATE VARIABLES
waypointIndex{index}.SetGLOBAL('position',waypointConfig.positions(:,index));
waypointIndex{index}.SetGLOBAL('velocity',waypointConfig.velocities(:,index));
waypointIndex{index}.SetGLOBAL('quaternion',waypointConfig.quaternions(:,index));
% Assign waypoint to agent with priority
waypointIndex{index} = waypointIndex{index}.CreateAgentAssociation(agentIndex{1},1/index); % Create waypoint with association to agent
end
% BUILD THE COLLECTIVE OBJECT INDEX
objectIndex = horzcat(agentIndex,waypointIndex);
% PLOT THE SCENE
if inputConfig.plot
SBinstance.plotObjectIndex(objectIndex);
end
clearvars -except objectIndex % Clean-up
end |
Formal statement is: lemma to_fract_1 [simp]: "to_fract 1 = 1" Informal statement is: The fractional part of $1$ is $1$. |
##plots=group
##Layer=vector
##Data=Field Layer
##Data_Name=string data
##showplots
library(ggplot2)
DF <- ggplot(NULL, aes(x= Layer[[Data]])) +
geom_histogram(fill= "red",
colour= "black") +
labs(x = Data_Name)
plot(DF)
|
\atsptt
\begin{frame}{\ft{Configuring the Data Set Application}}
\section{Group 1: Configuring the Data Set Application}
\begin{annotatedFigure}{20pt}{0pt}{\includegraphics[scale=1.25]{texs/config.png}}
\node [text width=8.1cm,inner sep=14pt,align=justify,fill=logoCyan!20, draw=logoBlue,
draw opacity=0.5,line width=1mm,fill opacity=0.9]
at (0.87,0.68){\annfont\textbf{Using Qt Creator, the Dataset Creator
will automatically launch the main Dataset \mbox{Application}
with every feature needed in order to \mbox{visualize}
and explore the data. In
addition, the data set includes several
configurations allowing users to incorporate more specialized
or complex features, such as XPDF, test suites, and
data export code. Users can fine-tune which additional
features they wish to utilize --- via a separate dialog box
\mbox{(\circled{1} and \circled{2})} --- to create a customized build of the
main Dataset Application and supplemental executables.}};
\annotatedFigureBox{0.61,0.93}{0.75,0.982}{1}{0.75,0.922}%
\annotatedFigureBox{0.033,0.12}{0.58,0.97}{2}{0.58,0.97}%
% \annotatedFigureBox{0.222,0.284}{0.3743,0.4934}{B}{0.3743,0.4934}%tr
% \annotatedFigureBox{0.555,0.784}{0.6815,0.874}{C}{0.555,0.784}%bl
% \annotatedFigureBox{0.557,0.322}{0.8985,0.5269}{D}{0.8985,0.5269}%tr
\node [text width=6.5cm,inner sep=14pt,align=justify,fill=logoCyan!20, draw=logoBlue,
draw opacity=0.5,line width=1mm, fill opacity=0.9]
at (0.83,0.28){\annfont\textbf{Dataset Creator
also recognizes distinct ``roles" (\circled{2}), including
general readers, authors, testers (those who double-check the
main Dataset Application via a test suite), and those
who design the test suite and write dataset code overall
(dubbed ``Administrators").}};
\annotatedFigureBox{0.05,0.16}{0.57,0.35}{2}{0.57,0.35}
\end{annotatedFigure}
% \caption{Expanded Sample (A)}
% \label{fig:teaser}
\end{frame}
|
State Before: α : Type ?u.278351
inst✝ : Preorder α
a b c d : ℕ
lr₂ : 3 * (b + c + 1 + d) ≤ 16 * a + 9
mr₂ : b + c + 1 ≤ 3 * d
mm₁ : b ≤ 3 * c
⊢ b < 3 * a + 1 State After: no goals Tactic: linarith |
/-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Yury Kudryashov
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.set.intervals.basic
import Mathlib.data.set.lattice
import Mathlib.PostPort
universes u_1 u_2
namespace Mathlib
/-!
# Intervals in `pi`-space
In this we prove various simple lemmas about intervals in `Π i, α i`. Closed intervals (`Ici x`,
`Iic x`, `Icc x y`) are equal to products of their projections to `α i`, while (semi-)open intervals
usually include the corresponding products as proper subsets.
-/
namespace set
@[simp] theorem pi_univ_Ici {ι : Type u_1} {α : ι → Type u_2} [(i : ι) → preorder (α i)]
(x : (i : ι) → α i) : (pi univ fun (i : ι) => Ici (x i)) = Ici x :=
sorry
@[simp] theorem pi_univ_Iic {ι : Type u_1} {α : ι → Type u_2} [(i : ι) → preorder (α i)]
(x : (i : ι) → α i) : (pi univ fun (i : ι) => Iic (x i)) = Iic x :=
sorry
@[simp] theorem pi_univ_Icc {ι : Type u_1} {α : ι → Type u_2} [(i : ι) → preorder (α i)]
(x : (i : ι) → α i) (y : (i : ι) → α i) : (pi univ fun (i : ι) => Icc (x i) (y i)) = Icc x y :=
sorry
theorem pi_univ_Ioi_subset {ι : Type u_1} {α : ι → Type u_2} [(i : ι) → preorder (α i)]
(x : (i : ι) → α i) [Nonempty ι] : (pi univ fun (i : ι) => Ioi (x i)) ⊆ Ioi x :=
sorry
theorem pi_univ_Iio_subset {ι : Type u_1} {α : ι → Type u_2} [(i : ι) → preorder (α i)]
(x : (i : ι) → α i) [Nonempty ι] : (pi univ fun (i : ι) => Iio (x i)) ⊆ Iio x :=
pi_univ_Ioi_subset x
theorem pi_univ_Ioo_subset {ι : Type u_1} {α : ι → Type u_2} [(i : ι) → preorder (α i)]
(x : (i : ι) → α i) (y : (i : ι) → α i) [Nonempty ι] :
(pi univ fun (i : ι) => Ioo (x i) (y i)) ⊆ Ioo x y :=
fun (x_1 : (i : ι) → α i) (hx : x_1 ∈ pi univ fun (i : ι) => Ioo (x i) (y i)) =>
{ left :=
pi_univ_Ioi_subset (fun (i : ι) => x i) fun (i : ι) (hi : i ∈ univ) => and.left (hx i hi),
right :=
pi_univ_Iio_subset (fun (i : ι) => y i) fun (i : ι) (hi : i ∈ univ) => and.right (hx i hi) }
theorem pi_univ_Ioc_subset {ι : Type u_1} {α : ι → Type u_2} [(i : ι) → preorder (α i)]
(x : (i : ι) → α i) (y : (i : ι) → α i) [Nonempty ι] :
(pi univ fun (i : ι) => Ioc (x i) (y i)) ⊆ Ioc x y :=
fun (x_1 : (i : ι) → α i) (hx : x_1 ∈ pi univ fun (i : ι) => Ioc (x i) (y i)) =>
{ left :=
pi_univ_Ioi_subset (fun (i : ι) => x i) fun (i : ι) (hi : i ∈ univ) => and.left (hx i hi),
right := fun (i : ι) => and.right (hx i trivial) }
theorem pi_univ_Ico_subset {ι : Type u_1} {α : ι → Type u_2} [(i : ι) → preorder (α i)]
(x : (i : ι) → α i) (y : (i : ι) → α i) [Nonempty ι] :
(pi univ fun (i : ι) => Ico (x i) (y i)) ⊆ Ico x y :=
fun (x_1 : (i : ι) → α i) (hx : x_1 ∈ pi univ fun (i : ι) => Ico (x i) (y i)) =>
{ left := fun (i : ι) => and.left (hx i trivial),
right :=
pi_univ_Iio_subset (fun (i : ι) => y i) fun (i : ι) (hi : i ∈ univ) => and.right (hx i hi) }
theorem pi_univ_Ioc_update_left {ι : Type u_1} {α : ι → Type u_2} [(i : ι) → preorder (α i)]
[DecidableEq ι] {x : (i : ι) → α i} {y : (i : ι) → α i} {i₀ : ι} {m : α i₀} (hm : x i₀ ≤ m) :
(pi univ fun (i : ι) => Ioc (function.update x i₀ m i) (y i)) =
(set_of fun (z : (i : ι) → α i) => m < z i₀) ∩ pi univ fun (i : ι) => Ioc (x i) (y i) :=
sorry
theorem pi_univ_Ioc_update_right {ι : Type u_1} {α : ι → Type u_2} [(i : ι) → preorder (α i)]
[DecidableEq ι] {x : (i : ι) → α i} {y : (i : ι) → α i} {i₀ : ι} {m : α i₀} (hm : m ≤ y i₀) :
(pi univ fun (i : ι) => Ioc (x i) (function.update y i₀ m i)) =
(set_of fun (z : (i : ι) → α i) => z i₀ ≤ m) ∩ pi univ fun (i : ι) => Ioc (x i) (y i) :=
sorry
theorem disjoint_pi_univ_Ioc_update_left_right {ι : Type u_1} {α : ι → Type u_2}
[(i : ι) → preorder (α i)] [DecidableEq ι] {x : (i : ι) → α i} {y : (i : ι) → α i} {i₀ : ι}
{m : α i₀} :
disjoint (pi univ fun (i : ι) => Ioc (x i) (function.update y i₀ m i))
(pi univ fun (i : ι) => Ioc (function.update x i₀ m i) (y i)) :=
sorry
theorem pi_univ_Ioc_update_union {ι : Type u_1} {α : ι → Type u_2} [DecidableEq ι]
[(i : ι) → linear_order (α i)] (x : (i : ι) → α i) (y : (i : ι) → α i) (i₀ : ι) (m : α i₀)
(hm : m ∈ Icc (x i₀) (y i₀)) :
((pi univ fun (i : ι) => Ioc (x i) (function.update y i₀ m i)) ∪
pi univ fun (i : ι) => Ioc (function.update x i₀ m i) (y i)) =
pi univ fun (i : ι) => Ioc (x i) (y i) :=
sorry
/-- If `x`, `y`, `x'`, and `y'` are functions `Π i : ι, α i`, then
the set difference between the box `[x, y]` and the product of the open intervals `(x' i, y' i)`
is covered by the union of the following boxes: for each `i : ι`, we take
`[x, update y i (x' i)]` and `[update x i (y' i), y]`.
E.g., if `x' = x` and `y' = y`, then this lemma states that the difference between a closed box
`[x, y]` and the corresponding open box `{z | ∀ i, x i < z i < y i}` is covered by the union
of the faces of `[x, y]`. -/
theorem Icc_diff_pi_univ_Ioo_subset {ι : Type u_1} {α : ι → Type u_2} [DecidableEq ι]
[(i : ι) → linear_order (α i)] (x : (i : ι) → α i) (y : (i : ι) → α i) (x' : (i : ι) → α i)
(y' : (i : ι) → α i) :
(Icc x y \ pi univ fun (i : ι) => Ioo (x' i) (y' i)) ⊆
(Union fun (i : ι) => Icc x (function.update y i (x' i))) ∪
Union fun (i : ι) => Icc (function.update x i (y' i)) y :=
sorry
/-- If `x`, `y`, `z` are functions `Π i : ι, α i`, then
the set difference between the box `[x, z]` and the product of the intervals `(y i, z i]`
is covered by the union of the boxes `[x, update z i (y i)]`.
E.g., if `x = y`, then this lemma states that the difference between a closed box
`[x, y]` and the product of half-open intervals `{z | ∀ i, x i < z i ≤ y i}` is covered by the union
of the faces of `[x, y]` adjacent to `x`. -/
theorem Icc_diff_pi_univ_Ioc_subset {ι : Type u_1} {α : ι → Type u_2} [DecidableEq ι]
[(i : ι) → linear_order (α i)] (x : (i : ι) → α i) (y : (i : ι) → α i) (z : (i : ι) → α i) :
(Icc x z \ pi univ fun (i : ι) => Ioc (y i) (z i)) ⊆
Union fun (i : ι) => Icc x (function.update z i (y i)) :=
sorry
end Mathlib |
theorem ex1 : True := sorry
|
/-
This is a section.
It contains 00DZ, 00E0, 00E1 and 00E2 and 00E3 and 00E4 and 00E5 and 00E6 and 00E7 and 00E8 and 04PM
It also contains the following useful claim, just under Lemma 10.16.2 (tag 00E0):
The sets D(f) are open and form a basis for this topology (on Spec(R))
-/
import Kenny_comm_alg.temp analysis.topology.topological_space Kenny_comm_alg.Zariski
universe u
variables α : Type u
variable t : topological_space α
#check t
#print topological_space
def topological_space.is_topological_basis' {α : Type u} [t : topological_space α] (s : set (set α)) :=
(∀ U : set α, U ∈ s → t.is_open U) ∧
(∀ U : set α, t.is_open U → (∀ x, x ∈ U → ∃ V : set α, V ∈ s ∧ x ∈ V ∧ V ⊆ U))
#print topological_space.generate_open
lemma topological_space.generate_from_apply {α : Type u} [t : topological_space α] (s : set (set α)) (U : set α) :
topological_space.is_open (topological_space.generate_from s) U ↔ topological_space.generate_open s U := iff.rfl
lemma basis_is_basis' {α : Type u} [t : topological_space α] (s : set (set α)) :
topological_space.is_topological_basis s ↔ topological_space.is_topological_basis' s :=
begin
split,
{ intro H,
split,
{ intros U HU,
rw H.right.right,
exact topological_space.generate_open.basic U HU },
{ intros U HU x Hx,
unfold topological_space.is_topological_basis at H,
rw H.2.2 at HU,
have H3 : topological_space.generate_open s U := HU,
induction H3 with U4 H5 U6 U7 H8 H9 H10 H11 UU12 H13 H14,
{ existsi U4,
split,exact H5,
split,exact Hx,
exact set.subset.refl U4
},
{ have H4 := H.2.1,
have H5 : x ∈ ⋃₀ s,
rw H4,unfold set.univ,
cases H5 with V HV,
cases HV with H6 H7,
existsi V,
split,exact H6,
split,exact H7,
exact set.subset_univ V,
},
{ have H12 := H10 (set.inter_subset_left U6 U7 Hx) H8,
have H13 := H11 (set.inter_subset_right U6 U7 Hx) H9,
cases H12 with V14 H14,
cases H13 with V15 H15,
have H16 := H.1 V14 H14.1 V15 H15.1 x ⟨H14.2.1,H15.2.1⟩,
cases H16 with V H17,
cases H17 with H18 H19,
existsi V,
split,exact H18,
split,exact H19.1,
refine set.subset.trans H19.2 _,
intro z,
apply and.imp,
{ intro hz, exact H14.2.2 hz },
{ intro hz, exact H15.2.2 hz }
},
{ cases Hx with V HV,
cases HV with H15 H16,
rcases H14 V H15 H16 (H13 V H15) with ⟨W, H17, H18, H19⟩,
refine ⟨W, H17, H18, _⟩,
intros z hz,
exact ⟨V, H15, H19 hz⟩
}
}
},
{ intro H,
split,
{ intros U1 H1 U2 H2 x H3,
have H4 := H.1 U1 H1,
have H5 := H.1 U2 H2,
have H6 := H.2 (U1 ∩ U2) (topological_space.is_open_inter t U1 U2 H4 H5) x H3,
rcases H6 with ⟨V, H7, H8, H9⟩,
exact ⟨V, H7, H8, H9⟩
},
split,
{ apply set.ext,
intro x,
rw iff_true_right (set.mem_univ x),
have H1 := H.2 set.univ (topological_space.is_open_univ t) x trivial,
rcases H1 with ⟨V, H2, H3, H4⟩,
existsi V,
existsi H2,
exact H3
},
{ apply topological_space_eq,
apply funext,
intro U,
apply propext,
rw topological_space.generate_from_apply,
split,
{ intro H1,
have H2 := H.2 U H1,
have H3 : U = ⋃₀ {V | ∃ x ∈ U, V ∈ s ∧ x ∈ V ∧ V ⊆ U},
{ apply set.ext,
intro x,
split,
{ intro H3,
have H4 := H2 x H3,
rcases H4 with ⟨V, H4⟩,
existsi V,
fapply exists.intro,
exact ⟨x, H3, H4⟩,
exact H4.2.1
},
{ intro H3,
rcases H3 with ⟨U1, H3, H4⟩,
rcases H3 with ⟨y, H3, H5, H6, H7⟩,
exact H7 H4
}
},
rw H3,
apply topological_space.generate_open.sUnion,
intros U1 H4,
rcases H4 with ⟨U1, H4, H5, H6, H7⟩,
apply topological_space.generate_open.basic,
exact H5
},
{ exact generate_from_le H.1 U }
}
}
end
lemma D_f_form_basis (R : Type) [comm_ring R] :
topological_space.is_topological_basis {U : set (X R) | ∃ f : R, U = Spec.D'(f)} :=
begin
rw basis_is_basis',
split,
{ intros U H,
cases H with f Hf,
existsi ({f} : set R),
rw Hf,
unfold Spec.D',
unfold Spec.V,
unfold Spec.V',
rw set.compl_compl,
simp
},
{ intros U H x H1,
cases H with U1 H,
have H2 : U = -Spec.V U1,
{ rw [H, set.compl_compl] },
rw set.set_eq_def at H2,
have H3 := H2 x,
rw iff_true_left H1 at H3,
simp [Spec.V, has_subset.subset, set.subset] at H3,
rw classical.not_forall at H3,
cases H3 with f H3,
rw @@not_imp (classical.prop_decidable _) at H3,
cases H3 with H3 H4,
existsi Spec.D' f,
split,
{ existsi f,
refl
},
split,
{ exact H4 },
{ intros y H5,
rw H2,
intro H6,
apply H5,
exact H6 H3
}
}
end |
[GOAL]
G : Type u_1
M : Type u
⊢ ∀ ⦃m₁ m₂ : MulOneClass M⦄, Mul.mul = Mul.mul → m₁ = m₂
[PROOFSTEP]
rintro @⟨⟨one₁⟩, ⟨mul₁⟩, one_mul₁, mul_one₁⟩ @⟨⟨one₂⟩, ⟨mul₂⟩, one_mul₂, mul_one₂⟩
⟨rfl⟩
-- FIXME (See https://github.com/leanprover/lean4/issues/1711)
-- congr
[GOAL]
case mk.mk.mk.mk.mk.mk.refl
G : Type u_1
M : Type u
one₁ : M
mul₁ : M → M → M
one_mul₁ : ∀ (a : M), 1 * a = a
mul_one₁ : ∀ (a : M), a * 1 = a
one₂ : M
one_mul₂ : ∀ (a : M), 1 * a = a
mul_one₂ : ∀ (a : M), a * 1 = a
⊢ mk one_mul₁ mul_one₁ = mk one_mul₂ mul_one₂
[PROOFSTEP]
suffices one₁ = one₂ by cases this; rfl
[GOAL]
G : Type u_1
M : Type u
one₁ : M
mul₁ : M → M → M
one_mul₁ : ∀ (a : M), 1 * a = a
mul_one₁ : ∀ (a : M), a * 1 = a
one₂ : M
one_mul₂ : ∀ (a : M), 1 * a = a
mul_one₂ : ∀ (a : M), a * 1 = a
this : one₁ = one₂
⊢ mk one_mul₁ mul_one₁ = mk one_mul₂ mul_one₂
[PROOFSTEP]
cases this
[GOAL]
case refl
G : Type u_1
M : Type u
one₁ : M
mul₁ : M → M → M
one_mul₁ : ∀ (a : M), 1 * a = a
mul_one₁ : ∀ (a : M), a * 1 = a
one_mul₂ : ∀ (a : M), 1 * a = a
mul_one₂ : ∀ (a : M), a * 1 = a
⊢ mk one_mul₁ mul_one₁ = mk one_mul₂ mul_one₂
[PROOFSTEP]
rfl
[GOAL]
case mk.mk.mk.mk.mk.mk.refl
G : Type u_1
M : Type u
one₁ : M
mul₁ : M → M → M
one_mul₁ : ∀ (a : M), 1 * a = a
mul_one₁ : ∀ (a : M), a * 1 = a
one₂ : M
one_mul₂ : ∀ (a : M), 1 * a = a
mul_one₂ : ∀ (a : M), a * 1 = a
⊢ one₁ = one₂
[PROOFSTEP]
exact (one_mul₂ one₁).symm.trans (mul_one₁ one₂)
[GOAL]
G : Type u_1
M : Type u
inst✝ : Monoid M
a b c : M
hba : b * a = 1
hac : a * c = 1
⊢ b = c
[PROOFSTEP]
rw [← one_mul c, ← hba, mul_assoc, hac, mul_one b]
[GOAL]
G : Type u_1
inst✝ : DivInvMonoid G
a✝ b a : G
n : ℕ
⊢ a ^ Int.negSucc n = (a ^ (n + 1))⁻¹
[PROOFSTEP]
rw [← zpow_ofNat]
[GOAL]
G : Type u_1
inst✝ : DivInvMonoid G
a✝ b a : G
n : ℕ
⊢ a ^ Int.negSucc n = (a ^ ↑(n + 1))⁻¹
[PROOFSTEP]
exact DivInvMonoid.zpow_neg' n a
[GOAL]
G✝ : Type u_1
inst✝¹ : DivInvMonoid G✝
a✝ b : G✝
G : Type u_2
inst✝ : SubNegMonoid G
a : G
n : ℕ
⊢ Int.negSucc n • a = -((n + 1) • a)
[PROOFSTEP]
rw [← ofNat_zsmul]
[GOAL]
G✝ : Type u_1
inst✝¹ : DivInvMonoid G✝
a✝ b : G✝
G : Type u_2
inst✝ : SubNegMonoid G
a : G
n : ℕ
⊢ Int.negSucc n • a = -(↑(n + 1) • a)
[PROOFSTEP]
exact SubNegMonoid.zsmul_neg' n a
[GOAL]
G : Type u_1
inst✝ : Group G
a✝ b c a : G
⊢ a * a⁻¹ = 1
[PROOFSTEP]
rw [← mul_left_inv a⁻¹, inv_eq_of_mul (mul_left_inv a)]
[GOAL]
G : Type u_1
inst✝ : Group G
a✝ b✝ c a b : G
⊢ a⁻¹ * (a * b) = b
[PROOFSTEP]
rw [← mul_assoc, mul_left_inv, one_mul]
[GOAL]
G : Type u_1
inst✝ : Group G
a✝ b✝ c a b : G
⊢ a * (a⁻¹ * b) = b
[PROOFSTEP]
rw [← mul_assoc, mul_right_inv, one_mul]
[GOAL]
G : Type u_1
inst✝ : Group G
a✝ b✝ c a b : G
⊢ a * b * b⁻¹ = a
[PROOFSTEP]
rw [mul_assoc, mul_right_inv, mul_one]
[GOAL]
G : Type u_1
inst✝ : Group G
a✝ b✝ c a b : G
⊢ a * b⁻¹ * b = a
[PROOFSTEP]
rw [mul_assoc, mul_left_inv, mul_one]
[GOAL]
G : Type u_1
inst✝ : Group G
a✝ b✝ c a b : G
⊢ a * b * (b⁻¹ * a⁻¹) = 1
[PROOFSTEP]
rw [mul_assoc, mul_inv_cancel_left, mul_right_inv]
[GOAL]
G : Type u_1
inst✝ : Group G
a✝ b✝ c✝ : G
src✝ : Group G := inst✝
a b c : G
h : a * b = a * c
⊢ b = c
[PROOFSTEP]
rw [← inv_mul_cancel_left a b, h, inv_mul_cancel_left]
[GOAL]
G : Type u_1
inst✝ : Group G
a✝ b✝ c✝ : G
src✝ : Group G := inst✝
a b c : G
h : a * b = c * b
⊢ a = c
[PROOFSTEP]
rw [← mul_inv_cancel_right a b, h, mul_inv_cancel_right]
[GOAL]
G✝ : Type u_1
G : Type u_2
⊢ Injective (@toDivInvMonoid G)
[PROOFSTEP]
rintro ⟨⟩ ⟨⟩ ⟨⟩
[GOAL]
case mk.mk.refl
G✝ : Type u_1
G : Type u_2
toDivInvMonoid✝ : DivInvMonoid G
mul_left_inv✝¹ mul_left_inv✝ : ∀ (a : G), a⁻¹ * a = 1
⊢ mk mul_left_inv✝¹ = mk mul_left_inv✝
[PROOFSTEP]
rfl
[GOAL]
G✝ : Type u_1
G : Type u
⊢ Injective (@toGroup G)
[PROOFSTEP]
rintro ⟨⟩ ⟨⟩ ⟨⟩
[GOAL]
case mk.mk.refl
G✝ : Type u_1
G : Type u
toGroup✝ : Group G
mul_comm✝¹ mul_comm✝ : ∀ (a b : G), a * b = b * a
⊢ mk mul_comm✝¹ = mk mul_comm✝
[PROOFSTEP]
rfl
|
-- import .repeat_at_least_once
-- import .recover
-- open tactic
-- variables {α : Type} [has_to_format α]
-- meta inductive synthetic_goal
-- | none
-- | goals (original synthetic type : expr) : synthetic_goal
-- meta def synthetic_goal.new : tactic synthetic_goal :=
-- (do g :: gs ← get_goals,
-- t ← infer_type g,
-- is_lemma ← is_prop t,
-- if is_lemma then
-- return synthetic_goal.none
-- else do
-- m ← mk_meta_var t,
-- set_goals (m :: gs),
-- return (synthetic_goal.goals g m t)) <|> return synthetic_goal.none
-- meta def synthetic_goal.update : synthetic_goal → tactic synthetic_goal
-- | synthetic_goal.none := synthetic_goal.new
-- | (synthetic_goal.goals g g' t) :=
-- do try_core (do {
-- val ← instantiate_mvars g',
-- do {
-- guard (val.metavariables = []),
-- c ← new_aux_decl_name,
-- gs ← get_goals,
-- set_goals [g],
-- add_aux_decl c t val ff >>= unify g,
-- set_goals gs } <|> unify g val }),
-- synthetic_goal.new
-- meta def luxembourg_chain_aux (tac : tactic α) : ℕ → synthetic_goal → tactic (synthetic_goal × list (ℕ × α))
-- | b s := do (done >> return (s, [])) <|>
-- (do a ← tac,
-- (s, c) ← luxembourg_chain_aux 0 s,
-- return (s, (b, a) :: c)) <|>
-- (do s ← s.update,
-- n ← num_goals,
-- if b = (n-1) then return (s, []) else do
-- rotate_left 1,
-- luxembourg_chain_aux (b+1) s)
-- /-- Returns a `list (ℕ × α)`, whose successive elements `(n, a)` represent
-- a successful result of `rotate_left n >> tac`.
-- (When `n = 0`, the `rotate_left` may of course be omitted.) -/
-- meta def luxembourg_chain_core (tac : tactic α) : tactic (list (ℕ × α)) :=
-- do b ← num_goals,
-- s ← synthetic_goal.new,
-- (s, r) ← luxembourg_chain_aux tac 0 s,
-- s.update,
-- return r
-- meta def luxembourg_chain (tactics : list (tactic α)) : tactic (list string) :=
-- do results ← luxembourg_chain_core (first tactics),
-- return (results.map (λ p, (if p.1 = 0 then "" else "rotate_left " ++ (to_string p.1) ++ ", ") ++ (format!"{p.2}").to_string))
|
section "Completeness of the standard Hoare logic"
theory StdLogicCompleteness imports StdLogic WhileLangLemmas begin
lemma Hoare_strengthen:
"(\<And>s. P s \<Longrightarrow> P' s) \<Longrightarrow> hoare P' p Q \<Longrightarrow> hoare P p Q" using h_weaken by blast
lemma Hoare_strengthen_post:
"(\<And>s. Q' s \<Longrightarrow> Q s) \<Longrightarrow> hoare P p Q' \<Longrightarrow> hoare P p Q" using h_weaken by blast
theorem Hoare_While:
assumes h1: "(\<And>s. P s \<Longrightarrow> R s)"
assumes h2: "(\<And>s. R s \<and> \<not>guard x s \<Longrightarrow> Q s)"
assumes h3: "\<And>s0. hoare (\<lambda>s. R s \<and> guard x s \<and> s = s0) p (\<lambda>s. R s \<and> m s < ((m s0)::nat))"
shows "hoare P (While x p) Q"
apply (rule_tac P'=R and Q'="\<lambda>s. R s \<and> \<not>guard x s" in h_weaken; (simp add: h1 h2)?)
apply (rule h_while[OF h3])
apply (clarsimp simp: wfP_def)
using wf_measure[where f=m, simplified measure_def inv_image_def]
by auto
lemma NRC_lemma:
"star_n (\<lambda>s t. guard f s \<and> terminates s c t) k0 m t0 \<Longrightarrow>
star_n (\<lambda>s t. guard f s \<and> terminates s c t) k1 m t1 \<Longrightarrow>
\<not>guard f t0 \<and> \<not>guard f t1 \<Longrightarrow>
t0 = t1 \<and> k0 = k1"
apply (induct k0 arbitrary: k1 m; clarsimp)
apply (case_tac k1; clarsimp)
apply (erule star_n.cases)+
apply clarsimp+
apply (erule star_n.cases)+
apply clarsimp+
apply (case_tac k1; clarsimp)
apply (erule star_n.cases)+
apply clarsimp+
apply (erule star_n.cases)+
apply clarsimp+
apply (rename_tac k1)
apply (drule_tac x=k1 in meta_spec)
apply (erule star_n.cases)
apply clarsimp+
apply (erule star_n.cases)
apply clarsimp+
apply (drule (1) terminates_deterministic)
apply clarsimp
done
lemma Hoare_terminates:
"hoare (\<lambda>s. \<exists>t. terminates s c t \<and> Q t) c Q"
proof (induct c arbitrary: Q)
case (Seq c1 c2)
then show ?case
apply (clarsimp simp: terminates_Seq)
apply (rule_tac M="\<lambda>s. \<exists>s'. terminates s c2 s' \<and> Q s'" in h_seq)
apply (drule_tac x="\<lambda>s. \<exists>s'. terminates s c2 s' \<and> Q s'" in meta_spec)
apply clarsimp
apply (rule Hoare_strengthen[rotated], simp, fastforce)
by fastforce
next
case (If x1 c1 c2)
then show ?case
apply (clarsimp simp: terminates_If)
apply (rule h_if)
by (rule Hoare_strengthen[rotated], fastforce+)+
next
case (While x1 c)
then show ?case
apply (rule_tac m="\<lambda>s. THE n. \<exists>t. (star_n (\<lambda>s t. guard x1 s \<and> terminates s c t) n s t)
\<and> \<not>guard x1 t"
in Hoare_While)
apply assumption
apply (clarsimp simp: terminates_While terminates_If terminates_Skip)
apply (rename_tac s0)
apply (rule_tac Q'="\<lambda>s. terminates s0 c s \<and> (\<exists>a b. terminates s (While x1 c) (a, b)
\<and> guard x1 s0 \<and> Q (a, b))"
in Hoare_strengthen_post[rotated])
apply (drule_tac x="\<lambda>s. terminates s0 c s \<and> (\<exists>a b. terminates s (While x1 c) (a, b)
\<and> guard x1 s0 \<and> Q (a, b))"
in meta_spec)
apply clarsimp
apply (rule Hoare_strengthen[rotated])
apply assumption
apply clarsimp
apply (subst (asm) (3) terminates_While)
apply (clarsimp simp: terminates_If terminates_Seq)
apply fastforce
apply (rule conjI)
apply fastforce
apply clarsimp
apply (drule_tac p="While x1 c" and f=x1 and c=c in terminates_While_NRC)
apply clarsimp
apply (erule exE)
apply (subst the_equality)
apply (rename_tac ab bb n)
apply (rule_tac x=ab in exI, rule_tac x=bb in exI)
apply (fastforce dest: NRC_lemma)+
apply clarsimp
apply (drule step_n[rotated], simp)
apply (subst the_equality)
apply (fastforce dest: NRC_lemma)+
done
qed (clarsimp simp: terminates_Skip terminates_Assign terminates_Print)+
theorem Hoare_completeness:
"hoare_sem P c Q \<Longrightarrow> hoare P c Q"
apply (unfold hoare_sem_def)
using h_weaken[OF _ Hoare_terminates] by blast
(* lemmas about properties of hoare *)
lemma hoare_pre_False:
"hoare (\<lambda>_. False) prog Q"
apply (rule Hoare_completeness)
apply (simp add: hoare_sem_def)
done
end |
using LinearAlgebra
function massmatrix(S::PBSpline{T}, q = S.p+1) where {T}
M = zeros(T, S.nₕ, S.nₕ)
for i in 1:S.nₕ
for k in 0:S.p
M[1,i] += integrate_gausslegendre(x -> (eval_PBSpline.(S, 1, x) .* eval_PBSpline.(S, i, x)),
k*S.h, (k+1)*S.h, q)
end
end
for j in 2:S.nₕ
for i in 1:S.nₕ
M[j,i] = M[j-1,(i-1+S.nₕ-1)%S.nₕ + 1]
end
end
return M
end
function stiffnessmatrix(S::PBSpline{T}, q = S.p) where {T}
K = zeros(T, S.nₕ, S.nₕ)
for i in 1:S.nₕ
for k in 0:S.p
K[1,i] += integrate_gausslegendre(x -> (eval_deriv_PBSpline.(S, 1, x) .* eval_deriv_PBSpline.(S, i, x) ),
k*S.h, (k+1)*S.h, q)
end
end
for j in 2:S.nₕ
for i in 1:S.nₕ
K[j,i] = K[j-1,(i-1+S.nₕ-1)%S.nₕ + 1]
end
end
return K
end
struct PoissonSolverPBSplines{DT <: Real} <: PoissonSolver{DT}
p::Int
nx::Int
Δx::DT
xgrid::Vector{DT}
L::DT
bspl::PBSpline{DT}
M::Matrix{DT}
S::Matrix{DT}
Ŝ::Matrix{DT}
P::Matrix{DT}
R::Matrix{DT}
ρ::Vector{DT}
ϕ::Vector{DT}
rhs::Vector{DT}
Mfac::LU{DT, Matrix{DT}}
Sfac::LU{DT, Matrix{DT}}
function PoissonSolverPBSplines{DT}(p::Int, nx::Int, L::DT) where {DT}
Δx = L/nx
xgrid = collect(0:Δx:1)
bspl = PBSpline(p, nx, L)
M = massmatrix(bspl)
S = stiffnessmatrix(bspl)
A = ones(nx)
R = A * A' / (A' * A)
P = Matrix(I, nx, nx) .- R
Ŝ = S .+ R
new(p, nx, Δx, xgrid, L, bspl, M, S, Ŝ, P, R,
zeros(DT,nx), zeros(DT,nx), zeros(DT,nx),
lu(M), lu(Ŝ))
end
end
PoissonSolverPBSplines(p::Int, nx::Int, L::DT) where {DT} = PoissonSolverPBSplines{DT}(p, nx, L)
Base.length(p::PoissonSolverPBSplines) = p.nx
function solve!(p::PoissonSolverPBSplines{DT}, x::AbstractVector{DT}, w::AbstractVector{DT} = one.(x) ./ length(x)) where {DT}
rhs_particles_PBSBasis(x, w, p.bspl, p.rhs)
ldiv!(p.ϕ, p.Sfac, - p.P * p.rhs)
ldiv!(p.ρ, p.Mfac, p.rhs)
return p
end
function eval_density(p::PoissonSolverPBSplines{DT}, x::DT) where {DT}
eval_PBSBasis(p.ρ, p.bspl, x)
end
function eval_potential(p::PoissonSolverPBSplines{DT}, x::DT) where {DT}
eval_PBSBasis(p.ϕ, p.bspl, x)
end
function eval_field(p::PoissonSolverPBSplines{DT}, x::DT) where {DT}
eval_deriv_PBSBasis(p.ϕ, p.bspl, x)
end
|
-- the commented-out cases are still wrong,
-- but fixing them as well would make other tests fail for mysterious reasons
-- see https://github.com/edwinb/Idris2/pull/281
main : IO ()
main = do
printLn $ 3
printLn $ 4.2
printLn $ "1.2"
printLn $ cast {to = Int} 4.8
printLn $ cast {to = Integer} 1.2
printLn $ cast {to = String} 2.7
-- printLn $ cast {to = Int} "1.2"
-- printLn $ cast {to = Integer} "2.7"
printLn $ cast {to = Double} "5.9"
printLn $ (the Int 6 `div` the Int 3)
printLn $ (the Integer 6 `div` the Integer 3)
-- printLn $ (cast {to = Int} "6.6" `div` cast "3.9")
-- printLn $ (cast {to = Integer} "6.6" `div` cast "3.9")
|
lemma multiplicity_characterization_int: "S = {p. 0 < f (p::int)} \<Longrightarrow> finite S \<Longrightarrow> \<forall>p\<in>S. prime p \<Longrightarrow> prime p \<Longrightarrow> n = (\<Prod>p\<in>S. p ^ f p) \<Longrightarrow> multiplicity p n = f p" |
/*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include <tbb/mutex.h>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/tuple/tuple.hpp>
#include "base/util.h"
#include "base/logging.h"
#include <tbb/atomic.h>
#include <cstdlib>
#include <cerrno>
#include <utility>
#include "hiredis/hiredis.h"
#include "hiredis/boostasio.hpp"
#include <list>
#include "../analytics/redis_connection.h"
#include "base/work_pipeline.h"
#include "QEOpServerProxy.h"
#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#include "query.h"
#include "analytics_types.h"
#include "stats_select.h"
#include <base/connection_info.h>
using std::list;
using std::string;
using std::vector;
using std::map;
using boost::assign::list_of;
using boost::ptr_map;
using boost::nullable;
using boost::tuple;
using boost::shared_ptr;
using boost::scoped_ptr;
using std::pair;
using std::auto_ptr;
using std::make_pair;
using process::ConnectionState;
using process::ConnectionType;
using process::ConnectionStatus;
extern RedisAsyncConnection * rac_alloc(EventManager *, const std::string & ,unsigned short,
RedisAsyncConnection::ClientConnectCbFn ,
RedisAsyncConnection::ClientDisconnectCbFn );
extern RedisAsyncConnection * rac_alloc_nocheck(EventManager *, const std::string & ,unsigned short,
RedisAsyncConnection::ClientConnectCbFn ,
RedisAsyncConnection::ClientDisconnectCbFn );
SandeshTraceBufferPtr QeTraceBuf(SandeshTraceBufferCreate(QE_TRACE_BUF, 10000));
struct RawResultT {
QEOpServerProxy::QPerfInfo perf;
shared_ptr<QEOpServerProxy::BufferT> res;
shared_ptr<QEOpServerProxy::OutRowMultimapT> mres;
shared_ptr<WhereResultT> wres;
};
typedef pair<redisReply,vector<string> > RedisT;
bool RedisAsyncArgCommand(RedisAsyncConnection * rac,
void *rpi, const vector<string>& args) {
return rac->RedisAsyncArgCmd(rpi, args);
}
class QEOpServerProxy::QEOpServerImpl {
public:
typedef std::vector<std::string> QEOutputT;
struct Input {
int cnum;
string hostname;
QueryEngine::QueryParams qp;
vector<uint64_t> chunk_size;
uint32_t wterms;
bool need_merge;
bool map_output;
string where;
string select;
string post;
uint64_t time_period;
string table;
uint32_t max_rows;
tbb::atomic<uint32_t> chunk_q;
tbb::atomic<uint32_t> total_rows;
};
void JsonInsert(std::vector<query_column> &columns,
contrail_rapidjson::Document& dd,
std::pair<const string,string> * map_it) {
bool found = false;
for (size_t j = 0; j < columns.size(); j++)
{
if ((0 == map_it->first.compare(0,5,string("COUNT")))) {
contrail_rapidjson::Value val(contrail_rapidjson::kNumberType);
unsigned long num = 0;
stringToInteger(map_it->second, num);
val.SetUint64(num);
contrail_rapidjson::Value vk;
dd.AddMember(vk.SetString(map_it->first.c_str(), dd.GetAllocator()), val, dd.GetAllocator());
found = true;
} else if (columns[j].name == map_it->first) {
if (map_it->second.length() == 0) {
contrail_rapidjson::Value val(contrail_rapidjson::kNullType);
contrail_rapidjson::Value vk;
dd.AddMember(vk.SetString(map_it->first.c_str(), dd.GetAllocator()), val, dd.GetAllocator());
found = true;
continue;
}
// find out type and convert
if (columns[j].datatype == "string" ||
columns[j].datatype == "uuid")
{
contrail_rapidjson::Value val(contrail_rapidjson::kStringType);
val.SetString(map_it->second.c_str(), dd.GetAllocator());
contrail_rapidjson::Value vk;
dd.AddMember(vk.SetString(map_it->first.c_str(), dd.GetAllocator()), val, dd.GetAllocator());
} else if (columns[j].datatype == "ipaddr") {
contrail_rapidjson::Value val(contrail_rapidjson::kStringType);
val.SetString(map_it->second.c_str(),
dd.GetAllocator());
contrail_rapidjson::Value vk;
dd.AddMember(vk.SetString(map_it->first.c_str(), dd.GetAllocator()), val, dd.GetAllocator());
} else if (columns[j].datatype == "double") {
contrail_rapidjson::Value val(contrail_rapidjson::kNumberType);
double dval = (double) strtod(map_it->second.c_str(), NULL);
val.SetDouble(dval);
contrail_rapidjson::Value vk;
dd.AddMember(vk.SetString(map_it->first.c_str(), dd.GetAllocator()), val, dd.GetAllocator());
} else {
contrail_rapidjson::Value val(contrail_rapidjson::kNumberType);
unsigned long num = 0;
stringToInteger(map_it->second, num);
val.SetUint64(num);
contrail_rapidjson::Value vk;
dd.AddMember(vk.SetString(map_it->first.c_str(), dd.GetAllocator()), val, dd.GetAllocator());
}
found = true;
}
}
assert(found);
}
void QueryJsonify(const string& table, bool map_output,
const BufferT* raw_res, const OutRowMultimapT* raw_mres, QEOutputT* raw_json) {
vector<OutRowT>::iterator res_it;
std::vector<query_column> columns;
if (!table.size()) return;
bool found = false;
for(size_t i = 0; i < g_viz_constants._TABLES.size(); i++)
{
if (g_viz_constants._TABLES[i].name == table) {
found = true;
columns = g_viz_constants._TABLES[i].schema.columns;
}
}
if (!found) {
found = true;
columns = g_viz_constants._OBJECT_TABLE_SCHEMA.columns;
}
assert(found || map_output);
if (map_output) {
OutRowMultimapT::const_iterator mres_it;
for (mres_it = raw_mres->begin(); mres_it != raw_mres->end(); ++mres_it) {
string jstr;
StatsSelect::Jsonify(mres_it->second.first, mres_it->second.second, jstr);
raw_json->push_back(jstr);
}
} else {
QEOpServerProxy::BufferT* raw_result =
const_cast<QEOpServerProxy::BufferT*>(raw_res);
QEOpServerProxy::BufferT::iterator res_it;
for (res_it = raw_result->begin(); res_it != raw_result->end(); ++res_it) {
std::map<std::string, std::string>::iterator map_it;
contrail_rapidjson::Document dd;
dd.SetObject();
for (map_it = (*res_it).first.begin();
map_it != (*res_it).first.end(); ++map_it) {
// search for column name in the schema
JsonInsert(columns, dd, &(*map_it));
}
contrail_rapidjson::StringBuffer sb;
contrail_rapidjson::Writer<contrail_rapidjson::StringBuffer> writer(sb);
dd.Accept(writer);
raw_json->push_back(sb.GetString());
}
}
}
void QECallback(void * qid, QPerfInfo qperf,
auto_ptr<std::vector<query_result_unit_t> > res) {
RawResultT* raw(new RawResultT);
raw->perf = qperf;
raw->wres = res;
ExternalProcIf<RawResultT> * rpi = NULL;
if (qid)
rpi = reinterpret_cast<ExternalProcIf<RawResultT> *>(qid);
if (rpi) {
QE_LOG_NOQID(DEBUG, " Rx data from QE for " <<
rpi->Key());
auto_ptr<RawResultT> rp(raw);
rpi->Response(rp);
}
}
void QECallback(void * qid, QPerfInfo qperf, auto_ptr<QEOpServerProxy::BufferT> res,
auto_ptr<QEOpServerProxy::OutRowMultimapT> mres) {
RawResultT* raw(new RawResultT);
raw->perf = qperf;
raw->res = res;
raw->mres = mres;
ExternalProcIf<RawResultT> * rpi = NULL;
if (qid)
rpi = reinterpret_cast<ExternalProcIf<RawResultT> *>(qid);
if (rpi) {
QE_LOG_NOQID(DEBUG, " Rx data from QE for " <<
rpi->Key());
auto_ptr<RawResultT> rp(raw);
rpi->Response(rp);
}
}
struct Stage0Out {
Input inp;
bool ret_code;
vector<QPerfInfo> ret_info;
vector<uint32_t> chunk_merge_time;
shared_ptr<BufferT> result;
shared_ptr<OutRowMultimapT> mresult;
vector<shared_ptr<WhereResultT> > welem;
shared_ptr<WhereResultT> wresult;
uint32_t current_chunk;
};
ExternalBase::Efn QueryExec(uint32_t inst, const vector<RawResultT*> & exts,
const Input & inp, Stage0Out & res) {
uint32_t step = exts.size();
if (!step) {
res.inp = inp;
res.ret_code = true;
if (inp.map_output)
res.mresult = shared_ptr<OutRowMultimapT>(new OutRowMultimapT());
else
res.result = shared_ptr<BufferT>(new BufferT());
res.wresult = shared_ptr<WhereResultT>(new WhereResultT());
for (size_t or_idx=0; or_idx<inp.wterms; or_idx++) {
shared_ptr<WhereResultT> ss;
res.welem.push_back(ss);
}
Input& cinp = const_cast<Input&>(inp);
res.current_chunk = cinp.chunk_q.fetch_and_increment();
const uint32_t chunknum = res.current_chunk;
if (chunknum < inp.chunk_size.size()) {
string key = "QUERY:" + res.inp.qp.qid;
// Update query status
RedisAsyncConnection * rac = conns_[res.inp.cnum].get();
string rkey = "REPLY:" + res.inp.qp.qid;
char stat[40];
uint prg = 10 + (chunknum * 75)/inp.chunk_size.size();
QE_LOG_NOQID(DEBUG, "QueryExec for inst " << inst <<
" step " << step << " PROGRESS " << prg);
sprintf(stat,"{\"progress\":%d}", prg);
RedisAsyncArgCommand(rac, NULL,
list_of(string("RPUSH"))(rkey)(stat));
return boost::bind(&QueryEngine::QueryExecWhere, qosp_->qe_,
_1, inp.qp, chunknum, 0);
} else {
return NULL;
}
}
res.ret_info.push_back(exts[step-1]->perf);
if (exts[step-1]->perf.error) {
res.ret_code =false;
}
if (!res.ret_code) return NULL;
// Number of substeps per chunk is the number of OR terms in WHERE
// plus one more substep for select and post processing
uint32_t substep = step % (inp.wterms + 1);
if (substep == inp.wterms) {
// Get the result of the final WHERE
res.welem[substep-1] = exts[step-1]->wres;
// The set "OR" API needs raw pointers
vector<WhereResultT*> oterms;
for (size_t or_idx = 0; or_idx < inp.wterms; or_idx++) {
oterms.push_back(res.welem[or_idx].get());
}
// Do SET operations
QE_ASSERT(res.wresult->size() == 0);
SetOperationUnit::op_or(res.inp.qp.qid, *res.wresult, oterms);
for (size_t or_idx=0; or_idx<inp.wterms; or_idx++) {
res.welem[or_idx].reset();
}
// Start the SELECT and POST-processing
return boost::bind(&QueryEngine::QueryExec, qosp_->qe_,
_1, inp.qp, res.current_chunk, res.wresult.get());
} else if (substep == 0) {
// A chunk is complete. Start another one
res.wresult->clear();
uint32_t added_rows;
if (inp.need_merge) {
uint64_t then = UTCTimestampUsec();
if (inp.map_output) {
uint32_t base_rows = res.mresult->size();
// TODO: This interface should not be Stats-Specific
StatsSelect::Merge(*(exts[step-1]->mres), *(res.mresult));
// Some rows of this chunk will merge into existing results
added_rows = res.mresult->size() - base_rows;
} else {
uint32_t base_rows = res.result->size();
res.ret_code =
qosp_->qe_->QueryAccumulate(inp.qp,
*(exts[step-1]->res), *(res.result));
// Some rows of this chunk will merge into existing results
added_rows = res.result->size() - base_rows;
}
res.chunk_merge_time.push_back(
static_cast<uint32_t>((UTCTimestampUsec() - then)/1000));
} else {
// TODO : When merge is not needed, we can just send
// a result upto redis at this point.
if (inp.map_output) {
added_rows = exts[step-1]->mres->size();
OutRowMultimapT::iterator jt = res.mresult->begin();
for (OutRowMultimapT::const_iterator it = exts[step-1]->mres->begin();
it != exts[step-1]->mres->end(); it++ ) {
jt = res.mresult->insert(jt,
std::make_pair(it->first, it->second));
}
} else {
added_rows = exts[step-1]->res->size();
res.result->insert(res.result->begin(),
exts[step-1]->res->begin(),
exts[step-1]->res->end());
}
}
Input& cinp = const_cast<Input&>(inp);
if (cinp.total_rows.fetch_and_add(added_rows) > cinp.max_rows) {
QE_LOG_NOQID(ERROR, "QueryExec Max Rows Exceeded " <<
cinp.total_rows << " chunk " << cinp.chunk_q);
return NULL;
}
res.current_chunk = cinp.chunk_q.fetch_and_increment();
const uint32_t chunknum = res.current_chunk;
if (chunknum < inp.chunk_size.size()) {
string key = "QUERY:" + res.inp.qp.qid;
// Update query status
RedisAsyncConnection * rac = conns_[res.inp.cnum].get();
string rkey = "REPLY:" + res.inp.qp.qid;
char stat[40];
uint prg = 10 + (chunknum * 75)/inp.chunk_size.size();
QE_LOG_NOQID(DEBUG, "QueryExec for inst " << inst <<
" step " << step << " PROGRESS " << prg);
sprintf(stat,"{\"progress\":%d}", prg);
RedisAsyncArgCommand(rac, NULL,
list_of(string("RPUSH"))(rkey)(stat));
return boost::bind(&QueryEngine::QueryExecWhere, qosp_->qe_,
_1, inp.qp, chunknum, 0);
} else {
return NULL;
}
} else {
// We are in the middle of doing WHERE processing for a chunk
res.welem[substep-1] = exts[step-1]->wres;
return boost::bind(&QueryEngine::QueryExecWhere, qosp_->qe_,
_1, inp.qp, res.current_chunk, substep);
}
return NULL;
}
struct Stage0Merge {
Input inp;
bool ret_code;
bool overflow;
uint32_t fm_time;
vector<vector<QPerfInfo> > ret_info;
vector<vector<uint32_t> > chunk_merge_time;
BufferT result;
OutRowMultimapT mresult;
};
bool QueryMerge(const std::vector<boost::shared_ptr<Stage0Out> > & subs,
const boost::shared_ptr<Input> & inp, Stage0Merge & res) {
res.ret_code = true;
res.overflow = false;
res.inp = subs[0]->inp;
res.fm_time = 0;
uint32_t total_rows = 0;
for (vector<shared_ptr<Stage0Out> >::const_iterator it = subs.begin() ;
it!=subs.end(); it++) {
if (res.inp.map_output)
total_rows += (*it)->mresult->size();
else
total_rows += (*it)->result->size();
}
// If max_rows have been exceeded, don't do any more processing
if (total_rows > res.inp.max_rows) {
res.overflow = true;
return true;
}
std::vector<boost::shared_ptr<OutRowMultimapT> > mqsubs;
std::vector<boost::shared_ptr<QEOpServerProxy::BufferT> > qsubs;
for (vector<shared_ptr<Stage0Out> >::const_iterator it = subs.begin() ;
it!=subs.end(); it++) {
res.ret_info.push_back((*it)->ret_info);
res.chunk_merge_time.push_back((*it)->chunk_merge_time);
if ((*it)->ret_code == false) {
res.ret_code = false;
} else {
if (res.inp.map_output)
mqsubs.push_back((*it)->mresult);
else
qsubs.push_back((*it)->result);
}
}
if (!res.ret_code) return true;
if (res.inp.need_merge) {
uint64_t then = UTCTimestampUsec();
if (res.inp.map_output) {
res.ret_code =
qosp_->qe_->QueryFinalMerge(res.inp.qp, mqsubs, res.mresult);
} else {
res.ret_code =
qosp_->qe_->QueryFinalMerge(res.inp.qp, qsubs, res.result);
}
uint64_t now = UTCTimestampUsec();
res.fm_time = static_cast<uint32_t>((now - then)/1000);
} else {
// TODO : If a merge was not needed, results have been sent to
// redis already. The only thing still needed is the status
for (vector<shared_ptr<Stage0Out> >::const_iterator it = subs.begin() ;
it!=subs.end(); it++) {
if (res.inp.map_output) {
OutRowMultimapT::iterator jt = res.mresult.begin();
for (OutRowMultimapT::const_iterator kt = (*it)->mresult->begin();
kt != (*it)->mresult->end(); kt++) {
jt = res.mresult.insert(jt,
std::make_pair(kt->first, kt->second));
}
} else {
res.result.insert(res.result.begin(),
(*it)->result->begin(),
(*it)->result->end());
}
}
}
return true;
}
struct Output {
Input inp;
uint32_t redis_time;
bool ret_code;
};
ExternalBase::Efn QueryResp(uint32_t inst, const vector<RedisT*> & exts,
const Stage0Merge & inp, Output & ret) {
uint32_t step = exts.size();
switch (inst) {
case 0: {
if (!step) {
ret.inp = inp.inp;
RedisAsyncConnection * rac = conns_[ret.inp.cnum].get();
std::stringstream keystr;
auto_ptr<QEOutputT> jsonresult(new QEOutputT);
QE_LOG_NOQID(INFO, "Will Jsonify #rows " <<
inp.result.size() + inp.mresult.size());
QueryJsonify(inp.inp.table, inp.inp.map_output,
&inp.result, &inp.mresult, jsonresult.get());
vector<string> const * const res = jsonresult.get();
vector<string>::size_type idx = 0;
uint32_t rownum = 0;
QE_LOG_NOQID(INFO, "Did Jsonify #rows " << res->size());
uint64_t then = UTCTimestampUsec();
char stat[80];
string key = "REPLY:" + ret.inp.qp.qid;
if (inp.overflow) {
sprintf(stat,"{\"progress\":%d}", - ENOBUFS);
} else if (!inp.ret_code) {
sprintf(stat,"{\"progress\":%d}", - EIO);
} else {
while (idx < res->size()) {
uint32_t rowsize = 0;
keystr.str(string());
keystr << "RESULT:" << ret.inp.qp.qid << ":" << rownum;
vector<string> command = list_of(string("RPUSH"))(keystr.str());
while ((idx < res->size()) && (((int)rowsize) < kMaxRowThreshold)) {
command.push_back(res->at(idx));
rowsize += res->at(idx).size();
idx++;
}
RedisAsyncArgCommand(rac, NULL, command);
RedisAsyncArgCommand(rac, NULL,
list_of(string("EXPIRE"))(keystr.str())("300"));
sprintf(stat,"{\"progress\":90, \"lines\":%d}",
(int)rownum);
RedisAsyncArgCommand(rac, NULL,
list_of(string("RPUSH"))(key)(stat));
rownum++;
}
sprintf(stat,"{\"progress\":100, \"lines\":%d, \"count\":%d}",
(int)rownum, (int)res->size());
}
uint64_t now = UTCTimestampUsec();
ret.redis_time = static_cast<uint32_t>((now - then)/1000);
QE_LOG_NOQID(DEBUG, "QE Query Result is " << stat);
return boost::bind(&RedisAsyncArgCommand,
conns_[ret.inp.cnum].get(), _1,
list_of(string("RPUSH"))(key)(stat));
} else {
RedisAsyncConnection * rac = conns_[ret.inp.cnum].get();
string key = "REPLY:" + ret.inp.qp.qid;
RedisAsyncArgCommand(rac, NULL,
list_of(string("EXPIRE"))(key)("300"));
key = "QUERY:" + ret.inp.qp.qid;
RedisAsyncArgCommand(rac, NULL,
list_of(string("EXPIRE"))(key)("300"));
uint64_t now = UTCTimestampUsec();
uint32_t qtime = static_cast<uint32_t>(
(now - ret.inp.qp.query_starttm)/1000);
uint64_t enqtm = atol(ret.inp.qp.terms["enqueue_time"].c_str());
uint32_t enq_delay = static_cast<uint32_t>(
(ret.inp.qp.query_starttm - enqtm)/1000);
QueryStats qs;
size_t outsize;
if (ret.inp.map_output)
outsize = inp.mresult.size();
else
outsize = inp.result.size();
qs.set_rows(static_cast<uint32_t>(outsize));
qs.set_time(qtime);
qs.set_qid(ret.inp.qp.qid);
qs.set_chunks(inp.inp.chunk_size.size());
std::ostringstream wherestr, selstr, poststr;
for (size_t i=0; i < inp.ret_info.size(); i++) {
for (size_t j=0; j < inp.ret_info[i].size(); j++) {
wherestr << inp.ret_info[i][j].chunk_where_time << ",";
selstr << inp.ret_info[i][j].chunk_select_time << ",";
poststr << inp.ret_info[i][j].chunk_postproc_time << ",";
}
wherestr << " ";
selstr << " ";
poststr << " ";
}
if (inp.overflow) {
qs.set_error("ERROR-ENOBUFS");
} else if (!inp.ret_code) {
qs.set_error("ERROR-EIO");
} else {
qs.set_error("None");
}
qs.set_chunk_where_time(wherestr.str());
qs.set_chunk_select_time(selstr.str());
qs.set_chunk_postproc_time(poststr.str());
std::ostringstream mergestr;
for (size_t i=0; i < inp.chunk_merge_time.size(); i++) {
for (size_t j=0; j < inp.chunk_merge_time[i].size(); j++) {
mergestr << inp.chunk_merge_time[i][j] << ",";
}
mergestr << " ";
}
qs.set_chunk_merge_time(mergestr.str());
qs.set_final_merge_time(inp.fm_time);
qs.set_where(inp.inp.where);
qs.set_select(inp.inp.select);
qs.set_post(inp.inp.post);
qs.set_time_span(static_cast<uint32_t>(inp.inp.time_period));
qs.set_enq_delay(enq_delay);
QUERY_PERF_INFO_SEND(Sandesh::source(), // name
inp.inp.table, // table
qs);
//g_viz_constants.COLLECTOR_GLOBAL_TABLE
QE_LOG_NOQID(INFO, "Finished: QID " << ret.inp.qp.qid <<
" Table " << inp.inp.table <<
" Time(ms) " << qtime <<
" RedisTime(ms) " << ret.redis_time <<
" MergeTime(ms) " << inp.fm_time <<
" Rows " << outsize <<
" EnQ-delay" << enq_delay);
ret.ret_code = true;
}
}
break;
case 1: {
if (!step) {
string key = "ENGINE:" + inp.inp.hostname;
return boost::bind(&RedisAsyncArgCommand,
conns_[inp.inp.cnum].get(), _1,
list_of(string("LREM"))(key)("0")(inp.inp.qp.qid));
} else {
ret.ret_code = true;
}
}
break;
}
return NULL;
}
typedef WorkPipeline<Input, Stage0Merge, Output> QEPipeT;
void QEPipeCb(QEPipeT *wp, bool ret_code) {
tbb::mutex::scoped_lock lock(mutex_);
boost::shared_ptr<Output> res = wp->Result();
assert(pipes_.find(res->inp.qp.qid)->second == wp);
pipes_.erase(res->inp.qp.qid);
m_analytics_queries.erase(res->inp.qp.qid);
npipes_[res->inp.cnum-1]--;
QE_LOG_NOQID(DEBUG, " Result " << res->ret_code << " , " << res->inp.cnum << " conn");
delete wp;
}
void ConnUpPostProcess(uint8_t cnum) {
if (!connState_[cnum]) {
QE_LOG_NOQID(DEBUG, "ConnUp SetCB" << (uint32_t)cnum);
cb_proc_fn_[cnum] = boost::bind(&QEOpServerImpl::CallbackProcess,
this, cnum, _1, _2, _3);
conns_[cnum].get()->SetClientAsyncCmdCb(cb_proc_fn_[cnum]);
connState_[cnum] = true;
}
bool isConnected = true;
for(int i=0; i<kConnections+1; i++)
if (!connState_[i]) isConnected = false;
if (isConnected) {
string key = "ENGINE:" + hostname_;
conns_[0].get()->RedisAsyncArgCmd(0,
list_of(string("BRPOPLPUSH"))("QUERYQ")(key)("0"));
}
}
int LeastLoadedConnection() {
int minvalue = npipes_[0];
int minindex = 0;
for (int i=1; i<kConnections; i++) {
if (npipes_[i] < minvalue) {
minvalue = npipes_[i];
minindex = i;
}
}
return minindex;
}
void QueryError(string qid, int ret_code) {
redisContext *c = redisConnect(redis_host_.c_str(), port_);
if (c->err) {
QE_LOG_NOQID(ERROR, "Cannot report query error for " << qid <<
" . No Redis Connection");
return;
}
//Authenticate the context with password
if (!redis_password_.empty()) {
redisReply * reply = (redisReply *) redisCommand(c, "AUTH %s",
redis_password_.c_str());
if (reply->type == REDIS_REPLY_ERROR) {
QE_LOG_NOQID(ERROR, "Authentication to redis error");
freeReplyObject(reply);
redisFree(c);
return;
}
freeReplyObject(reply);
}
char stat[80];
string key = "REPLY:" + qid;
sprintf(stat,"{\"progress\":%d}", - ret_code);
redisReply * reply = (redisReply *) redisCommand(c, "RPUSH %s %s",
key.c_str(), stat);
freeReplyObject(reply);
redisFree(c);
}
void StartPipeline(const string qid) {
QueryStats qs;
qs.set_qid(qid);
qs.set_rows(0);
qs.set_time(0);
qs.set_final_merge_time(0);
qs.set_enq_delay(0);
uint64_t now = UTCTimestampUsec();
tbb::mutex::scoped_lock lock(mutex_);
redisContext *c = redisConnect(redis_host_.c_str(), port_);
if (c->err) {
QE_LOG_NOQID(ERROR, "Cannot start Pipleline for " << qid <<
" . No Redis Connection");
qs.set_error("No Redis Connection");
QUERY_PERF_INFO_SEND(Sandesh::source(), // name
"__UNKNOWN__", // table
qs);
return;
}
//Authenticate the context with password
if ( !redis_password_.empty()) {
redisReply * reply = (redisReply *) redisCommand(c, "AUTH %s",
redis_password_.c_str());
if (reply->type == REDIS_REPLY_ERROR) {
QE_LOG_NOQID(ERROR, "Authentication to redis error");
freeReplyObject(reply);
redisFree(c);
qs.set_error("Redis Auth Failed");
QUERY_PERF_INFO_SEND(Sandesh::source(), // name
"__UNKNOWN__", // table
qs);
return;
}
freeReplyObject(reply);
}
string key = "QUERY:" + qid;
redisReply * reply = (redisReply *) redisCommand(c, "hgetall %s",
key.c_str());
map<string,string> terms;
if (!(c->err) && (reply->type == REDIS_REPLY_ARRAY)) {
for (uint32_t i=0; i<reply->elements; i+=2) {
string idx(reply->element[i]->str);
string val(reply->element[i+1]->str);
terms[idx] = val;
}
} else {
QE_LOG_NOQID(ERROR, "Cannot start Pipleline for " << qid <<
". Could not read query input");
freeReplyObject(reply);
redisFree(c);
QueryError(qid, 5);
qs.set_error("Could not read query input");
QUERY_PERF_INFO_SEND(Sandesh::source(), // name
"__UNKNOWN__", // table
qs);
return;
}
freeReplyObject(reply);
redisFree(c);
QueryEngine::QueryParams qp(qid, terms, max_tasks_,
UTCTimestampUsec());
vector<uint64_t> chunk_size;
bool need_merge;
bool map_output;
string table;
string where;
uint32_t wterms;
string select;
string post;
uint64_t time_period;
int ret = qosp_->qe_->QueryPrepare(qp, chunk_size, need_merge, map_output,
where, wterms, select, post, time_period, table);
qs.set_where(where);
qs.set_select(select);
qs.set_post(post);
qs.set_time_span(time_period);
uint64_t enqtm = atol(terms["enqueue_time"].c_str());
uint32_t enq_delay = static_cast<uint32_t>((now - enqtm)/1000);
qs.set_enq_delay(enq_delay);
if (ret!=0) {
QueryError(qid, ret);
QE_LOG_NOQID(ERROR, "Cannot start Pipleline for " << qid <<
". Query Parsing Error " << ret);
qs.set_error("Query Parsing Error");
QUERY_PERF_INFO_SEND(Sandesh::source(), // name
table, // table
qs);
return;
} else {
QE_LOG_NOQID(INFO, "Chunks: " << chunk_size.size() <<
" Need Merge: " << need_merge);
}
if (pipes_.size() >= 32) {
QueryError(qid, EMFILE);
QE_LOG_NOQID(ERROR, "Cannot start Pipleline for " << qid <<
". Too many queries : " << pipes_.size());
qs.set_error("EMFILE");
QUERY_PERF_INFO_SEND(Sandesh::source(), // name
table, // table
qs);
return;
}
shared_ptr<Input> inp(new Input());
inp.get()->hostname = hostname_;
inp.get()->qp = qp;
inp.get()->map_output = map_output;
inp.get()->need_merge = need_merge;
inp.get()->chunk_size = chunk_size;
inp.get()->where = where;
inp.get()->select = select;
inp.get()->post = post;
inp.get()->time_period = time_period;
inp.get()->table = table;
inp.get()->chunk_q = 0;
inp.get()->total_rows = 0;
inp.get()->max_rows = max_rows_;
inp.get()->wterms = wterms;
vector<pair<int,int> > tinfo;
for (uint idx=0; idx<(uint)max_tasks_; idx++) {
tinfo.push_back(make_pair(0, -1));
}
QEPipeT * wp = new QEPipeT(
new WorkStage<Input, Stage0Merge,
RawResultT, Stage0Out>(
tinfo,
boost::bind(&QEOpServerImpl::QueryExec, this, _1,_2,_3,_4),
boost::bind(&QEOpServerImpl::QueryMerge, this, _1,_2,_3)),
new WorkStage<Stage0Merge, Output,
RedisT>(
list_of(make_pair(0,-1))(make_pair(0,-1)),
boost::bind(&QEOpServerImpl::QueryResp, this, _1,_2,_3,_4)));
pipes_.insert(make_pair(qid, wp));
// Initialize the m_analytics_queries for this qid
m_analytics_queries[qid] = std::vector<boost::shared_ptr<AnalyticsQuery> > ();
int conn = LeastLoadedConnection();
npipes_[conn]++;
// The cnum with index 0 is only used for receiving new queries
inp.get()->cnum = conn+1;
wp->Start(boost::bind(&QEOpServerImpl::QEPipeCb, this, wp, _1), inp);
QE_LOG_NOQID(DEBUG, "Starting Pipeline for " << qid << " , " << conn+1 <<
" conn, " << tinfo.size() << " tasks");
// Update query status
RedisAsyncConnection * rac = conns_[inp.get()->cnum].get();
string rkey = "REPLY:" + qid;
char stat[40];
sprintf(stat,"{\"progress\":15}");
RedisAsyncArgCommand(rac, NULL,
list_of(string("RPUSH"))(rkey)(stat));
}
void ConnUpPrePostProcess(uint8_t cnum) {
//Assign callback for AUTH command
cb_proc_fn_[cnum] = boost::bind(&QEOpServerImpl::ConnectCallbackProcess,
this, cnum, _1, _2, _3);
conns_[cnum].get()->SetClientAsyncCmdCb(cb_proc_fn_[cnum]);
//Send AUTH command
RedisAsyncConnection * rac = conns_[cnum].get();
if (!redis_password_.empty()) {
RedisAsyncArgCommand(rac, NULL,
list_of(string("AUTH"))(redis_password_.c_str()));
} else {
RedisAsyncArgCommand(rac, NULL,
list_of(string("PING")));
}
}
void ConnUp(uint8_t cnum) {
std::ostringstream ostr;
ostr << "ConnUp.. UP " << (uint32_t)cnum;
QE_LOG_NOQID(DEBUG, ostr.str());
qosp_->evm_->io_service()->post(
boost::bind(&QEOpServerImpl::ConnUpPrePostProcess,
this, cnum));
}
void ConnDown(uint8_t cnum) {
QE_LOG_NOQID(DEBUG, "ConnDown.. DOWN.. Reconnect.." << (uint32_t)cnum);
connState_[cnum] = false;
ConnectionState::GetInstance()->Update(ConnectionType::REDIS_QUERY,
"Query", ConnectionStatus::DOWN, conns_[cnum]->Endpoint(),
std::string());
qosp_->evm_->io_service()->post(boost::bind(&RedisAsyncConnection::RAC_Connect,
conns_[cnum].get()));
}
void ConnectCallbackProcess(uint8_t cnum, const redisAsyncContext *c, void *r, void *privdata) {
if (r == NULL) {
QE_LOG_NOQID(DEBUG, "In ConnectCallbackProcess.. NULL Reply");
return;
}
redisReply reply = *reinterpret_cast<redisReply*>(r);
if (reply.type != REDIS_REPLY_ERROR) {
QE_LOG_NOQID(DEBUG, "In ConnectCallbackProcess..");
ConnectionState::GetInstance()->Update(ConnectionType::REDIS_QUERY,
"Query", ConnectionStatus::UP, conns_[cnum]->Endpoint(),
std::string());
qosp_->evm_->io_service()->post(
boost::bind(&QEOpServerImpl::ConnUpPostProcess,
this, cnum));
} else {
QE_LOG_NOQID(ERROR,"In connectCallbackProcess.. Error");
QE_ASSERT(reply.type != REDIS_REPLY_ERROR);
}
}
void CallbackProcess(uint8_t cnum, const redisAsyncContext *c, void *r, void *privdata) {
//QE_TRACE_NOQID(DEBUG, "Redis CB" << cnum);
if (0 == cnum) {
if (r == NULL) {
QE_LOG_NOQID(DEBUG, __func__ << ": received NULL reply from redis");
return;
}
redisReply reply = *reinterpret_cast<redisReply*>(r);
if (reply.type != REDIS_REPLY_STRING) {
QE_LOG_NOQID(ERROR, __func__ << " Bad Redis reply on control connection: " << reply.type);
if (reply.type == REDIS_REPLY_ERROR) {
string errstr(reply.str);
QE_LOG_NOQID(ERROR, __func__ << " Redis Error: " << reply.str);
sleep(1000);
}
}
QE_ASSERT(reply.type == REDIS_REPLY_STRING);
string qid(reply.str);
StartPipeline(qid);
qosp_->evm_->io_service()->post(
boost::bind(&QEOpServerImpl::ConnUpPostProcess,
this, cnum));
return;
}
auto_ptr<RedisT> fullReply;
vector<string> elements;
if (r == NULL) {
//QE_TRACE_NOQID(DEBUG, "NULL Reply...\n");
} else {
redisReply reply = *reinterpret_cast<redisReply*>(r);
fullReply.reset(new RedisT);
fullReply.get()->first = reply;
if (reply.type == REDIS_REPLY_ARRAY) {
for (uint32_t i=0; i<reply.elements; i++) {
string element(reply.element[i]->str);
fullReply.get()->second.push_back(element);
}
} else if (reply.type == REDIS_REPLY_STRING) {
fullReply.get()->second.push_back(string(reply.str));
}
}
if (!privdata) {
//QE_TRACE_NOQID(DEBUG, "Ignoring redis reply");
return;
}
ExternalProcIf<RedisT> * rpi =
reinterpret_cast<ExternalProcIf<RedisT> *>(privdata);
QE_TRACE_NOQID(DEBUG, " Rx data from REDIS for " << rpi->Key());
rpi->Response(fullReply);
}
QEOpServerImpl(const string & redis_host, uint16_t port,
const string & redis_password, QEOpServerProxy * qosp,
int max_tasks, int max_rows) :
hostname_(boost::asio::ip::host_name()),
redis_host_(redis_host),
port_(port),
redis_password_(redis_password),
qosp_(qosp),
max_tasks_(max_tasks),
max_rows_(max_rows) {
for (int i=0; i<kConnections+1; i++) {
cb_proc_fn_[i] = boost::bind(&QEOpServerImpl::CallbackProcess,
this, i, _1, _2, _3);
connState_[i] = false;
if (i)
conns_[i].reset(rac_alloc(qosp->evm_, redis_host_, port,
boost::bind(&QEOpServerImpl::ConnUp, this, i),
boost::bind(&QEOpServerImpl::ConnDown, this, i)));
else
conns_[i].reset(rac_alloc_nocheck(qosp->evm_, redis_host_, port,
boost::bind(&QEOpServerImpl::ConnUp, this, i),
boost::bind(&QEOpServerImpl::ConnDown, this, i)));
// The cnum with index 0 is only used for receiving new queries
// It does not host any pipelines
if (i) npipes_[i-1] = 0;
}
}
~QEOpServerImpl() {
}
void AddAnalyticsQuery(const std::string &qid,
boost::shared_ptr<AnalyticsQuery> q) {
tbb::mutex::scoped_lock lock(mutex_);
m_analytics_queries[qid].push_back(q);
}
private:
static const int kMaxRowThreshold = 10000;
// We always have one connection to receive new queries from OpServer
// This is the number of addition connections, which will be
// used to read query parameters and write query results
static const uint8_t kConnections = 4;
const string hostname_;
const string redis_host_;
const unsigned short port_;
const string redis_password_;
QEOpServerProxy * const qosp_;
boost::shared_ptr<RedisAsyncConnection> conns_[kConnections+1];
RedisAsyncConnection::ClientAsyncCmdCbFn cb_proc_fn_[kConnections+1];
bool connState_[kConnections+1];
tbb::mutex mutex_;
map<string,QEPipeT*> pipes_;
int npipes_[kConnections];
int max_tasks_;
int max_rows_;
std::map<std::string, std::vector<boost::shared_ptr<AnalyticsQuery> > >
m_analytics_queries;
};
QEOpServerProxy::QEOpServerProxy(EventManager *evm, QueryEngine *qe,
const string & hostname, uint16_t port, const string & redis_password,
int max_tasks, int max_rows) :
evm_(evm),
qe_(qe),
impl_(new QEOpServerImpl(hostname, port, redis_password, this,
max_tasks, max_rows)) {}
QEOpServerProxy::~QEOpServerProxy() {}
void
QEOpServerProxy::QueryResult(void * qid, QPerfInfo qperf,
auto_ptr<BufferT> res, auto_ptr<OutRowMultimapT> mres) {
impl_->QECallback(qid, qperf, res, mres);
}
void
QEOpServerProxy::QueryResult(void * qid, QPerfInfo qperf,
auto_ptr<std::vector<query_result_unit_t> > res) {
impl_->QECallback(qid, qperf, res);
}
void QEOpServerProxy::AddAnalyticsQuery(const std::string &qid,
boost::shared_ptr<AnalyticsQuery> q) {
impl_->AddAnalyticsQuery(qid, q);
}
|
library(ggvis)
# Histogram, fully specified
mtcars %>% ggvis(x = ~wt) %>%
compute_bin(~wt, width = 1, pad = FALSE) %>%
layer_rects(x = ~xmin_, x2 = ~xmax_, y = ~count_, y2 = 0)
# Or using shorthand layer
mtcars %>% ggvis(x = ~wt) %>% layer_histograms()
mtcars %>% ggvis(x = ~wt) %>% layer_histograms(width = 1)
# Histogram, filled by cyl
mtcars %>% ggvis(x = ~wt, fill = ~factor(cyl)) %>%
group_by(cyl) %>%
layer_histograms(width = 1)
# Bigger dataset
data(diamonds, package = "ggplot2")
diamonds %>% ggvis(x = ~table) %>% layer_histograms()
# Stacked histogram
diamonds %>% ggvis(x = ~table, fill = ~cut) %>%
group_by(cut) %>%
layer_histograms(width = 1)
# Histogram of dates
set.seed(2934)
dat <- data.frame(times = as.POSIXct("2013-07-01", tz = "GMT") + rnorm(200) * 60 * 60 * 24 * 7)
dat %>% ggvis(x = ~times) %>% layer_histograms()
|
-- vim: ts=2 sw=0 sts=-1 et ai tw=70
import .basic
import .le
import .lt
namespace hidden
namespace mynat
variables {m n k p a b c: mynat}
theorem lt_to_mul:
1 < k → n ≠ 0 → n < n * k :=
(λ h1k hnn0, lt_mul hnn0 h1k)
theorem lt_rhs_nonzero:
m < n → n ≠ 0 :=
begin
assume hmn hn0,
rw hn0 at hmn,
from lt_nzero hmn,
end
theorem pow_gt_1:
1 < a → 1 < a ^ succ n :=
begin
assume h1a,
induction n, {
from h1a,
}, {
rw pow_succ,
from lt_comb_mul h1a n_ih,
},
end
-- maybe should be done better than this
theorem pow_gt_1_converse:
1 < a ^ succ n → 1 < a :=
begin
cases a, {
simp,
assume h, from h,
}, {
cases a, {
simp,
assume h, from h,
}, {
assume _,
apply @lt_add _ _ 1,
from zero_lt_succ,
},
},
end
theorem exp_nonzero:
a ≠ 0 → a ^ n ≠ 0 :=
begin
assume han0 hexp0,
induction n with n_n n_ih, {
cases hexp0,
}, {
rw pow_succ at hexp0,
from n_ih (mul_integral han0 hexp0),
},
end
theorem exp_monotone:
1 < a → n < m → a ^ n < a ^ m :=
begin
assume h1a hnm,
cases (lt_iff_succ_le.mp hnm) with d hd,
rw [hd, succ_add, ←add_succ, pow_add],
have han0: a ≠ 0, {
assume ha0,
rw ha0 at h1a,
from lt_nzero h1a,
},
from lt_to_mul (pow_gt_1 h1a) (exp_nonzero han0),
end
theorem lt_impl_neq:
m < n → m ≠ n :=
begin
assume hmltn hmeqn,
rw hmeqn at hmltn,
from lt_nrefl hmltn,
end
theorem pow_cancel_left: -- aka, "taking base-a logs"
1 < a → a ^ n = a ^ m → n = m :=
begin
wlog_le m n, {
assume h1a hanam,
symmetry,
from hsymm h1a hanam.symm,
}, {
assume h1a haman,
cases (le_iff_lt_or_eq.mp hle) with hlt heq, {
exfalso,
from lt_impl_neq (exp_monotone h1a hlt) haman,
}, {
assumption,
},
},
end
theorem pow_monotone:
1 < a → n ≠ 0 → a < b → a ^ n < b ^ n :=
begin
assume h1a hnn0 hab,
cases n, {
contradiction,
}, {
clear hnn0,
induction n with n hn, {
assumption,
}, {
conv {
congr,
rw pow_succ,
skip,
rw pow_succ,
},
from lt_comb_mul hab hn,
},
},
end
theorem pow_monotone_nonstrict:
a ≤ b → a ^ n ≤ b ^ n :=
begin
assume hab,
induction n with n hn, {
from le_refl,
}, {
apply le_mul_comb, {
assumption,
}, {
assumption,
},
},
end
theorem pow_cancel_right: -- aka, "taking n-th roots"
1 < a → n ≠ 0 → a ^ n = b ^ n → a = b :=
begin
assume h1a hnn0 hanbn,
have h1b: 1 < b, {
cases n, {
contradiction,
}, {
have h1asn := pow_gt_1 h1a,
rw hanbn at h1asn,
from pow_gt_1_converse h1asn,
},
},
wlog_le a b, {
assume h1a hanbn h1b,
symmetry,
from hsymm h1b hanbn.symm h1a,
}, {
assume h1b hbnan h1a,
cases (le_iff_lt_or_eq.mp hle) with hlt heq, {
have := pow_monotone h1a hnn0 hlt,
exfalso,
from (lt_impl_neq this) hbnan.symm,
}, {
symmetry,
assumption,
},
},
end
-- this is probably bad, I'm rusty
theorem root_monotone:
1 < a → n ≠ 0 → a ^ n ≤ b ^ n → a ≤ b :=
begin
assume h1a hnn0 hanbn,
by_contradiction,
cases n, {
contradiction,
}, {
cases b, {
simp at hanbn,
rw ←pow_succ at hanbn,
have := @pow_gt_1 n a h1a,
have := lt_le_chain _ this hanbn,
from lt_nzero this,
}, {
cases b, {
simp at hanbn,
rw ←pow_succ at hanbn,
have := @pow_gt_1 n a h1a,
have := lt_le_chain _ this hanbn,
from lt_nrefl this,
}, {
have h1b: 1 < b.succ.succ, {
rw ←add_one_succ,
rw add_comm,
from @lt_to_add_succ 1 b,
},
have := pow_monotone h1b hnn0 a_1,
contradiction,
},
},
},
end
end mynat
end hidden
|
lemmas mult_poly_0 = mult_poly_0_left mult_poly_0_right |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.