text
stringlengths 0
3.34M
|
---|
/-
Copyright (c) 2019 Calle Sönne. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Calle Sönne
-/
import analysis.special_functions.trigonometric.basic
import analysis.normed.group.add_circle
import algebra.char_zero.quotient
import algebra.order.to_interval_mod
import topology.instances.sign
/-!
# The type of angles
In this file we define `real.angle` to be the quotient group `ℝ/2πℤ` and prove a few simple lemmas
about trigonometric functions and angles.
-/
open_locale real
noncomputable theory
namespace real
/-- The type of angles -/
@[derive [normed_add_comm_group, inhabited, has_coe_t ℝ]]
def angle : Type := add_circle (2 * π)
namespace angle
@[continuity] lemma continuous_coe : continuous (coe : ℝ → angle) :=
continuous_quotient_mk
/-- Coercion `ℝ → angle` as an additive homomorphism. -/
def coe_hom : ℝ →+ angle := quotient_add_group.mk' _
@[simp] lemma coe_coe_hom : (coe_hom : ℝ → angle) = coe := rfl
/-- An induction principle to deduce results for `angle` from those for `ℝ`, used with
`induction θ using real.angle.induction_on`. -/
@[elab_as_eliminator]
protected lemma induction_on {p : angle → Prop} (θ : angle) (h : ∀ x : ℝ, p x) : p θ :=
quotient.induction_on' θ h
@[simp] lemma coe_zero : ↑(0 : ℝ) = (0 : angle) := rfl
@[simp] lemma coe_add (x y : ℝ) : ↑(x + y : ℝ) = (↑x + ↑y : angle) := rfl
@[simp] lemma coe_neg (x : ℝ) : ↑(-x : ℝ) = -(↑x : angle) := rfl
@[simp] lemma coe_sub (x y : ℝ) : ↑(x - y : ℝ) = (↑x - ↑y : angle) := rfl
lemma coe_nsmul (n : ℕ) (x : ℝ) : ↑(n • x : ℝ) = (n • ↑x : angle) := rfl
lemma coe_zsmul (z : ℤ) (x : ℝ) : ↑(z • x : ℝ) = (z • ↑x : angle) := rfl
@[simp, norm_cast] lemma coe_nat_mul_eq_nsmul (x : ℝ) (n : ℕ) :
↑((n : ℝ) * x) = n • (↑x : angle) :=
by simpa only [nsmul_eq_mul] using coe_hom.map_nsmul x n
@[simp, norm_cast] lemma coe_int_mul_eq_zsmul (x : ℝ) (n : ℤ) :
↑((n : ℝ) * x : ℝ) = n • (↑x : angle) :=
by simpa only [zsmul_eq_mul] using coe_hom.map_zsmul x n
lemma angle_eq_iff_two_pi_dvd_sub {ψ θ : ℝ} : (θ : angle) = ψ ↔ ∃ k : ℤ, θ - ψ = 2 * π * k :=
by simp only [quotient_add_group.eq, add_subgroup.zmultiples_eq_closure,
add_subgroup.mem_closure_singleton, zsmul_eq_mul', (sub_eq_neg_add _ _).symm, eq_comm]
@[simp] lemma coe_two_pi : ↑(2 * π : ℝ) = (0 : angle) :=
angle_eq_iff_two_pi_dvd_sub.2 ⟨1, by rw [sub_zero, int.cast_one, mul_one]⟩
@[simp] lemma neg_coe_pi : -(π : angle) = π :=
begin
rw [←coe_neg, angle_eq_iff_two_pi_dvd_sub],
use -1,
simp [two_mul, sub_eq_add_neg]
end
@[simp] lemma two_nsmul_coe_div_two (θ : ℝ) : (2 : ℕ) • (↑(θ / 2) : angle) = θ :=
by rw [←coe_nsmul, two_nsmul, add_halves]
@[simp] lemma two_zsmul_coe_div_two (θ : ℝ) : (2 : ℤ) • (↑(θ / 2) : angle) = θ :=
by rw [←coe_zsmul, two_zsmul, add_halves]
@[simp] lemma two_nsmul_neg_pi_div_two : (2 : ℕ) • (↑(-π / 2) : angle) = π :=
by rw [two_nsmul_coe_div_two, coe_neg, neg_coe_pi]
@[simp] lemma two_zsmul_neg_pi_div_two : (2 : ℤ) • (↑(-π / 2) : angle) = π :=
by rw [two_zsmul, ←two_nsmul, two_nsmul_neg_pi_div_two]
lemma sub_coe_pi_eq_add_coe_pi (θ : angle) : θ - π = θ + π :=
by rw [sub_eq_add_neg, neg_coe_pi]
@[simp] lemma two_nsmul_coe_pi : (2 : ℕ) • (π : angle) = 0 :=
by simp [←coe_nat_mul_eq_nsmul]
@[simp] lemma two_zsmul_coe_pi : (2 : ℤ) • (π : angle) = 0 :=
by simp [←coe_int_mul_eq_zsmul]
@[simp] lemma coe_pi_add_coe_pi : (π : real.angle) + π = 0 :=
by rw [←two_nsmul, two_nsmul_coe_pi]
lemma zsmul_eq_iff {ψ θ : angle} {z : ℤ} (hz : z ≠ 0) :
z • ψ = z • θ ↔ (∃ k : fin z.nat_abs, ψ = θ + (k : ℕ) • (2 * π / z : ℝ)) :=
quotient_add_group.zmultiples_zsmul_eq_zsmul_iff hz
lemma nsmul_eq_iff {ψ θ : angle} {n : ℕ} (hz : n ≠ 0) :
n • ψ = n • θ ↔ (∃ k : fin n, ψ = θ + (k : ℕ) • (2 * π / n : ℝ)) :=
quotient_add_group.zmultiples_nsmul_eq_nsmul_iff hz
lemma two_zsmul_eq_iff {ψ θ : angle} : (2 : ℤ) • ψ = (2 : ℤ) • θ ↔ (ψ = θ ∨ ψ = θ + π) :=
by rw [zsmul_eq_iff two_ne_zero, int.nat_abs_bit0, int.nat_abs_one,
fin.exists_fin_two, fin.coe_zero, fin.coe_one, zero_smul, add_zero, one_smul,
int.cast_two, mul_div_cancel_left (_ : ℝ) two_ne_zero]
lemma two_nsmul_eq_iff {ψ θ : angle} : (2 : ℕ) • ψ = (2 : ℕ) • θ ↔ (ψ = θ ∨ ψ = θ + π) :=
by simp_rw [←coe_nat_zsmul, int.coe_nat_bit0, int.coe_nat_one, two_zsmul_eq_iff]
lemma two_nsmul_eq_zero_iff {θ : angle} : (2 : ℕ) • θ = 0 ↔ (θ = 0 ∨ θ = π) :=
by convert two_nsmul_eq_iff; simp
lemma two_nsmul_ne_zero_iff {θ : angle} : (2 : ℕ) • θ ≠ 0 ↔ θ ≠ 0 ∧ θ ≠ π :=
by rw [←not_or_distrib, ←two_nsmul_eq_zero_iff]
lemma two_zsmul_eq_zero_iff {θ : angle} : (2 : ℤ) • θ = 0 ↔ (θ = 0 ∨ θ = π) :=
by simp_rw [two_zsmul, ←two_nsmul, two_nsmul_eq_zero_iff]
lemma two_zsmul_ne_zero_iff {θ : angle} : (2 : ℤ) • θ ≠ 0 ↔ θ ≠ 0 ∧ θ ≠ π :=
by rw [←not_or_distrib, ←two_zsmul_eq_zero_iff]
lemma eq_neg_self_iff {θ : angle} : θ = -θ ↔ θ = 0 ∨ θ = π :=
by rw [←add_eq_zero_iff_eq_neg, ←two_nsmul, two_nsmul_eq_zero_iff]
lemma ne_neg_self_iff {θ : angle} : θ ≠ -θ ↔ θ ≠ 0 ∧ θ ≠ π :=
by rw [←not_or_distrib, ←eq_neg_self_iff.not]
lemma neg_eq_self_iff {θ : angle} : -θ = θ ↔ θ = 0 ∨ θ = π :=
by rw [eq_comm, eq_neg_self_iff]
lemma neg_ne_self_iff {θ : angle} : -θ ≠ θ ↔ θ ≠ 0 ∧ θ ≠ π :=
by rw [←not_or_distrib, ←neg_eq_self_iff.not]
lemma two_nsmul_eq_pi_iff {θ : angle} : (2 : ℕ) • θ = π ↔ (θ = (π / 2 : ℝ) ∨ θ = (-π / 2 : ℝ)) :=
begin
have h : (π : angle) = (2 : ℕ) • (π / 2 : ℝ), { rw [two_nsmul, ←coe_add, add_halves] },
nth_rewrite 0 h,
rw [two_nsmul_eq_iff],
congr',
rw [add_comm, ←coe_add, ←sub_eq_zero, ←coe_sub, add_sub_assoc, neg_div, sub_neg_eq_add,
add_halves, ←two_mul, coe_two_pi]
end
lemma two_zsmul_eq_pi_iff {θ : angle} : (2 : ℤ) • θ = π ↔ (θ = (π / 2 : ℝ) ∨ θ = (-π / 2 : ℝ)) :=
by rw [two_zsmul, ←two_nsmul, two_nsmul_eq_pi_iff]
theorem cos_eq_iff_coe_eq_or_eq_neg {θ ψ : ℝ} :
cos θ = cos ψ ↔ (θ : angle) = ψ ∨ (θ : angle) = -ψ :=
begin
split,
{ intro Hcos,
rw [← sub_eq_zero, cos_sub_cos, mul_eq_zero, mul_eq_zero, neg_eq_zero,
eq_false_intro (two_ne_zero' ℝ), false_or, sin_eq_zero_iff, sin_eq_zero_iff] at Hcos,
rcases Hcos with ⟨n, hn⟩ | ⟨n, hn⟩,
{ right,
rw [eq_div_iff_mul_eq (two_ne_zero' ℝ), ← sub_eq_iff_eq_add] at hn,
rw [← hn, coe_sub, eq_neg_iff_add_eq_zero, sub_add_cancel, mul_assoc,
coe_int_mul_eq_zsmul, mul_comm, coe_two_pi, zsmul_zero] },
{ left,
rw [eq_div_iff_mul_eq (two_ne_zero' ℝ), eq_sub_iff_add_eq] at hn,
rw [← hn, coe_add, mul_assoc,
coe_int_mul_eq_zsmul, mul_comm, coe_two_pi, zsmul_zero, zero_add] }, },
{ rw [angle_eq_iff_two_pi_dvd_sub, ← coe_neg, angle_eq_iff_two_pi_dvd_sub],
rintro (⟨k, H⟩ | ⟨k, H⟩),
rw [← sub_eq_zero, cos_sub_cos, H, mul_assoc 2 π k,
mul_div_cancel_left _ (two_ne_zero' ℝ), mul_comm π _, sin_int_mul_pi, mul_zero],
rw [← sub_eq_zero, cos_sub_cos, ← sub_neg_eq_add, H, mul_assoc 2 π k,
mul_div_cancel_left _ (two_ne_zero' ℝ), mul_comm π _, sin_int_mul_pi, mul_zero,
zero_mul] }
end
theorem sin_eq_iff_coe_eq_or_add_eq_pi {θ ψ : ℝ} :
sin θ = sin ψ ↔ (θ : angle) = ψ ∨ (θ : angle) + ψ = π :=
begin
split,
{ intro Hsin, rw [← cos_pi_div_two_sub, ← cos_pi_div_two_sub] at Hsin,
cases cos_eq_iff_coe_eq_or_eq_neg.mp Hsin with h h,
{ left, rw [coe_sub, coe_sub] at h, exact sub_right_inj.1 h },
right, rw [coe_sub, coe_sub, eq_neg_iff_add_eq_zero, add_sub,
sub_add_eq_add_sub, ← coe_add, add_halves, sub_sub, sub_eq_zero] at h,
exact h.symm },
{ rw [angle_eq_iff_two_pi_dvd_sub, ←eq_sub_iff_add_eq, ←coe_sub, angle_eq_iff_two_pi_dvd_sub],
rintro (⟨k, H⟩ | ⟨k, H⟩),
rw [← sub_eq_zero, sin_sub_sin, H, mul_assoc 2 π k,
mul_div_cancel_left _ (two_ne_zero' ℝ), mul_comm π _, sin_int_mul_pi, mul_zero,
zero_mul],
have H' : θ + ψ = (2 * k) * π + π := by rwa [←sub_add, sub_add_eq_add_sub, sub_eq_iff_eq_add,
mul_assoc, mul_comm π _, ←mul_assoc] at H,
rw [← sub_eq_zero, sin_sub_sin, H', add_div, mul_assoc 2 _ π,
mul_div_cancel_left _ (two_ne_zero' ℝ), cos_add_pi_div_two, sin_int_mul_pi, neg_zero,
mul_zero] }
end
theorem cos_sin_inj {θ ψ : ℝ} (Hcos : cos θ = cos ψ) (Hsin : sin θ = sin ψ) : (θ : angle) = ψ :=
begin
cases cos_eq_iff_coe_eq_or_eq_neg.mp Hcos with hc hc, { exact hc },
cases sin_eq_iff_coe_eq_or_add_eq_pi.mp Hsin with hs hs, { exact hs },
rw [eq_neg_iff_add_eq_zero, hs] at hc,
obtain ⟨n, hn⟩ : ∃ n, n • _ = _ := quotient_add_group.left_rel_apply.mp (quotient.exact' hc),
rw [← neg_one_mul, add_zero, ← sub_eq_zero, zsmul_eq_mul, ← mul_assoc, ← sub_mul,
mul_eq_zero, eq_false_intro (ne_of_gt pi_pos), or_false, sub_neg_eq_add,
← int.cast_zero, ← int.cast_one, ← int.cast_bit0, ← int.cast_mul, ← int.cast_add,
int.cast_inj] at hn,
have : (n * 2 + 1) % (2:ℤ) = 0 % (2:ℤ) := congr_arg (%(2:ℤ)) hn,
rw [add_comm, int.add_mul_mod_self] at this,
exact absurd this one_ne_zero
end
/-- The sine of a `real.angle`. -/
def sin (θ : angle) : ℝ := sin_periodic.lift θ
@[simp] lemma sin_coe (x : ℝ) : sin (x : angle) = real.sin x :=
rfl
@[continuity] lemma continuous_sin : continuous sin :=
real.continuous_sin.quotient_lift_on' _
/-- The cosine of a `real.angle`. -/
def cos (θ : angle) : ℝ := cos_periodic.lift θ
@[simp] lemma cos_coe (x : ℝ) : cos (x : angle) = real.cos x :=
rfl
@[continuity] lemma continuous_cos : continuous cos :=
real.continuous_cos.quotient_lift_on' _
lemma cos_eq_real_cos_iff_eq_or_eq_neg {θ : angle} {ψ : ℝ} : cos θ = real.cos ψ ↔ θ = ψ ∨ θ = -ψ :=
begin
induction θ using real.angle.induction_on,
exact cos_eq_iff_coe_eq_or_eq_neg
end
lemma cos_eq_iff_eq_or_eq_neg {θ ψ : angle} : cos θ = cos ψ ↔ θ = ψ ∨ θ = -ψ :=
begin
induction ψ using real.angle.induction_on,
exact cos_eq_real_cos_iff_eq_or_eq_neg
end
lemma sin_eq_real_sin_iff_eq_or_add_eq_pi {θ : angle} {ψ : ℝ} :
sin θ = real.sin ψ ↔ θ = ψ ∨ θ + ψ = π :=
begin
induction θ using real.angle.induction_on,
exact sin_eq_iff_coe_eq_or_add_eq_pi
end
lemma sin_eq_iff_eq_or_add_eq_pi {θ ψ : angle} : sin θ = sin ψ ↔ θ = ψ ∨ θ + ψ = π :=
begin
induction ψ using real.angle.induction_on,
exact sin_eq_real_sin_iff_eq_or_add_eq_pi
end
@[simp] lemma sin_zero : sin (0 : angle) = 0 :=
by rw [←coe_zero, sin_coe, real.sin_zero]
@[simp] lemma sin_coe_pi : sin (π : angle) = 0 :=
by rw [sin_coe, real.sin_pi]
lemma sin_eq_zero_iff {θ : angle} : sin θ = 0 ↔ θ = 0 ∨ θ = π :=
begin
nth_rewrite 0 ←sin_zero,
rw sin_eq_iff_eq_or_add_eq_pi,
simp
end
lemma sin_ne_zero_iff {θ : angle} : sin θ ≠ 0 ↔ θ ≠ 0 ∧ θ ≠ π :=
by rw [←not_or_distrib, ←sin_eq_zero_iff]
@[simp] lemma sin_neg (θ : angle) : sin (-θ) = -sin θ :=
begin
induction θ using real.angle.induction_on,
exact real.sin_neg _
end
lemma sin_antiperiodic : function.antiperiodic sin (π : angle) :=
begin
intro θ,
induction θ using real.angle.induction_on,
exact real.sin_antiperiodic θ
end
@[simp] lemma sin_add_pi (θ : angle) : sin (θ + π) = -sin θ :=
sin_antiperiodic θ
@[simp] lemma sin_sub_pi (θ : angle) : sin (θ - π) = -sin θ :=
sin_antiperiodic.sub_eq θ
@[simp] lemma cos_zero : cos (0 : angle) = 1 :=
by rw [←coe_zero, cos_coe, real.cos_zero]
@[simp] lemma cos_coe_pi : cos (π : angle) = -1 :=
by rw [cos_coe, real.cos_pi]
@[simp] lemma cos_neg (θ : angle) : cos (-θ) = cos θ :=
begin
induction θ using real.angle.induction_on,
exact real.cos_neg _
end
lemma cos_antiperiodic : function.antiperiodic cos (π : angle) :=
begin
intro θ,
induction θ using real.angle.induction_on,
exact real.cos_antiperiodic θ
end
@[simp] lemma cos_add_pi (θ : angle) : cos (θ + π) = -cos θ :=
cos_antiperiodic θ
@[simp] lemma cos_sub_pi (θ : angle) : cos (θ - π) = -cos θ :=
cos_antiperiodic.sub_eq θ
lemma cos_eq_zero_iff {θ : angle} : cos θ = 0 ↔ (θ = (π / 2 : ℝ) ∨ θ = (-π / 2 : ℝ)) :=
by rw [← cos_pi_div_two, ← cos_coe, cos_eq_iff_eq_or_eq_neg, ← coe_neg, ← neg_div]
lemma sin_add (θ₁ θ₂ : real.angle) : sin (θ₁ + θ₂) = sin θ₁ * cos θ₂ + cos θ₁ * sin θ₂ :=
begin
induction θ₁ using real.angle.induction_on,
induction θ₂ using real.angle.induction_on,
exact real.sin_add θ₁ θ₂
end
lemma cos_add (θ₁ θ₂ : real.angle) : cos (θ₁ + θ₂) = cos θ₁ * cos θ₂ - sin θ₁ * sin θ₂ :=
begin
induction θ₂ using real.angle.induction_on,
induction θ₁ using real.angle.induction_on,
exact real.cos_add θ₁ θ₂,
end
@[simp] lemma cos_sq_add_sin_sq (θ : real.angle) : cos θ ^ 2 + sin θ ^ 2 = 1 :=
begin
induction θ using real.angle.induction_on,
exact real.cos_sq_add_sin_sq θ,
end
lemma sin_add_pi_div_two (θ : angle) : sin (θ + ↑(π / 2)) = cos θ :=
begin
induction θ using real.angle.induction_on,
exact sin_add_pi_div_two _
end
lemma sin_sub_pi_div_two (θ : angle) : sin (θ - ↑(π / 2)) = -cos θ :=
begin
induction θ using real.angle.induction_on,
exact sin_sub_pi_div_two _
end
lemma sin_pi_div_two_sub (θ : angle) : sin (↑(π / 2) - θ) = cos θ :=
begin
induction θ using real.angle.induction_on,
exact sin_pi_div_two_sub _
end
lemma cos_add_pi_div_two (θ : angle) : cos (θ + ↑(π / 2)) = -sin θ :=
begin
induction θ using real.angle.induction_on,
exact cos_add_pi_div_two _
end
lemma cos_sub_pi_div_two (θ : angle) : cos (θ - ↑(π / 2)) = sin θ :=
begin
induction θ using real.angle.induction_on,
exact cos_sub_pi_div_two _
end
lemma cos_pi_div_two_sub (θ : angle) : cos (↑(π / 2) - θ) = sin θ :=
begin
induction θ using real.angle.induction_on,
exact cos_pi_div_two_sub _
end
lemma abs_sin_eq_of_two_nsmul_eq {θ ψ : angle} (h : (2 : ℕ) • θ = (2 : ℕ) • ψ) :
|sin θ| = |sin ψ| :=
begin
rw two_nsmul_eq_iff at h,
rcases h with rfl | rfl,
{ refl },
{ rw [sin_add_pi, abs_neg] }
end
lemma abs_sin_eq_of_two_zsmul_eq {θ ψ : angle} (h : (2 : ℤ) • θ = (2 : ℤ) • ψ) :
|sin θ| = |sin ψ| :=
begin
simp_rw [two_zsmul, ←two_nsmul] at h,
exact abs_sin_eq_of_two_nsmul_eq h
end
lemma abs_cos_eq_of_two_nsmul_eq {θ ψ : angle} (h : (2 : ℕ) • θ = (2 : ℕ) • ψ) :
|cos θ| = |cos ψ| :=
begin
rw two_nsmul_eq_iff at h,
rcases h with rfl | rfl,
{ refl },
{ rw [cos_add_pi, abs_neg] }
end
lemma abs_cos_eq_of_two_zsmul_eq {θ ψ : angle} (h : (2 : ℤ) • θ = (2 : ℤ) • ψ) :
|cos θ| = |cos ψ| :=
begin
simp_rw [two_zsmul, ←two_nsmul] at h,
exact abs_cos_eq_of_two_nsmul_eq h
end
@[simp] lemma coe_to_Ico_mod (θ ψ : ℝ) : ↑(to_Ico_mod ψ two_pi_pos θ) = (θ : angle) :=
begin
rw angle_eq_iff_two_pi_dvd_sub,
refine ⟨-to_Ico_div ψ two_pi_pos θ, _⟩,
rw [to_Ico_mod_sub_self, zsmul_eq_mul, mul_comm]
end
@[simp] lemma coe_to_Ioc_mod (θ ψ : ℝ) : ↑(to_Ioc_mod ψ two_pi_pos θ) = (θ : angle) :=
begin
rw angle_eq_iff_two_pi_dvd_sub,
refine ⟨-to_Ioc_div ψ two_pi_pos θ, _⟩,
rw [to_Ioc_mod_sub_self, zsmul_eq_mul, mul_comm]
end
/-- Convert a `real.angle` to a real number in the interval `Ioc (-π) π`. -/
def to_real (θ : angle) : ℝ :=
(to_Ioc_mod_periodic (-π) two_pi_pos).lift θ
lemma to_real_coe (θ : ℝ) : (θ : angle).to_real = to_Ioc_mod (-π) two_pi_pos θ :=
rfl
lemma to_real_coe_eq_self_iff {θ : ℝ} : (θ : angle).to_real = θ ↔ -π < θ ∧ θ ≤ π :=
begin
rw [to_real_coe, to_Ioc_mod_eq_self two_pi_pos],
ring_nf
end
lemma to_real_coe_eq_self_iff_mem_Ioc {θ : ℝ} : (θ : angle).to_real = θ ↔ θ ∈ set.Ioc (-π) π :=
by rw [to_real_coe_eq_self_iff, ←set.mem_Ioc]
lemma to_real_injective : function.injective to_real :=
begin
intros θ ψ h,
induction θ using real.angle.induction_on,
induction ψ using real.angle.induction_on,
simpa [to_real_coe, to_Ioc_mod_eq_to_Ioc_mod, zsmul_eq_mul, mul_comm _ (2 * π),
←angle_eq_iff_two_pi_dvd_sub, eq_comm] using h,
end
@[simp] lemma to_real_inj {θ ψ : angle} : θ.to_real = ψ.to_real ↔ θ = ψ :=
to_real_injective.eq_iff
@[simp] lemma coe_to_real (θ : angle): (θ.to_real : angle) = θ :=
begin
induction θ using real.angle.induction_on,
exact coe_to_Ioc_mod _ _
end
lemma neg_pi_lt_to_real (θ : angle) : -π < θ.to_real :=
begin
induction θ using real.angle.induction_on,
exact left_lt_to_Ioc_mod _ two_pi_pos _
end
lemma to_real_le_pi (θ : angle) : θ.to_real ≤ π :=
begin
induction θ using real.angle.induction_on,
convert to_Ioc_mod_le_right _ two_pi_pos _,
ring
end
lemma abs_to_real_le_pi (θ : angle) : |θ.to_real| ≤ π :=
abs_le.2 ⟨(neg_pi_lt_to_real _).le, to_real_le_pi _⟩
lemma to_real_mem_Ioc (θ : angle) : θ.to_real ∈ set.Ioc (-π) π :=
⟨neg_pi_lt_to_real _, to_real_le_pi _⟩
@[simp] lemma to_Ioc_mod_to_real (θ : angle): to_Ioc_mod (-π) two_pi_pos θ.to_real = θ.to_real :=
begin
induction θ using real.angle.induction_on,
rw to_real_coe,
exact to_Ioc_mod_to_Ioc_mod _ _ _ _
end
@[simp] lemma to_real_zero : (0 : angle).to_real = 0 :=
begin
rw [←coe_zero, to_real_coe_eq_self_iff],
exact ⟨(left.neg_neg_iff.2 real.pi_pos), real.pi_pos.le⟩
end
@[simp] lemma to_real_eq_zero_iff {θ : angle} : θ.to_real = 0 ↔ θ = 0 :=
begin
nth_rewrite 0 ←to_real_zero,
exact to_real_inj
end
@[simp] lemma to_real_pi : (π : angle).to_real = π :=
begin
rw [to_real_coe_eq_self_iff],
exact ⟨left.neg_lt_self real.pi_pos, le_refl _⟩
end
@[simp] lemma to_real_eq_pi_iff {θ : angle} : θ.to_real = π ↔ θ = π :=
by rw [← to_real_inj, to_real_pi]
lemma pi_ne_zero : (π : angle) ≠ 0 :=
begin
rw [←to_real_injective.ne_iff, to_real_pi, to_real_zero],
exact pi_ne_zero
end
@[simp] lemma to_real_pi_div_two : ((π / 2 : ℝ) : angle).to_real = π / 2 :=
to_real_coe_eq_self_iff.2 $ by split; linarith [pi_pos]
@[simp] lemma to_real_eq_pi_div_two_iff {θ : angle} : θ.to_real = π / 2 ↔ θ = (π / 2 : ℝ) :=
by rw [← to_real_inj, to_real_pi_div_two]
@[simp] lemma to_real_neg_pi_div_two : ((-π / 2 : ℝ) : angle).to_real = -π / 2 :=
to_real_coe_eq_self_iff.2 $ by split; linarith [pi_pos]
@[simp] lemma to_real_eq_neg_pi_div_two_iff {θ : angle} : θ.to_real = -π / 2 ↔ θ = (-π / 2 : ℝ) :=
by rw [← to_real_inj, to_real_neg_pi_div_two]
lemma pi_div_two_ne_zero : ((π / 2 : ℝ) : angle) ≠ 0 :=
begin
rw [←to_real_injective.ne_iff, to_real_pi_div_two, to_real_zero],
exact div_ne_zero real.pi_ne_zero two_ne_zero
end
lemma neg_pi_div_two_ne_zero : ((-π / 2 : ℝ) : angle) ≠ 0 :=
begin
rw [←to_real_injective.ne_iff, to_real_neg_pi_div_two, to_real_zero],
exact div_ne_zero (neg_ne_zero.2 real.pi_ne_zero) two_ne_zero
end
lemma abs_to_real_coe_eq_self_iff {θ : ℝ} : |(θ : angle).to_real| = θ ↔ 0 ≤ θ ∧ θ ≤ π :=
⟨λ h, h ▸ ⟨abs_nonneg _, abs_to_real_le_pi _⟩, λ h,
(to_real_coe_eq_self_iff.2 ⟨(left.neg_neg_iff.2 real.pi_pos).trans_le h.1, h.2⟩).symm ▸
abs_eq_self.2 h.1⟩
lemma abs_to_real_neg_coe_eq_self_iff {θ : ℝ} : |(-θ : angle).to_real| = θ ↔ 0 ≤ θ ∧ θ ≤ π :=
begin
refine ⟨λ h, h ▸ ⟨abs_nonneg _, abs_to_real_le_pi _⟩, λ h, _⟩,
by_cases hnegpi : θ = π, { simp [hnegpi, real.pi_pos.le] },
rw [←coe_neg, to_real_coe_eq_self_iff.2 ⟨neg_lt_neg (lt_of_le_of_ne h.2 hnegpi),
(neg_nonpos.2 h.1).trans real.pi_pos.le⟩, abs_neg,
abs_eq_self.2 h.1]
end
lemma abs_to_real_eq_pi_div_two_iff {θ : angle} :
|θ.to_real| = π / 2 ↔ (θ = (π / 2 : ℝ) ∨ θ = (-π / 2 : ℝ)) :=
by rw [abs_eq (div_nonneg real.pi_pos.le two_pos.le), ←neg_div, to_real_eq_pi_div_two_iff,
to_real_eq_neg_pi_div_two_iff]
lemma nsmul_to_real_eq_mul {n : ℕ} (h : n ≠ 0) {θ : angle} :
(n • θ).to_real = n * θ.to_real ↔ θ.to_real ∈ set.Ioc (-π / n) (π / n) :=
begin
nth_rewrite 0 ←coe_to_real θ,
have h' : 0 < (n : ℝ), { exact_mod_cast nat.pos_of_ne_zero h },
rw [←coe_nsmul, nsmul_eq_mul, to_real_coe_eq_self_iff, set.mem_Ioc, div_lt_iff' h',
le_div_iff' h']
end
lemma two_nsmul_to_real_eq_two_mul {θ : angle} :
((2 : ℕ) • θ).to_real = 2 * θ.to_real ↔ θ.to_real ∈ set.Ioc (-π / 2) (π / 2) :=
by exact_mod_cast nsmul_to_real_eq_mul two_ne_zero
lemma two_zsmul_to_real_eq_two_mul {θ : angle} :
((2 : ℤ) • θ).to_real = 2 * θ.to_real ↔ θ.to_real ∈ set.Ioc (-π / 2) (π / 2) :=
by rw [two_zsmul, ←two_nsmul, two_nsmul_to_real_eq_two_mul]
lemma to_real_coe_eq_self_sub_two_mul_int_mul_pi_iff {θ : ℝ} {k : ℤ} :
(θ : angle).to_real = θ - 2 * k * π ↔ θ ∈ set.Ioc ((2 * k - 1 : ℝ) * π) ((2 * k + 1) * π) :=
begin
rw [←sub_zero (θ : angle), ←zsmul_zero k, ←coe_two_pi, ←coe_zsmul, ←coe_sub,
zsmul_eq_mul, ←mul_assoc, mul_comm (k : ℝ), to_real_coe_eq_self_iff, set.mem_Ioc],
exact ⟨λ h, ⟨by linarith, by linarith⟩, λ h, ⟨by linarith, by linarith⟩⟩
end
lemma to_real_coe_eq_self_sub_two_pi_iff {θ : ℝ} :
(θ : angle).to_real = θ - 2 * π ↔ θ ∈ set.Ioc π (3 * π) :=
by { convert @to_real_coe_eq_self_sub_two_mul_int_mul_pi_iff θ 1; norm_num }
lemma to_real_coe_eq_self_add_two_pi_iff {θ : ℝ} :
(θ : angle).to_real = θ + 2 * π ↔ θ ∈ set.Ioc (-3 * π) (-π) :=
by { convert @to_real_coe_eq_self_sub_two_mul_int_mul_pi_iff θ (-1); norm_num }
lemma two_nsmul_to_real_eq_two_mul_sub_two_pi {θ : angle} :
((2 : ℕ) • θ).to_real = 2 * θ.to_real - 2 * π ↔ π / 2 < θ.to_real :=
begin
nth_rewrite 0 ←coe_to_real θ,
rw [←coe_nsmul, two_nsmul, ←two_mul, to_real_coe_eq_self_sub_two_pi_iff, set.mem_Ioc],
exact ⟨λ h, by linarith,
λ h, ⟨(div_lt_iff' (zero_lt_two' ℝ)).1 h, by linarith [pi_pos, to_real_le_pi θ]⟩⟩
end
lemma two_zsmul_to_real_eq_two_mul_sub_two_pi {θ : angle} :
((2 : ℤ) • θ).to_real = 2 * θ.to_real - 2 * π ↔ π / 2 < θ.to_real :=
by rw [two_zsmul, ←two_nsmul, two_nsmul_to_real_eq_two_mul_sub_two_pi]
lemma two_nsmul_to_real_eq_two_mul_add_two_pi {θ : angle} :
((2 : ℕ) • θ).to_real = 2 * θ.to_real + 2 * π ↔ θ.to_real ≤ -π / 2 :=
begin
nth_rewrite 0 ←coe_to_real θ,
rw [←coe_nsmul, two_nsmul, ←two_mul, to_real_coe_eq_self_add_two_pi_iff, set.mem_Ioc],
refine ⟨λ h, by linarith,
λ h, ⟨by linarith [pi_pos, neg_pi_lt_to_real θ], (le_div_iff' (zero_lt_two' ℝ)).1 h⟩⟩
end
lemma two_zsmul_to_real_eq_two_mul_add_two_pi {θ : angle} :
((2 : ℤ) • θ).to_real = 2 * θ.to_real + 2 * π ↔ θ.to_real ≤ -π / 2 :=
by rw [two_zsmul, ←two_nsmul, two_nsmul_to_real_eq_two_mul_add_two_pi]
@[simp] lemma sin_to_real (θ : angle) : real.sin θ.to_real = sin θ :=
by conv_rhs { rw [← coe_to_real θ, sin_coe] }
@[simp] lemma cos_to_real (θ : angle) : real.cos θ.to_real = cos θ :=
by conv_rhs { rw [← coe_to_real θ, cos_coe] }
lemma cos_nonneg_iff_abs_to_real_le_pi_div_two {θ : angle} : 0 ≤ cos θ ↔ |θ.to_real| ≤ π / 2 :=
begin
nth_rewrite 0 ←coe_to_real θ,
rw [abs_le, cos_coe],
refine ⟨λ h, _, cos_nonneg_of_mem_Icc⟩,
by_contra hn,
rw [not_and_distrib, not_le, not_le] at hn,
refine (not_lt.2 h) _,
rcases hn with hn | hn,
{ rw ←real.cos_neg,
refine cos_neg_of_pi_div_two_lt_of_lt (by linarith) _,
linarith [neg_pi_lt_to_real θ] },
{ refine cos_neg_of_pi_div_two_lt_of_lt hn _,
linarith [to_real_le_pi θ] }
end
lemma cos_pos_iff_abs_to_real_lt_pi_div_two {θ : angle} : 0 < cos θ ↔ |θ.to_real| < π / 2 :=
begin
rw [lt_iff_le_and_ne, lt_iff_le_and_ne, cos_nonneg_iff_abs_to_real_le_pi_div_two,
←and_congr_right],
rintro -,
rw [ne.def, ne.def, not_iff_not, @eq_comm ℝ 0, abs_to_real_eq_pi_div_two_iff, cos_eq_zero_iff]
end
lemma cos_neg_iff_pi_div_two_lt_abs_to_real {θ : angle} : cos θ < 0 ↔ π / 2 < |θ.to_real| :=
by rw [←not_le, ←not_le, not_iff_not, cos_nonneg_iff_abs_to_real_le_pi_div_two]
lemma abs_cos_eq_abs_sin_of_two_nsmul_add_two_nsmul_eq_pi {θ ψ : angle}
(h : (2 : ℕ) • θ + (2 : ℕ) • ψ = π) : |cos θ| = |sin ψ| :=
begin
rw [←eq_sub_iff_add_eq, ←two_nsmul_coe_div_two, ←nsmul_sub, two_nsmul_eq_iff] at h,
rcases h with rfl | rfl;
simp [cos_pi_div_two_sub]
end
lemma abs_cos_eq_abs_sin_of_two_zsmul_add_two_zsmul_eq_pi {θ ψ : angle}
(h : (2 : ℤ) • θ + (2 : ℤ) • ψ = π) : |cos θ| = |sin ψ| :=
begin
simp_rw [two_zsmul, ←two_nsmul] at h,
exact abs_cos_eq_abs_sin_of_two_nsmul_add_two_nsmul_eq_pi h
end
/-- The tangent of a `real.angle`. -/
def tan (θ : angle) : ℝ := sin θ / cos θ
lemma tan_eq_sin_div_cos (θ : angle) : tan θ = sin θ / cos θ := rfl
@[simp] lemma tan_coe (x : ℝ) : tan (x : angle) = real.tan x :=
by rw [tan, sin_coe, cos_coe, real.tan_eq_sin_div_cos]
@[simp] lemma tan_zero : tan (0 : angle) = 0 :=
by rw [←coe_zero, tan_coe, real.tan_zero]
@[simp] lemma tan_coe_pi : tan (π : angle) = 0 :=
by rw [tan_eq_sin_div_cos, sin_coe_pi, zero_div]
lemma tan_periodic : function.periodic tan (π : angle) :=
begin
intro θ,
induction θ using real.angle.induction_on,
rw [←coe_add, tan_coe, tan_coe],
exact real.tan_periodic θ
end
@[simp] lemma tan_add_pi (θ : angle) : tan (θ + π) = tan θ :=
tan_periodic θ
@[simp] lemma tan_sub_pi (θ : angle) : tan (θ - π) = tan θ :=
tan_periodic.sub_eq θ
@[simp] lemma tan_to_real (θ : angle) : real.tan θ.to_real = tan θ :=
by conv_rhs { rw [←coe_to_real θ, tan_coe] }
lemma tan_eq_of_two_nsmul_eq {θ ψ : angle} (h : (2 : ℕ) • θ = (2 : ℕ) • ψ) : tan θ = tan ψ :=
begin
rw two_nsmul_eq_iff at h,
rcases h with rfl | rfl,
{ refl },
{ exact tan_add_pi _ }
end
lemma tan_eq_of_two_zsmul_eq {θ ψ : angle} (h : (2 : ℤ) • θ = (2 : ℤ) • ψ) : tan θ = tan ψ :=
begin
simp_rw [two_zsmul, ←two_nsmul] at h,
exact tan_eq_of_two_nsmul_eq h
end
lemma tan_eq_inv_of_two_nsmul_add_two_nsmul_eq_pi {θ ψ : angle}
(h : (2 : ℕ) • θ + (2 : ℕ) • ψ = π) : tan ψ = (tan θ)⁻¹ :=
begin
induction θ using real.angle.induction_on,
induction ψ using real.angle.induction_on,
rw [←smul_add, ←coe_add, ←coe_nsmul, two_nsmul, ←two_mul, angle_eq_iff_two_pi_dvd_sub] at h,
rcases h with ⟨k, h⟩,
rw [sub_eq_iff_eq_add, ←mul_inv_cancel_left₀ two_ne_zero π, mul_assoc, ←mul_add,
mul_right_inj' (two_ne_zero' ℝ), ←eq_sub_iff_add_eq',
mul_inv_cancel_left₀ two_ne_zero π, inv_mul_eq_div, mul_comm] at h,
rw [tan_coe, tan_coe, ←tan_pi_div_two_sub, h, add_sub_assoc, add_comm],
exact real.tan_periodic.int_mul _ _
end
lemma tan_eq_inv_of_two_zsmul_add_two_zsmul_eq_pi {θ ψ : angle}
(h : (2 : ℤ) • θ + (2 : ℤ) • ψ = π) : tan ψ = (tan θ)⁻¹ :=
begin
simp_rw [two_zsmul, ←two_nsmul] at h,
exact tan_eq_inv_of_two_nsmul_add_two_nsmul_eq_pi h
end
/-- The sign of a `real.angle` is `0` if the angle is `0` or `π`, `1` if the angle is strictly
between `0` and `π` and `-1` is the angle is strictly between `-π` and `0`. It is defined as the
sign of the sine of the angle. -/
def sign (θ : angle) : sign_type := sign (sin θ)
@[simp]
@[simp] lemma sign_coe_pi : (π : angle).sign = 0 :=
by rw [sign, sin_coe_pi, _root_.sign_zero]
@[simp] lemma sign_neg (θ : angle) : (-θ).sign = - θ.sign :=
by simp_rw [sign, sin_neg, left.sign_neg]
lemma sign_antiperiodic : function.antiperiodic sign (π : angle) :=
λ θ, by rw [sign, sign, sin_add_pi, left.sign_neg]
@[simp] lemma sign_add_pi (θ : angle) : (θ + π).sign = -θ.sign :=
sign_antiperiodic θ
@[simp] lemma sign_pi_add (θ : angle) : ((π : angle) + θ).sign = -θ.sign :=
by rw [add_comm, sign_add_pi]
@[simp] lemma sign_sub_pi (θ : angle) : (θ - π).sign = -θ.sign :=
sign_antiperiodic.sub_eq θ
@[simp] lemma sign_pi_sub (θ : angle) : ((π : angle) - θ).sign = θ.sign :=
by simp [sign_antiperiodic.sub_eq']
lemma sign_eq_zero_iff {θ : angle} : θ.sign = 0 ↔ θ = 0 ∨ θ = π :=
by rw [sign, sign_eq_zero_iff, sin_eq_zero_iff]
lemma sign_ne_zero_iff {θ : angle} : θ.sign ≠ 0 ↔ θ ≠ 0 ∧ θ ≠ π :=
by rw [←not_or_distrib, ←sign_eq_zero_iff]
lemma to_real_neg_iff_sign_neg {θ : angle} : θ.to_real < 0 ↔ θ.sign = -1 :=
begin
rw [sign, ←sin_to_real, sign_eq_neg_one_iff],
rcases lt_trichotomy θ.to_real 0 with (h|h|h),
{ exact ⟨λ _, real.sin_neg_of_neg_of_neg_pi_lt h (neg_pi_lt_to_real θ), λ _, h⟩ },
{ simp [h] },
{ exact ⟨λ hn, false.elim (h.asymm hn),
λ hn, false.elim (hn.not_le (sin_nonneg_of_nonneg_of_le_pi h.le (to_real_le_pi θ)))⟩ }
end
lemma to_real_nonneg_iff_sign_nonneg {θ : angle} : 0 ≤ θ.to_real ↔ 0 ≤ θ.sign :=
begin
rcases lt_trichotomy θ.to_real 0 with (h|h|h),
{ refine ⟨λ hn, false.elim (h.not_le hn), λ hn, _⟩,
rw [to_real_neg_iff_sign_neg.1 h] at hn,
exact false.elim (hn.not_lt dec_trivial) },
{ simp [h, sign, ←sin_to_real] },
{ refine ⟨λ _, _, λ _, h.le⟩,
rw [sign, ←sin_to_real, sign_nonneg_iff],
exact sin_nonneg_of_nonneg_of_le_pi h.le (to_real_le_pi θ) }
end
@[simp] lemma sign_to_real {θ : angle} (h : θ ≠ π) : _root_.sign θ.to_real = θ.sign :=
begin
rcases lt_trichotomy θ.to_real 0 with (ht|ht|ht),
{ simp [ht, to_real_neg_iff_sign_neg.1 ht] },
{ simp [sign, ht, ←sin_to_real] },
{ rw [sign, ←sin_to_real, sign_pos ht,
sign_pos (sin_pos_of_pos_of_lt_pi ht
((to_real_le_pi θ).lt_of_ne (to_real_eq_pi_iff.not.2 h)))] }
end
lemma coe_abs_to_real_of_sign_nonneg {θ : angle} (h : 0 ≤ θ.sign) : ↑|θ.to_real| = θ :=
by rw [abs_eq_self.2 (to_real_nonneg_iff_sign_nonneg.2 h), coe_to_real]
lemma neg_coe_abs_to_real_of_sign_nonpos {θ : angle} (h : θ.sign ≤ 0) : -↑|θ.to_real| = θ :=
begin
rw sign_type.nonpos_iff at h,
rcases h with h|h,
{ rw [abs_of_neg (to_real_neg_iff_sign_neg.2 h), coe_neg, neg_neg, coe_to_real] },
{ rw sign_eq_zero_iff at h,
rcases h with rfl|rfl;
simp [abs_of_pos real.pi_pos] }
end
lemma eq_iff_sign_eq_and_abs_to_real_eq {θ ψ : angle} :
θ = ψ ↔ θ.sign = ψ.sign ∧ |θ.to_real| = |ψ.to_real| :=
begin
refine ⟨_, λ h, _⟩, { rintro rfl, exact ⟨rfl, rfl⟩ },
rcases h with ⟨hs, hr⟩,
rw abs_eq_abs at hr,
rcases hr with (hr|hr),
{ exact to_real_injective hr },
{ by_cases h : θ = π,
{ rw [h, to_real_pi, ← neg_eq_iff_eq_neg] at hr,
exact false.elim ((neg_pi_lt_to_real ψ).ne hr) },
{ by_cases h' : ψ = π,
{ rw [h', to_real_pi] at hr,
exact false.elim ((neg_pi_lt_to_real θ).ne hr.symm) },
{ rw [←sign_to_real h, ←sign_to_real h', hr, left.sign_neg, sign_type.neg_eq_self_iff,
_root_.sign_eq_zero_iff, to_real_eq_zero_iff] at hs,
rw [hs, to_real_zero, neg_zero, to_real_eq_zero_iff] at hr,
rw [hr, hs] } } }
end
lemma eq_iff_abs_to_real_eq_of_sign_eq {θ ψ : angle} (h : θ.sign = ψ.sign) :
θ = ψ ↔ |θ.to_real| = |ψ.to_real| :=
by simpa [h] using @eq_iff_sign_eq_and_abs_to_real_eq θ ψ
@[simp] lemma sign_coe_pi_div_two : (↑(π / 2) : angle).sign = 1 :=
by rw [sign, sin_coe, sin_pi_div_two, sign_one]
@[simp] lemma sign_coe_neg_pi_div_two : (↑(-π / 2) : angle).sign = -1 :=
by rw [sign, sin_coe, neg_div, real.sin_neg, sin_pi_div_two, left.sign_neg, sign_one]
lemma sign_coe_nonneg_of_nonneg_of_le_pi {θ : ℝ} (h0 : 0 ≤ θ) (hpi : θ ≤ π) :
0 ≤ (θ : angle).sign :=
begin
rw [sign, sign_nonneg_iff],
exact sin_nonneg_of_nonneg_of_le_pi h0 hpi
end
lemma sign_neg_coe_nonpos_of_nonneg_of_le_pi {θ : ℝ} (h0 : 0 ≤ θ) (hpi : θ ≤ π) :
(-θ : angle).sign ≤ 0 :=
begin
rw [sign, sign_nonpos_iff, sin_neg, left.neg_nonpos_iff],
exact sin_nonneg_of_nonneg_of_le_pi h0 hpi
end
lemma sign_two_nsmul_eq_sign_iff {θ : angle} :
((2 : ℕ) • θ).sign = θ.sign ↔ (θ = π ∨ |θ.to_real| < π / 2) :=
begin
by_cases hpi : θ = π, { simp [hpi] },
rw or_iff_right hpi,
refine ⟨λ h, _, λ h, _⟩,
{ by_contra hle,
rw [not_lt, le_abs, le_neg] at hle,
have hpi' : θ.to_real ≠ π, { simpa using hpi },
rcases hle with hle | hle; rcases hle.eq_or_lt with heq | hlt,
{ rw [←coe_to_real θ, ←heq] at h, simpa using h },
{ rw [←sign_to_real hpi, sign_pos (pi_div_two_pos.trans hlt),
←sign_to_real, two_nsmul_to_real_eq_two_mul_sub_two_pi.2 hlt, _root_.sign_neg] at h,
{ simpa using h },
{ rw ←mul_sub,
exact mul_neg_of_pos_of_neg two_pos (sub_neg.2 ((to_real_le_pi _).lt_of_ne hpi')) },
{ intro he, simpa [he] using h } },
{ rw [←coe_to_real θ, heq] at h, simpa using h },
{ rw [←sign_to_real hpi,
_root_.sign_neg (hlt.trans (left.neg_neg_iff.2 pi_div_two_pos)),
←sign_to_real] at h, swap, { intro he, simpa [he] using h },
rw ←neg_div at hlt,
rw [two_nsmul_to_real_eq_two_mul_add_two_pi.2 hlt.le, sign_pos] at h,
{ simpa using h },
{ linarith [neg_pi_lt_to_real θ] } } },
{ have hpi' : (2 : ℕ) • θ ≠ π,
{ rw [ne.def, two_nsmul_eq_pi_iff, not_or_distrib],
split,
{ rintro rfl, simpa [pi_pos, div_pos, abs_of_pos] using h },
{ rintro rfl,
rw [to_real_neg_pi_div_two] at h,
simpa [pi_pos, div_pos, neg_div, abs_of_pos] using h } },
rw [abs_lt, ←neg_div] at h,
rw [←sign_to_real hpi, ←sign_to_real hpi', two_nsmul_to_real_eq_two_mul.2 ⟨h.1, h.2.le⟩,
sign_mul, sign_pos (zero_lt_two' ℝ), one_mul] }
end
lemma sign_two_zsmul_eq_sign_iff {θ : angle} :
((2 : ℤ) • θ).sign = θ.sign ↔ (θ = π ∨ |θ.to_real| < π / 2) :=
by rw [two_zsmul, ←two_nsmul, sign_two_nsmul_eq_sign_iff]
lemma continuous_at_sign {θ : angle} (h0 : θ ≠ 0) (hpi : θ ≠ π) : continuous_at sign θ :=
(continuous_at_sign_of_ne_zero (sin_ne_zero_iff.2 ⟨h0, hpi⟩)).comp continuous_sin.continuous_at
lemma _root_.continuous_on.angle_sign_comp {α : Type*} [topological_space α] {f : α → angle}
{s : set α} (hf : continuous_on f s) (hs : ∀ z ∈ s, f z ≠ 0 ∧ f z ≠ π) :
continuous_on (sign ∘ f) s :=
begin
refine (continuous_at.continuous_on (λ θ hθ, _)).comp hf (set.maps_to_image f s),
obtain ⟨z, hz, rfl⟩ := hθ,
exact continuous_at_sign (hs _ hz).1 (hs _ hz).2
end
/-- Suppose a function to angles is continuous on a connected set and never takes the values `0`
or `π` on that set. Then the values of the function on that set all have the same sign. -/
lemma sign_eq_of_continuous_on {α : Type*} [topological_space α] {f : α → angle} {s : set α}
{x y : α} (hc : is_connected s) (hf : continuous_on f s) (hs : ∀ z ∈ s, f z ≠ 0 ∧ f z ≠ π)
(hx : x ∈ s) (hy : y ∈ s) : (f y).sign = (f x).sign :=
(hc.image _ (hf.angle_sign_comp hs)).is_preconnected.subsingleton
(set.mem_image_of_mem _ hy) (set.mem_image_of_mem _ hx)
end angle
end real
|
The interval $[a, b]$ is equal to the closed ball of radius $(b - a)/2$ centered at $(a + b)/2$.
|
/**
* Copyright (c) 2012, Akamai Technologies
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* Neither the name of the Akamai Technologies nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <list>
#include <boost/algorithm/string.hpp>
#include <boost/make_shared.hpp>
#include <boost/lexical_cast.hpp>
// #include <antlr3defs.h>
// #include "IQLLexer.h"
// #include "IQLParser.h"
// #include "IQLTypeCheck.h"
#include "RuntimePlan.hh"
#include "RuntimeOperator.hh"
#include "Merger.hh"
#include "QueueImport.hh"
#include "ConstantScan.hh"
#include "AsyncRecordParser.hh"
#include "GzipOperator.hh"
#include "TcpOperator.hh"
#include "HttpOperator.hh"
#include "FileWriteOperator.hh"
#include "QueryStringOperator.hh"
#include "GraphBuilder.hh"
#if defined(TRECUL_HAS_HADOOP)
#include "HdfsOperator.hh"
#endif
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/filter/zlib.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/serialization/export.hpp>
// It appears that one does not need BOOST_CLASS_EXPORT for
// non polymorphic classes.
BOOST_CLASS_EXPORT(ImporterSpec);
BOOST_CLASS_EXPORT(ConsumeTerminatedStringSpec);
BOOST_CLASS_EXPORT(ImportDecimalInt32Spec);
BOOST_CLASS_EXPORT(ImportFixedLengthStringSpec);
BOOST_CLASS_EXPORT(FileCreationPolicy);
BOOST_CLASS_EXPORT(MultiFileCreationPolicy);
BOOST_CLASS_EXPORT(WritableFileFactory);
BOOST_CLASS_EXPORT(LocalWritableFileFactory);
BOOST_CLASS_EXPORT(AssignedOperatorType);
BOOST_CLASS_EXPORT(ConstrainedOperatorType);
BOOST_CLASS_EXPORT(RuntimeOperatorType);
BOOST_CLASS_EXPORT(RuntimeDevNullOperatorType);
BOOST_CLASS_EXPORT(RuntimeGenerateOperatorType);
BOOST_CLASS_EXPORT(RuntimePrintOperatorType);
BOOST_CLASS_EXPORT(RuntimeHashJoinOperatorType);
BOOST_CLASS_EXPORT(RuntimeCrossJoinOperatorType);
BOOST_CLASS_EXPORT(RuntimeSortMergeJoinOperatorType);
BOOST_CLASS_EXPORT(RuntimeHashGroupByOperatorType);
BOOST_CLASS_EXPORT(RuntimeSortGroupByOperatorType);
BOOST_CLASS_EXPORT(RuntimeSortRunningTotalOperatorType);
BOOST_CLASS_EXPORT(RuntimeHashPartitionerOperatorType);
BOOST_CLASS_EXPORT(RuntimeBroadcastPartitionerOperatorType);
BOOST_CLASS_EXPORT(RuntimeNondeterministicCollectorOperatorType);
BOOST_CLASS_EXPORT(RuntimeCopyOperatorType);
BOOST_CLASS_EXPORT(RuntimeFilterOperatorType);
BOOST_CLASS_EXPORT(RuntimeSortMergeOperatorType);
BOOST_CLASS_EXPORT(RuntimeSortOperatorType);
BOOST_CLASS_EXPORT(RuntimeSwitchOperatorType);
BOOST_CLASS_EXPORT(RuntimeHdfsWriteOperatorType);
BOOST_CLASS_EXPORT(RuntimeWriteOperatorType);
BOOST_CLASS_EXPORT(RuntimeUnionAllOperatorType);
BOOST_CLASS_EXPORT(NativeInputQueueOperatorType);
BOOST_CLASS_EXPORT(TcpReadOperatorType);
BOOST_CLASS_EXPORT(TcpWriteOperatorType);
BOOST_CLASS_EXPORT(HttpReadOperatorType);
BOOST_CLASS_EXPORT(QueryStringOperatorType);
BOOST_CLASS_EXPORT(GenericAsyncParserOperatorType);
BOOST_CLASS_EXPORT(GenericAsyncReadOperatorType<ExplicitChunkStrategy>);
BOOST_CLASS_EXPORT(GenericAsyncReadOperatorType<SerialChunkStrategy>);
BOOST_CLASS_EXPORT(InternalFileParserOperatorType<AsyncDoubleBufferStream<AsyncFileTraits<stdio_file_traits> > >);
BOOST_CLASS_EXPORT(InternalFileWriteOperatorType);
BOOST_CLASS_EXPORT(GenericParserOperatorType<ExplicitChunkStrategy>);
BOOST_CLASS_EXPORT(GenericParserOperatorType<SerialChunkStrategy>);
BOOST_CLASS_EXPORT(RuntimeConstantScanOperatorType);
#if defined(TRECUL_HAS_HADOOP)
BOOST_CLASS_EXPORT(HdfsWritableFileFactory);
BOOST_CLASS_EXPORT(RuntimeHadoopEmitOperatorType);
#endif
/*
base64.cpp and base64.h
Copyright (C) 2004-2008 René Nyffenegger
This source code is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this source code must not be misrepresented; you must not
claim that you wrote the original source code. If you use this source code
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original source code.
3. This notice may not be removed or altered from any source distribution.
René Nyffenegger [email protected]
*/
/**
* Commented out header file
*/
//#include "base64.h"
//#include <iostream>
static const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i <4) ; i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for(j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while((i++ < 3))
ret += '=';
}
return ret;
}
std::string base64_decode(std::string const& encoded_string) {
int in_len = encoded_string.size();
int i = 0;
int j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::string ret;
while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_]; in_++;
if (i ==4) {
for (i = 0; i <4; i++)
char_array_4[i] = base64_chars.find(char_array_4[i]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++)
ret += char_array_3[i];
i = 0;
}
}
if (i) {
for (j = i; j <4; j++)
char_array_4[j] = 0;
for (j = 0; j <4; j++)
char_array_4[j] = base64_chars.find(char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
}
return ret;
}
std::string PlanGenerator::serialize(boost::shared_ptr<RuntimeOperatorPlan> plan)
{
std::ostringstream s(std::ios_base::binary | std::ios_base::out);
boost::archive::binary_oarchive oa(s);
RuntimeOperatorPlan * tmp = plan.get();
oa << BOOST_SERIALIZATION_NVP(tmp);
return s.str();
}
boost::shared_ptr<RuntimeOperatorPlan> PlanGenerator::deserialize(const char * buf, std::size_t sz)
{
boost::iostreams::stream<boost::iostreams::array_source> archiveStream(boost::iostreams::array_source(buf,sz));
boost::archive::binary_iarchive ia(archiveStream);
RuntimeOperatorPlan * tmp=NULL;
ia >> BOOST_SERIALIZATION_NVP(tmp);
return boost::shared_ptr<RuntimeOperatorPlan>(tmp);
}
std::string PlanGenerator::serialize64(boost::shared_ptr<RuntimeOperatorPlan> plan)
{
namespace io = boost::iostreams;
std::string compressedBuf;
{
// put ostream in a scope so its d'tor
// is executed; that flushes everything
// through the zlib filter.
io::filtering_ostream out;
out.push(io::zlib_compressor());
out.push(io::back_inserter(compressedBuf));
boost::archive::binary_oarchive oa(out);
RuntimeOperatorPlan * tmp = plan.get();
oa << BOOST_SERIALIZATION_NVP(tmp);
out.flush();
}
return base64_encode((const unsigned char *) &compressedBuf[0],
compressedBuf.size());
}
boost::shared_ptr<RuntimeOperatorPlan> PlanGenerator::deserialize64(const char * buf,
std::size_t sz)
{
namespace io = boost::iostreams;
std::string encoded(buf, sz);
std::string decoded = base64_decode(encoded);
io::filtering_istream in;
in.push(io::zlib_decompressor());
in.push(boost::iostreams::array_source(&decoded[0],decoded.size()));
boost::archive::binary_iarchive ia(in);
RuntimeOperatorPlan * tmp=NULL;
ia >> BOOST_SERIALIZATION_NVP(tmp);
return boost::shared_ptr<RuntimeOperatorPlan>(tmp);
}
DataflowGraphBuilder::DataflowGraphBuilder(PlanCheckContext & ctxt)
:
mPlan(new LogicalPlan(ctxt)),
mCurrentOp(NULL)
{
}
DataflowGraphBuilder::~DataflowGraphBuilder()
{
delete mPlan;
}
void DataflowGraphBuilder::buildGraph(const std::string& str)
{
IQLGraphBuilder::buildGraph(str, false);
}
void DataflowGraphBuilder::buildGraphFromFile(const std::string& str)
{
if (str == "-") {
std::stringstream ss;
std::copy(std::istreambuf_iterator<char>(std::cin),
std::istreambuf_iterator<char>(),
std::ostreambuf_iterator<char>(ss));
std::string tmp = ss.str();
IQLGraphBuilder::buildGraph(tmp, false);
} else {
IQLGraphBuilder::buildGraph(str, true);
}
}
void DataflowGraphBuilder::nodeStart(const char * type,
const char * name)
{
LogicalOperatorFactory & f(LogicalOperatorFactory::get());
// Case sensitive or insensitive?
if (mOps.find(name) != mOps.end()) {
throw std::runtime_error((boost::format("Operator with name %1% already defined") % name).str());
}
if (boost::algorithm::iequals("constant_sink", type)) {
mCurrentOp = new LogicalConstantSink();
} else if (boost::algorithm::iequals("copy", type)) {
mCurrentOp = new CopyOp();
} else if (boost::algorithm::iequals("emit", type)) {
#if defined(TRECUL_HAS_HADOOP)
mCurrentOp = new LogicalEmit();
#endif
} else if (boost::algorithm::iequals("filter", type)) {
mCurrentOp = new LogicalFilter();
} else if (boost::algorithm::iequals("generate", type)) {
mCurrentOp = new LogicalGenerate();
} else if (boost::algorithm::iequals("group_by", type)) {
mCurrentOp = new LogicalGroupBy(LogicalGroupBy::HYBRID);
} else if (boost::algorithm::iequals("gunzip", type)) {
mCurrentOp = new LogicalGunzip();
} else if (boost::algorithm::iequals("hash_group_by", type)) {
mCurrentOp = new LogicalGroupBy(LogicalGroupBy::HASH);
} else if (boost::algorithm::iequals("hash_join", type)) {
mCurrentOp = new HashJoin(HashJoin::INNER);
} else if (boost::algorithm::iequals("hash_full_outer_join", type)) {
mCurrentOp = new HashJoin(HashJoin::FULL_OUTER);
} else if (boost::algorithm::iequals("hash_left_outer_join", type)) {
mCurrentOp = new HashJoin(HashJoin::LEFT_OUTER);
} else if (boost::algorithm::iequals("hash_right_anti_semi_join", type)) {
mCurrentOp = new HashJoin(HashJoin::RIGHT_ANTI_SEMI);
} else if (boost::algorithm::iequals("hash_right_outer_join", type)) {
mCurrentOp = new HashJoin(HashJoin::RIGHT_OUTER);
} else if (boost::algorithm::iequals("hash_right_semi_join", type)) {
mCurrentOp = new HashJoin(HashJoin::RIGHT_SEMI);
} else if (boost::algorithm::iequals("http_read", type)) {
mCurrentOp = new LogicalHttpRead();
} else if (boost::algorithm::iequals("map", type)) {
mCurrentOp = new LogicalInputQueue();
} else if (boost::algorithm::iequals("merge_join", type)) {
mCurrentOp = new SortMergeJoin(SortMergeJoin::INNER);
} else if (boost::algorithm::iequals("merge_full_outer_join", type)) {
mCurrentOp = new SortMergeJoin(SortMergeJoin::FULL_OUTER);
} else if (boost::algorithm::iequals("merge_left_outer_join", type)) {
mCurrentOp = new SortMergeJoin(SortMergeJoin::LEFT_OUTER);
} else if (boost::algorithm::iequals("merge_right_anti_semi_join", type)) {
mCurrentOp = new SortMergeJoin(SortMergeJoin::RIGHT_ANTI_SEMI);
} else if (boost::algorithm::iequals("merge_right_outer_join", type)) {
mCurrentOp = new SortMergeJoin(SortMergeJoin::RIGHT_OUTER);
} else if (boost::algorithm::iequals("merge_right_semi_join", type)) {
mCurrentOp = new SortMergeJoin(SortMergeJoin::RIGHT_SEMI);
} else if (boost::algorithm::iequals("read", type)) {
mCurrentOp = new LogicalFileRead();
} else if (boost::algorithm::iequals("read_block", type)) {
mCurrentOp = new LogicalBlockRead();
} else if (boost::algorithm::iequals("reduce", type)) {
mCurrentOp = new LogicalInputQueue();
} else if (boost::algorithm::iequals("parse", type)) {
mCurrentOp = new LogicalAsyncParser();
} else if (boost::algorithm::iequals("parse_query_string", type)) {
mCurrentOp = new LogicalQueryString();
} else if (boost::algorithm::iequals("print", type)) {
mCurrentOp = new LogicalPrint();
} else if (boost::algorithm::iequals("sort", type)) {
mCurrentOp = new LogicalSort();
} else if (boost::algorithm::iequals("sort_group_by", type)) {
mCurrentOp = new LogicalGroupBy(LogicalGroupBy::SORT);
} else if (boost::algorithm::iequals("sort_merge", type)) {
mCurrentOp = new LogicalSortMerge();
} else if (boost::algorithm::iequals("switch", type)) {
mCurrentOp = new LogicalSwitch();
} else if (boost::algorithm::iequals("tcp_read", type)) {
mCurrentOp = new LogicalTcpRead();
} else if (boost::algorithm::iequals("tcp_write", type)) {
mCurrentOp = new LogicalTcpWrite();
} else if (boost::algorithm::iequals("union_all", type)) {
mCurrentOp = new LogicalUnionAll();
} else if (boost::algorithm::iequals("unpivot", type)) {
mCurrentOp = new LogicalUnpivot();
} else if (boost::algorithm::iequals("write", type)) {
mCurrentOp = new LogicalFileWrite();
} else if (boost::algorithm::iequals("devNull", type)) {
mCurrentOp = new LogicalDevNull();
} else {
mCurrentOp = f.create(type);
}
mOps[name] = mCurrentOp;
mCurrentOp->setName(name);
mPlan->addOperator(mCurrentOp);
}
void DataflowGraphBuilder::nodeComplete()
{
mCurrentOp = NULL;
}
void DataflowGraphBuilder::nodeAddIntegerParam(const char * name,
const char * val)
{
mCurrentOp->addParam(name, LogicalOperator::param_type(boost::lexical_cast<int32_t>(val)));
}
void DataflowGraphBuilder::nodeAddStringParam(const char * name,
const char * val)
{
// TODO: Properly unquotify.
std::string strVal(val);
strVal = strVal.substr(1, strVal.size()-2);
mCurrentOp->addParam(name, LogicalOperator::param_type(strVal));
}
void DataflowGraphBuilder::edgeBuild(const char * from,
const char * to)
{
if (mOps.find(from) == mOps.end()) {
throw std::runtime_error((boost::format("Operator %1% not defined") % from).str());
}
if (mOps.find(to) == mOps.end()) {
throw std::runtime_error((boost::format("Operator %1% not defined") % to).str());
}
mPlan->addEdge(mOps.find(from)->second,
mOps.find(to)->second);
}
boost::shared_ptr<RuntimeOperatorPlan> DataflowGraphBuilder::create(int32_t numPartitions)
{
mPlan->check();
// If everything is OK we can apply rules to create
// operator types.
RuntimePlanBuilder bld;
for(std::vector<LogicalPlan::vertex_descriptor>::iterator it = mPlan->begin_operators();
it != mPlan->end_operators();
++it) {
(*it)->create(bld);
}
boost::shared_ptr<RuntimeOperatorPlan> plan =
boost::make_shared<RuntimeOperatorPlan>(numPartitions, true);
// Stitch together the generated operators into
// the final graph. Add all operator types and
// then for each logical edge, connect the corresponding
// operator type ports.
for(RuntimePlanBuilder::optype_iterator it = bld.begin_operator_types();
it != bld.end_operator_types();
++it) {
plan->addOperatorType(*it);
}
for(LogicalPlan::edge_iterator it = mPlan->begin_edges();
it != mPlan->end_edges();
++it) {
std::pair<RuntimeOperatorType*, std::size_t> s =
bld.mapOutputPort((*it)->source(), (*it)->getSourcePort());
std::pair<RuntimeOperatorType*, std::size_t> t =
bld.mapInputPort((*it)->target(), (*it)->getTargetPort());
plan->connectStraight(s.first, s.second, t.first, t.second, true, true);
}
for(RuntimePlanBuilder::internal_edge_iterator it = bld.begin_internal_edges();
it != bld.end_internal_edges();
++it) {
plan->connectStraight(it->Source.OpType, it->Source.Index,
it->Target.OpType, it->Target.Index,
it->Buffered, true);
}
return plan;
}
|
# MIT License
#
# Copyright (C) IBM Corporation 2018
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
This module implements abstract base classes defining to properties for all classifiers.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import abc
import sys
import numpy as np
from art.utils import check_and_transform_label_format
# Ensure compatibility with Python 2 and 3 when using ABCMeta
if sys.version_info >= (3, 4):
ABC = abc.ABC
else:
ABC = abc.ABCMeta(str('ABC'), (), {})
class Classifier(ABC):
"""
Base class defining the minimum classifier functionality and is required for all classifiers. A classifier of this
type can be combined with black-box attacks.
"""
def __init__(self, clip_values=None, defences=None, preprocessing=None, **kwargs):
"""
Initialize a `Classifier` object.
:param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and
maximum values allowed for features. If floats are provided, these will be used as the range of all
features. If arrays are provided, each value will be considered the bound for a feature, thus
the shape of clip values needs to match the total number of features.
:type clip_values: `tuple`
:param defences: Defence(s) to be activated with the classifier.
:type defences: :class:`.Preprocessor` or `list(Preprocessor)` instances
:param preprocessing: Tuple of the form `(subtractor, divider)` of floats or `np.ndarray` of values to be
used for data preprocessing. The first value will be subtracted from the input. The input will then
be divided by the second one.
:type preprocessing: `tuple`
"""
from art.defences.preprocessor import Preprocessor
self._clip_values = clip_values
if clip_values is not None:
if len(clip_values) != 2:
raise ValueError('`clip_values` should be a tuple of 2 floats or arrays containing the allowed'
'data range.')
if np.array(clip_values[0] >= clip_values[1]).any():
raise ValueError('Invalid `clip_values`: min >= max.')
if isinstance(defences, Preprocessor):
self.defences = [defences]
else:
self.defences = defences
if preprocessing is not None and len(preprocessing) != 2:
raise ValueError('`preprocessing` should be a tuple of 2 floats with the values to subtract and divide'
'the model inputs.')
self.preprocessing = preprocessing
super().__init__(**kwargs)
@abc.abstractmethod
def predict(self, x, **kwargs): # lgtm [py/inheritance/incorrect-overridden-signature]
"""
Perform prediction of the classifier for input `x`.
:param x: Features in array of shape (nb_samples, nb_features) or (nb_samples, nb_pixels_1, nb_pixels_2,
nb_channels) or (nb_samples, nb_channels, nb_pixels_1, nb_pixels_2)
:type x: `np.ndarray`
:return: Array of predictions of shape `(nb_inputs, nb_classes)`.
:rtype: `np.ndarray`
"""
raise NotImplementedError
@abc.abstractmethod
def fit(self, x, y, **kwargs): # lgtm [py/inheritance/incorrect-overridden-signature]
"""
Fit the classifier using the training data `(x, y)`.
:param x: Features in array of shape (nb_samples, nb_features) or (nb_samples, nb_pixels_1, nb_pixels_2,
nb_channels) or (nb_samples, nb_channels, nb_pixels_1, nb_pixels_2)
:type x: `np.ndarray`
:param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape
(nb_samples,).
:type y: `np.ndarray`
:param kwargs: Dictionary of framework-specific arguments.
:type kwargs: `dict`
:return: `None`
"""
raise NotImplementedError
@property
def clip_values(self):
"""
:return: Tuple of form `(min, max)` containing the minimum and maximum values allowed for the input features.
:rtype: `tuple`
"""
return self._clip_values
@property
def input_shape(self):
"""
Return the shape of one input.
:return: Shape of one input for the classifier.
:rtype: `tuple`
"""
return self._input_shape
@abc.abstractmethod
def nb_classes(self):
"""
Return the number of output classes.
:return: Number of classes in the data.
:rtype: `int`
"""
raise NotImplementedError
@abc.abstractmethod
def save(self, filename, path=None):
"""
Save a model to file specific to the backend framework.
:param filename: Name of the file where to save the model.
:type filename: `str`
:param path: Path of the directory where to save the model. If no path is specified, the model will be stored in
the default data location of ART at `DATA_PATH`.
:type path: `str`
:return: None
"""
raise NotImplementedError
def _apply_preprocessing(self, x, y, fit):
"""
Apply all defences and preprocessing operations on the inputs `(x, y)`. This function has to be applied to all
raw inputs (x, y) provided to the classifier.
:param x: Features, where first dimension is the number of samples.
:type x: `np.ndarray`
:param y: Target values (class labels), where first dimension is the number of samples.
:type y: `np.ndarray` or `None`
:param fit: `True` if the defences are applied during training.
:return: Value of the data after applying the defences.
:rtype: `np.ndarray`
"""
y = check_and_transform_label_format(y, self.nb_classes())
x_preprocessed, y_preprocessed = self._apply_preprocessing_defences(x, y, fit=fit)
x_preprocessed = self._apply_preprocessing_standardisation(x_preprocessed)
return x_preprocessed, y_preprocessed
def _apply_preprocessing_defences(self, x, y, fit=False):
"""
Apply all defences of the classifier on the raw inputs `(x, y)`. This function is intended to only be called
from function `_apply_defences_and_preprocessing`.
:param x: Features, where first dimension is the number of samples.
:type x: `np.ndarray`
:param y: Target values (class labels), where first dimension is the number of samples.
:type y: `np.ndarray`
:param fit: `True` if the function is call before fit/training and `False` if the function is called before a
predict operation
:return: Arrays for `x` and `y` after applying the defences.
:rtype: `np.ndarray`
"""
if self.defences is not None:
for defence in self.defences:
if fit:
if defence.apply_fit:
x, y = defence(x, y)
else:
if defence.apply_predict:
x, y = defence(x, y)
return x, y
def _apply_preprocessing_standardisation(self, x):
"""
Apply standardisation to input data `x`.
:param x: Input data, where first dimension is the number of samples.
:type x: `np.ndarray`
:return: Array for `x` with the standardized data.
:rtype: `np.ndarray`
"""
if self.preprocessing is not None:
sub, div = self.preprocessing
sub = np.asarray(sub, dtype=x.dtype)
div = np.asarray(div, dtype=x.dtype)
res = x - sub
res = res / div
else:
res = x
return res
def __repr__(self):
class_name = self.__class__.__name__
attributes = {(k[1:], v) if k[0] == '_' else (k, v) for (k, v) in self.__dict__.items()}
attributes = ['{}={}'.format(k, v) for (k, v) in attributes]
repr_string = class_name + '(' + ', '.join(attributes) + ')'
return repr_string
class ClassifierNeuralNetwork(ABC):
"""
Base class defining additional classifier functionality required for neural network classifiers. This base class
has to be mixed in with class `Classifier` to extend the minimum classifier functionality.
"""
def __init__(self, channel_index=None, **kwargs):
"""
Initialize a `ClassifierNeuralNetwork` object.
:param channel_index: Index of the axis in input (feature) array `x` representing the color channels.
:type channel_index: `int`
"""
self._channel_index = channel_index
super().__init__(**kwargs)
@abc.abstractmethod
def predict(self, x, batch_size=128, **kwargs):
"""
Perform prediction of the classifier for input `x`.
:param x: Features in array of shape (nb_samples, nb_features) or (nb_samples, nb_pixels_1, nb_pixels_2,
nb_channels) or (nb_samples, nb_channels, nb_pixels_1, nb_pixels_2)
:param batch_size: The batch size used for evaluating the classifer's `model`.
:type batch_size: `int`
:return: Array of predictions of shape `(nb_inputs, nb_classes)`.
:rtype: `np.ndarray`
"""
raise NotImplementedError
@abc.abstractmethod
def fit(self, x, y, batch_size=128, nb_epochs=20, **kwargs):
"""
Fit the classifier on the training set `(x, y)`.
:param x: Features in array of shape (nb_samples, nb_features) or (nb_samples, nb_pixels_1, nb_pixels_2,
nb_channels) or (nb_samples, nb_channels, nb_pixels_1, nb_pixels_2)
:param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape
(nb_samples,).
:type y: `np.ndarray`
:param batch_size: The batch size used for evaluating the classifer's `model`.
:type batch_size: `int`
:param nb_epochs: Number of epochs to use for training.
:type nb_epochs: `int`
:param kwargs: Dictionary of framework-specific arguments.
:type kwargs: `dict`
:return: `None`
"""
raise NotImplementedError
def fit_generator(self, generator, nb_epochs=20, **kwargs):
"""
Fit the classifier using `generator` yielding training batches as specified. Framework implementations can
provide framework-specific versions of this function to speed-up computation.
:param generator: Batch generator providing `(x, y)` for each epoch.
:type generator: :class:`.DataGenerator`
:param nb_epochs: Number of epochs to use for training.
:type nb_epochs: `int`
:param kwargs: Dictionary of framework-specific arguments.
:type kwargs: `dict`
:return: `None`
"""
from art.data_generators import DataGenerator
if not isinstance(generator, DataGenerator):
raise ValueError('Expected instance of `DataGenerator` for `fit_generator`, got %s instead.'
% str(type(generator)))
for _ in range(nb_epochs):
x, y = generator.get_batch()
# Apply preprocessing and defences
x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=True)
# Fit for current batch
self.fit(x_preprocessed, y_preprocessed, nb_epochs=1, batch_size=len(x), **kwargs)
@property
def channel_index(self):
"""
:return: Index of the axis in input data containing the color channels.
:rtype: `int`
"""
return self._channel_index
@property
def learning_phase(self):
"""
Return the learning phase set by the user for the current classifier. Possible values are `True` for training,
`False` for prediction and `None` if it has not been set through the library. In the latter case, the library
does not do any explicit learning phase manipulation and the current value of the backend framework is used.
If a value has been set by the user for this property, it will impact all following computations for
model fitting, prediction and gradients.
:return: Value of the learning phase.
:rtype: `bool` or `None`
"""
return self._learning_phase if hasattr(self, '_learning_phase') else None
@property
def layer_names(self):
"""
Return the hidden layers in the model, if applicable.
:return: The hidden layers in the model, input and output layers excluded.
:rtype: `list`
.. warning:: `layer_names` tries to infer the internal structure of the model.
This feature comes with no guarantees on the correctness of the result.
The intended order of the layers tries to match their order in the model, but this is not
guaranteed either.
"""
raise NotImplementedError
@abc.abstractmethod
def get_activations(self, x, layer, batch_size):
"""
Return the output of the specified layer for input `x`. `layer` is specified by layer index (between 0 and
`nb_layers - 1`) or by name. The number of layers can be determined by counting the results returned by
calling `layer_names`.
:param x: Input for computing the activations.
:type x: `np.ndarray`
:param layer: Layer for computing the activations
:type layer: `int` or `str`
:param batch_size: Size of batches.
:type batch_size: `int`
:return: The output of `layer`, where the first dimension is the batch size corresponding to `x`.
:rtype: `np.ndarray`
"""
raise NotImplementedError
@abc.abstractmethod
def set_learning_phase(self, train):
"""
Set the learning phase for the backend framework.
:param train: `True` if the learning phase is training, `False` if learning phase is not training.
:type train: `bool`
"""
raise NotImplementedError
def __repr__(self):
name = self.__class__.__name__
attributes = {(k[1:], v) if k[0] == '_' else (k, v) for (k, v) in self.__dict__.items()}
attrs = ['{}={}'.format(k, v) for (k, v) in attributes]
repr_ = name + '(' + ', '.join(attrs) + ')'
return repr_
class ClassifierGradients(ABC):
"""
Base class defining additional classifier functionality for classifiers providing access to loss and class
gradients. A classifier of this type can be combined with white-box attacks. This base class has to be mixed in with
class `Classifier` and optionally class `ClassifierNeuralNetwork` to extend the minimum classifier functionality.
"""
@abc.abstractmethod
def class_gradient(self, x, label=None, **kwargs):
"""
Compute per-class derivatives w.r.t. `x`.
:param x: Input with shape as expected by the classifier's model.
:type x: `np.ndarray`
:param label: Index of a specific per-class derivative. If an integer is provided, the gradient of that class
output is computed for all samples. If multiple values as provided, the first dimension should
match the batch size of `x`, and each value will be used as target for its corresponding sample in
`x`. If `None`, then gradients for all classes will be computed for each sample.
:type label: `int` or `list`
:return: Array of gradients of input features w.r.t. each class in the form
`(batch_size, nb_classes, input_shape)` when computing for all classes, otherwise shape becomes
`(batch_size, 1, input_shape)` when `label` parameter is specified.
:rtype: `np.ndarray`
"""
raise NotImplementedError
@abc.abstractmethod
def loss_gradient(self, x, y, **kwargs):
"""
Compute the gradient of the loss function w.r.t. `x`.
:param x: Input with shape as expected by the classifier's model.
:type x: `np.ndarray`
:param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape
(nb_samples,).
:type y: `np.ndarray`
:return: Array of gradients of the same shape as `x`.
:rtype: `np.ndarray`
"""
raise NotImplementedError
def _apply_preprocessing_gradient(self, x, gradients):
"""
Apply the backward pass through all preprocessing operations to the gradients.
Apply the backward pass through all preprocessing operations and defences on the inputs `(x, y)`. This function
has to be applied to all gradients returned by the classifier.
:param x: Features, where first dimension is the number of samples.
:type x: `np.ndarray`
:param gradients: Input gradients.
:type gradients: `np.ndarray`
:return: Gradients after backward step through preprocessing operations and defences.
:rtype: `np.ndarray`
"""
gradients = self._apply_preprocessing_normalization_gradient(gradients)
gradients = self._apply_preprocessing_defences_gradient(x, gradients)
return gradients
def _apply_preprocessing_defences_gradient(self, x, gradients, fit=False):
"""
Apply the backward pass through the preprocessing defences.
Apply the backward pass through all defences of the classifier on the gradients. This function is intended to
only be called from function `_apply_preprocessing_gradient`.
:param x: Features, where first dimension is the number of samples.
:type x: `np.ndarray`
:param gradients: Input gradient.
:type gradients: `np.ndarray`
:param fit: `True` if the gradient is computed during training.
:return: Gradients after backward step through defences.
:rtype: `np.ndarray`
"""
if self.defences is not None:
for defence in self.defences[::-1]:
if fit:
if defence.apply_fit:
gradients = defence.estimate_gradient(x, gradients)
else:
if defence.apply_predict:
gradients = defence.estimate_gradient(x, gradients)
return gradients
def _apply_preprocessing_normalization_gradient(self, gradients):
"""
Apply the backward pass through standardisation of `x` to `gradients`.
:param gradients: Input gradients.
:type gradients: `np.ndarray`
:return: Gradients after backward step through standardisation.
:rtype: `np.ndarray
"""
_, div = self.preprocessing
div = np.asarray(div, dtype=gradients.dtype)
res = gradients / div
return res
class ClassifierDecisionTree(ABC):
"""
Base class defining additional classifier functionality for decision-tree-based classifiers This base class has to
be mixed in with class `Classifier` to extend the minimum classifier functionality.
"""
@abc.abstractmethod
def get_trees(self):
"""
Get the decision trees.
:return: A list of decision trees.
:rtype: `[Tree]`
"""
raise NotImplementedError
|
SUBROUTINE ks2d1s(x1,y1,n1,quadvl,d1,prob)
INTEGER n1
REAL d1,prob,x1(n1),y1(n1)
EXTERNAL quadvl
CU USES pearsn,probks,quadct,quadvl
INTEGER j
REAL dum,dumm,fa,fb,fc,fd,ga,gb,gc,gd,r1,rr,sqen,probks
d1=0.0
do 11 j=1,n1
call quadct(x1(j),y1(j),x1,y1,n1,fa,fb,fc,fd)
call quadvl(x1(j),y1(j),ga,gb,gc,gd)
d1=max(d1,abs(fa-ga),abs(fb-gb),abs(fc-gc),abs(fd-gd))
11 continue
call pearsn(x1,y1,n1,r1,dum,dumm)
sqen=sqrt(float(n1))
rr=sqrt(1.0-r1**2)
prob=probks(d1*sqen/(1.0+rr*(0.25-0.75/sqen)))
return
END
|
%!TEX root = ../thesis.tex
%*******************************************************************************
%****************************** Third Chapter **********************************
%*******************************************************************************
\chapter{Quantifying and classifying tissue structure}
% **************************** Define Graphics Path **************************
\ifpdf
\graphicspath{{Chapter3/Figs/Raster/}{Chapter3/Figs/PDF/}{Chapter3/Figs/}}
\else
\graphicspath{{Chapter3/Figs/Vector/}{Chapter3/Figs/}}
\fi
\section{Introduction}
As shown in the previous section, stromal and epithelial immune infiltration may have differing roles within the response to a developing tumour. It is clear from observing image of tumour sections that the structure of the epithelium and stromal regions varies dramatically. These morphological differences have been discussed by Lisio et al. \cite{Lisio2019Feb} amongst others. This section of the thesis aims to set out an automated classification of such tissue structure, to investigate whether this can be reliably obtained from multiple types of tissue image and whether the structure defined this way is related to the infiltration of the tumour by particular types of immune infiltrate. The workflow of this Chapter is illustrated in Figures \ref{fig:VA_ch4} and \ref{fig:VA_ch4_2}.
\begin{figure}
\centering
\includegraphics{Chapter3/Figs/Chapter3_VA.PNG}
\caption{Visual Abstract for Chapter 4}
\label{fig:VA_ch4}
\end{figure}
\begin{figure}
\centering
\includegraphics{Chapter3/Figs/VAch2_2.png}
\caption{Visual Abstract for Chapter 4}
\label{fig:VA_ch4_2}
\end{figure}
\section{Collaborators and Roles}
Sarwah Al-Khalidi(SAK) stained the OV04 TMA sections for CK7 and H\&E.
\section{Methodology}
\subsection{Patient Cohorts}
Data from the OV04 Cohort was used for this section as it had existing sections that had H\&E and CK staining. This cohort also had sections available for further analysis using SHG.
\subsection{IHC}
\subsubsection{Cytokeratin 7 staining}
Tissue sections from the OV04 cohort were stained with Cytokeratin7 by Sarwah Al-Khalidi and the method of staining and imaging is laid out in section \ref{sec:sarwah_staining}.
\subsection{H\&E}
Automated Haemotoxylin and Eosin staining was carried out by SAK and is described in \ref{sec:sarwah_staining}.
\subsection{SHG}
SHG microscopy excited at wavelength 900nm and detected at 440-460nm was performed on the Leica SP5 microscope and imaged using a 20x objective. DAKO mounting media and a coverslip of thickness 150$\mu$m was used.
\subsection{DBSCAN}
The package \textbf{dbscan} in R was used for density based clustering analysis. The mathematics of this method is discussed in the Methods.
\section{Results}
Having found in the previous chapter that the specific localisation of several immune infiltrates was an important factor in the prognosis of patients, I wanted to investigate the structure of tissue sections and assess the impact of structure on immune infiltrate. I wanted to use both H\&E and Cytokeratin stained images to derive this structure. Cytokeratin 7 was used as an epithelial marker to have a gold standard for structure analysis and to validate tissue classification of H\&E so that structures can be compared across multiple sections from the same core.
The morphologies discussed by Lisio et al are solid architecture, glandular architecture with slit-like spaces, papillary architecture and cribriform and pseudoendometroid architecture\cite{Lisio2019Feb} and in order to assess whether these structures could be automatically derived from images, the segmentation of tumour and stroma cells must first be acquired.
\subsection{Patient Characteristics}
TMAs had been previously constructed from the CTCR-OV04 clinical studies, which were designed to collect imaging, blood, and tissue samples for exploratory biomarker studies. All patients provided written, informed consent for participation in these studies and for the use of their donated tissue, blood specimens, and anonymized data for the laboratory studies carried out. The CTCR-OV04 studies were approved by the Suffolk Local Research Ethics Committee (reference 05/Q0102/160) and Cambridgeshire Research Ethics Committee (reference 08/H0306/61).\cite{}
This cohort contained 40 patients with HGSOC. Samples were collected where possible for each patient from Normal Fallopian Tube, Malignant Ovary, Omentum and Metastasis. Two cores were extracted per tissue block where possible and two TMA blocks were constructed per tissue type.
\begin{table}[]
\centering
\begin{tabular}{lc}
\hline
N & 40 \\
Age & 77 (60-90)
\hline
\end{tabular}
\caption{OV04 study patient characteristics}
\label{tab:OV04_patient}
\end{table}
\subsection{Cell classifier performance and comparison between H\&E and CK}
Images of tissue sections stained with both H\&E and a CK7 marker were analysed. QuPath was used to segment nuclei based upon their optical density. Nuclei were then classified based upon size, shape and smoothed features using a random forest based classifier. Cells were split randomly into a test and training data set. Examples of tissue classification on H\&E and CK stained images. Over 5000 cells from each TMA section were labelled and 70\% were used for training and 30\% were used for validation test sets. Confusion matrices for the H\&E and CK classifier are shown in Tables (\ref{tab:classifier_he} and \ref{tab:classifier_ck}). These show a very good performance by both classifiers and show that such analysis could be carried across to H\&E images.
\begin{figure}
\centering
\includegraphics{Figs/heck/A-2_core_class.png}
\caption[Example of Stroma and Tumour classifier built in QuPath software]{Example of Stroma and Tumour classifier built in QuPath software. Tumour is highlighted in yellow and stroma in blue. Classifier is trained on both H\&E and CK7 stained images.}
\label{fig:he_classify}
\end{figure}
\begin{table}[]
\centering
\begin{tabular}{llcc}
\hline
& & \multicolumn{2}{c}{Label}\\
& & Stroma & Tumor\\
\hline
Classification&Stroma & 1263 & 2\\
&Tumor & 2 & 346 \\ \hline \\
\end{tabular}
\label{tab:classifier_ck}
\end{table}
\begin{table}[]
\centering
\begin{tabular}{llcc}
\hline
& & \multicolumn{2}{c}{Label}\\
& & Stroma & Tumor\\
\hline
Classification & Stroma & 2653 & 40\\
& Tumor & 11 & 2165\\
\hline \\
\end{tabular}
\caption[Confusion matrix for QuPath H\&E based classifier.]{Confusion matrix for QuPath H\&E based classifier. Percentage of correctly classified objects in test set: 98.95\% (n=4869).}
\label{tab:classifier_he}
\end{table}
The classifiers both perform well and as further validation across the image types, figure\ref{fig:correlation_tumourarea} shows that the percentage of epithelial cells in each image are strongly correlated, as would be expected from serial sections. I observed that at least 1000 training cells were required to get a good classification across all images which naturally vary slightly in staining intensity and tissue texture.
\begin{figure}
\centering
\includegraphics[width=0.5\textwidth]{Chapter3/Figs/correlation_TS_he_Ck.png}
\caption{Correlation between percentage epithelium measured via H\&E and that measured by analysis of an image of a CK stained serial section.}
\label{fig:correlation_tumourarea}
\end{figure}
\subsection{Metrics for tissue structure analysis}
I was interested in being able to quantify the tissue structure of a sample and in order to define a tissue structure of each core I selected several possible metrics to define, examine and measure;
\begin{itemize}
\item Stroma/Tumour percentage
\item Surface Area:Volume ratio of Epithelial regions
\item Cellular entropy
\item Number of clusters
\item Minimum Spanning Tree
\end{itemize}
I aimed to derive these values and then compare these metrics between duplicate samples from a different region of the same tissue block and between different tissues from the same patient.
\subsection{Stroma/Epithelium percentage}
This most basic measure of tissue composition was utilized in the previous chapter. In this chapter I measured this percentage as both an area and a cell proportion for each image type. The distribution of epithelial cell percentages as derived from CK and H\&E images are shown in Figure \ref{fig:epi_percent}. The notches represent the approximate 95\% confidence interval around the median and as shown these overlap, meaning statistically these values could be drawn from the same distributions.
\begin{figure}
\centering
\includegraphics[width=0.5\textwidth]{Chapter3/Figs/boxplot_epithelium.png}
\caption{Histograms of the distribution of epithelial percentages in the OV04 cohort based upon H\&E and CK7 stained images}
\label{fig:epi_percent}
\end{figure}
\subsubsection{Comparison across same tissue section}
\begin{figure}
\centering
\includegraphics[width=0.5\textwidth]{Chapter3/Figs/correlation_T_CK1_Ck2.png}
\caption{Correlation between epithelial percentage from sections of tissue cores from the same sample.}
\label{fig:epi_percent_2slides}
\end{figure}
\subsubsection{Comparison across different tissue sites}
Omentum comparison
\subsection{Density based analysis}
The following routine can be carried out for any core but is demonstrated with a single example.
\subsection{Quantifying border cells and the invasive front}
In a purely diffusive model of immune infiltration where immune infiltrate travels from the stroma into the epithelial nests, epithelial infiltrate would be proportional to the surface area of the epithelial nodules that are exposed to the surrounding stroma.
The surface area to volume ratio of a sphere is proportional to $\frac{1}{r}$ as is the ratio of a circumference to the area of a circle, as such the surface area of a nodule to its volume can be estimated as the following:
\[\frac{SA}{Vol} ~ \frac{(N_{\mathrm{edge}})} {(N_{\mathrm{epi}})}\]
Where $N_{\mathrm{border}}$ is the number of cells on the border between an epithelial tissue compartment and stromal one and $N_{\mathrm{epi}}$ is the number of cells making up the epithelial cluster.
In order to gain an approximation of this surface area, I defined border cells as those epithelial cells which had a close stromal neighbour.
As shown in Figure \ref{fig:TT_SS}, tumour cells are on average closer to each other than stromal cells are. As such I used this domain knowledge to define the neighbour distance cutoff as within twice the distance of the nearest epithelium.
Figure \ref{fig:edge_cells1} shows an example of a tissue section and the cells classified as border cells, as shown these cells are visually a good approximation to the edges of the epithelium in contact with stroma in the tissue section.
\begin{figure}
\centering
\includegraphics[width=0.5\textwidth]{Chapter3/Figs/Thesis-08.png}
\caption{Example of classified images (left) and the cells in the image designated as border cells(right).}
\label{fig:edge_cells1}
\end{figure}
\begin{figure}
\centering
\includegraphics[width=0.5\textwidth]{Chapter4/figs/percent_edge.png}
\caption{The distribution of edge cells as a percentage of epithelial cells.}
\label{fig:edge_cells2}
\end{figure}
\subsubsection{Comparison across same tissue section}
I used the OV04 cohort to examine the number of epithelial cells classified as border cells and compare this between cores extracted from the same tumour block. A plot of the percent of border cells for two cores from the the same tumour block in the same patient is shown in \ref{fig:border_cells}.
\begin{figure}
\centering
\includegraphics[width=0.5\textwidth]{Chapter3/edge_plot_676514_676513.png}
\caption[Correlation between percentage of epithelial cells classified for matched Ovarian samples]{Correlation between percentage of epithelial cells classified for matched ovarian tumour samples from the same patient. Both Pearson and Spearman coefficients shown due to obvious outliers (highlighted in red) from the general trend.}
\label{fig:border_cells}
\end{figure}
As shown there are cores whose structure seems to vary significantly between cores from the same tissue block, I was interested in these outliers and so I extracted the images for the four most outlying (largest residuals from the fit). These are shown in Figure \ref{fig:outlying_edges}. This example shows that there can be very distinct morphological differences across a single tumour block.
\begin{figure}
\centering
\includegraphics[width=\textwidth]{Chapter3/Figs/Thesis-28.png}
\caption{Four examples of matched samples that have the most different number of border cells. Top line is TMA1 and bottom line is TMA2. Accompanying serial section H\&E image accompanies each image in the top left to verify no random mispositioning of cores during staining was responsible.}
\label{fig:outlying_edges}
\end{figure}
\subsubsection{Comparison across different tissue sites}
In order to assess whether this element of tissue structure is conserved across sites of tumours I compared the percent of edge cells in omental vs. ovarian cores.
\begin{figure}
\centering
\includegraphics[width=0.5\textwidth]{Chapter3/Figs/edge_plot_676517_676513.png}
\caption[Correlation between percentage of epithelial cells classified as border cells for matched Ovarian and Omentum tumour samples]{Correlation between percentage of epithelial cells classified as border cells for matched ovarian and omentum tumour samples from the same patient. Both Pearson and Spearman R and p-value shown.}
\label{fig:diff_sites_edge}
\end{figure}
\subsubsection{Comparison with Tumour Grade and Survival}
\subsection{Entropy}
Entropy on some level measures information content and I proposed the use of Entropy measures in order to assess the heterogeneity of samples. The simplest calculation for entropy is the Shannon entropy. In order to utilise this I initially examined entropy as a function of cell types alone and analysed this at multiple scales to examine the tissue features. The formula for deriving entropy is given in Methods \ref{eq:entropy}. I hypothesised that given that tissue regions with mixed cell types would have a higher entropy than those without, that with multiscale area sampling, a reliable classification into tumours with mixing and without could be achieved.
For each tissue image I calculated the entropy for the whole core, the median across a 4x4 and 10x10.
%Plot increasing jxj median entropy
\subsubsection{Comparing entropy measures across H\&E and CK}
Figure \ref{fig:entropy} gives the mean entropy of the image for serial H\&E and CK stained sections. There was a moderate correlation between these samples.
\begin{figure}
\centering
\includegraphics{Chapter3/Figs/Thesis-06.png}
\caption{Shannon entropy derived for a H\&E and CK image of serial sections from the same patient core.}
\label{fig:entropy}
\end{figure}
\subsubsection{Comparing across tissue cores from the same block}
Figure \ref{fig:entropy_block} compares the measures of entropy across tissue samples from the same block but different cores.
\begin{figure}
\centering
\includegraphics{Chapter3/Figs/Thesis____.png}
\caption{Shannon entropy derived for CK stained images of sections from different cores from the same block. Pearson coefficient was 0.63, $p=1e-10$.}
\label{fig:entropy_block}
\end{figure}
\subsection{Cell Clustering}
I wanted to understand how cells clustered within a tissue, and to understand the overall composition of the core, is it one solid tissue section or does it have gaps and separations. This can also be understood as whether the tumour and stroma in the core are in multiple parts and whether they are separate or well mixed.
I assessed multiple methods for clustering tissues and in terms of identifying different sizes and shapes of clusters of cells I found that it was best to use DBSCAN, a density based clustering method. An example of a results of another clustering method is shown in Figure \ref{fig:clust_bad}. K-nn clustering, for example, requires a pre-requisite number of clusters, a parameter that varies dramatically between tissue sections. K-nn is also an unsuitable method as when tissue sections comprise varying numbers within groups and varying spatial densities of cells, the method tends to split the cells equally into the pre-specified number of clusters, rather than recognising different sized clusters within.
\begin{figure}
\centering
\includegraphics{Chapter3/Figs/knn_example_2.png}
\caption[k-nearest neighbour clustering of cells]{k-nearest neighbour clustering of cells identified in a tissue section. Densely packed cells are split into pre-specified(n=5) clusters with no biological meaning.}
\label{fig:clust_bad}
\end{figure}
The DBSCAN method requires two parameters, epsilon (\textit{eps}), the distance within which two points are considered neighbours and \textit{minPts}, the minimum number of points in a cluster.
I decided to only call clusters of at least 15 cells, in tissues making up over 1500 cells, I thought each cluster should contain at least 1\% of the cells in order to improve signal to noise. To derive the optimum \textit{eps} distance for clustering groups of cells on the tissue structure level, I plotted the $k^{th}$ neighbour distribution and located the "elbow" of the curve as discussed in Rahmah et.al. for $k=10$\cite{rahmah2016determination}. The \textit{eps} value obtained from these was 80$\mu$m for Epithelium and 85$\mu$m for Stromal cells. The larger value was used for clustering all cells. These plots for tumour and stroma and the \textit{eps} cutoff from each are shown in Figure \ref{fig:eps}.
\begin{figure}
\centering
\includegraphics[width=\textwidth]{Chapter3/Figs/Thesis-11.png}
\caption{10th nearest neighbour plotted against index, the optimal value for the \texit{eps} is at the elbow of the curve. The \texit{eps} was 80 for All cells, 82 for Tumour and 85 for Stroma.}
\label{fig:eps}
\end{figure}
An example of DBSCAN clustering on serial H\&E and CK sections is shown in Figure \ref{fig:dbclust}. These show visually accurate identifications of cell clusters across H\&E and CK images. Distributions of the number of stroma, tumour and all cell clusters are shown in figure \ref{fig:dbscatter}.
\begin{figure}
\centering
\includegraphics[width=\textwidth]{Chapter3/Figs/dbscan_fullexample.png}
\caption[DBSCAN example]{Examples of clusters of cells generated with DBSCAN algorithm. Clusters generated from images of tissue sections when epithelial, stromal cells are viewed separately and when all cells are input.}
\label{fig:dbclust}
\end{figure}
\begin{figure}
\centering
\includegraphics{}
\caption{Number of clusters.}
\label{fig:dbscatter}
\end{figure}
\subsubsection{Comparison across H\&E and CK}
\subsubsection{Comparison across Tissue Sections}
\subsection{Morphology classification}
Having reliably obtained all the properties above, the quantity of stromal and epithelial cells, identified subclusters, entropy, density of tissue and surface area to volume ratio of the epithelium, I aimed to then investigate whether I could classify tissue sections based upon these features into some of the morphological subtypes mentioned earlier.
I excluded sections which were over 95\% stromal cells, these were classified as stromal and didn't require further analysis of their structure.
I decided to select a training set of sections which could easily be classified into the morphologies mentioned by Murakami et. al. This training set and their labels are shown in \ref{fig:appendix_morphology}.
I compared the metrics measured earlier between these tissue morphologies as shown in Figure \ref{fig:morph_edge}
\begin{figure}
\centering
\includegraphics[width=0.8\textwidth]{Chapter3/manual_class_edge_cells.png}
\caption{Boxplot of the distribution of edge cells for different morphologies.}
\label{fig:morph_edge}
\end{figure}
Following this decision tree I classified each tissue section as Solid, Papillary Glandular, Desmoplastic/Cribriform or .
\begin{figure}
\centering
\includegraphics{}
\caption{Histogram of the number of cases classified as solid, glandular, epithelial or cribriform structure.}
\label{fig:num_classl}
\end{figure}
\subsection{Relationship between Structure and Immune infiltration}
\subsubsection{Immune quantification}
CD8 and FOXP3 were assessed in OV04 samples.
\begin{itemize}
\item Correlation between CD8, FOXP3 and edge cells
\item Immune cells for different structures
\end{itemize}
\subsection{Structure and Survival}
\subsection{Diffusive infiltration model}
\subsection{Collagen structure analysis}
Desmoplasia as mentioned in the previous morphology classification is the formation of fibrous stroma, one dense fibrous stroma component is Collagen. I used Second Harmonic Generation (SHG) to image Collagen on OV04 sections. SHG uses harmonic wave generation by Collagen fibres to image. Figure X shows plot of median collagen entropy and collagen energy for different classifications of tissue.
\subsection{IMC Collagen Analysis?}
\section{Discussion}
Attempts like those of Murakami et. al. \cite{murakami2016establishment} have been made to robustly classify morphologies of HGSOC tissue. Studies have achieved inter-pathologist agreement but automated digital analysis that successfully categorises tissues within HGSOC has not been published. Methods such as deep learning are being attempted but even if successful will not necessarily provide clear insights into the physical features that define the morphologies or a physical understanding of the natural structural variation in samples.
Furthermore, in spite of multiple data sources implying a continuous distribution of densities of infiltration of immune cells into tumours, the literature still dichotimises immune infiltrate and even categorises a subclass of tumour structures as immune reactive, an approach which fails to address the reality that differences in structure may influence immune cells and the rate at which they infiltrate tumours.
In order to address the need for a better structural understanding of tumours before we can relate this to immune infiltration and in order to address the need for automated structural categorisation I generated structural metrics from point patterns of epithelial and stromal cells and examined whether these metrics were correlated across multiple patient samples.
To do this I successfully built classifiers of stroma and epithelium across both Cytokeratin stained and H\&E stained slides. The latter demonstrated that similar methods need not require new staining of sections and could be applied to already available H\&E images that are routinely collected and part of larger public cohorts.
I generated epithelial percentage, border cell, edge cell, entropy based and cluster based metrics and compared them across serial sections stained with H\&E, across sections from cores from the same tissue blocks and across other tumour sites and metastases. I found that the majority of cases were moderately correlated in terms epithelial percentage, border and edge cells. The most basic method of calculating entropy was not correlated across samples from the same tissue block but the addition of structural information in graphs demonstrated correlation across samples.
|
\section{Permutations}
\prob{https://artofproblemsolving.com/community/c5h1434000p8108658}{USAMO 2017
P5}{M}{
Let $m_1, m_2, \ldots, m_n$ be a collection of $n$ positive integers, not
necessarily distinct. For any sequence of integers $A = (a_1, \ldots,
a_n)$ and any permutation $w = w_1, \ldots, w_n$ of $m_1, \ldots, m_n$,
define an $A$-inversion of $w$ to be a pair of entries $w_i, w_j$ with $i
< j$ for which one of the following conditions holds:
\[\begin{aligned}
a_i \ge w_i > w_j,\quad
w_j > a_i \ge w_i,\quad
w_i > w_j > a_i
\end{aligned}\]
Show that, for any two sequences of integers $A = (a_1, \ldots, a_n)$ and $B =
(b_1, \ldots, b_n)$, and for any positive integer $k$, the number of
permutations of $m_1, \ldots, m_n$ having exactly $k$ $A$-inversions is equal
to the number of permutations of $m_1, \ldots, m_n$ having exactly $k$ $B$-inversions.
\index[cat]{Permutations!USAMO 2017 P5}
\index[strat]{Bijection!USAMO 2017 P5}
}
\begin{solution}
Notice that if we take $B$ as a sequence with all elements greater than
all $w_i$, then we have the $B$-inversions to be normal inversions wrt
$M$. So we need to show that there exists a bijection between $A$-inversion and
normal inversion. \\
So we can either show that there for a permutation $w$ with $k$ normal
inversions, there is a permutation $p$ with $k$ $A$-inversions. But we
soon figure out it is pretty hard.\\
If we try the other way, show that for every $w$ with $k$ $A$-inversions,
there is a $p$ with the same $k$ normal inversions, and if we can show
injectivity, we will be done. It turns out that this is much easier.
\end{solution}
\prob{https://artofproblemsolving.com/community/c6h271833p1472110}
{ISL 2008 C2}{E}{
Let $n \in \mathbb N$ and $A_n$ set of all permutations $(a_1, \ldots,
a_n)$ of the set $\{1, 2, \ldots , n\}$ for which
\[k\ |\ 2(a_1 + \cdots+ a_k), \text{ for all } 1 \leq k \leq n.\]
Find the number of elements of the set $A_n$.
\index[cat]{Permutations!ISL 2008 C2}
\index[strat]{Induction!ISL 2008 C2}
}
\begin{solution}
First we try some smaller cases: $ |A_1| = 1$, $ |A_2| = 2$, $ |A_3| = 6$,
$ |A_4| = 12$, which has a clear pattern. So we proceed with induction.\\
With induction, we focus on $a_n$ only, it can have values eiher $n, 1$ or
$\frac{n+1}{2}$. But the later case is impossible, and so we only have two
options for $a_n$, which gives us our desired inductive relation.
\end{solution}
|
Formal statement is: lemma holomorphic_factor_order_of_zero_strong: assumes holf: "f holomorphic_on S" "open S" "\<xi> \<in> S" "0 < n" and "(deriv ^^ n) f \<xi> \<noteq> 0" and "\<And>i. \<lbrakk>0 < i; i < n\<rbrakk> \<Longrightarrow> (deriv ^^ i) f \<xi> = 0" obtains g r where "0 < r" "g holomorphic_on ball \<xi> r" "\<And>w. w \<in> ball \<xi> r \<Longrightarrow> f w - f \<xi> = ((w - \<xi>) * g w) ^ n" "\<And>w. w \<in> ball \<xi> r \<Longrightarrow> g w \<noteq> 0" Informal statement is: Suppose $f$ is a holomorphic function on an open set $S$, and $\xi \in S$. If $f$ has a zero of order $n$ at $\xi$, then there exists a holomorphic function $g$ and a positive real number $r$ such that for all $w \in B(\xi, r)$, we have $f(w) - f(\xi) = (w - \xi)^n g(w)$ and $g(w) \neq 0$.
|
[STATEMENT]
lemma Qp_cong_set_evimage:
assumes "f \<in> carrier (SA n)"
assumes "a \<in> carrier Z\<^sub>p"
shows "is_semialgebraic n (f \<inverse>\<^bsub>n\<^esub> (Qp_cong_set \<alpha> a))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. is_semialgebraic n (f \<inverse>\<^bsub>n\<^esub> Qp_cong_set \<alpha> a)
[PROOF STEP]
using assms Qp_cong_set_is_univ_semialgebraic evimage_is_semialg
[PROOF STATE]
proof (prove)
using this:
f \<in> carrier (SA n)
a \<in> carrier Z\<^sub>p
?a \<in> carrier Z\<^sub>p \<Longrightarrow> is_univ_semialgebraic (Qp_cong_set ?\<alpha> ?a)
\<lbrakk>?h \<in> carrier (SA ?n); is_univ_semialgebraic ?S\<rbrakk> \<Longrightarrow> is_semialgebraic ?n (?h \<inverse>\<^bsub>?n\<^esub> ?S)
goal (1 subgoal):
1. is_semialgebraic n (f \<inverse>\<^bsub>n\<^esub> Qp_cong_set \<alpha> a)
[PROOF STEP]
by blast
|
[STATEMENT]
lemma distinct_ExcessTable:
"distinct vs \<Longrightarrow> distinct [fst p. p \<leftarrow> ExcessTable g vs]"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. distinct vs \<Longrightarrow> distinct (map fst (ExcessTable g vs))
[PROOF STEP]
by (simp_all add: ExcessTable_eq ExcessTable'_def distinct_ExcessTable_cont)
|
/-
Copyright (c) 2018 Alexander Bentkamp. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alexander Bentkamp
-/
import algebra.module.pi
import algebra.big_operators.basic
/-!
# Basic properties of holors
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Holors are indexed collections of tensor coefficients. Confusingly,
they are often called tensors in physics and in the neural network
community.
A holor is simply a multidimensional array of values. The size of a
holor is specified by a `list ℕ`, whose length is called the dimension
of the holor.
The tensor product of `x₁ : holor α ds₁` and `x₂ : holor α ds₂` is the
holor given by `(x₁ ⊗ x₂) (i₁ ++ i₂) = x₁ i₁ * x₂ i₂`. A holor is "of
rank at most 1" if it is a tensor product of one-dimensional holors.
The CP rank of a holor `x` is the smallest N such that `x` is the sum
of N holors of rank at most 1.
Based on the tensor library found in <https://www.isa-afp.org/entries/Deep_Learning.html>
## References
* <https://en.wikipedia.org/wiki/Tensor_rank_decomposition>
-/
universes u
open list
open_locale big_operators
/-- `holor_index ds` is the type of valid index tuples used to identify an entry of a holor
of dimensions `ds`. -/
def holor_index (ds : list ℕ) : Type := {is : list ℕ // forall₂ (<) is ds}
namespace holor_index
variables {ds₁ ds₂ ds₃ : list ℕ}
def take : Π {ds₁ : list ℕ}, holor_index (ds₁ ++ ds₂) → holor_index ds₁
| ds is := ⟨ list.take (length ds) is.1, forall₂_take_append is.1 ds ds₂ is.2 ⟩
def drop : Π {ds₁ : list ℕ}, holor_index (ds₁ ++ ds₂) → holor_index ds₂
| ds is := ⟨ list.drop (length ds) is.1, forall₂_drop_append is.1 ds ds₂ is.2 ⟩
lemma cast_type (is : list ℕ) (eq : ds₁ = ds₂) (h : forall₂ (<) is ds₁) :
(cast (congr_arg holor_index eq) ⟨is, h⟩).val = is :=
by subst eq; refl
def assoc_right :
holor_index (ds₁ ++ ds₂ ++ ds₃) → holor_index (ds₁ ++ (ds₂ ++ ds₃)) :=
cast (congr_arg holor_index (append_assoc ds₁ ds₂ ds₃))
def assoc_left :
holor_index (ds₁ ++ (ds₂ ++ ds₃)) → holor_index (ds₁ ++ ds₂ ++ ds₃) :=
cast (congr_arg holor_index (append_assoc ds₁ ds₂ ds₃).symm)
lemma take_take :
∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃),
t.assoc_right.take = t.take.take
| ⟨ is , h ⟩ := subtype.eq $ by simp [assoc_right,take, cast_type, list.take_take,
nat.le_add_right, min_eq_left]
lemma drop_take :
∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃),
t.assoc_right.drop.take = t.take.drop
| ⟨ is , h ⟩ := subtype.eq (by simp [assoc_right, take, drop, cast_type, list.drop_take])
lemma drop_drop :
∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃),
t.assoc_right.drop.drop = t.drop
| ⟨ is , h ⟩ := subtype.eq (by simp [add_comm, assoc_right, drop, cast_type, list.drop_drop])
end holor_index
/-- Holor (indexed collections of tensor coefficients) -/
def holor (α : Type u) (ds : list ℕ) := holor_index ds → α
namespace holor
variables {α : Type} {d : ℕ} {ds : list ℕ} {ds₁ : list ℕ} {ds₂ : list ℕ} {ds₃ : list ℕ}
instance [inhabited α] : inhabited (holor α ds) := ⟨λ t, default⟩
instance [has_zero α] : has_zero (holor α ds) := ⟨λ t, 0⟩
instance [has_add α] : has_add (holor α ds) := ⟨λ x y t, x t + y t⟩
instance [has_neg α] : has_neg (holor α ds) := ⟨λ a t, - a t⟩
instance [add_semigroup α] : add_semigroup (holor α ds) :=
by refine_struct { add := (+), .. }; tactic.pi_instance_derive_field
instance [add_comm_semigroup α] : add_comm_semigroup (holor α ds) :=
by refine_struct { add := (+), .. }; tactic.pi_instance_derive_field
instance [add_monoid α] : add_monoid (holor α ds) :=
by refine_struct { zero := (0 : holor α ds), add := (+), nsmul := λ n x i, n • (x i) };
tactic.pi_instance_derive_field
instance [add_comm_monoid α] : add_comm_monoid (holor α ds) :=
by refine_struct { zero := (0 : holor α ds), add := (+), nsmul := add_monoid.nsmul };
tactic.pi_instance_derive_field
instance [add_group α] : add_group (holor α ds) :=
by refine_struct { zero := (0 : holor α ds), add := (+), nsmul := add_monoid.nsmul,
zsmul := λ n x i, n • (x i) };
tactic.pi_instance_derive_field
instance [add_comm_group α] : add_comm_group (holor α ds) :=
by refine_struct { zero := (0 : holor α ds), add := (+), nsmul := add_monoid.nsmul,
zsmul := sub_neg_monoid.zsmul };
tactic.pi_instance_derive_field
/- scalar product -/
instance [has_mul α] : has_smul α (holor α ds) :=
⟨λ a x, λ t, a * x t⟩
instance [semiring α] : module α (holor α ds) := pi.module _ _ _
/-- The tensor product of two holors. -/
def mul [s : has_mul α] (x : holor α ds₁) (y : holor α ds₂) : holor α (ds₁ ++ ds₂) :=
λ t, x (t.take) * y (t.drop)
local infix ` ⊗ ` : 70 := mul
lemma cast_type (eq : ds₁ = ds₂) (a : holor α ds₁) :
cast (congr_arg (holor α) eq) a = (λ t, a (cast (congr_arg holor_index eq.symm) t)) :=
by subst eq; refl
def assoc_right :
holor α (ds₁ ++ ds₂ ++ ds₃) → holor α (ds₁ ++ (ds₂ ++ ds₃)) :=
cast (congr_arg (holor α) (append_assoc ds₁ ds₂ ds₃))
def assoc_left :
holor α (ds₁ ++ (ds₂ ++ ds₃)) → holor α (ds₁ ++ ds₂ ++ ds₃) :=
cast (congr_arg (holor α) (append_assoc ds₁ ds₂ ds₃).symm)
lemma mul_assoc0 [semigroup α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₃) :
x ⊗ y ⊗ z = (x ⊗ (y ⊗ z)).assoc_left :=
funext (assume t : holor_index (ds₁ ++ ds₂ ++ ds₃),
begin
rw assoc_left,
unfold mul,
rw mul_assoc,
rw [←holor_index.take_take, ←holor_index.drop_take, ←holor_index.drop_drop],
rw cast_type,
refl,
rw append_assoc
end)
lemma mul_assoc [semigroup α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₃) :
mul (mul x y) z == (mul x (mul y z)) :=
by simp [cast_heq, mul_assoc0, assoc_left].
lemma mul_left_distrib [distrib α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₂) :
x ⊗ (y + z) = x ⊗ y + x ⊗ z :=
funext (λt, left_distrib (x (holor_index.take t)) (y (holor_index.drop t)) (z (holor_index.drop t)))
lemma mul_right_distrib [distrib α] (x : holor α ds₁) (y : holor α ds₁) (z : holor α ds₂) :
(x + y) ⊗ z = x ⊗ z + y ⊗ z :=
funext $ λt, add_mul (x (holor_index.take t)) (y (holor_index.take t)) (z (holor_index.drop t))
@[simp] lemma zero_mul {α : Type} [ring α] (x : holor α ds₂) :
(0 : holor α ds₁) ⊗ x = 0 :=
funext (λ t, zero_mul (x (holor_index.drop t)))
@[simp] lemma mul_zero {α : Type} [ring α] (x : holor α ds₁) :
x ⊗ (0 :holor α ds₂) = 0 :=
funext (λ t, mul_zero (x (holor_index.take t)))
lemma mul_scalar_mul [monoid α] (x : holor α []) (y : holor α ds) :
x ⊗ y = x ⟨[], forall₂.nil⟩ • y :=
by simp [mul, has_smul.smul, holor_index.take, holor_index.drop]
/- holor slices -/
/-- A slice is a subholor consisting of all entries with initial index i. -/
def slice (x : holor α (d :: ds)) (i : ℕ) (h : i < d) : holor α ds :=
(λ is : holor_index ds, x ⟨ i :: is.1, forall₂.cons h is.2⟩)
/-- The 1-dimensional "unit" holor with 1 in the `j`th position. -/
def unit_vec [monoid α] [add_monoid α] (d : ℕ) (j : ℕ) : holor α [d] :=
λ ti, if ti.1 = [j] then 1 else 0
lemma holor_index_cons_decomp (p: holor_index (d :: ds) → Prop) :
Π (t : holor_index (d :: ds)),
(∀ i is, Π h : t.1 = i :: is, p ⟨ i :: is, begin rw [←h], exact t.2 end ⟩ ) → p t
| ⟨[], hforall₂⟩ hp := absurd (forall₂_nil_left_iff.1 hforall₂) (cons_ne_nil d ds)
| ⟨(i :: is), hforall₂⟩ hp := hp i is rfl
/-- Two holors are equal if all their slices are equal. -/
lemma slice_eq (x : holor α (d :: ds)) (y : holor α (d :: ds))
(h : slice x = slice y) : x = y :=
funext $ λ t : holor_index (d :: ds), holor_index_cons_decomp (λ t, x t = y t) t $ λ i is hiis,
have hiisdds: forall₂ (<) (i :: is) (d :: ds), begin rw [←hiis], exact t.2 end,
have hid: i<d, from (forall₂_cons.1 hiisdds).1,
have hisds: forall₂ (<) is ds, from (forall₂_cons.1 hiisdds).2,
calc
x ⟨i :: is, _⟩ = slice x i hid ⟨is, hisds⟩ : congr_arg (λ t, x t) (subtype.eq rfl)
... = slice y i hid ⟨is, hisds⟩ : by rw h
... = y ⟨i :: is, _⟩ : congr_arg (λ t, y t) (subtype.eq rfl)
lemma slice_unit_vec_mul [ring α] {i : ℕ} {j : ℕ}
(hid : i < d) (x : holor α ds) :
slice (unit_vec d j ⊗ x) i hid = if i=j then x else 0 :=
funext $ λ t : holor_index ds, if h : i = j
then by simp [slice, mul, holor_index.take, unit_vec, holor_index.drop, h]
else by simp [slice, mul, holor_index.take, unit_vec, holor_index.drop, h]; refl
lemma slice_add [has_add α] (i : ℕ) (hid : i < d) (x : holor α (d :: ds)) (y : holor α (d :: ds)) :
slice x i hid + slice y i hid = slice (x + y) i hid := funext (λ t, by simp [slice,(+)])
lemma slice_zero [has_zero α] (i : ℕ) (hid : i < d) :
slice (0 : holor α (d :: ds)) i hid = 0 := rfl
lemma slice_sum [add_comm_monoid α] {β : Type}
(i : ℕ) (hid : i < d) (s : finset β) (f : β → holor α (d :: ds)) :
∑ x in s, slice (f x) i hid = slice (∑ x in s, f x) i hid :=
begin
letI := classical.dec_eq β,
refine finset.induction_on s _ _,
{ simp [slice_zero] },
{ intros _ _ h_not_in ih,
rw [finset.sum_insert h_not_in, ih, slice_add, finset.sum_insert h_not_in] }
end
/-- The original holor can be recovered from its slices by multiplying with unit vectors and
summing up. -/
@[simp] lemma sum_unit_vec_mul_slice [ring α] (x : holor α (d :: ds)) :
∑ i in (finset.range d).attach,
unit_vec d i ⊗ slice x i (nat.succ_le_of_lt (finset.mem_range.1 i.prop)) = x :=
begin
apply slice_eq _ _ _,
ext i hid,
rw [←slice_sum],
simp only [slice_unit_vec_mul hid],
rw finset.sum_eq_single (subtype.mk i $ finset.mem_range.2 hid),
{ simp },
{ assume (b : {x // x ∈ finset.range d}) (hb : b ∈ (finset.range d).attach) (hbi : b ≠ ⟨i, _⟩),
have hbi' : i ≠ b,
{ simpa only [ne.def, subtype.ext_iff, subtype.coe_mk] using hbi.symm },
simp [hbi'] },
{ assume hid' : subtype.mk i _ ∉ finset.attach (finset.range d),
exfalso,
exact absurd (finset.mem_attach _ _) hid' }
end
/- CP rank -/
/-- `cprank_max1 x` means `x` has CP rank at most 1, that is,
it is the tensor product of 1-dimensional holors. -/
inductive cprank_max1 [has_mul α]: Π {ds}, holor α ds → Prop
| nil (x : holor α []) :
cprank_max1 x
| cons {d} {ds} (x : holor α [d]) (y : holor α ds) :
cprank_max1 y → cprank_max1 (x ⊗ y)
/-- `cprank_max N x` means `x` has CP rank at most `N`, that is,
it can be written as the sum of N holors of rank at most 1. -/
inductive cprank_max [has_mul α] [add_monoid α] : ℕ → Π {ds}, holor α ds → Prop
| zero {ds} :
cprank_max 0 (0 : holor α ds)
| succ n {ds} (x : holor α ds) (y : holor α ds) :
cprank_max1 x → cprank_max n y → cprank_max (n+1) (x + y)
lemma cprank_max_nil [monoid α] [add_monoid α] (x : holor α nil) : cprank_max 1 x :=
have h : _, from cprank_max.succ 0 x 0 (cprank_max1.nil x) (cprank_max.zero),
by rwa [add_zero x, zero_add] at h
lemma cprank_max_1 [monoid α] [add_monoid α] {x : holor α ds}
(h : cprank_max1 x) : cprank_max 1 x :=
have h' : _, from cprank_max.succ 0 x 0 h cprank_max.zero,
by rwa [zero_add, add_zero] at h'
lemma cprank_max_add [monoid α] [add_monoid α]:
∀ {m : ℕ} {n : ℕ} {x : holor α ds} {y : holor α ds},
cprank_max m x → cprank_max n y → cprank_max (m + n) (x + y)
| 0 n x y (cprank_max.zero) hy := by simp [hy]
| (m+1) n _ y (cprank_max.succ k x₁ x₂ hx₁ hx₂) hy :=
begin
simp only [add_comm, add_assoc],
apply cprank_max.succ,
{ assumption },
{ exact cprank_max_add hx₂ hy }
end
lemma cprank_max_mul [ring α] :
∀ (n : ℕ) (x : holor α [d]) (y : holor α ds), cprank_max n y → cprank_max n (x ⊗ y)
| 0 x _ (cprank_max.zero) := by simp [mul_zero x, cprank_max.zero]
| (n+1) x _ (cprank_max.succ k y₁ y₂ hy₁ hy₂) :=
begin
rw mul_left_distrib,
rw nat.add_comm,
apply cprank_max_add,
{ exact cprank_max_1 (cprank_max1.cons _ _ hy₁) },
{ exact cprank_max_mul k x y₂ hy₂ }
end
lemma cprank_max_sum [ring α] {β} {n : ℕ} (s : finset β) (f : β → holor α ds) :
(∀ x ∈ s, cprank_max n (f x)) → cprank_max (s.card * n) (∑ x in s, f x) :=
by letI := classical.dec_eq β;
exact finset.induction_on s
(by simp [cprank_max.zero])
(begin
assume x s (h_x_notin_s : x ∉ s) ih h_cprank,
simp only [finset.sum_insert h_x_notin_s, finset.card_insert_of_not_mem h_x_notin_s],
rw nat.right_distrib,
simp only [nat.one_mul, nat.add_comm],
have ih' : cprank_max (finset.card s * n) (∑ x in s, f x),
{ apply ih,
assume (x : β) (h_x_in_s: x ∈ s),
simp only [h_cprank, finset.mem_insert_of_mem, h_x_in_s] },
exact (cprank_max_add (h_cprank x (finset.mem_insert_self x s)) ih')
end)
lemma cprank_max_upper_bound [ring α] : Π {ds}, ∀ x : holor α ds, cprank_max ds.prod x
| [] x := cprank_max_nil x
| (d :: ds) x :=
have h_summands : Π (i : {x // x ∈ finset.range d}),
cprank_max ds.prod (unit_vec d i.1 ⊗ slice x i.1 (mem_range.1 i.2)),
from λ i, cprank_max_mul _ _ _ (cprank_max_upper_bound (slice x i.1 (mem_range.1 i.2))),
have h_dds_prod : (list.cons d ds).prod = finset.card (finset.range d) * prod ds,
by simp [finset.card_range],
have cprank_max (finset.card (finset.attach (finset.range d)) * prod ds)
(∑ i in finset.attach (finset.range d), unit_vec d (i.val)⊗slice x (i.val) (mem_range.1 i.2)),
from cprank_max_sum (finset.range d).attach _ (λ i _, h_summands i),
have h_cprank_max_sum : cprank_max (finset.card (finset.range d) * prod ds)
(∑ i in finset.attach (finset.range d), unit_vec d (i.val)⊗slice x (i.val) (mem_range.1 i.2)),
by rwa [finset.card_attach] at this,
begin
rw [←sum_unit_vec_mul_slice x],
rw [h_dds_prod],
exact h_cprank_max_sum,
end
/-- The CP rank of a holor `x`: the smallest N such that
`x` can be written as the sum of N holors of rank at most 1. -/
noncomputable def cprank [ring α] (x : holor α ds) : nat :=
@nat.find (λ n, cprank_max n x) (classical.dec_pred _) ⟨ds.prod, cprank_max_upper_bound x⟩
lemma cprank_upper_bound [ring α] :
Π {ds}, ∀ x : holor α ds, cprank x ≤ ds.prod :=
λ ds (x : holor α ds),
by letI := classical.dec_pred (λ (n : ℕ), cprank_max n x);
exact nat.find_min'
⟨ds.prod, show (λ n, cprank_max n x) ds.prod, from cprank_max_upper_bound x⟩
(cprank_max_upper_bound x)
end holor
|
(* Title: HOL/Auth/n_g2kAbsAfter_lemma_inv__62_on_rules.thy
Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
*)
header{*The n_g2kAbsAfter Protocol Case Study*}
theory n_g2kAbsAfter_lemma_inv__62_on_rules imports n_g2kAbsAfter_lemma_on_inv__62
begin
section{*All lemmas on causal relation between inv__62*}
lemma lemma_inv__62_on_rules:
assumes b1: "r \<in> rules N" and b2: "(f=inv__62 )"
shows "invHoldForRule s f r (invariants N)"
proof -
have c1: "(\<exists> d. d\<le>N\<and>r=n_n_Store_i1 d)\<or>
(\<exists> d. d\<le>N\<and>r=n_n_AStore_i1 d)\<or>
(r=n_n_SendReqS_j1 )\<or>
(r=n_n_SendReqEI_i1 )\<or>
(r=n_n_SendReqES_i1 )\<or>
(r=n_n_RecvReq_i1 )\<or>
(r=n_n_SendInvE_i1 )\<or>
(r=n_n_SendInvS_i1 )\<or>
(r=n_n_SendInvAck_i1 )\<or>
(r=n_n_RecvInvAck_i1 )\<or>
(r=n_n_SendGntS_i1 )\<or>
(r=n_n_SendGntE_i1 )\<or>
(r=n_n_RecvGntS_i1 )\<or>
(r=n_n_RecvGntE_i1 )\<or>
(r=n_n_ASendReqIS_j1 )\<or>
(r=n_n_ASendReqSE_j1 )\<or>
(r=n_n_ASendReqEI_i1 )\<or>
(r=n_n_ASendReqES_i1 )\<or>
(r=n_n_SendReqEE_i1 )\<or>
(r=n_n_ARecvReq_i1 )\<or>
(r=n_n_ASendInvE_i1 )\<or>
(r=n_n_ASendInvS_i1 )\<or>
(r=n_n_ASendInvAck_i1 )\<or>
(r=n_n_ARecvInvAck_i1 )\<or>
(r=n_n_ASendGntS_i1 )\<or>
(r=n_n_ASendGntE_i1 )\<or>
(r=n_n_ARecvGntS_i1 )\<or>
(r=n_n_ARecvGntE_i1 )"
apply (cut_tac b1, auto) done
moreover {
assume d1: "(\<exists> d. d\<le>N\<and>r=n_n_Store_i1 d)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_Store_i1Vsinv__62) done
}
moreover {
assume d1: "(\<exists> d. d\<le>N\<and>r=n_n_AStore_i1 d)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_AStore_i1Vsinv__62) done
}
moreover {
assume d1: "(r=n_n_SendReqS_j1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendReqS_j1Vsinv__62) done
}
moreover {
assume d1: "(r=n_n_SendReqEI_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendReqEI_i1Vsinv__62) done
}
moreover {
assume d1: "(r=n_n_SendReqES_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendReqES_i1Vsinv__62) done
}
moreover {
assume d1: "(r=n_n_RecvReq_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_RecvReq_i1Vsinv__62) done
}
moreover {
assume d1: "(r=n_n_SendInvE_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendInvE_i1Vsinv__62) done
}
moreover {
assume d1: "(r=n_n_SendInvS_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendInvS_i1Vsinv__62) done
}
moreover {
assume d1: "(r=n_n_SendInvAck_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendInvAck_i1Vsinv__62) done
}
moreover {
assume d1: "(r=n_n_RecvInvAck_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_RecvInvAck_i1Vsinv__62) done
}
moreover {
assume d1: "(r=n_n_SendGntS_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendGntS_i1Vsinv__62) done
}
moreover {
assume d1: "(r=n_n_SendGntE_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendGntE_i1Vsinv__62) done
}
moreover {
assume d1: "(r=n_n_RecvGntS_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_RecvGntS_i1Vsinv__62) done
}
moreover {
assume d1: "(r=n_n_RecvGntE_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_RecvGntE_i1Vsinv__62) done
}
moreover {
assume d1: "(r=n_n_ASendReqIS_j1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendReqIS_j1Vsinv__62) done
}
moreover {
assume d1: "(r=n_n_ASendReqSE_j1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendReqSE_j1Vsinv__62) done
}
moreover {
assume d1: "(r=n_n_ASendReqEI_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendReqEI_i1Vsinv__62) done
}
moreover {
assume d1: "(r=n_n_ASendReqES_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendReqES_i1Vsinv__62) done
}
moreover {
assume d1: "(r=n_n_SendReqEE_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendReqEE_i1Vsinv__62) done
}
moreover {
assume d1: "(r=n_n_ARecvReq_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ARecvReq_i1Vsinv__62) done
}
moreover {
assume d1: "(r=n_n_ASendInvE_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendInvE_i1Vsinv__62) done
}
moreover {
assume d1: "(r=n_n_ASendInvS_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendInvS_i1Vsinv__62) done
}
moreover {
assume d1: "(r=n_n_ASendInvAck_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendInvAck_i1Vsinv__62) done
}
moreover {
assume d1: "(r=n_n_ARecvInvAck_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ARecvInvAck_i1Vsinv__62) done
}
moreover {
assume d1: "(r=n_n_ASendGntS_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendGntS_i1Vsinv__62) done
}
moreover {
assume d1: "(r=n_n_ASendGntE_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendGntE_i1Vsinv__62) done
}
moreover {
assume d1: "(r=n_n_ARecvGntS_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ARecvGntS_i1Vsinv__62) done
}
moreover {
assume d1: "(r=n_n_ARecvGntE_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ARecvGntE_i1Vsinv__62) done
}
ultimately show "invHoldForRule s f r (invariants N)"
by satx
qed
end
|
function varargout = plotsparsemarkers(varargin)
%
% [h =] plotsparsemarkers(hp, hl, markerStyle[, numberOfMarkers = 6 [,staggered = true]])
%
% Adds only a limited number of markers to a set of lines given by
% the handle array hp. If hl is not [] it should be the handle of
% the legend corresponding to the lines.
%
% markerStyle is a cell array of styles, e.g. {'o', 'x'} describing
% the markers for the lines in hp, the length of the cell array has
% to be the same as hp (or shorter in which case not all lines will get
% markers).
%
% numberOfMarkers is an optional parameter, default = 6, that sets
% the number of markers on each line, this number must be equal or less
% than the number of points plotted for each line.
%
% staggered is a boolean that tries to stagger the markers so that the
% are not at the same x value for all lines. This defaults to true and
% is intended to avoid markers overwriting each other if the x-values
% are identical for the lines.
%
%%
% Check input parameters
if nargin <3
disp('[sparsemarker]: wrong number of arguments')
help sparsemarker
return
end
hp = varargin{1};
hl = varargin{2};
markStyle = varargin{3};
if nargin >3
numberOfMarkers = varargin{4};
else
numberOfMarkers = 6;
end
if nargin >4
staggered = varargin{5};
else
staggered = true;
end
%%
% Define marker lines
nrLines = length(markStyle);
%Create stagger distance
if staggered
x = 1:nrLines;
stag = -1.^(mod(x,2)+1).*x./nrLines./2;
else
stag = zeros(1,nrLines);
end
for ii = 1:nrLines
% Determine number of points in line ii
X = get(hp(ii),'XDATA');
Y = get(hp(ii),'YDATA');
interval = (X(end)-X(1))./(numberOfMarkers+2);
targetx = stag(ii)*interval + ... %Stagger offset
linspace(X(1)+interval,X(end)-interval,...
numberOfMarkers);
for jj = 1:numberOfMarkers
[~,ind] = min(abs(targetx(jj)-X));
mx(ii,jj) = X(ind);
my(ii,jj) = Y(ind);
end
end
whos mx my
%%
% plot marker lines
hpp = get(hp(ii),'Parent');
set(hpp,'LineStyleOrder',markStyle); %This is a bad solution
%that works
hold on
h = plot(mx',my');
hold off
%Change markers to same color as the line
for ii = 1:nrLines
set(h(ii),'MarkerEdgeColor',get(hp(ii),'Color'));
set(h(ii),'Marker',markStyle{ii});
set(h(ii),'MarkerSize',12); %These are sizes I like
set(h(ii),'LineWidth',2); %you can change them using
end %the handle that is returned
%%
% update legend
if ~isempty(hl)
hlc = get(hl,'Children');
for ii = 1:nrLines
jj = (nrLines-ii)*3+1;
set(hlc(jj),'Marker',markStyle{ii});
set(hlc(jj),'Marker',markStyle{ii});
set(hlc(jj),'MarkerEdgeColor',get(hp(ii),'Color'));
set(hlc(jj),'MarkerSize',12);
end
end
%%
% Return handle to markers
if nargout > 0
varargout{1} = h;
end
|
forexone.me 9 out of 10 based on 200 ratings. 800 user reviews.
Replacement Jeep batteries, trays, terminals, wiring and cables from popular brands like Omix, CTEK, Odyssey and Crown. Available same day shipping.
Shopping for Jeep audio accessories? We offer antennas, wiring, bezels, adapters and mounts from popular brands at guaranteed lowest pricing.
|
/-
Copyright (c) 2021 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Std.Classes.SetNotation
import Std.Classes.LawfulMonad
import Std.Tactic.NoMatch
namespace Option
/-- An elimination principle for `Option`. It is a nondependent version of `Option.recOn`. -/
@[simp] protected def elim : Option α → β → (α → β) → β
| some x, _, f => f x
| none, y, _ => y
instance : Membership α (Option α) := ⟨fun a b => b = some a⟩
@[simp] theorem mem_def {a : α} {b : Option α} : a ∈ b ↔ b = some a := .rfl
theorem isNone_iff_eq_none {o : Option α} : o.isNone ↔ o = none :=
⟨Option.eq_none_of_isNone, fun e => e.symm ▸ rfl⟩
theorem some_inj {a b : α} : some a = some b ↔ a = b := by simp
/--
`o = none` is decidable even if the wrapped type does not have decidable equality.
This is not an instance because it is not definitionally equal to `instance : DecidableEq Option`.
Try to use `o.isNone` or `o.isSome` instead.
-/
@[inline] def decidable_eq_none {o : Option α} : Decidable (o = none) :=
decidable_of_decidable_of_iff isNone_iff_eq_none
instance {p : α → Prop} [DecidablePred p] : ∀ o : Option α, Decidable (∀ a ∈ o, p a)
| none => isTrue (by simp)
| some a =>
if h : p a then isTrue fun o e => some_inj.1 e ▸ h
else isFalse <| mt (· _ rfl) h
instance {p : α → Prop} [DecidablePred p] : ∀ o : Option α, Decidable (∃ a ∈ o, p a)
| none => isFalse fun.
| some a => if h : p a then isTrue ⟨_, rfl, h⟩ else isFalse fun ⟨_, ⟨rfl, hn⟩⟩ => h hn
/-- Extracts the value `a` from an option that is known to be `some a` for some `a`. -/
def get {α : Type u} : (o : Option α) → isSome o → α
| some x, _ => x
/-- `guard p a` returns `some a` if `p a` holds, otherwise `none`. -/
def guard (p : α → Prop) [DecidablePred p] (a : α) : Option α := if p a then some a else none
/--
Cast of `Option` to `List`. Returns `[a]` if the input is `some a`, and `[]` if it is `none`.
-/
def toList : Option α → List α
| none => []
| some a => [a]
/--
Cast of `Option` to `Array`. Returns `[a]` if the input is `some a`, and `[]` if it is `none`.
-/
def toArray : Option α → Array α
| none => #[]
| some a => #[a]
/--
Two arguments failsafe function. Returns `f a b` if the inputs are `some a` and `some b`, and
"does nothing" otherwise.
-/
def liftOrGet (f : α → α → α) : Option α → Option α → Option α
| none, none => none
| some a, none => some a
| none, some b => some b
| some a, some b => some (f a b)
/-- Lifts a relation `α → β → Prop` to a relation `Option α → Option β → Prop` by just adding
`none ~ none`. -/
inductive Rel (r : α → β → Prop) : Option α → Option β → Prop
/-- If `a ~ b`, then `some a ~ some b` -/
| some {a b} : r a b → Rel r (some a) (some b)
/-- `none ~ none` -/
| none : Rel r none none
/--
Partial bind. If for some `x : Option α`, `f : Π (a : α), a ∈ x → Option β` is a
partial function defined on `a : α` giving an `Option β`, where `some a = x`,
then `pbind x f h` is essentially the same as `bind x f`
but is defined only when all `x = some a`, using the proof to apply `f`.
-/
@[simp]
def pbind : ∀ x : Option α, (∀ a : α, a ∈ x → Option β) → Option β
| none, _ => none
| some a, f => f a rfl
/--
Partial map. If `f : Π a, p a → β` is a partial function defined on `a : α` satisfying `p`,
then `pmap f x h` is essentially the same as `map f x` but is defined only when all members of `x`
satisfy `p`, using the proof to apply `f`.
-/
@[simp] def pmap {p : α → Prop} (f : ∀ a : α, p a → β) : ∀ x : Option α, (∀ a ∈ x, p a) → Option β
| none, _ => none
| some a, H => f a (H a rfl)
/-- Flatten an `Option` of `Option`, a specialization of `joinM`. -/
@[simp, inline] def join (x : Option (Option α)) : Option α := x.bind id
/-- Map a monadic function which returns `Unit` over an `Option`. -/
protected def forM [Pure m] : Option α → (α → m PUnit) → m PUnit
| none , _ => pure ()
| some a, f => f a
instance : ForM m (Option α) α :=
⟨Option.forM⟩
instance : ForIn' m (Option α) α inferInstance where
forIn' x init f := do
match x with
| none => return init
| some a =>
match ← f a rfl init with
| .done r | .yield r => return r
/-- Like `Option.mapM` but for applicative functors. -/
protected def mapA [Applicative m] {α β} (f : α → m β) : Option α → m (Option β)
| none => pure none
| some x => some <$> f x
/--
If you maybe have a monadic computation in a `[Monad m]` which produces a term of type `α`, then
there is a naturally associated way to always perform a computation in `m` which maybe produces a
result.
-/
def sequence [Monad m] {α : Type u} : Option (m α) → m (Option α)
| none => pure none
| some fn => some <$> fn
/-- A monadic analogue of `Option.elim`. -/
@[inline] def elimM [Monad m] (x : m (Option α)) (y : m β) (z : α → m β) : m β :=
do (← x).elim y z
/-- A monadic analogue of `Option.getD`. -/
@[inline] def getDM [Monad m] (x : Option α) (y : m α) : m α :=
match x with
| some a => pure a
| none => y
|
State Before: α : Type u_1
β : Type ?u.11642
γ : Type ?u.11645
inst✝¹ : Fintype α
s t : Finset α
inst✝ : DecidableEq α
a : α
⊢ erase s aᶜ = insert a (sᶜ) State After: case a
α : Type u_1
β : Type ?u.11642
γ : Type ?u.11645
inst✝¹ : Fintype α
s t : Finset α
inst✝ : DecidableEq α
a a✝ : α
⊢ a✝ ∈ erase s aᶜ ↔ a✝ ∈ insert a (sᶜ) Tactic: ext State Before: case a
α : Type u_1
β : Type ?u.11642
γ : Type ?u.11645
inst✝¹ : Fintype α
s t : Finset α
inst✝ : DecidableEq α
a a✝ : α
⊢ a✝ ∈ erase s aᶜ ↔ a✝ ∈ insert a (sᶜ) State After: no goals Tactic: simp only [or_iff_not_imp_left, mem_insert, not_and, mem_compl, mem_erase]
|
(*
Copyright (C) 2017 M.A.L. Marques
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*)
(* type: mgga_exc *)
(* prefix:
mgga_x_m05_params *params;
assert(p->params != NULL);
params = (mgga_x_m05_params * )(p->params);
*)
$define gga_x_pbe_params
$include "gga_x_pbe.mpl"
m05_f := (x, u, t) ->
+ params_a_csi_HF*pbe_f(x)*mgga_series_w(params_a_a, 12, t):
f := (rs, z, xt, xs0, xs1, u0, u1, t0, t1) ->
mgga_exchange(m05_f, rs, z, xs0, xs1, u0, u1, t0, t1):
|
Rev. Canon Chasuble , D.D. — H. H. Vincent
|
# 2. faza: Uvoz podatkov
# Funkcija, ki uvozi podatke iz datoteke druzine.csv
uvozi.druzine <- function() {
return(read.table("podatki/druzine.csv", sep = ";", as.is = TRUE,
row.names = 1,
col.names = c("obcina", "en", "dva", "tri", "stiri"),
fileEncoding = "Windows-1250"))
}
# Zapišimo podatke v razpredelnico druzine.
druzine <- uvozi.druzine()
obcine <- uvozi.obcine()
# Če bi imeli več funkcij za uvoz in nekaterih npr. še ne bi
# potrebovali v 3. fazi, bi bilo smiselno funkcije dati v svojo
# datoteko, tukaj pa bi klicali tiste, ki jih potrebujemo v
# 2. fazi. Seveda bi morali ustrezno datoteko uvoziti v prihodnjih
# fazah.
uvozi.zita <- function() {
return(read.table("podatki/zita1.csv", sep = ";", as.is = TRUE,
col.names = c("drzava", "vrsta pridelka", "enota", "2010", "2011", "2012", "2013", "2014"),
fileEncoding = "Windows-1250"))
}
|
= = = Royal Navy = = =
|
Playing in his 14th and final NBA All @-@ Star Game in 2003 , Jordan passed Kareem Abdul @-@ Jabbar as the all @-@ time leading scorer in All @-@ Star Game history ( a record since broken by Kobe Bryant ) . That year , Jordan was the only Washington player to play in all 82 games , starting in 67 of them . He averaged 20 @.@ 0 points , 6 @.@ 1 rebounds , 3 @.@ 8 assists , and 1 @.@ 5 steals per game . He also shot 45 % from the field , and 82 % from the free throw line . Even though he turned 40 during the season , he scored 20 or more points 42 times , 30 or more points nine times , and 40 or more points three times . On February 21 , 2003 , Jordan became the first 40 @-@ year @-@ old to tally 43 points in an NBA game . During his stint with the Wizards , all of Jordan 's home games at the MCI Center were sold out , and the Wizards were the second most @-@ watched team in the NBA , averaging 20 @,@ 172 fans a game at home and 19 @,@ 311 on the road . However , neither of Jordan 's final two seasons resulted in a playoff appearance for the Wizards , and Jordan was often unsatisfied with the play of those around him . At several points he openly criticized his teammates to the media , citing their lack of focus and intensity , notably that of the number one draft pick in the 2001 NBA draft , Kwame Brown .
|
[STATEMENT]
lemma comp_char:
shows "g \<cdot> f = (if seq g f then
if f = Zero then g else if g = One then f else null
else null)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. g \<cdot> f = (if seq g f then if f = Zero then g else if g = One then f else null else null)
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. g \<cdot> f = (if seq g f then if f = Zero then g else if g = One then f else null else null)
[PROOF STEP]
have "seq g f \<Longrightarrow> f = Zero \<Longrightarrow> g \<cdot> f = g"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>seq g f; f = Zero\<rbrakk> \<Longrightarrow> g \<cdot> f = g
[PROOF STEP]
using seq_char comp_char [of g f] Zero_def dom_char cod_char comp_arr_dom
[PROOF STATE]
proof (prove)
using this:
seq ?g ?f = (arr ?g \<and> arr ?f \<and> (?f = Zero \<and> ?g \<noteq> One \<or> ?f \<noteq> Zero \<and> ?g = One))
g \<cdot> f = (if seq g f then MkArr (Dom f) (Cod g) (Map f @ Map g) else null)
Zero \<equiv> MkIde False
local.dom ?f = (if arr ?f then if ?f = One then One else Zero else null)
cod ?f = (if arr ?f then if ?f = Zero then Zero else One else null)
\<lbrakk>arr ?f; local.dom ?f = ?a\<rbrakk> \<Longrightarrow> ?f \<cdot> ?a = ?f
goal (1 subgoal):
1. \<lbrakk>seq g f; f = Zero\<rbrakk> \<Longrightarrow> g \<cdot> f = g
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
\<lbrakk>seq g f; f = Zero\<rbrakk> \<Longrightarrow> g \<cdot> f = g
goal (1 subgoal):
1. g \<cdot> f = (if seq g f then if f = Zero then g else if g = One then f else null else null)
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
\<lbrakk>seq g f; f = Zero\<rbrakk> \<Longrightarrow> g \<cdot> f = g
goal (1 subgoal):
1. g \<cdot> f = (if seq g f then if f = Zero then g else if g = One then f else null else null)
[PROOF STEP]
have "seq g f \<Longrightarrow> g = One \<Longrightarrow> g \<cdot> f = f"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>seq g f; g = One\<rbrakk> \<Longrightarrow> g \<cdot> f = f
[PROOF STEP]
using seq_char comp_char [of g f] One_def dom_char cod_char comp_cod_arr
[PROOF STATE]
proof (prove)
using this:
seq ?g ?f = (arr ?g \<and> arr ?f \<and> (?f = Zero \<and> ?g \<noteq> One \<or> ?f \<noteq> Zero \<and> ?g = One))
g \<cdot> f = (if seq g f then MkArr (Dom f) (Cod g) (Map f @ Map g) else null)
One \<equiv> MkIde True
local.dom ?f = (if arr ?f then if ?f = One then One else Zero else null)
cod ?f = (if arr ?f then if ?f = Zero then Zero else One else null)
\<lbrakk>arr ?f; cod ?f = ?b\<rbrakk> \<Longrightarrow> ?b \<cdot> ?f = ?f
goal (1 subgoal):
1. \<lbrakk>seq g f; g = One\<rbrakk> \<Longrightarrow> g \<cdot> f = f
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
\<lbrakk>seq g f; g = One\<rbrakk> \<Longrightarrow> g \<cdot> f = f
goal (1 subgoal):
1. g \<cdot> f = (if seq g f then if f = Zero then g else if g = One then f else null else null)
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
\<lbrakk>seq g f; g = One\<rbrakk> \<Longrightarrow> g \<cdot> f = f
goal (1 subgoal):
1. g \<cdot> f = (if seq g f then if f = Zero then g else if g = One then f else null else null)
[PROOF STEP]
have "seq g f \<Longrightarrow> f \<noteq> Zero \<Longrightarrow> g \<noteq> One \<Longrightarrow> g \<cdot> f = null"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>seq g f; f \<noteq> Zero; g \<noteq> One\<rbrakk> \<Longrightarrow> g \<cdot> f = null
[PROOF STEP]
using seq_char Zero_def One_def
[PROOF STATE]
proof (prove)
using this:
seq ?g ?f = (arr ?g \<and> arr ?f \<and> (?f = Zero \<and> ?g \<noteq> One \<or> ?f \<noteq> Zero \<and> ?g = One))
Zero \<equiv> MkIde False
One \<equiv> MkIde True
goal (1 subgoal):
1. \<lbrakk>seq g f; f \<noteq> Zero; g \<noteq> One\<rbrakk> \<Longrightarrow> g \<cdot> f = null
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
\<lbrakk>seq g f; f \<noteq> Zero; g \<noteq> One\<rbrakk> \<Longrightarrow> g \<cdot> f = null
goal (1 subgoal):
1. g \<cdot> f = (if seq g f then if f = Zero then g else if g = One then f else null else null)
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
\<lbrakk>seq g f; f \<noteq> Zero; g \<noteq> One\<rbrakk> \<Longrightarrow> g \<cdot> f = null
goal (1 subgoal):
1. g \<cdot> f = (if seq g f then if f = Zero then g else if g = One then f else null else null)
[PROOF STEP]
have "\<not>seq g f \<Longrightarrow> g \<cdot> f = null"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<not> seq g f \<Longrightarrow> g \<cdot> f = null
[PROOF STEP]
using comp_char ext
[PROOF STATE]
proof (prove)
using this:
?g \<cdot> ?f = (if seq ?g ?f then MkArr (Dom ?f) (Cod ?g) (Map ?f @ Map ?g) else null)
?g \<cdot> ?f \<noteq> null \<Longrightarrow> seq ?g ?f
goal (1 subgoal):
1. \<not> seq g f \<Longrightarrow> g \<cdot> f = null
[PROOF STEP]
by fastforce
[PROOF STATE]
proof (state)
this:
\<not> seq g f \<Longrightarrow> g \<cdot> f = null
goal (1 subgoal):
1. g \<cdot> f = (if seq g f then if f = Zero then g else if g = One then f else null else null)
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
\<lbrakk>seq g f; f = Zero\<rbrakk> \<Longrightarrow> g \<cdot> f = g
\<lbrakk>seq g f; g = One\<rbrakk> \<Longrightarrow> g \<cdot> f = f
\<lbrakk>seq g f; f \<noteq> Zero; g \<noteq> One\<rbrakk> \<Longrightarrow> g \<cdot> f = null
\<not> seq g f \<Longrightarrow> g \<cdot> f = null
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>seq g f; f = Zero\<rbrakk> \<Longrightarrow> g \<cdot> f = g
\<lbrakk>seq g f; g = One\<rbrakk> \<Longrightarrow> g \<cdot> f = f
\<lbrakk>seq g f; f \<noteq> Zero; g \<noteq> One\<rbrakk> \<Longrightarrow> g \<cdot> f = null
\<not> seq g f \<Longrightarrow> g \<cdot> f = null
goal (1 subgoal):
1. g \<cdot> f = (if seq g f then if f = Zero then g else if g = One then f else null else null)
[PROOF STEP]
by argo
[PROOF STATE]
proof (state)
this:
g \<cdot> f = (if seq g f then if f = Zero then g else if g = One then f else null else null)
goal:
No subgoals!
[PROOF STEP]
qed
|
[STATEMENT]
lemma conga_obtuse__obtuse:
assumes "Obtuse A B C" and
"A B C CongA D E F"
shows "Obtuse D E F"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Obtuse D E F
[PROOF STEP]
using assms(1) assms(2) conga__lea lea_obtuse_obtuse
[PROOF STATE]
proof (prove)
using this:
Obtuse A B C
A B C CongA D E F
?A ?B ?C CongA ?D ?E ?F \<Longrightarrow> ?A ?B ?C LeA ?D ?E ?F
\<lbrakk>Obtuse ?D ?E ?F; ?D ?E ?F LeA ?A ?B ?C\<rbrakk> \<Longrightarrow> Obtuse ?A ?B ?C
goal (1 subgoal):
1. Obtuse D E F
[PROOF STEP]
by blast
|
State Before: α : Type u_1
β : Type ?u.61989
inst✝ : LinearOrder α
a a₁ a₂ b b₁ b₂ c d : α
⊢ Ioi a \ Ici b = Ioo a b State After: no goals Tactic: rw [diff_eq, compl_Ici, Ioi_inter_Iio]
|
Property giant Hammerson - one of three partners behind Birmingham's hugely successful Bullring shopping centre - yesterday shrugged off the depression hanging over the UK retail sector with strong first half results.
Property giant Hammerson - one of three partners behind Birmingham's hugely successful Bullring shopping centre - yesterday shrugged off the depression hanging over the UK retail sector with strong first half results.
The company, which also owns major stakes in shopping centres, said that despite the slowdown in consumer confidence, its retail assets were continuing to attract good levels of demand from tenants.
Hammerson is part of the Birmingham Alliance, the partnership behind Bullring and Martineau Place shopping centres. Henderson Global Investors and Land Securities are the other companies involved.
Chief executive John Richards said: "There are some uncertainties in retail trends in the UK but I have to say that Hammerson properties are well positioned in the best sectors of the market - dominant regional shopping centres and high-quality retail parks."
Mr Richards said Bullring had performed particularly well - in fact "outperforming the general trend in UK retailing" and continuing to attract tourist shoppers as well as regular customers.
Hammerson posted a 21.6 per cent rise in half-year pretax profits to £247.3 million, while its property portfolio was valued at £4.8 billion at the end of June, with retail accounting for 71 per cent of the estate.
Profits were boosted by a £31.5 million gain on property sales, which included the sale of a property on Boulevard Haussmann in Paris. In total, the group raised £217 million from disposals.
Looking ahead, the property specialist said demand for office space in London and Paris was "encouraging". It also has significant new projects coming on stream, including the former Stock Exchange building in the City of London.
Outgoing chairman Ronald Spinney said: "I believe Hammerson is well placed to achieve good income growth from its reversionary retail portfolio, notwithstanding some uncertainties over trends in consumer expenditure in the UK.
"In addition, there is an encouraging improvement in demand for office accommodation, both in central London and Paris, and this should enable the group to achieve further lettings in its office portfolio."
Mr Spinney is standing down from the board at the end of September having spent 12 years with the company. He will be succeeded as chairman by non-executive director John Reynolds from October 1.
As well as working with councils to advance schemes in Kingston- upon- Thames, Leeds, Peterborough and Sheffield, Hammerson said it believed there were opportunities to "extend and enhance" a number of its existing shopping centres, including Bernt Cross in north London, West-Quay in Southampton and The Oracle in Reading.
Hammerson also forecast growth in office rents next year, when it expects to benefit from a low level of new supply, particularly in the City of London, and further falls in vacancy rates during the remainder of this year.
The company is also confident that office lettings will improve from their recent below-par performance.
Earnings per share fell 23.6 per cent, from 94.5p to 72.2p.
However, the interim dividend payment rises 6.4 per cent, from 5.45p to 5.8p per share.
Shares closed up 8p at 887p.
|
lemma pcompose_eq_0: fixes p q :: "'a::{comm_semiring_0,semiring_no_zero_divisors} poly" assumes "pcompose p q = 0" "degree q > 0" shows "p = 0"
|
######################################################################
# nonempty_subsets(A) is the set of all nonempty subsets of A
`is_element/nonempty_subsets` := (A::set) -> proc(B)
type(B,set) and B minus A = {} and nops(B) > 0;
end;
`is_equal/nonempty_subsets` := (A::set) -> (B,C) -> evalb(B = C):
`is_leq/nonempty_subsets` := (A::set) -> (B,C) -> evalb(B minus C = {}):
`random_element/nonempty_subsets` := (A::set) -> proc()
local r,B;
if nops(A) = 0 then return FAIL; fi;
r := rand(2);
B := {};
while nops(B) = 0 do
B := select(a -> (r() = 1),A);
od;
return B;
end;
`list_elements/nonempty_subsets` := (A::set) ->
sort(map(sort,[op(combinat[powerset](A) minus {{}})])):
`count_elements/nonempty_subsets` := (A::set) -> 2^nops(A) - 1;
|
subroutine initmerge (nmmax, lsed, runid, gdp)
!----- GPL ---------------------------------------------------------------------
!
! Copyright (C) Stichting Deltares, 2011-2016.
!
! This program is free software: you can redistribute it and/or modify
! it under the terms of the GNU General Public License as published by
! the Free Software Foundation version 3.
!
! This program is distributed in the hope that it will be useful,
! but WITHOUT ANY WARRANTY; without even the implied warranty of
! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
! GNU General Public License for more details.
!
! You should have received a copy of the GNU General Public License
! along with this program. If not, see <http://www.gnu.org/licenses/>.
!
! contact: [email protected]
! Stichting Deltares
! P.O. Box 177
! 2600 MH Delft, The Netherlands
!
! All indications and logos of, and references to, "Delft3D" and "Deltares"
! are registered trademarks of Stichting Deltares, and remain the property of
! Stichting Deltares. All rights reserved.
!
!-------------------------------------------------------------------------------
! $Id: initmerge.f90 5717 2016-01-12 11:35:24Z mourits $
! $HeadURL: https://svn.oss.deltares.nl/repos/delft3d/tags/6686/src/engines_gpl/flow2d3d/packages/kernel/src/inichk/initmerge.f90 $
!!--description-----------------------------------------------------------------
!
!
!!--pseudo code and references--------------------------------------------------
! NONE
!!--declarations----------------------------------------------------------------
use precision
!
use globaldata
!
implicit none
!
type(globdat),target :: gdp
!
! The following list of pointer parameters is used to point inside the gdp structure
!
integer , pointer :: lundia
integer , pointer :: mergehandle
real(hp) , dimension(:) , pointer :: mergebuf
character(256) , pointer :: mmsyncfilnam
type (morpar_type) , pointer :: gdmorpar
!
! Global variables
!
integer :: nmmax
integer :: lsed
character(*) :: runid
!
! Local variables
!
integer :: conditionend
integer :: i
integer :: istat
integer, external :: getstream
integer :: lunfil
integer, external :: newlun
integer :: pathlen
real(hp), dimension(2) :: rn
logical :: ex
character(1) :: slash
character(256) :: condition
character(256) :: streamfile
character(256) :: filhand
!
!! executable statements -------------------------------------------------------
!
lundia => gdp%gdinout%lundia
mergehandle => gdp%gdmorpar%mergehandle
mergebuf => gdp%gdmorpar%mergebuf
mmsyncfilnam => gdp%gdmorpar%mmsyncfilnam
gdmorpar => gdp%gdmorpar
!
write(*,'(10x,a)')'- Waiting for connection with mormerge...'
filhand = ' '
inquire(file='streamfile', exist=ex)
if (ex) then
lunfil = newlun(gdp)
open (lunfil, file='streamfile')
read (lunfil,'(a)') filhand
close(lunfil)
write(filhand,'(2a)') trim(filhand), trim(runid)
!
! filhand is assumed to be:
! <path><condition>stream<runid>
! mmsync file name is going to be:
! <path>/sync/<condition>flow<runid>
!
if (gdp%arch == 'win32' .or. gdp%arch == 'win64') then
slash = '\'
!
! In filhand: replace all occurences of / by \
! Needed for further parsing
!
do i=1,len(filhand)
if (filhand(i:i) == '/') then
filhand(i:i) = '\'
endif
enddo
else
slash = '/'
!
! In filhand: replace all occurences of \ by /
! Needed for further parsing
!
do i=1,len(filhand)
if (filhand(i:i) == '\') then
filhand(i:i) = '/'
endif
enddo
endif
pathlen = len_trim(filhand)
do while ( filhand(pathlen:pathlen) /= slash .and. pathlen>1)
pathlen = pathlen - 1
enddo
conditionend = index(filhand, 'stream', .true.)
!
! The position of the first character of the word 'stream' (s),
! behind the condition should be at least pathlen+2
!
if (conditionend < pathlen+2) conditionend = pathlen + 4
condition = filhand(pathlen+1 : conditionend-1)
write(mmsyncfilnam,'(6a)') filhand(:pathlen), 'sync', slash, &
& trim(condition) , 'flow', trim(runid)
lunfil = newlun(gdp)
open (lunfil, file=mmsyncfilnam, position='append', action='write', iostat=istat)
if (istat /= 0) then
write(*,*)' *** WARNING: unable to write in file ',trim(mmsyncfilnam)
else
write(lunfil,'(a)') 'Initialized'
close(lunfil)
endif
!
! This is the actual connection with mormerge
!
mergehandle = getstream(filhand)
else
call prterr(lundia, 'U021', 'File named streamfile not found')
call d3stop(1,gdp)
endif
rn(1) = nmmax * 1.0_hp
rn(2) = lsed * 1.0_hp
! write(*,*)nmmax, lsed, rn
call putarray(mergehandle, rn, 2)
!
! allocate buffer array
!
allocate (gdp%gdmorpar%mergebuf(nmmax*lsed), stat = istat)
if (istat /= 0) then
call prterr(lundia, 'U021', 'Initmerge: memory alloc error')
call d3stop(1,gdp)
endif
end subroutine initmerge
|
Formal statement is: lemma [field_split_simps]: "a = b /\<^sub>R c \<longleftrightarrow> (if c = 0 then a = 0 else c *\<^sub>R a = b)" "b /\<^sub>R c = a \<longleftrightarrow> (if c = 0 then a = 0 else b = c *\<^sub>R a)" "a + b /\<^sub>R c = (if c = 0 then a else (c *\<^sub>R a + b) /\<^sub>R c)" "a /\<^sub>R c + b = (if c = 0 then b else (a + c *\<^sub>R b) /\<^sub>R c)" "a - b /\<^sub>R c = (if c = 0 then a else (c *\<^sub>R a - b) /\<^sub>R c)" "a /\<^sub>R c - b = (if c = 0 then - b else (a - c *\<^sub>R b) /\<^sub>R c)" "- (a /\<^sub>R c) + b = (if c = 0 then b else (- a + c *\<^sub>R b) /\<^sub>R c)" "- (a /\<^sub>R c) - b = (if c = 0 then - b else (- a - c *\<^sub>R b) /\<^sub>R c)" for a b :: "'a :: real_vector" Informal statement is: The following equations hold for all real vectors $a$, $b$, and $c$: $a = b / c$ if and only if $c = 0$ or $c a = b$ $b / c = a$ if and only if $c = 0$ or $b = c a$ $a + b / c = (c a + b) / c$ if and only if $c \neq 0$ $a / c + b = (a + c b) / c$ if and only if $c \neq 0$ $a - b / c = (c a - b) / c$ if and only if $c \neq 0$ $a / c - b = (a - c b) / c$ if and only if $c \neq 0$ $- (a / c) + b = (- a + c b) / c$ if and only if $c \neq 0$ $- (a / c) - b = (- a - c b) / c$ if and only if $c \neq 0$
|
function conv2conv()
global config mem;
curr_layer_idx = config.misc.current_layer;
conv_layer_idx = get_conv_layer_idx_from_layer_idx(curr_layer_idx);
P_reshape = reshape(mem.activations{curr_layer_idx-1}', config.feature_map_sizes{curr_layer_idx-1}(1), config.feature_map_sizes{curr_layer_idx-1}(2)*config.feature_map_sizes{curr_layer_idx-1}(3)*config.batch_size);
P_expand = config.IM2COL(P_reshape, [config.kernel_size(conv_layer_idx, 1), config.kernel_size(conv_layer_idx, 2)]);
P_expand(:, mem.conv2conv{curr_layer_idx}{2}) = 0;
input_size = [0 0];
input_size(1) = config.kernel_size(conv_layer_idx, 1)*config.kernel_size(conv_layer_idx, 2)*config.feature_map_sizes{curr_layer_idx-1}(3);
input_size(2) = (config.feature_map_sizes{curr_layer_idx-1}(1)-config.kernel_size(conv_layer_idx, 1)+1)*(config.feature_map_sizes{curr_layer_idx-1}(2)-config.kernel_size(conv_layer_idx, 2)+1)*config.batch_size;
mem.layer_inputs{curr_layer_idx} = reshape(accumarray(mem.conv2conv{curr_layer_idx}{1}, P_expand(:), [input_size(1)*input_size(2), 1]), input_size(1), input_size(2));
% memory redundancy, need improve
mem.orig_activation_size{curr_layer_idx-1} = size(mem.activations{curr_layer_idx-1});
mem.activations{curr_layer_idx-1} = mem.layer_inputs{curr_layer_idx};
end
|
\section{Computer exercises for the lab}
This week is a good time for
\begin{itemize}
\item[(a)] making sure you are comfortable with the mathematics behind matrices as well as:
\item[(b)] making sure you are comfortable with the matrix operators in R.
\item[(c)] Check that you are very very sure you can subscript R matrices, i.e. use things such as \text{[,1]} to select column 1, \text{[,-1]} to select everything \emph{except} column 1, and \text{[,2:3]} to select columns 2 and 3.
\end{itemize}
Although we will use in built multivariate analysis functions in R, you should consider checking you understand the techniques by using R as a matrix calculator.
\begin{enumerate}
\item Find (where possible) the determinants and the inverse of the following matrices:
$C_{1} = \left[ \begin {array}{cc} 4& 4\\\noalign{\medskip} 4& 4\end {array} \right]$, $C_{2} = \left[ \begin {array}{cc} 4& 4.001\\\noalign{\medskip} 4.001& 4.002\end {array} \right]$ and $C_{3} = \left[ \begin {array}{cc} 4& 4.001\\\noalign{\medskip} 4.001& 4.002001\end {array} \right] $
Very briefly comment on the magnitude of the difference between $C_{2}^{-1}$ and $C_{3}^{-1}$ given the only difference between $C_{2}$ and $C_{2}$ amounts to a difference of $0.000001$ in the bottom right position.
\begin{Schunk}
\begin{Sinput}
> A <- matrix(c(4, 4, 4, 4), 2, 2)
> A
> det(A)
> try(solve(A))
> B <- matrix(c(4, 4.001, 4.001, 4.002), 2, 2)
> B
> det(B)
> solve(B)
> C <- matrix(c(4, 4.001, 4.001, 4.002001), 2, 2)
> C
> det(C)
> solve(C)
\end{Sinput}
\end{Schunk}
\begin{itemize}
\item What's going on here?
\end{itemize}
\textit{Note that A is singular, the determinant is zero and it can't be inverted. Also note that the inverses of B and C are very very different - but this is something of a pathological example}
\item Matrix partitioning. Consider Sterling's financial data held in the R object LifeCycleSavings (see \verb+?LifeCycleSavings+). To make life a little easier, reorder the columns using \texttt{X <- LifeCycleSavings[,c(2,3,1,4,5)]}.
\begin{itemize}
\item Find the correlation matrix of \texttt{X} (longhand, using the centering matrix), call this matrix \texttt{R}
\begin{Schunk}
\begin{Sinput}
> data(LifeCycleSavings)
> X <- LifeCycleSavings[, c(2, 3, 1, 4, 5)]
> R <- cor(X)
> R
\end{Sinput}
\end{Schunk}
\item Partition \textit{R = cov(X)} following the scheme below such that $\boldsymbol{R_{11}}$ is a $2 \times 2$ matrix containing the covariance of \texttt{pop15} and \texttt{pop75}, and $\boldsymbol{R_{22}}$ contains the covariance of \texttt{sr}, \texttt{dpi} and \texttt{ddpi}
\begin{displaymath}
\boldsymbol{R} = \left( \begin{array}{l|l} \boldsymbol{R_{11}} & \boldsymbol{R_{12}} \\ \hline \boldsymbol{R_{21}} & \boldsymbol{R_{22}} \end{array} \right)
\end{displaymath}
You should find for example that $\boldsymbol{R_{11}}$ is given by:
% latex table generated in R 2.3.1 by xtable 1.3-2 package
% Wed Nov 15 22:15:30 2006
\begin{table}[ht]
\begin{center}
\begin{tabular}{rrr}
\hline
& pop15 & pop75 \\
\hline
pop15 & 83.75 & $-$10.73 \\
pop75 & $-$10.73 & 1.67 \\
\hline
\end{tabular}
\end{center}
\end{table}
\begin{Schunk}
\begin{Sinput}
> R11 <- R[1:2, 1:2]
> R12 <- R[1:2, 3:5]
> R21 <- R[3:5, 1:2]
> R22 <- R[3:5, 3:5]
> R11
> R22
> R21
> R12
> t(R21)
\end{Sinput}
\end{Schunk}
\item Find the matrix $\boldsymbol{A}$, where:
\begin{displaymath}
\boldsymbol{A} = \boldsymbol{R_{22}^{-1}R_{21}R_{11}^{-1}R_{12}}
\end{displaymath}
\begin{Schunk}
\begin{Sinput}
> A <- solve(R22) %*% R21 %*% solve(R11) %*% R12
\end{Sinput}
\end{Schunk}
%\begin{itemize}
\item Are $\boldsymbol{A}$ and $\boldsymbol{B}$ symmetric? What is the difference between symmetric and asymmetric matrices in terms of their eigenvalues and eigenvectors?\\
\textit{Note that they are both asymmetric matrices, it just so happens for these particular matrices that the eigenvalues are positive and the eigenvectors are real. This isn't always the case for asymmetric matrices!}
\item Find the eigenvalues and eigenvectors of $\boldsymbol{A}$ and $\boldsymbol{B}$ then find the square roots of the eigenvalues.
\begin{Schunk}
\begin{Sinput}
> eigen(B)
> sqrt(eigen(A)$values)
> sqrt(eigen(B)$values)
\end{Sinput}
\end{Schunk}
\item Do you notice any similarities between the first two eigenvalues from either matrix?\\
\textit{Note that the square roots of the eigen values are identical.}
\end{itemize}
\item Revisit the \texttt{wines} data in the \texttt{Flury} package. Consider only Y1, Y5, Y6, Y8 and Y9, use matrix algebra to find the means, correlation and covariance of these data. Compare the eigenvalues and eigenvectors, and the determinants and inverse you get from the covariance matrix and the correlation matrix.\\
\end{enumerate}
\section{Summary of week 2}
\fbox{\parbox[c]{0.9\textwidth}{\color{blue}
\begin{itemize}
\item We have revised, and are comfortable with matrix multiplication, matrix inverse, (normalised) eigenvalues and eigenvectors. We can center and scale matrices. We can do this by hand and in R.
\item We are also comfortable using R as a matrix calculator if and when we wish.
\end{itemize}
}}
|
{-# OPTIONS --cubical --no-import-sorts --safe #-}
module Cubical.Algebra.Semigroup.Subsemigroup where
open import Cubical.Core.Everything
open import Cubical.Foundations.Prelude
open import Cubical.Foundations.HLevels
open import Cubical.Data.Sigma
open import Cubical.Algebra
open import Cubical.Algebra.Semigroup.Morphism
open import Cubical.Algebra.Magma.Submagma
open import Cubical.Relation.Unary
open import Cubical.Relation.Unary.Subtype
record IsSubsemigroup {c ℓ} (S : Semigroup c) (Member : Pred ⟨ S ⟩ ℓ) : Type (ℓ-max c ℓ) where
constructor issubsemigroup
private module S = Semigroup S
field
closed : S._•_ Preserves₂ Member
isSubmagma : IsSubmagma S.magma Member
isSubmagma = record { closed = closed }
open IsSubmagma isSubmagma hiding (closed) public
assoc : Associative _•_
assoc _ _ _ = ΣPathTransport→PathΣ _ _ (S.assoc _ _ _ , isProp[ Member ] _ _ _)
isSemigroup : IsSemigroup Carrier _•_
isSemigroup = record
{ isMagma = isMagma
; assoc = assoc
}
semigroup : Semigroup _
semigroup = record { isSemigroup = isSemigroup }
open Semigroup semigroup using (_^_) public
record Subsemigroup {c} (S : Semigroup c) ℓ : Type (ℓ-max c (ℓ-suc ℓ)) where
constructor mksubsemigroup
private module S = Semigroup S
field
Member : Pred ⟨ S ⟩ ℓ
isSubsemigroup : IsSubsemigroup S Member
open IsSubsemigroup isSubsemigroup public
submagma : Submagma S.magma ℓ
submagma = record { isSubmagma = isSubmagma }
instance
SubsemigroupCarrier : ∀ {c ℓ} {S : Semigroup c} → HasCarrier (Subsemigroup S ℓ) _
SubsemigroupCarrier = record { ⟨_⟩ = Subsemigroup.Carrier }
module _ {ℓ} (S : Semigroup ℓ) where
open Semigroup S
∅-isSubsemigroup : IsSubsemigroup S ∅
∅-isSubsemigroup = record { closed = λ () }
∅-subsemigroup : Subsemigroup S _
∅-subsemigroup = record { isSubsemigroup = ∅-isSubsemigroup }
U-isSubsemigroup : IsSubsemigroup S U
U-isSubsemigroup = record {} -- trivial
U-subsemigroup : Subsemigroup S _
U-subsemigroup = record { isSubsemigroup = U-isSubsemigroup }
|
State Before: R : Type u
inst✝ : CommRing R
W : ModuleCat R
X : ModuleCat R
Y : ModuleCat R
Z : ModuleCat R
⊢ tensorHom (associator W X Y).hom (𝟙 Z) ≫
(associator W (tensorObj X Y) Z).hom ≫ tensorHom (𝟙 W) (associator X Y Z).hom =
(associator (tensorObj W X) Y Z).hom ≫ (associator W X (tensorObj Y Z)).hom State After: no goals Tactic: convert pentagon_aux R W X Y Z using 1
|
## extended methods for computing covariance and scatter matrix
# auxiliary functions
function _symmetrize!(a::DenseMatrix)
m, n = size(a)
m == n || error("a must be a square matrix.")
for j = 1:n
@inbounds for i = j+1:n
vl = a[i,j]
vr = a[j,i]
a[i,j] = a[j,i] = middle(vl, vr)
end
end
return a
end
function _scalevars(x::DenseMatrix, s::DenseVector, vardim::Int)
vardim == 1 ? scale(s, x) :
vardim == 2 ? scale(x, s) :
error("vardim should be either 1 or 2.")
end
## scatter matrix
scattermat_zm(x::DenseMatrix, vardim::Int) = Base.unscaled_covzm(x, vardim)
scattermat_zm(x::DenseMatrix, wv::WeightVec, vardim::Int) =
_symmetrize!(Base.unscaled_covzm(x, _scalevars(x, values(wv), vardim), vardim))
function scattermat(x::DenseMatrix; mean=nothing, vardim::Int=1)
mean == 0 ? scattermat_zm(x, vardim) :
mean == nothing ? scattermat_zm(x .- Base.mean(x, vardim), vardim) :
scattermat_zm(x .- mean, vardim)
end
function scattermat(x::DenseMatrix, wv::WeightVec; mean=nothing, vardim::Int=1)
mean == 0 ? scattermat_zm(x, wv, vardim) :
mean == nothing ? scattermat_zm(x .- Base.mean(x, wv, vardim), wv, vardim) :
scattermat_zm(x .- mean, wv, vardim)
end
## weighted cov
Base.cov(x::DenseMatrix, wv::WeightVec; mean=nothing, vardim::Int=1) =
scale!(scattermat(x, wv; mean=mean, vardim=vardim), inv(sum(wv)))
mean_and_cov(x::DenseMatrix; vardim::Int=1) = (m = mean(x, vardim); (m, Base.covm(x, m; vardim=vardim)))
mean_and_cov(x::DenseMatrix, wv::WeightVec; vardim::Int=1) =
(m = mean(x, wv, vardim); (m, Base.cov(x, wv; mean=m, vardim=vardim)))
|
John L McMurdie served on the City Council from 4/20/1962 to 4/20/1966.
McMurdie ran for reelection in 66, but he failed to sense that the political winds in Davis were changing. One of his more memorable campaign statements was:
The horse and buggy have had their day, and the bicycle is on its way OUT! (As per an interview with Donna Lott, 2005)
|
-- 2016-01-14 Andreas, issue reported by Martin Stone Davis
open import Common.Equality
module _ {K : Set} where
record Map : Set where
field
unmap : K
record _∉_ (k : K) (m : Map) : Set where
field
un∉ : Map.unmap m ≡ k
pattern ∉∅ = record { un∉ = refl }
not-here : ∀ {k : K} {m : Map} (k∉m : k ∉ m) → Set
not-here ∉∅ = K
-- WAS: internal error due to record pattern not yet treated
-- for pattern synonyms.
|
#' Convert to Queue
#'
#' @param x
#' An object either to be converted to the first element of a queue
#' (default), or the elements of a list (or columns of a dataframe)
#' to be set as elements of a queue.
#'
#' @return
#' A queue object.
#'
#' @examples
#' \dontrun{
#' library(dequer)
#' q <- as.queue(lapply(1:5, identity))
#' q
#' }
#'
#' @export
#' @name as.queue
#' @rdname as.queue
as.queue <- function(x) UseMethod("as.queue")
#' @export
#' @rdname as.queue
as.queue.list <- function(x)
{
q <- queue()
for (obj in x)
pushback(q, obj)
return(q)
}
#' @export
#' @rdname as.queue
as.queue.default <- function(x)
{
q <- queue()
pushback(q, x)
return(q)
}
#' @export
#' @rdname as.queue
as.queue.deque <- function(x)
{
class(x) <- "queue"
return(x)
}
#' @export
#' @rdname as.queue
as.queue.stack <- function(x)
{
class(x) <- "queue"
rev.deque(x)
return(x)
}
|
/-
Copyright (c) 2020 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Oliver Nash
-/
import tactic.abel
namespace tactic
namespace interactive
/-- A tactic for simplifying identities in not-necessarily-commutative rings.
An example:
```lean
example {R : Type*} [ring R] (a b c : R) : a * (b + c + c - b) = 2*a*c :=
by noncomm_ring
```
-/
meta def noncomm_ring :=
`[simp only [-- Expand everything out.
add_mul, mul_add, sub_eq_add_neg,
-- Right associate all products.
mul_assoc,
-- Expand powers to numerals.
pow_bit0, pow_bit1, pow_one,
-- Replace multiplication by numerals with `gsmul`.
bit0_mul, mul_bit0, bit1_mul, mul_bit1, one_mul, mul_one, zero_mul, mul_zero,
-- Pull `gsmul n` out the front so `abel` can see them.
←mul_gsmul_assoc, ←mul_gsmul_left,
-- Pull out negations.
neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm] {fail_if_unchanged := ff};
abel]
add_tactic_doc
{ name := "noncomm_ring",
category := doc_category.tactic,
decl_names := [`tactic.interactive.noncomm_ring],
tags := ["arithmetic", "simplification", "decision procedure"] }
end interactive
end tactic
|
lemma path_connected_complement_countable: fixes S :: "'a::euclidean_space set" assumes "2 \<le> DIM('a)" "countable S" shows "path_connected(- S)"
|
-- -------------------------------------------------------------- [ Lens.idr ]
-- Description : Idris port of Control.Lens
-- Copyright : (c) Huw Campbell
-- --------------------------------------------------------------------- [ EOH ]
module Control.Lens.At
import Control.Lens.Setter
import Control.Lens.Types
import Control.Monad.Identity
import Data.Profunctor
import Data.List
%default total
public export
interface Ixed ( m : Type ) where
IxInd : Type
IxVal : Type
ix : IxInd -> { f : Type -> Type } -> Applicative f => LensLike' f m IxVal
public export
implementation {a : Type} -> Ixed (List a) where
IxInd = Nat
IxVal = a
ix k (Mor h) = Mor (\xs0 => go xs0 k)
where
go : List a -> Nat -> f (List a)
go Nil _ = pure Nil
go (a :: as) Z = (:: as) <$> (h a)
go (a :: as) (S n) = (a ::) <$> (go as n)
public export
implementation {a : Type} -> Ixed (Maybe a) where
IxInd = Unit
IxVal = a
ix _ (Mor f) = Mor (\g => case g of
(Just a) => Just <$> f a
Nothing => pure Nothing
)
public export
interface At m where
AtInd : Type
AtVal : Type
-- |
-- >>> Map.fromList [(1,"world")] ^.at 1
-- Just "world"
--
-- >>> at 1 ?~ "hello" $ Map.empty
-- fromList [(1,"hello")]
--
-- /Note:/ 'Map'-like containers form a reasonable instance, but not 'Array'-like ones, where
-- you cannot satisfy the 'Lens' laws.
at : AtInd -> { f : Type -> Type } -> Applicative f => LensLike' f m (Maybe AtVal)
public export
sans : At m => AtInd { m } -> m -> m
sans k m = m |> at k .~ Nothing
public export
implementation {a : Type} -> At (Maybe a) where
AtInd = Unit
AtVal = a
at () (Mor f) = (Mor f)
-- --------------------------------------------------------------------- [ EOF ]
|
module Thesis.BigStepSILR2 where
open import Data.Empty
open import Data.Unit.Base hiding (_≤_)
open import Data.Product
open import Relation.Binary.PropositionalEquality
open import Relation.Binary hiding (_⇒_)
open import Data.Nat -- using (ℕ; zero; suc; decTotalOrder; _<_; _≤_)
open import Data.Nat.Properties
open import Thesis.FunBigStepSILR2
-- Standard relational big-step semantics, with step-indexes matching a small-step semantics.
-- Protip: doing this on ANF terms would be much easier.
data _⊢_↓[_]_ {Γ} (ρ : ⟦ Γ ⟧Context) : ∀ {τ} → Term Γ τ → ℕ → Val τ → Set where
abs : ∀ {τ₁ τ₂} {t : Term (τ₁ • Γ) τ₂} →
ρ ⊢ abs t ↓[ 0 ] closure t ρ
app : ∀ n1 n2 n3 {Γ′ τ₁ τ₂ ρ′ v₂ v′} {t₁ : Term Γ (τ₁ ⇒ τ₂)} {t₂ : Term Γ τ₁} {t′ : Term (τ₁ • Γ′) τ₂} →
ρ ⊢ t₁ ↓[ n1 ] closure t′ ρ′ →
ρ ⊢ t₂ ↓[ n2 ] v₂ →
(v₂ • ρ′) ⊢ t′ ↓[ n3 ] v′ →
ρ ⊢ app t₁ t₂ ↓[ suc n1 + n2 + n3 ] v′
var : ∀ {τ} (x : Var Γ τ) →
ρ ⊢ var x ↓[ 0 ] (⟦ x ⟧Var ρ)
lit : ∀ n →
ρ ⊢ const (lit n) ↓[ 0 ] intV n
-- Silly lemmas for eval-dec-sound
module _ where
Done-inj : ∀ {τ} m n {v1 v2 : Val τ} → Done v1 m ≡ Done v2 n → m ≡ n
Done-inj _ _ refl = refl
lem1 : ∀ n d → d ≢ suc (n + d)
lem1 n d eq rewrite +-comm n d = m≢1+m+n d eq
subd : ∀ n d → n + d ≡ d → n ≡ 0
subd zero d eq = refl
subd (suc n) d eq = ⊥-elim (lem1 n d (sym eq))
comp∸ : ∀ a b → b ≤ a → suc a ∸ b ≡ suc (a ∸ b)
comp∸ a zero le = refl
comp∸ zero (suc b) ()
comp∸ (suc a) (suc b) (s≤s le) = comp∸ a b le
rearr∸ : ∀ a b c → c ≤ b → a + (b ∸ c) ≡ (a + b) ∸ c
rearr∸ a b zero c≤b = refl
rearr∸ a zero (suc c) ()
rearr∸ a (suc b) (suc c) (s≤s c≤b) rewrite +-suc a b = rearr∸ a b c c≤b
cancel∸ : ∀ a b → b ≤ a → a ∸ b + b ≡ a
cancel∸ a zero b≤a = +-identityʳ a
cancel∸ zero (suc b) ()
cancel∸ (suc a) (suc b) (s≤s b≤a) rewrite +-suc (a ∸ b) b = cong suc (cancel∸ a b b≤a)
lemR : ∀ {τ} n m {v1 v2 : Val τ} → Done v1 m ≡ Done v2 n → m ≡ n
lemR n .n refl = refl
lem2 : ∀ n n3 r → n3 ≤ n → n + n3 ≡ suc r → ∃ λ s → (n ≡ suc s)
lem2 zero .0 r z≤n ()
lem2 (suc n) n3 .(n + n3) le refl = n , refl
{-# TERMINATING #-}
eval-dec-sound : ∀ {Γ τ} → (t : Term Γ τ) → ∀ ρ v m n → eval t ρ m ≡ Done v n → ρ ⊢ t ↓[ m ∸ n ] v
eval-dec-sound (const (lit x)) ρ (intV v) m n eq with lemR n m eq
eval-dec-sound (const (lit x)) ρ (intV .x) m .m refl | refl rewrite n∸n≡0 m = lit x
eval-dec-sound (var x) ρ v m n eq with lemR n m eq
eval-dec-sound (var x) ρ .(⟦ x ⟧Var ρ) m .m refl | refl rewrite n∸n≡0 m = var x
eval-dec-sound (abs t) ρ v m n eq with lemR n m eq
eval-dec-sound (abs t) ρ .(closure t ρ) m .m refl | refl rewrite n∸n≡0 m = abs
eval-dec-sound (app s t) ρ v zero n ()
eval-dec-sound (app s t) ρ v (suc r) n eq with eval s ρ r | inspect (eval s ρ) r
eval-dec-sound (app s t) ρ v (suc r) n eq | (Done sv n1) | [ seq ] with eval t ρ n1 | inspect (eval t ρ) n1
eval-dec-sound (app s t) ρ v (suc r) n eq | (Done (closure st sρ) n1) | [ seq ] | (Done tv n2) | [ teq ] with eval st (tv • sρ) n2 | inspect (eval st (tv • sρ)) n2
eval-dec-sound (app s t) ρ .v (suc r) .n3 refl | (Done sv@(closure st sρ) n1) | [ seq ] | (Done tv n2) | [ teq ] | (Done v n3) | [ veq ] = body
where
n1≤r : n1 ≤ r
n1≤r = eval-dec s ρ sv r n1 seq
n2≤n1 : n2 ≤ n1
n2≤n1 = eval-dec t ρ tv n1 n2 teq
n3≤n2 : n3 ≤ n2
n3≤n2 = eval-dec st (tv • sρ) v n2 n3 veq
eval1 = eval-dec-sound s ρ sv r n1 seq
eval2 = eval-dec-sound t ρ tv n1 n2 teq
eval3 = eval-dec-sound st (tv • sρ) v n2 n3 veq
l1 : suc r ∸ n3 ≡ suc (r ∸ n3)
l1 = comp∸ r n3 (≤-trans n3≤n2 (≤-trans n2≤n1 n1≤r))
l2 : suc r ∸ n3 ≡ suc (((r ∸ n1) + (n1 ∸ n2)) + (n2 ∸ n3))
l2
rewrite rearr∸ (r ∸ n1) n1 n2 n2≤n1 | cancel∸ r n1 n1≤r
| rearr∸ (r ∸ n2) n2 n3 n3≤n2 | cancel∸ r n2 (≤-trans n2≤n1 n1≤r) = l1
foo : ρ ⊢ app s t ↓[ suc (r ∸ n1 + (n1 ∸ n2) + (n2 ∸ n3)) ] v
foo = app (r ∸ n1) (n1 ∸ n2) (n2 ∸ n3) {t₁ = s} {t₂ = t} {t′ = st} eval1 eval2 eval3
body : ρ ⊢ app s t ↓[ suc r ∸ n3 ] v
body rewrite l2 = foo
eval-dec-sound (app s t) ρ v (suc r) n () | (Done (closure st sρ) n1) | [ seq ] | (Done tv n2) | [ teq ] | Error | [ veq ]
eval-dec-sound (app s t) ρ v (suc r) n () | (Done (closure st sρ) n1) | [ seq ] | (Done tv n2) | [ teq ] | TimeOut | [ veq ]
eval-dec-sound (app s t) ρ v (suc r) n () | (Done sv n1) | [ seq ] | Error | [ teq ]
eval-dec-sound (app s t) ρ v (suc r) n () | (Done sv n1) | [ seq ] | TimeOut | [ teq ]
eval-dec-sound (app s t) ρ v (suc r) n () | Error | [ seq ]
eval-dec-sound (app s t) ρ v (suc r) n () | TimeOut | [ seq ]
-- ↦-sound : ∀ {Γ τ} ρ (x : Var Γ τ) →
-- ((Den.⟦ x ⟧Var) (⟦ ρ ⟧Context)) ≡ (⟦ (⟦ x ⟧Var) ρ ⟧Val)
-- ↦-sound (px • ρ) this = refl
-- ↦-sound (px • ρ) (that x) = ↦-sound ρ x
-- ↓-sound : ∀ {Γ τ ρ v} {t : Term Γ τ} →
-- ρ ⊢ t ↓ v →
-- ⟦ t ⟧Term ⟦ ρ ⟧Env ≡ ⟦ v ⟧Val
-- ↓-sound abs = refl
-- ↓-sound (app ↓₁ ↓₂ ↓′) rewrite ↓-sound ↓₁ | ↓-sound ↓₂ | ↓-sound ↓′ = refl
-- ↓-sound (var x) = ↦-sound _ x
-- ↓-sound (lit n) = refl
import Data.Integer as I
open I using (ℤ)
-- The extra "r" stands for "relational", because unlike relT and relV, rrelV
-- and rrelT are based on a *relational* big-step semantics.
mutual
rrelT : ∀ {τ Γ} (t1 : Term Γ τ) (t2 : Term Γ τ) (ρ1 : ⟦ Γ ⟧Context) (ρ2 : ⟦ Γ ⟧Context) → ℕ → Set
rrelT {τ} t1 t2 ρ1 ρ2 k =
(v1 : Val τ) →
∀ j (j<k : j < k) →
(ρ1⊢t1↓[j]v1 : ρ1 ⊢ t1 ↓[ j ] v1) →
Σ[ v2 ∈ Val τ ] Σ[ n2 ∈ ℕ ] ρ2 ⊢ t2 ↓[ n2 ] v2 × rrelV τ v1 v2 (k ∸ j)
rrelV : ∀ τ (v1 v2 : Val τ) → ℕ → Set
rrelV nat (intV v1) (intV v2) n = Σ[ dv ∈ ℤ ] dv I.+ (I.+ v1) ≡ (I.+ v2)
rrelV (σ ⇒ τ) (closure {Γ1} t1 ρ1) (closure {Γ2} t2 ρ2) n =
Σ (Γ1 ≡ Γ2) λ { refl →
∀ (k : ℕ) (k<n : k < n) v1 v2 →
(vv : rrelV σ v1 v2 k) →
rrelT t1 t2 (v1 • ρ1) (v2 • ρ2) k
}
rrelρ : ∀ Γ (ρ1 ρ2 : ⟦ Γ ⟧Context) → ℕ → Set
rrelρ ∅ ∅ ∅ n = ⊤
rrelρ (τ • Γ) (v1 • ρ1) (v2 • ρ2) n = rrelV τ v1 v2 n × rrelρ Γ ρ1 ρ2 n
⟦_⟧RelVar : ∀ {Γ τ n} (x : Var Γ τ) {ρ1 ρ2 : ⟦ Γ ⟧Context} →
rrelρ Γ ρ1 ρ2 n →
rrelV τ (⟦ x ⟧Var ρ1) (⟦ x ⟧Var ρ2) n
⟦ this ⟧RelVar {v1 • ρ1} {v2 • ρ2} (vv , ρρ) = vv
⟦ that x ⟧RelVar {v1 • ρ1} {v2 • ρ2} (vv , ρρ) = ⟦ x ⟧RelVar ρρ
rrelV-mono : ∀ m n → m ≤ n → ∀ τ v1 v2 → rrelV τ v1 v2 n → rrelV τ v1 v2 m
rrelV-mono m n m≤n nat (intV v1) (intV v2) vv = vv
rrelV-mono m n m≤n (σ ⇒ τ) (closure t1 ρ1) (closure t2 ρ2) (refl , ff) = refl , λ k k≤m → ff k (≤-trans k≤m m≤n)
rrelρ-mono : ∀ m n → m ≤ n → ∀ Γ ρ1 ρ2 → rrelρ Γ ρ1 ρ2 n → rrelρ Γ ρ1 ρ2 m
rrelρ-mono m n m≤n ∅ ∅ ∅ tt = tt
rrelρ-mono m n m≤n (τ • Γ) (v1 • ρ1) (v2 • ρ2) (vv , ρρ) = rrelV-mono m n m≤n _ v1 v2 vv , rrelρ-mono m n m≤n Γ ρ1 ρ2 ρρ
rfundamentalV : ∀ {Γ τ} (x : Var Γ τ) → (n : ℕ) → (ρ1 ρ2 : ⟦ Γ ⟧Context) (ρρ : rrelρ Γ ρ1 ρ2 n) → rrelT (var x) (var x) ρ1 ρ2 n
rfundamentalV x n ρ1 ρ2 ρρ .(⟦ x ⟧Var ρ1) .0 j<n (var .x) = ⟦ x ⟧Var ρ2 , 0 , (var x) , ⟦ x ⟧RelVar ρρ
bar : ∀ m {n o} → o ≤ n → m ≤ (m + n) ∸ o
bar m {n} {o} o≤n rewrite +-∸-assoc m o≤n = m≤m+n m (n ∸ o)
suc∸ : ∀ m n → n ≤ m → suc (m ∸ n) ≡ suc m ∸ n
suc∸ m zero z≤n = refl
suc∸ (suc m) (suc n) (s≤s n≤m) = suc∸ m n n≤m
suc∸suc : ∀ m n → n < m → suc (m ∸ suc n) ≡ m ∸ n
suc∸suc (suc m) zero (s≤s n<m) = refl
suc∸suc (suc m) (suc n) (s≤s n<m) = suc∸suc m n n<m
m≡m∸1+1 : ∀ m {n} → n < m → m ≡ suc (m ∸ 1)
m≡m∸1+1 (suc m) (s≤s n<m) = refl
m∸[n+1]<m : ∀ m n → n < m → m ∸ suc n < m
m∸[n+1]<m (suc m) zero (s≤s n<m) = s≤s ≤-refl
m∸[n+1]<m (suc m) (suc n) (s≤s n<m) rewrite sym (suc∸suc m n n<m) = ≤-step (m∸[n+1]<m m n n<m)
sub∸ : ∀ m n o → m + n ≤ o → n ≤ o ∸ m
sub∸ m n o n+m≤o rewrite +-comm m n | cong (_≤ o ∸ m) (sym (m+n∸n≡m n m)) = ∸-mono n+m≤o (≤-refl {m})
rfundamental : ∀ {Γ τ} (t : Term Γ τ) → (n : ℕ) → (ρ1 ρ2 : ⟦ Γ ⟧Context) (ρρ : rrelρ Γ ρ1 ρ2 n) → rrelT t t ρ1 ρ2 n
rfundamental (var x) n ρ1 ρ2 ρρ = rfundamentalV x n ρ1 ρ2 ρρ
rfundamental (const (lit x)) n ρ1 ρ2 ρρ .(intV x) .0 j<n (lit .x) = intV x , 0 , lit x , I.+ 0 , refl
rfundamental (abs t) n ρ1 ρ2 ρρ .(closure t ρ1) .0 j<n abs = closure t ρ2 , 0 , abs , refl , (λ k k<n v1 v2 vv v3 j j<k ρ1⊢t1↓[j]v1 → rfundamental t k (v1 • ρ1) (v2 • ρ2) (vv , rrelρ-mono k n (lt1 k<n) _ _ _ ρρ) v3 j j<k ρ1⊢t1↓[j]v1 )
rfundamental (app s t) n ρ1 ρ2 ρρ v1 .(suc (n1 + n2 + n3)) 1+n1+n2+n3<n (app n1 n2 n3 ρ1⊢t1↓[j]v1 ρ1⊢t1↓[j]v2 ρ1⊢t1↓[j]v3) = body
where
open ≤-Reasoning
n1≤sum : n1 ≤ n1 + n2 + n3
n1≤sum rewrite +-assoc n1 n2 n3 = m≤m+n n1 (n2 + n3)
n1<n : n1 < n
n1<n = ≤-trans (s≤s (≤-step n1≤sum)) 1+n1+n2+n3<n
n2≤sum : n2 ≤ n1 + n2 + n3
n2≤sum rewrite +-assoc n1 n2 n3 = ≤-steps {n2} {n2 + n3} n1 (m≤m+n n2 n3)
n2<n : n2 < n
n2<n = ≤-trans (s≤s (≤-step n2≤sum)) 1+n1+n2+n3<n
n1+n2<n : n1 + n2 < n
n1+n2<n = ≤-trans (s≤s (≤-step (m≤m+n (n1 + n2) n3))) 1+n1+n2+n3<n
n2+n1<n : n2 + n1 < n
n2+n1<n rewrite +-comm n2 n1 = n1+n2<n
n1+n3≤sum : n1 + n3 ≤ (n1 + n2) + n3
n1+n3≤sum = m≤m+n n1 n2 +-mono (≤-refl {n3})
foo : suc n2 ≡ suc (n1 + n2 + n3) ∸ (n1 + n3)
foo rewrite cong suc (sym (m+n∸n≡m n2 (n1 + n3))) | sym (+-assoc n2 n1 n3) | +-comm n2 n1 = suc∸ (n1 + n2 + n3) (n1 + n3) n1+n3≤sum
n2<n∸n1 : n2 < n ∸ n1
n2<n∸n1 rewrite foo = ∸-mono {suc (n1 + n2 + n3)} {n} {n1 + n3} {n1} (lt1 1+n1+n2+n3<n) (m≤m+n n1 n3)
n-[1+n1+n2]<n-n1 : n ∸ n1 ∸ suc n2 < n ∸ n1
n-[1+n1+n2]<n-n1 = m∸[n+1]<m (n ∸ n1) n2 n2<n∸n1
n-[1+n1+n2]<n-n2 : n ∸ n1 ∸ suc n2 < n ∸ n2
n-[1+n1+n2]<n-n2 rewrite ∸-+-assoc n n1 (suc n2) | +-suc n1 n2 | +-comm n1 n2 | suc∸suc n (n2 + n1) n2+n1<n | sym (∸-+-assoc n n2 n1) = n∸m≤n n1 (n ∸ n2)
baz : n1 + suc (n2 + suc n3) ≤ n
baz rewrite +-suc n2 n3 | +-suc n1 (suc (n2 + n3)) | +-suc n1 (n2 + n3) | +-assoc n1 n2 n3 = 1+n1+n2+n3<n
n3<n-n1-[1+n2] : n3 < n ∸ n1 ∸ suc n2
n3<n-n1-[1+n2] = sub∸ (suc n2) (suc n3) (n ∸ n1) (sub∸ n1 (suc (n2 + suc n3)) n baz)
l1 : suc (n1 + n2 + n3) ≡ n1 + suc n2 + n3
l1 = cong (_+ n3) (sym (+-suc n1 n2))
n-1+sum≡alt : n ∸ suc (n1 + n2 + n3) ≡ n ∸ n1 ∸ suc n2 ∸ n3
n-1+sum≡alt rewrite l1 | sym (∸-+-assoc n (n1 + suc n2) n3) | sym (∸-+-assoc n n1 (suc n2)) = refl
body : Σ[ v2 ∈ Val _ ] Σ[ tn ∈ ℕ ] ρ2 ⊢ app s t ↓[ tn ] v2 × rrelV _ v1 v2 (n ∸ suc (n1 + n2 + n3))
body with rfundamental s n ρ1 ρ2 ρρ _ n1 n1<n ρ1⊢t1↓[j]v1 | rfundamental t n ρ1 ρ2 ρρ _ n2 n2<n ρ1⊢t1↓[j]v2
... | sv2@(closure st2 sρ2) , sn2 , ρ2⊢s↓ , refl , sv1v2 | tv2 , tn2 , ρ2⊢t↓ , tv1v2 with sv1v2 (n ∸ n1 ∸ suc n2) n-[1+n1+n2]<n-n1 _ tv2 (rrelV-mono (n ∸ n1 ∸ suc n2) (n ∸ n2) (lt1 n-[1+n1+n2]<n-n2) _ _ tv2 tv1v2) v1 n3 n3<n-n1-[1+n2] ρ1⊢t1↓[j]v3
... | v2 , stn , ρ2⊢st2↓ , vv rewrite n-1+sum≡alt = v2 , suc (sn2 + tn2 + stn) , app _ _ _ ρ2⊢s↓ ρ2⊢t↓ ρ2⊢st2↓ , vv
mutual
rrelT3 : ∀ {τ Γ ΔΓ} (t1 : Term Γ τ) (dt : Term ΔΓ (Δτ τ)) (t2 : Term Γ τ) (ρ1 : ⟦ Γ ⟧Context) (dρ : ⟦ ΔΓ ⟧Context) (ρ2 : ⟦ Γ ⟧Context) → ℕ → Set
rrelT3 {τ} t1 dt t2 ρ1 dρ ρ2 k =
(v1 v2 : Val τ) →
∀ j n2 (j<k : j < k) →
(ρ1⊢t1↓[j]v1 : ρ1 ⊢ t1 ↓[ j ] v1) →
(ρ2⊢t2↓[n2]v2 : ρ2 ⊢ t2 ↓[ n2 ] v2) →
Σ[ dv ∈ Val (Δτ τ) ] Σ[ dn ∈ ℕ ]
dρ ⊢ dt ↓[ dn ] dv ×
rrelV3 τ v1 dv v2 (k ∸ j)
rrelV3 : ∀ τ (v1 : Val τ) (dv : Val (Δτ τ)) (v2 : Val τ) → ℕ → Set
rrelV3 nat (intV v1) (intV dv) (intV v2) n = dv + v1 ≡ v2
-- XXX What we want for rrelV3:
-- rrelV3 (σ ⇒ τ) (closure {Γ1} t1 ρ1) (dclosure dt dρ) (closure {Γ2} t2 ρ2) n =
-- Σ (Γ1 ≡ Γ2) λ { refl →
-- ∀ (k : ℕ) (k<n : k < n) v1 dv v2 →
-- rrelV3 σ v1 dv v2 k →
-- rrelT3
-- t1
-- dt
-- t2
-- (v1 • ρ1)
-- (dv • v1 • dρ)
-- (v2 • ρ2) k
-- }
-- However, we don't have separate change values, so we write:
rrelV3 (σ ⇒ τ) (closure {Γ1} t1 ρ1) (closure dt' dρ) (closure {Γ2} t2 ρ2) n =
-- Require a proof that the two contexts match:
Σ (Γ1 ≡ Γ2) λ { refl →
∀ (k : ℕ) (k<n : k < n) v1 dv v2 →
rrelV3 σ v1 dv v2 k →
rrelT3
t1
-- XXX The next expression is wrong.
-- rrelV3 should require dv to be a change closure,
-- (λ x dx . dt , dρ) or (dclosure dt dρ).
-- Then, here we could write as conclusion.
-- rrelT3 t1 dt t2 (v1 • ρ1) (dv • v1 • dρ) (v2 • ρ2) k
-- Instead, with this syntax I can just match dv as a normal closure,
-- closure dt' dρ or (λ x . dt', dρ), where we hope that dt' evaluates
-- to λ dx. dt. So, instead of writing dt, I must write dt' dx where
-- dx is a newly bound variable (hence, var this), and dt' must be
-- weakened once. Hence, we write instead:
(app (weaken (drop (Δτ σ) • ≼-refl) dt') (var this))
t2
(v1 • ρ1)
(dv • v1 • dρ)
(v2 • ρ2)
k
}
ΔΓ : Context → Context
ΔΓ ∅ = ∅
ΔΓ (τ • Γ) = Δτ τ • ΔΓ Γ
rrelρ3 : ∀ Γ (ρ1 : ⟦ Γ ⟧Context) (dρ : ⟦ ΔΓ Γ ⟧Context) (ρ2 : ⟦ Γ ⟧Context) → ℕ → Set
rrelρ3 ∅ ∅ ∅ ∅ n = ⊤
rrelρ3 (τ • Γ) (v1 • ρ1) (dv • dρ) (v2 • ρ2) n = rrelV3 τ v1 dv v2 n × rrelρ3 Γ ρ1 dρ ρ2 n
derive-var : ∀ {Γ τ} → Var Γ τ → Var (ΔΓ Γ) (Δτ τ)
derive-var this = this
derive-var (that x) = that (derive-var x)
⟦_⟧RelVar3 : ∀ {Γ τ n} (x : Var Γ τ)
{ρ1 : ⟦ Γ ⟧Context} {dρ : ⟦ ΔΓ Γ ⟧Context} {ρ2 : ⟦ Γ ⟧Context} →
rrelρ3 Γ ρ1 dρ ρ2 n →
rrelV3 τ (⟦ x ⟧Var ρ1) (⟦ derive-var x ⟧Var dρ) (⟦ x ⟧Var ρ2) n
⟦ this ⟧RelVar3 {v1 • ρ1} {dv • dρ} {v2 • ρ2} (vv , ρρ) = vv
⟦ that x ⟧RelVar3 {v1 • ρ1} {dv • dρ} {v2 • ρ2} (vv , ρρ) = ⟦ x ⟧RelVar3 ρρ
rfundamentalV3 : ∀ {Γ τ} (x : Var Γ τ) → (n : ℕ) → (ρ1 : ⟦ Γ ⟧Context) (dρ : ⟦ ΔΓ Γ ⟧Context) (ρ2 : ⟦ Γ ⟧Context) (ρρ : rrelρ3 Γ ρ1 dρ ρ2 n) → rrelT3 (var x) (var (derive-var x)) (var x) ρ1 dρ ρ2 n
rfundamentalV3 x n ρ1 dρ ρ2 ρρ .(⟦ x ⟧Var ρ1) .(⟦ x ⟧Var ρ2) .0 .0 j<n (var .x) (var .x) = ⟦ derive-var x ⟧Var dρ , 0 , (var (derive-var x)) , ⟦ x ⟧RelVar3 ρρ
|
/-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Johannes Hölzl, Reid Barton, Sean Leather
! This file was ported from Lean 3 source module category_theory.concrete_category.bundled
! leanprover-community/mathlib commit 448144f7ae193a8990cb7473c9e9a01990f64ac7
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Tactic.Lint.Default
/-!
# Bundled types
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
`bundled c` provides a uniform structure for bundling a type equipped with a type class.
We provide `category` instances for these in `category_theory/unbundled_hom.lean`
(for categories with unbundled homs, e.g. topological spaces)
and in `category_theory/bundled_hom.lean` (for categories with bundled homs, e.g. monoids).
-/
universe u v
namespace CategoryTheory
variable {c d : Type u → Type v} {α : Type u}
#print CategoryTheory.Bundled /-
/-- `bundled` is a type bundled with a type class instance for that type. Only
the type class is exposed as a parameter. -/
@[nolint has_nonempty_instance]
structure Bundled (c : Type u → Type v) : Type max (u + 1) v where
α : Type u
str : c α := by infer_instance
#align category_theory.bundled CategoryTheory.Bundled
-/
namespace Bundled
#print CategoryTheory.Bundled.of /-
-- Usually explicit instances will provide their own version of this, e.g. `Mon.of` and `Top.of`.
/-- A generic function for lifting a type equipped with an instance to a bundled object. -/
def of {c : Type u → Type v} (α : Type u) [str : c α] : Bundled c :=
⟨α, str⟩
#align category_theory.bundled.of CategoryTheory.Bundled.of
-/
instance : CoeSort (Bundled c) (Type u) :=
⟨Bundled.α⟩
#print CategoryTheory.Bundled.coe_mk /-
@[simp]
theorem coe_mk (α) (str) : (@Bundled.mk c α str : Type u) = α :=
rfl
#align category_theory.bundled.coe_mk CategoryTheory.Bundled.coe_mk
-/
#print CategoryTheory.Bundled.map /-
/-
`bundled.map` is reducible so that, if we define a category
def Ring : Type (u+1) := induced_category SemiRing (bundled.map @ring.to_semiring)
instance search is able to "see" that a morphism R ⟶ S in Ring is really
a (semi)ring homomorphism from R.α to S.α, and not merely from
`(bundled.map @ring.to_semiring R).α` to `(bundled.map @ring.to_semiring S).α`.
-/
/-- Map over the bundled structure -/
@[reducible]
def map (f : ∀ {α}, c α → d α) (b : Bundled c) : Bundled d :=
⟨b, f b.str⟩
#align category_theory.bundled.map CategoryTheory.Bundled.map
-/
end Bundled
end CategoryTheory
|
theory Proofs5
imports Requirements VCTheoryLemmas
begin
definition inv5 where "inv5 s \<equiv> R5 s \<and> extraInv s"
thm extraInv_def
lemma minimalOpened_R5: "toEnvP s1 \<and> toEnvP s2 \<and> toEnvP s0 \<and> substate s1 s2 \<and> substate s2 s0 \<and> substate s0 s \<and>
toEnvNum s1 s2 = 1 \<and> toEnvNum s2 s0 < 9 \<and> getPstate s0 Controller' = Controller'minimalOpened' \<and>
ltime s0 Controller' = 10 \<and>
(\<forall>s1. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Init'init' = Controller'minimalOpened' \<longrightarrow> ltime s1 Init'init' \<le> 10) \<and>
(\<forall>s2. toEnvP s2 \<and> substate s2 s \<and> getPstate s2 Init'init' = Controller'minimalOpened' \<longrightarrow>
(\<forall>s1. toEnvP s1 \<and> substate s1 s2 \<and> toEnvNum s1 s2 < ltime s2 Init'init' \<longrightarrow>
getPstate s1 Init'init' = Controller'minimalOpened')) \<and>
(\<forall>s1. toEnvP s1 \<and>
substate s1 s \<and> (getPstate s1 Init'init' = Controller'isOpened' \<or> getPstate s1 Init'init' = Controller'minimalOpened') \<longrightarrow>
getVarBool s1 Controller'minimalOpened')
\<longrightarrow> \<not> (\<not> getVarBool s1 open' \<and> getVarBool s2 open')"
using substate_trans
by (smt (verit, ccfv_SIG) BitM_inc_eq eval_nat_numeral(2) inc.simps(2) nat_add_left_cancel_less plus_1_eq_Suc toEnvNum3)
lemma isOpened_timeout_R5: "toEnvP s1 \<and> toEnvP s2 \<and> toEnvP s0 \<and> substate s1 s2 \<and> substate s2 s0 \<and> substate s0 s \<and>
toEnvNum s1 s2 = 1 \<and> toEnvNum s2 s0 < 9 \<and> getPstate s0 Controller' = Controller'isOpened' \<and>
ltime s0 Controller' = 90 \<and>
(\<forall>s1. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Init'init' = Controller'isOpened' \<longrightarrow> ltime s1 Init'init' \<le> 90) \<and>
(\<forall>s3. toEnvP s3 \<and> substate s3 s \<and> getPstate s3 Init'init' = Controller'isOpened' \<longrightarrow>
(\<forall>s1. toEnvP s1 \<and> substate s1 s3 \<and> toEnvNum s1 s3 < ltime s3 Init'init' \<longrightarrow> getPstate s1 Init'init' = Controller'isOpened') \<and>
(\<forall>s2. toEnvP s2 \<and> substate s2 s3 \<and> toEnvNum s2 s3 + 1 < ltime s3 Init'init' \<longrightarrow> \<not> getVarBool s2 Init')) \<and>
(\<forall>s1. toEnvP s1 \<and>
substate s1 s \<and> (getPstate s1 Init'init' = Controller'isOpened' \<or> getPstate s1 Init'init' = Controller'minimalOpened') \<longrightarrow>
getVarBool s1 Controller'minimalOpened')
\<longrightarrow> \<not>(\<not> getVarBool s1 open' \<and> getVarBool s2 open')"
apply(rule impI)
apply(rule cut_rl[of "toEnvNum s1 s0 < ltime s0 Controller'"])
using substate_trans
apply meson
using toEnvNum3 by auto
lemma isOpened_R5: "toEnvP s1 \<and> toEnvP s2 \<and> toEnvP s0 \<and> substate s1 s2 \<and> substate s2 s0 \<and> substate s0 s \<and>
toEnvNum s1 s2 = 1 \<and> toEnvNum s2 s0 < 9 \<and> getPstate s0 Controller' = Controller'isOpened' \<and>
(\<forall>s1. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Init'init' = Controller'minimalOpened' \<longrightarrow> ltime s1 Init'init' \<le> 10) \<and>
(\<forall>s2. toEnvP s2 \<and> substate s2 s \<and> getPstate s2 Init'init' = Controller'minimalOpened' \<longrightarrow>
(\<forall>s1. toEnvP s1 \<and> substate s1 s2 \<and> toEnvNum s1 s2 < ltime s2 Init'init' \<longrightarrow>
getPstate s1 Init'init' = Controller'minimalOpened')) \<and>
(\<forall>s1. toEnvP s1 \<and>
substate s1 s \<and> (getPstate s1 Init'init' = Controller'isOpened' \<or> getPstate s1 Init'init' = Controller'minimalOpened') \<longrightarrow>
getVarBool s1 Controller'minimalOpened') \<and>
(\<forall>s1. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Init'init' = Controller'isOpened' \<longrightarrow> ltime s1 Init'init' \<le> 90) \<and>
(\<forall>s1. toEnvP s1 \<and> substate s1 s \<and> getPstate s1 Init'init' = Controller'isOpened' \<longrightarrow>
(\<exists>s2 s3.
toEnvP s2 \<and>
toEnvP s3 \<and>
substate s2 s3 \<and>
substate s3 s1 \<and>
toEnvNum s2 s3 = 1 \<and>
toEnvNum s2 s1 = ltime s1 Init'init' \<and>
getPstate s2 Init'init' = Controller'minimalOpened' \<and>
ltime s2 Init'init' = 10 \<and> \<not> getVarBool s3 EntranceController'isOpened')) \<and>
(\<forall>s3. toEnvP s3 \<and> substate s3 s \<and> getPstate s3 Init'init' = Controller'isOpened' \<longrightarrow>
(\<forall>s1. toEnvP s1 \<and> substate s1 s3 \<and> toEnvNum s1 s3 < ltime s3 Init'init' \<longrightarrow> getPstate s1 Init'init' = Controller'isOpened') \<and>
(\<forall>s2. toEnvP s2 \<and> substate s2 s3 \<and> toEnvNum s2 s3 + 1 < ltime s3 Init'init' \<longrightarrow> \<not> getVarBool s2 Init'))
\<longrightarrow> \<not> (\<not> getVarBool s1 open' \<and> getVarBool s2 open')"
apply(rule impI)
apply(cases "toEnvNum s1 s0 < ltime s0 Controller'")
using substate_trans
apply meson
apply(rule exE[of " (\<lambda> s2. \<exists> s3.
toEnvP s2 \<and>
toEnvP s3 \<and>
substate s2 s3 \<and>
substate s3 s0 \<and>
toEnvNum s2 s3 = 1 \<and>
toEnvNum s2 s0 = ltime s0 Init'init' \<and>
getPstate s2 Init'init' = Controller'minimalOpened' \<and> ltime s2 Init'init' = 10 \<and> \<not> getVarBool s3 EntranceController'isOpened')"])
apply blast
apply(drule exE)
prefer 2
apply assumption
subgoal for s3 s4
apply(rule cut_rl[of "substate s3 s0"])
apply(cases "substate s2 s3")
apply(rule impE[OF minimalOpened_R5[of s1 s2 s3 s]])
using substate_trans toEnvNum3
apply (smt (verit) leD le_neq_implies_less le_trans less_or_eq_imp_le toEnvNum_substate1)
apply assumption
apply(rule cut_rl[of "s1=s3"])
using substate_trans
apply meson
apply(rule cut_rl[of "toEnvNum s1 s0 = toEnvNum s3 s0"])
using toEnvNum_eq_imp_eq2 substate_trans
apply meson
apply(rule le_antisym)
apply(rule cut_rl[of "substate s3 s2 \<and> s2 \<noteq> s3"])
using toEnvNum_substate2 toEnvNum_eq_imp_eq2 toEnvNum3[of s1 s2 s0]
apply (metis Suc_leI order.order_iff_strict plus_1_eq_Suc)
using substate_linear substate_refl
apply meson
apply arith
using substate_trans by meson
done
theorem proof_5_1: "VC1 inv5 s0"
apply(unfold VC1_def inv5_def R5_def extraInv_def)
by auto
theorem proof_5_2: "VC2 R5 env s0 PdOut_value paid_value opened_value"
apply(unfold VC2_def)
apply simp
apply(unfold R5_def)
apply(rule impI)
apply(rule conjI)
apply simp
subgoal premises vc_prems
apply((rule allI)+)
apply(rule impI)
apply(simp split: if_splits)
using vc_prems
by (metis One_nat_def)
done
theorem proof_5_500: "VC500 R5 env s0 PdOut_value paid_value opened_value"
apply(unfold VC500_def)
apply simp
apply(unfold R5_def)
apply(rule impI)
apply(rule conjI)
apply simp
subgoal premises vc_prems
apply((rule allI)+)
apply(rule impI)
apply(simp split: if_splits)
subgoal for s1 s2
apply(rule cut_rl[of "toEnvNum s2 s0 <10"])
using vc_prems substate_refl apply(metis One_nat_def)
by simp
using vc_prems by(metis One_nat_def)
done
end
|
function [F,h,x] = sedumi2yalmip(At,b,c,K)
nvars = length(b);
x = sdpvar(nvars,1);
if size(At,2)~=length(b)
At = At';
end
F = ([]);
top = 1;
if isvalidfield(K,'f')
X = c(top:top+K.f-1)-At(top:top+K.f-1,:)*x;
F = F + (X(:) == 0);
top = top + K.f;
end
if isvalidfield(K,'l')
X = c(top:top+K.l-1)-At(top:top+K.l-1,:)*x;
F = F + (X(:)>=0);
top = top + K.l;
end
if isvalidfield(K,'q')
for i = 1:length(K.q)
X = c(top:top+K.q(i)-1)-At(top:top+K.q(i)-1,:)*x;
F = F + (cone(X(2:end),X(1)));
top = top + K.q(i);
end
end
if isvalidfield(K,'r')
for i = 1:length(K.r)
X = c(top:top+K.r(i)-1)-At(top:top+K.r(i)-1,:)*x;
F = F + (rcone(X(3:end),X(2),X(1)));
top = top + K.r(i);
end
end
if isvalidfield(K,'s')
for i = 1:length(K.s)
[ix,iy,iv] = find([c(top:top+K.s(i)^2-1) At(top:top+K.s(i)^2-1,:)]);
off = (ix-1)/(K.s(i)+1);
if all(off == round(off))
X = c(top:top+K.s(i)^2-1)-At(top:top+K.s(i)^2-1,:)*x;
if isa(X,'sdpvar')
F = F + (diag(reshape(X,K.s(i),K.s(i))) >= 0);
else
X
i
'silly data!'
end
top = top + K.s(i)^2;
else
X = c(top:top+K.s(i)^2-1)-At(top:top+K.s(i)^2-1,:)*x;
X = reshape(X,K.s(i),K.s(i));
X = (X+X')/2;
F = F + (X >= 0);
top = top + K.s(i)^2;
end
end
end
h = -b'*x;
function ok = isvalidfield(K,fld)
ok = 0;
if isfield(K,fld)
s = getfield(K,fld);
if prod(size(s))>0
if s(1)>0
ok = 1;
end
end
end
|
-- p q r s are used in all the examples so they are defined only here
variables p q r s : Prop
-- Conjunction
-- Prove p, q -> p ∧ q
example (hp : p) (hq : q): p ∧ q := and.intro hp hq
-- Prove p ∧ q -> q
example (h : p ∧ q) : p := and.elim_left h
-- Prove p ∧ q -> p
example (h : p ∧ q) : q := and.elim_right h
-- Some examples of type assignment
variables (h : p) (i : q)
#check and.elim_left ⟨h, i⟩
#reduce and.elim_left ⟨h, i⟩
#check and.elim_right ⟨h, i⟩
#reduce and.elim_right ⟨h, i⟩
#check (⟨h, i⟩ : p ∧ q)
#reduce (⟨h, i⟩ : p ∧ q)
-- Prove q ∧ p → p ∧ q
example (h : p ∧ q) : q ∧ p :=
and.intro (and.elim_right h) (and.elim_left h)
-- Lean allows us to use anonymous constructor notation ⟨arg1, arg2, ...⟩
-- In situations like these, when the relevant type is an inductive type and can be inferred from the context.
-- In particular, we can often write ⟨hp, hq⟩ instead of and.intro hp hq:
example (h : p ∧ q) : q ∧ p :=
⟨and.elim_right h, and.elim_left h⟩
-- More examples of using the constructor notation
example (h : p ∧ q) : q ∧ p ∧ q:=
⟨h.right, ⟨h.left, h.right⟩⟩
example (h : p ∧ q) : q ∧ p ∧ q:=
⟨h.right, h.left, h.right⟩
-- Disjunction
-- ∨ introduction left
example (hp : p): p ∨ q := or.intro_left q hp
-- ∨ introduction right
example (hq : q): p ∨ q := or.intro_right p hq
-- Prove p ∨ p → p
example (h: p ∨ p): p :=
or.elim h
(assume hpr : p, show p, from hpr)
(assume hpl : p, show p, from hpl)
-- Prove p ∨ p → p, simplified notation
example (h: p ∨ p): p :=
or.elim h
(assume hpr : p, hpr)
(assume hpl : p, hpl)
-- Prove p ∨ q, p → r, q -> r, -> r
example (h : p ∨ q) (i : p → r) (j : q -> r) : r :=
or.elim h
(assume hp : p, show r, from i hp)
(assume hq : q, show r, from j hq)
-- Prove p ∨ q → q ∨ p
example (h : p ∨ q) : q ∨ p :=
or.elim h
(assume hp : p, show q ∨ p, from or.intro_right q hp)
(assume hq : q, show q ∨ p, from or.intro_left p hq)
-- Modus tollens, deriving a contradiction from p to obtain false.
-- Everything follows from false, in this case ¬p
-- order of propositions matters when using absurd
example (hpq : p → q) (hnq : ¬q) : ¬p :=
assume hp : p, show false, from hnq (hpq hp)
-- Equivalent to the previous one
example (hpq : p → q) (hnq : ¬q) : ¬p :=
assume hp : p, show false, from false.elim (hnq (hpq hp))
-- Equivalent to the previous one
example (hpq : p → q) (hnq : ¬q) : ¬p :=
assume hp : p, show false, from (hnq (hpq hp))
-- More examples of false and absurd use
example (hp : p) (hnp : ¬p) : q := false.elim (hnp hp)
-- order of propositions matters when using absurd
example (hp : p) (hnp : ¬p) : q := absurd hp hnp
-- Prove ¬p → q → (q → p) → r, premise ¬p must be added
example (hnp : ¬p) (hq : q) (hqp : q → p): r :=
false.elim (hnp (hqp hq))
-- equivalent proove as the above
example (hnp : ¬p) (hq : q) (hqp : q → p): r :=
absurd (hqp hq) hnp
-- Other variant from the above
-- Prove ¬p → q → (q → p) → r, premise ¬p must be added
example (hnp : ¬ p) (hnpq : ¬p → q) (hqp : q → p): r :=
absurd (hqp (hnpq hnp)) hnp
example (hnp : ¬ p) (hnpq : ¬p → q) (hqp : q → p): r :=
false.elim (hnp (hqp (hnpq hnp)))
-- Prove p ∧ q ↔ q ∧ p
example : (p ∧ q) ↔ (q ∧ p) :=
iff.intro
(assume h : p ∧ q,
show q ∧ p,
from and.intro (and.elim_right h) (and.elim_left h))
(assume h : q ∧ p,
show p ∧ q,
from and.intro (and.elim_right h) (and.elim_left h))
-- Derive q ∧ p from p ∧ q
example (h : p ∧ q) : (q ∧ p) :=
and.intro (and.elim_right h) (and.elim_left h)
-- Define a theorem and use the anomimous constructor to prove p ∧ q ↔ q ∧ p
theorem and_swap : p ∧ q ↔ q ∧ p :=
⟨ λ h, ⟨h.right, h.left⟩, λ h, ⟨h.right, h.left⟩ ⟩
-- Prove, using and_swap theorem that p ∧ q → q ∧ p
example (h : p ∧ q) : q ∧ p := (and_swap p q).mp h
-- Introducing auxiliary subgoals with `have`
example (h : p ∧ q) : q ∧ p :=
have hp : p, from and.left h,
have hq : q, from and.right h,
show q ∧ p, from and.intro hq hp
-- Introducing auxiliary subgoals with `suffices`
example (h : p ∧ q) : q ∧ p :=
have hp : p, from and.left h,
suffices hq : q, from and.intro hq hp,
show q, from and.right h
-- Classical logic
-- Prove double negation
-- To use `em` we can invoke it using classical namespace like so: `classical.em`
-- or import the classical module with 'open classical' and just use 'em' directly,
-- no need to prefix it with namespace name
theorem dne {p : Prop} (h : ¬¬p) : p :=
or.elim (classical.em p)
(assume hp : p, show p, from hp)
(assume hnp : ¬p, show p, from absurd hnp h)
-- Prove double negation, p is defined at the top of the file as p : Prop,
-- so no need to add {p : Prop} to the premises
example (h : ¬¬p) : p :=
or.elim (classical.em p)
(assume hp : p, show p, from hp)
(assume hnp : ¬p, show p, from absurd hnp h)
-- Proof by cases
example (h : ¬¬p) : p :=
classical.by_cases
(assume h1 : p, h1)
(assume h1 : ¬p, absurd h1 h)
-- Proof by contradiction
example (h : ¬¬p) : p :=
classical.by_contradiction
(assume h1 : ¬p, absurd h1 h)
example (h : ¬¬p) : p :=
classical.by_contradiction
(assume h1 : ¬p, show false, from h h1)
-- Prove ¬(p ∧ q) → ¬p ∨ ¬q
example (h : ¬(p ∧ q)) : ¬p ∨ ¬q :=
or.elim (classical.em p)
(assume hp : p,
or.inr (show ¬q, from
assume hq : q,
h ⟨hp, hq⟩))
(assume hnp : ¬p, show ¬p ∨ ¬q, from or.inl hnp)
-- Prove p ∧ q → (p → q) :=
example : p ∧ q → (p → q) :=
assume hpq : p ∧ q,
assume hp : p, show q, from and.elim_right hpq
-- Prove p → q → (p ∧ q) :=
example : p → q → (p ∧ q) :=
assume hp : p,
assume hq : q, show p ∧ q, from and.intro hp hq
-- 3.6. Examples of Propositional Validities
-- commutativity of ∧ and ∨
-- Prove p ∨ q ↔ q ∨ p
example : p ∨ q ↔ q ∨ p :=
iff.intro
(assume h : p ∨ q, show q ∨ p,
from or.elim h
(assume hp : p, show q ∨ p, from or.intro_right q hp)
(assume hq : q, show q ∨ p, from or.intro_left p hq))
(assume h : q ∨ p, show p ∨ q,
from or.elim h
(assume hq : q, show p ∨ q, from or.intro_right p hq)
(assume hp : p, show p ∨ q, from or.intro_left q hp))
-- Associativity of ∧ and ∨ --
-- Prove (p ∧ q) ∧ r ↔ p ∧ (q ∧ r)
example : (p ∧ q) ∧ r ↔ p ∧ (q ∧ r) :=
iff.intro
(assume hpqr : (p ∧ q) ∧ r, show p ∧ (q ∧ r), from
⟨hpqr.left.left, ⟨hpqr.left.right, hpqr.right⟩⟩)
(assume hpqr : p ∧ (q ∧ r), show (p ∧ q) ∧ r, from
⟨⟨hpqr.left, hpqr.right.left⟩, hpqr.right.right⟩)
-- Prove (p ∨ q) ∨ r ↔ p ∨ (q ∨ r)
example : (p ∨ q) ∨ r ↔ p ∨ (q ∨ r) :=
iff.intro
(assume hpqr : (p ∨ q) ∨ r, show p ∨ (q ∨ r), from
or.elim hpqr
(assume hpq : p ∨ q, show p ∨ (q ∨ r), from
or.elim hpq
(assume hp : p, show p ∨ (q ∨ r), from or.inl hp)
(assume hq : q, show p ∨ (q ∨ r), from or.inr (or.inl hq)))
(assume hr : r, show p ∨ (q ∨ r), from or.inr (or.inr hr)))
(assume hpqr : p ∨ (q ∨ r), show (p ∨ q) ∨ r, from
or.elim hpqr
(assume hp : p, show (p ∨ q) ∨ r, from or.inl (or.inl hp))
(assume hqr : q ∨ r, show (p ∨ q) ∨ r, from or.elim hqr
(assume hq: q, show (p ∨ q) ∨ r, from or.inl (or.inr hq ))
(assume hr : r, show (p ∨ q) ∨ r, from or.inr hr)))
-- Distributivity --
-- Prove p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r)
example : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) :=
iff.intro
(assume h : p ∧ (q ∨ r),
have hp : p, from h.left,
or.elim (h.right)
(assume hq : q,
show (p ∧ q) ∨ (p ∧ r), from or.inl ⟨hp, hq⟩)
(assume hr : r,
show (p ∧ q) ∨ (p ∧ r), from or.inr ⟨hp, hr⟩))
(assume h : (p ∧ q) ∨ (p ∧ r),
or.elim h
(assume hpq : (p ∧ q),
show p ∧ (q ∨ r), from and.intro hpq.left (or.inl hpq.right))
(assume hpr : (p ∧ r),
show p ∧ (q ∨ r), from and.intro hpr.left (or.inr hpr.right)))
-- Prove p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (p ∨ r) := sorry
example : p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (p ∨ r) :=
iff.intro
(assume h: p ∨ (q ∧ r),
show (p ∨ q) ∧ (p ∨ r),
from or.elim h
(assume hp: p, show (p ∨ q) ∧ (p ∨ r), from ⟨or.inl hp, or.inl hp⟩)
(assume hqr: (q ∧ r), show (p ∨ q) ∧ (p ∨ r), from ⟨or.inr hqr.left, or.inr hqr.right⟩))
(assume h: (p ∨ q) ∧ (p ∨ r),
show p ∨ (q ∧ r),
from or.elim (h.left)
(assume hp : p, show p ∨ (q ∧ r), from or.inl hp)
(assume hq : q, show p ∨ (q ∧ r), from or.elim h.right
(assume hp : p, show p ∨ (q ∧ r), from or.inl hp)
(assume hr : r, show p ∨ (q ∧ r), from or.inr ⟨hq, hr⟩)
))
-- Other properties
-- Prove (p → (q → r)) ↔ (p ∧ q → r)
example : (p → (q → r)) ↔ (p ∧ q → r) :=
iff.intro
(assume hpqr : p → (q → r), show p ∧ q → r, from
(assume hpq : p ∧ q,
have hp : p, from hpq.left,
have hq : q, from hpq.right,
show r, from (hpqr hp) hq))
(assume hpqr : (p ∧ q → r), show (p → (q → r)), from
(assume hp : p, show q → r, from
(assume hq, show r, from (hpqr ⟨hp, hq⟩))))
-- Prove ((p ∨ q) → r) ↔ (p → r) ∧ (q → r)
example : ((p ∨ q) → r) ↔ (p → r) ∧ (q → r) :=
iff.intro
(assume hpqr : (p ∨ q) → r, show (p → r) ∧ (q → r), from
⟨(assume hp : p, show r, from hpqr(or.inl hp)),
(assume hq : q, show r, from hpqr(or.inr hq))⟩)
(assume hprqr : (p → r) ∧ (q → r), show (p ∨ q) → r, from
(assume hpq : p ∨ q, show r, from
or.elim hpq
(assume hp : p, show r, from hprqr.left hp)
(assume hq : q, show r, from hprqr.right hq)
)
)
-- Prove ¬(p ∨ q) ↔ ¬p ∧ ¬q := sorry
example (p q : Prop) : ¬(p ∨ q) ↔ ¬p ∧ ¬q :=
⟨λ h, ⟨λ hp, h (or.inl hp), λ hq, h (or.inr hq)⟩,
λ hn h, or.elim h hn.1 hn.2⟩
-- Another proof for ¬(p ∨ q) ↔ ¬p ∧ ¬q := sorry
example (p q : Prop) : ¬(p ∨ q) ↔ ¬p ∧ ¬q :=
iff.intro
(assume hnpq : ¬(p ∨ q), show ¬p ∧ ¬q, from
and.intro
(assume hp : p, show false, from hnpq (or.inl hp))
(assume hq : q, show false, from hnpq (or.inr hq)))
(assume (hnpnq : ¬p ∧ ¬q),
show ¬(p ∨ q), from
assume hnpq : p ∨ q, show false, from
or.elim hnpq (and.left hnpnq) (and.right hnpnq))
-- Prove ¬p ∨ ¬q → ¬(p ∧ q) := sorry
example : ¬p ∨ ¬q → ¬(p ∧ q) :=
(assume hnpnq : ¬p ∨ ¬q,
assume hpq : p ∧ q,
show false, from
(or.elim hnpnq
(assume hnp : ¬p, show false, from hnp (and.left hpq))
(assume hnq : ¬q, show false, from hnq (and.right hpq))
)
)
-- Prove ¬(p ∧ ¬p) := sorry
example : ¬(p ∧ ¬p) :=
assume h : p ∧ ¬p,
show false, from h.right h.left
example : ¬(p ∧ ¬p) :=
assume h,
absurd h.left h.right
-- Prove p ∧ ¬q → ¬(p → q)
example : p ∧ ¬q → ¬(p → q) :=
assume hpnq : p ∧ ¬ q,
assume hpq : p → q,
absurd (hpq hpnq.left) hpnq.right
example : p ∧ ¬q → ¬(p → q) :=
assume hpnq : p ∧ ¬ q,
assume hpq : p → q,
show false, from hpnq.right (hpq hpnq.left)
-- Prove ¬p → (p → q) := sorry
example : ¬p → (p → q) :=
assume hnp,
assume hp,
absurd hp hnp
example : ¬p → (p → q) :=
assume hnp,
assume hp,
show q , from absurd hp hnp
example : ¬p → (p → q) :=
assume hp,
assume hnp,
show q , from false.elim(hp hnp)
-- Prove (¬p ∨ q) → (p → q)
example : (¬p ∨ q) → (p → q) :=
(assume hnpq : ¬p ∨ q,
or.elim hnpq
(assume hnp : ¬p,
assume hp : p,
show q, from absurd hp hnp)
(assume hq : q,
assume hp : p,
show q, from hq))
example : (¬p ∨ q) → (p → q) :=
(assume hnpq : ¬p ∨ q,
or.elim hnpq
(assume hnp : ¬p,
assume hp : p,
show q, from false.elim (hnp hp))
(assume hq : q,
assume hp : p,
show q, from hq))
-- Prove p ∨ false ↔ p
example : p ∨ false ↔ p :=
iff.intro
(assume hpf,
or.elim hpf
(assume hp, show p, from hp)
(assume false, show p, from false.elim))
(assume hp,
show p ∨ false, from or.inl hp)
-- Prove p ∧ false ↔ false
example : p ∧ false ↔ false :=
iff.intro
(assume hpf,
show false, from hpf.right)
(assume hf,
show p ∧ false, from and.intro (show p, from hf.elim) hf)
-- Prove ¬(p ↔ ¬p)
example : ¬(p ↔ ¬p) :=
assume hpnp,
have hnp : ¬ p, from
assume hp : p, show false, from (hpnp.elim_left hp) hp,
show false, from hnp (hpnp.elim_right hnp)
-- Prove (p → q) → (¬q → ¬p)
example : (p → q) → (¬q → ¬p) :=
assume hpq,
assume hnq,
assume hp, show false, from hnq (hpq hp)
example : (p → q) → (¬q → ¬p) :=
assume hpq,
assume hnq,
assume hp, absurd (hpq hp) hnq
-- these require classical reasoning
open classical
-- Prove (p → r ∨ s) → ((p → r) ∨ (p → s))
example : (p → r ∨ s) → ((p → r) ∨ (p → s)) :=
(assume hprs, show (p → r) ∨ (p → s), from sorry)
example : (p → r ∨ s) → ((p → r) ∨ (p → s)) :=
(assume hprs, assume hp, show (p → r) ∨ (p → s), from sorry)
example (h : ¬¬p) : p :=
by_cases
(assume h1 : p, h1)
(assume h1 : ¬p, absurd h1 h)
example (h : ¬¬p) : p :=
by_contradiction
(assume h1 : ¬p,
show false, from h h1)
example (h : ¬(p ∧ q)) : ¬p ∨ ¬q :=
or.elim (em p)
(assume hp : p,
or.inr
(show ¬q, from
assume hq : q,
h ⟨hp, hq⟩))
(assume hp : ¬p,
or.inl hp)
-- Prove ¬(p ∧ q) → ¬p ∨ ¬q
example : ¬(p ∧ q) → ¬p ∨ ¬q :=
assume hnpq,
or.elim (em p)
(assume hp, show ¬p ∨ ¬q, from or.inr (assume hq, hnpq (and.intro hp hq)))
(assume hnp, show ¬p ∨ ¬q, from or.inl hnp)
-- Prove: ¬(p ∧ ¬q) → (p → q)
example : ¬(p ∧ ¬q) → (p → q) :=
assume hnpnq : ¬(p ∧ ¬q), show p → q, from (assume hp: p, show q, from
by_contradiction (assume hnq: ¬q, show false,
from hnpnq (and.intro hp hnq)))
-- Prove ¬(p → q) → p ∧ ¬q
example : ¬(p → q) → p ∧ ¬q :=
assume hnpq : ¬(p → q),
show p ∧ ¬q, from by_contradiction (
assume hnpnq : ¬(p ∧ ¬q), show false, from
hnpq
(assume hp: p, show q, from
by_contradiction (assume hnq: ¬q, show false,
from hnpnq (and.intro hp hnq))
)
)
-- Prove (p → q) → (¬p ∨ q)
example : (p → q) → (¬p ∨ q) :=
assume hpq : p → q,
show ¬p ∨ q, from
or.elim (em p)
(assume hp, show ¬p ∨ q, from or.inr(hpq hp))
(assume hnp, show ¬p ∨ q, from or.inl hnp)
-- Prove (¬q → ¬p) → (p → q)
example : (¬q → ¬p) → (p → q) :=
assume hnpnq : ¬q → ¬p,
show p → q, from (
assume hp: p, show q, from by_contradiction (
assume hnq: ¬q, show false, from (hnpnq hnq) hp
)
)
-- Prove p ∨ ¬p
example : p ∨ ¬p :=
by_contradiction(assume hnpnp: ¬(p ∨ ¬p), show false, from
or.elim (em p)
(assume hp : p, show false, from
false.elim(hnpnp (or.inl hp)))
(assume hnp : ¬p, show false, from
false.elim(hnpnp (or.inr hnp)))
)
-- Prove (((p → q) → p) → p)
example : (((p → q) → p) → p) :=
assume hpqp : (p → q) → p, show p, from
by_contradiction(
assume hnp : ¬p, show false, from
false.elim(
hnp
(hpqp (assume hp : p,
show q, from false.elim(hnp hp)))
)
)
|
[STATEMENT]
lemma perfect_imp_continuous_map:
"perfect_map X Y f \<Longrightarrow> continuous_map X Y f"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. perfect_map X Y f \<Longrightarrow> continuous_map X Y f
[PROOF STEP]
using perfect_map_def
[PROOF STATE]
proof (prove)
using this:
perfect_map ?X ?Y ?f \<equiv> continuous_map ?X ?Y ?f \<and> proper_map ?X ?Y ?f \<and> ?f ` topspace ?X = topspace ?Y
goal (1 subgoal):
1. perfect_map X Y f \<Longrightarrow> continuous_map X Y f
[PROOF STEP]
by blast
|
module STLCInterp
data HasType : List a -> a -> Type where
VZ : HasType (t :: env) t
VS : HasType env t -> HasType (_ :: env) t
data Expr : List Type -> Type -> Type where
Val : Int -> Expr env Int
Var : HasType env t -> Expr env t
Lam : Expr (a :: env) b -> Expr env (a -> b)
App : Expr env (a -> b) -> Expr env a -> Expr env b
interpEnv : List Type -> Type
interpEnv [] = ()
interpEnv (x :: xs) = (x, interpEnv xs)
lookup : HasType env t -> interpEnv env -> t
lookup VZ (t, _) = t
lookup (VS x) (_, ts) = lookup x ts
eval : interpEnv env -> %static Expr env t -> t
eval env (Val x) = x
eval env (Var x) = lookup x env
eval env (Lam body) = \x => eval (x, env) body
eval env (App f x) = (eval env f) (eval env x)
example : Expr [] Int
example = App (Lam (Var VZ)) (Val 42)
test : Int
test = eval () example
|
module NetTest
import Network.Socket
main : IO ()
main = do
putStrLn "net"
printLn $ toCode AF_UNIX
Right sock <- socket AF_INET Stream 0
| Left err => printLn err
let addr = IPv4Addr 127 0 0 1
0 <- bind sock (Just addr) 4077
| err => putStrLn $ "bind error: " ++ show err
0 <- listen sock
| err => putStrLn $ "listen error: " ++ show err
Right (conn, saddr) <- accept sock
| Left err => putStrLn $ "accept error: " ++ show err
pure ()
|
(*
* Types.v
* Wolf Honore
*
* Defines the types of Tiger expressions.
*)
Require Import List.
Require Import DecEqFacts.
Require Import Symbol.
Require Import Unique.
Module Types' (S : SYMBOL) (U : UNIQUE).
Definition upool := list U.t.
Definition uinit : upool := U.init.
Definition unew us : upool * U.t := U.new us.
Inductive ty : Set :=
| RECORD : list rfield -> U.t -> ty
| NIL : ty
| INT : ty
| STRING : ty
| ARRAY : ty -> U.t -> ty
| NAME : S.t -> ty
| UNIT : ty
with rfield : Set :=
| mk_rfield : S.t -> ty -> rfield.
Definition rf_name (rf : rfield) := let (name, _) := rf in name.
Definition rf_type (rf : rfield) := let (_, type) := rf in type.
Fixpoint ty_eq (t1 t2 : ty) : {t1 = t2} + {t1 <> t2}.
repeat decide equality; try apply U.eq; try apply S.eq.
Defined.
Definition rf_eq (rf1 rf2 : rfield) : {rf1 = rf2} + {rf1 <> rf2}.
decide equality; try apply ty_eq; try apply S.eq.
Defined.
Definition ty_compat (t1 t2 : ty) : bool :=
if ty_eq t1 t2
then true
else match t1, t2 with
| RECORD _ u1, RECORD _ u2 => if U.eq u1 u2 then true else false
| RECORD fs u, NIL => true
| NIL, RECORD fs u => true
| _, _ => false
end.
Fixpoint tys_compat (ts1 ts2 : list ty) : bool :=
match ts1, ts2 with
| nil, nil => true
| t1 :: ts1', t2 :: ts2' => andb (ty_compat t1 t2) (tys_compat ts1' ts2')
| _, _ => false
end.
Lemma ty_compat_refl : forall t,
ty_compat t t = true.
Proof.
destruct t; unfold ty_compat; try apply eq_refl.
Qed.
Lemma ty_compat_sym : forall t1 t2,
ty_compat t1 t2 = ty_compat t2 t1.
Proof.
destruct t1, t2; unfold ty_compat; try rewrite eq_sym; try rewrite eq_refl; try reflexivity.
rewrite (@eq_sym U.t). reflexivity.
Qed.
Lemma ty_compat_simpl_eq : forall t1 t2,
t2 = INT \/ t2 = STRING \/ t2 = UNIT ->
ty_compat t1 t2 = true ->
t1 = t2.
Proof.
intros; destruct H as [H | [H | H]]; subst;
destruct t1; try reflexivity;
unfold ty_compat in H0;
match type of H0 with
| (if ?X then _ else _) = _ => destruct X
end; discriminate.
Qed.
Lemma ty_compat_arr : forall t1 t2 aty u,
t2 = ARRAY aty u ->
ty_compat t1 t2 = true ->
t1 = t2.
Proof.
intros. destruct t1, t2; try discriminate;
unfold ty_compat in H0;
match type of H0 with
| (if ?X then _ else _) = _ => destruct X
end; congruence.
Qed.
Lemma ty_compat_rec : forall fs1 fs2 u1 u2,
ty_compat (RECORD fs1 u1) (RECORD fs2 u2) = true ->
u1 = u2.
Proof.
intros; unfold ty_compat in H;
destruct (ty_eq (RECORD fs1 u1) (RECORD fs2 u2));
destruct (U.eq u1 u2); congruence.
Qed.
(* actual_ty might return another Name, but with the possibility of infinite cycles need to add a max depth *)
Definition max_depth := 100.
Fixpoint actual_ty' (d : nat) (te : S.table ty) (t : ty) : option ty :=
match d with
| 0 => None
| S d' => match t with
| NAME n => match S.look te n with
| None => None
| Some t => actual_ty' d' te t
end
| _ => Some t
end
end.
Definition actual_ty te t := actual_ty' max_depth te t.
Fixpoint actual_tys (te : S.table ty) (ts : list ty) : option (list ty) :=
match ts with
| nil => Some nil
| t :: ts' => match actual_ty te t with
| None => None
| Some t' => option_map (cons t') (actual_tys te ts')
end
end.
Lemma actual_not_name' : forall te t n d,
actual_ty' d te t <> Some (NAME n).
Proof.
intros; destruct t; try solve [destruct d; simpl; discriminate].
generalize dependent t; induction d; intros.
- discriminate.
- simpl. destruct (S.look te t); try discriminate.
destruct t0; try solve [destruct d; simpl; try discriminate].
apply IHd.
Qed.
Lemma actual_not_name : forall te t n,
actual_ty te t <> Some (NAME n).
Proof.
intros; unfold actual_ty; apply actual_not_name'.
Qed.
Lemma actual_tys_no_none : forall te ts,
In None (map (actual_ty te) ts) <->
actual_tys te ts = None.
Proof.
split; intros.
- induction ts; inversion H.
+ simpl; rewrite H0; reflexivity.
+ simpl. apply IHts in H0; rewrite H0.
destruct (actual_ty te a); reflexivity.
- induction ts; inversion H.
destruct (actual_ty te a) eqn:?; simpl.
+ right; apply IHts; destruct (actual_tys te ts); [discriminate | reflexivity].
+ left; assumption.
Qed.
(* Return record if the other is nil *)
Definition most_general (t1 t2 : ty) :=
match t1, t2 with
| RECORD _ _, NIL => t1
| NIL, RECORD _ _ => t2
| _, _ => t1
end.
End Types'.
Module Types := Types' Symbol NatUnique.
|
{-# OPTIONS --safe #-}
module Cubical.Algebra.CommMonoid.Properties where
open import Cubical.Foundations.Prelude
open import Cubical.Foundations.Equiv
open import Cubical.Foundations.Equiv.HalfAdjoint
open import Cubical.Foundations.HLevels
open import Cubical.Foundations.Isomorphism
open import Cubical.Foundations.Univalence
open import Cubical.Foundations.Transport
open import Cubical.Foundations.SIP
open import Cubical.Data.Sigma
open import Cubical.Structures.Axioms
open import Cubical.Structures.Auto
open import Cubical.Structures.Macro
open import Cubical.Algebra.Semigroup
open import Cubical.Algebra.Monoid
open import Cubical.Algebra.CommMonoid.Base
private
variable
ℓ : Level
module CommMonoidTheory (M' : CommMonoid ℓ) where
open CommMonoidStr (snd M')
private M = ⟨ M' ⟩
commAssocl : (x y z : M) → x · (y · z) ≡ y · (x · z)
commAssocl x y z = assoc x y z ∙∙ cong (_· z) (comm x y) ∙∙ sym (assoc y x z)
commAssocr : (x y z : M) → x · y · z ≡ x · z · y
commAssocr x y z = sym (assoc x y z) ∙∙ cong (x ·_) (comm y z) ∙∙ assoc x z y
commAssocr2 : (x y z : M) → x · y · z ≡ z · y · x
commAssocr2 x y z = commAssocr _ _ _ ∙∙ cong (_· y) (comm _ _) ∙∙ commAssocr _ _ _
commAssocSwap : (x y z w : M) → (x · y) · (z · w) ≡ (x · z) · (y · w)
commAssocSwap x y z w = assoc (x · y) z w ∙∙ cong (_· w) (commAssocr x y z)
∙∙ sym (assoc (x · z) y w)
|
var $g <*ptr>
var $h <*ptr> = addrof ptr $g
var $g <*ptr> = addrof ptr $h
var $h <*ptr>
# EXEC: %irbuild Main.mpl
# EXEC: %irbuild Main.irb.mpl
# EXEC: %cmp Main.irb.mpl Main.irb.irb.mpl
|
(* include libraries and notations *)
Require Import Arith Lia List String.
Import ListNotations.
Open Scope string.
Set Implicit Arguments.
Definition eq_dec (A : Type) :=
forall (x : A),
forall (y : A),
{x = y} + {x <> y}.
Notation var := string.
Definition var_eq : eq_dec var := string_dec.
Definition valuation := list (var * nat).
Fixpoint lookup (x : var) (v : valuation) : option nat :=
match v with
| [] => None
| (y, n) :: v' =>
if var_eq x y
then Some n
else lookup x v'
end.
Inductive arith : Set :=
| Const (n : nat)
| Var (x : var)
| Plus (e1 e2 : arith)
| Minus (e1 e2 : arith)
| Times (e1 e2 : arith).
Fixpoint eval_arith (e : arith) (v : valuation) : nat :=
match e with
| Const n => n
| Var x =>
match lookup x v with
| None => 0
| Some n => n
end
| Plus e1 e2 => eval_arith e1 v + eval_arith e2 v
| Minus e1 e2 => eval_arith e1 v - eval_arith e2 v
| Times e1 e2 => eval_arith e1 v * eval_arith e2 v
end.
Declare Scope arith_scope.
Coercion Const : nat >-> arith.
Coercion Var : var >-> arith.
Infix "+" := Plus : arith_scope.
Infix "-" := Minus : arith_scope.
Infix "*" := Times : arith_scope.
Delimit Scope arith_scope with arith.
Bind Scope arith_scope with arith.
(*
If you could use a refresher on any of these definitions, please check out
the code from Week04 where they're discussed in detail:
https://gitlab.cs.washington.edu/cse505-23wi/cse505-23wi/-/blob/main/week04/Week04.v
*)
(* Copied from Week04.v *)
Inductive trc {A} (R : A -> A -> Prop) : A -> A -> Prop :=
| trc_refl :
forall x,
trc R x x
| trc_front :
forall x y z,
R x y ->
trc R y z ->
trc R x z.
Record trsys state :=
{ Init : state -> Prop
; Step : state -> state -> Prop }.
Definition is_invariant {state} (sys : trsys state) (P : state -> Prop) :=
forall s0,
sys.(Init) s0 ->
forall sN,
trc sys.(Step) s0 sN ->
P sN.
Definition initially_holds {state} (sys : trsys state) (P : state -> Prop) :=
forall s,
sys.(Init) s ->
P s.
Definition closed_under_step {state} (sys : trsys state) (P : state -> Prop) :=
forall s1,
P s1 ->
forall s2,
sys.(Step) s1 s2 ->
P s2.
Lemma closed_under_step_trc :
forall {state} (sys : trsys state) (P : state -> Prop) s0 sN,
trc sys.(Step) s0 sN ->
closed_under_step sys P ->
P s0 ->
P sN.
Proof.
unfold closed_under_step.
intros state sys P s0 sN Htrc.
induction Htrc; intros Hclosed HP0.
- assumption.
- apply IHHtrc; auto.
eapply Hclosed; eauto.
Qed.
Theorem invariant_induction :
forall {state} (sys : trsys state) (P : state -> Prop),
initially_holds sys P ->
closed_under_step sys P ->
is_invariant sys P.
Proof.
unfold is_invariant. intros.
eapply closed_under_step_trc; eauto.
Qed.
Lemma invariant_implies :
forall {state} (sys : trsys state) (P Q : state -> Prop),
is_invariant sys P ->
(forall s, P s -> Q s) ->
is_invariant sys Q.
Proof.
unfold is_invariant.
eauto.
Qed.
Ltac unfold_predicate P :=
match P with
| ?head _ => unfold_predicate head
| _ => try unfold P
end.
Ltac invariant_induction_boilerplate :=
intros;
apply invariant_induction; [
unfold initially_holds; simpl;
match goal with
| [ |- forall _, ?P _ -> ?Q _ ] =>
unfold_predicate P;
unfold_predicate Q;
intros s Hinit;
try subst
end
|
unfold closed_under_step; simpl;
match goal with
| [ |- forall _, ?P _ -> forall _, ?Q _ _ -> _ ] =>
unfold_predicate P;
unfold_predicate Q;
intros s1 IH s2 Hstep
end
].
(* End of copied stuff *)
Module Imp.
(*
CREDITS: This formalization also follows the development from Chlipala's
excellent FRAP textbook: http://adam.chlipala.net/frap/
*)
(* Syntax of Imp. *)
Inductive cmd :=
| Skip
| Assign (x : var) (e : arith)
| Sequence (c1 c2 : cmd)
| If (e : arith) (then_ else_ : cmd) (* new this week (but nothing fundamental) *)
| While (e : arith) (body : cmd). (* new this week (and fundamentally different!) *)
Notation "x <- e" := (Assign x e%arith) (at level 75).
Infix ";;" := Sequence (at level 76). (* ;; instead of ; because it interferes
with record syntax *)
Notation "'when' e 'then' then_ 'else' else_ 'done'" :=
(If e%arith then_ else_) (at level 75, e at level 0).
Notation "'while' e 'loop' body 'done'" :=
(While e%arith body) (at level 75).
(* Translate our long horizontal lines to an inductive definition. *)
Inductive step : valuation * cmd -> valuation * cmd -> Prop :=
| StepAssign :
forall v x e v',
v' = (x, eval_arith e v) :: v ->
(* --------------------------- *)
step (v, Assign x e) (v', Skip)
| StepSeqLStep :
forall v c1 c2 v' c1',
step (v, c1) (v', c1') ->
step (v, Sequence c1 c2) (v', Sequence c1' c2)
| StepSeqLDone :
forall v c2,
step (v, Sequence Skip c2) (v, c2)
| StepIfTrue :
forall v e then_ else_,
eval_arith e v <> 0 ->
step (v, If e then_ else_) (v, then_)
| StepIfFalse :
forall v e then_ else_,
eval_arith e v = 0 ->
step (v, If e then_ else_) (v, else_)
| StepWhileTrue :
forall v e body,
eval_arith e v <> 0 ->
(* -------------- *)
step (v, While e body) (v, Sequence body (While e body))
| StepWhileFalse :
forall v e body,
eval_arith e v = 0 ->
step (v, While e body) (v, Skip).
Definition counter :=
"x" <- 5;;
while 1 loop
"x" <- "x" + 1
done.
Example counter_steps_10_times :
exists v,
trc step ([], counter) (v, while 1 loop
"x" <- "x" + 1
done) /\
lookup "x" v = Some 15.
Proof.
Admitted.
(* Here's our old friend the factorial program. *)
Definition factorial : cmd :=
"n" <- "input";;
"acc" <- 1;;
while "n" loop
"acc" <- "acc" * "n";;
"n" <- "n" - 1
done;;
"output" <- "acc".
Print factorial.
Example factorial_4 :
forall v1,
lookup "input" v1 = Some 4 ->
exists v2,
trc step (v1, factorial) (v2, Skip) /\
lookup "output" v2 = Some 24.
Proof.
intros v1 Hv1.
eexists.
split.
- unfold factorial.
Print trc.
eapply trc_front.
eapply StepSeqLStep.
eapply StepSeqLStep.
eapply StepSeqLStep.
apply StepAssign.
reflexivity.
eapply trc_front.
eapply StepSeqLStep.
eapply StepSeqLStep.
apply StepSeqLDone.
Restart.
intros v1 H.
eexists.
split.
- eapply trc_front.
apply StepSeqLStep.
apply StepSeqLStep.
apply StepSeqLStep.
apply StepAssign.
reflexivity.
(* Now we are left with a Skip out front of our Seq. Get rid of it. *)
eapply trc_front.
apply StepSeqLStep.
apply StepSeqLStep.
apply StepSeqLDone.
(* Time for the next assignment statement... *)
eapply trc_front.
apply StepSeqLStep.
apply StepSeqLStep.
apply StepAssign.
reflexivity.
eapply trc_front.
apply StepSeqLStep.
apply StepSeqLDone.
(* Now we're at the top of the loop. *)
cbn. rewrite H.
eapply trc_front.
apply StepSeqLStep.
apply StepWhileTrue. (* Try to enter the loop. *)
cbn. lia. (* Prove that we actually do enter the loop. *)
(* Now execute the body of the loop. *)
eapply trc_front.
apply StepSeqLStep.
apply StepSeqLStep.
apply StepSeqLStep.
apply StepAssign.
reflexivity.
eapply trc_front.
apply StepSeqLStep.
apply StepSeqLStep.
apply StepSeqLDone.
eapply trc_front.
apply StepSeqLStep.
apply StepSeqLStep.
apply StepAssign.
reflexivity.
eapply trc_front.
apply StepSeqLStep.
apply StepSeqLDone.
(* We're back at the top of the loop. Time for the next iteration. *)
cbn.
eapply trc_front.
apply StepSeqLStep.
apply StepWhileTrue.
cbn. lia.
eapply trc_front.
apply StepSeqLStep.
apply StepSeqLStep.
apply StepSeqLStep.
apply StepAssign.
reflexivity.
eapply trc_front.
apply StepSeqLStep.
apply StepSeqLStep.
apply StepSeqLDone.
eapply trc_front.
apply StepSeqLStep.
apply StepSeqLStep.
apply StepAssign.
reflexivity.
eapply trc_front.
apply StepSeqLStep.
apply StepSeqLDone.
(* next iteration *)
cbn.
eapply trc_front.
apply StepSeqLStep.
apply StepWhileTrue.
cbn. lia.
eapply trc_front.
apply StepSeqLStep.
apply StepSeqLStep.
apply StepSeqLStep.
apply StepAssign.
reflexivity.
eapply trc_front.
apply StepSeqLStep.
apply StepSeqLStep.
apply StepSeqLDone.
eapply trc_front.
apply StepSeqLStep.
apply StepSeqLStep.
apply StepAssign.
reflexivity.
eapply trc_front.
apply StepSeqLStep.
apply StepSeqLDone.
(* next iteration *)
cbn.
eapply trc_front.
apply StepSeqLStep.
apply StepWhileTrue.
cbn. lia.
eapply trc_front.
apply StepSeqLStep.
apply StepSeqLStep.
apply StepSeqLStep.
apply StepAssign.
reflexivity.
eapply trc_front.
apply StepSeqLStep.
apply StepSeqLStep.
apply StepSeqLDone.
eapply trc_front.
apply StepSeqLStep.
apply StepSeqLStep.
apply StepAssign.
reflexivity.
eapply trc_front.
apply StepSeqLStep.
apply StepSeqLDone.
cbn.
(* Finally n is 0. Try to exit the loop. *)
eapply trc_front.
apply StepSeqLStep.
apply StepWhileFalse.
cbn. lia. (* Prove we actually do exit the loop. *)
(* Just a few more steps left after the loop. *)
eapply trc_front.
apply StepSeqLDone.
eapply trc_front.
apply StepAssign.
reflexivity.
cbn.
(* Finally, we end the proof of trc using trc_refl. If you look carefully at
the goal here, you can "see" the actual v2 that gets plugged in for our
placeholder. Yikes! *)
apply trc_refl.
- (* All that's left is to show *)
cbn.
reflexivity.
Qed. (* Nailed it, only 130 ish tactics. Lots of copy paste! *)
(* like econstructor, but avoid StepWhileTrue b/c infinite tactic loops *)
Ltac step_easy :=
repeat (
apply StepSeqLDone ||
eapply StepSeqLStep ||
(apply StepWhileFalse; cbn; reflexivity) ||
(apply StepAssign; reflexivity)
); cbn.
Example factorial_4_again :
forall v1,
lookup "input" v1 = Some 4 ->
exists v2,
trc step (v1, factorial) (v2, Skip) /\
lookup "output" v2 = Some 24.
Proof.
intros v1 H.
eexists.
split.
- econstructor.
step_easy.
cbn. rewrite H.
econstructor.
step_easy.
econstructor.
step_easy.
cbn.
econstructor.
step_easy.
econstructor.
step_easy.
apply StepWhileTrue.
cbn. lia.
econstructor.
step_easy.
econstructor.
step_easy.
cbn.
econstructor.
step_easy.
cbn.
econstructor.
step_easy.
econstructor.
step_easy.
apply StepWhileTrue.
cbn. lia.
econstructor.
step_easy.
econstructor.
step_easy.
cbn.
econstructor.
step_easy.
cbn.
econstructor.
step_easy.
econstructor.
step_easy.
apply StepWhileTrue.
cbn. lia.
econstructor.
step_easy.
econstructor.
step_easy.
cbn.
econstructor.
step_easy.
cbn.
econstructor.
step_easy.
econstructor.
step_easy.
apply StepWhileTrue.
cbn. lia.
econstructor.
step_easy.
econstructor.
step_easy.
cbn.
econstructor.
step_easy.
cbn.
econstructor.
step_easy.
econstructor.
step_easy.
econstructor.
step_easy.
econstructor.
step_easy.
cbn.
econstructor.
- reflexivity. (* ok that only took half as many tactics *)
Restart.
(* We can do even better with more tactics. *)
Ltac trc_easy :=
eapply trc_front; [solve [step_easy]|]; cbn.
Ltac trc_enter_loop :=
eapply trc_front; [step_easy; apply StepWhileTrue; cbn; try lia|]; cbn.
intros v1 H.
eexists.
split.
- trc_easy. rewrite H.
repeat trc_easy. (* Executes as many assignments/skips as possible. *)
trc_enter_loop.
repeat trc_easy.
trc_enter_loop.
repeat trc_easy.
trc_enter_loop.
repeat trc_easy.
trc_enter_loop.
repeat trc_easy.
(* exited the loop *)
apply trc_refl.
- reflexivity.
Qed.
Definition cmd_init (v : valuation) (c : cmd) (s : valuation * cmd) : Prop :=
s = (v, c).
Definition cmd_to_trsys (v : valuation) (c : cmd) : trsys (valuation * cmd) :=
{| Init := cmd_init v c
; Step := step
|}.
Definition counter_sys : trsys (valuation * cmd) :=
cmd_to_trsys [] counter.
Definition counter_ge_5_attempt (s : valuation * cmd) :=
let (v, c) := s in
exists x,
lookup "x" v = Some x /\
x >= 5.
Theorem counter_ge_5_attempt_invariant :
is_invariant counter_sys counter_ge_5_attempt.
Proof.
invariant_induction_boilerplate.
(* Uh oh, this just isn't true initially! x is not mapped to anything yet. *)
Abort.
Definition counter_ge_5 (s : valuation * cmd) :=
let (v, c) := s in
c = counter \/
exists x,
lookup "x" v = Some x /\
x >= 5.
Theorem counter_ge_5_invariant :
is_invariant counter_sys counter_ge_5.
Proof.
invariant_induction_boilerplate.
- auto.
- destruct s1 as [v1 c1], s2 as [v2 c2].
destruct IH as [IH|IH].
+ subst. unfold counter in *.
inversion Hstep; subst; clear Hstep.
inversion H0; subst; clear H0.
cbn. eauto.
+
Abort.
(*
Definition counter :=
"x" <- 5;;
while 1 loop
"x" <- "x" + 1
done.
Skip;;
while 1 loop
"x" <- "x" + 1
done.
while 1 loop
"x" <- "x" + 1
done.
"x" <- "x" + 1;;
while 1 loop
"x" <- "x" + 1
done.
*)
Definition counter_programs (s : valuation * cmd) :=
let (v, c) := s in
c = counter \/
c = (Skip;;
while 1 loop
"x" <- "x" + 1
done) \/
c = (while 1 loop
"x" <- "x" + 1
done) \/
c = ("x" <- "x" + 1;;
while 1 loop
"x" <- "x" + 1
done) \/
c = Skip.
Theorem counter_programs_invariant :
is_invariant counter_sys counter_programs.
Proof.
invariant_induction_boilerplate.
- auto.
- destruct s1 as [v1 c1], s2 as [v2 c2].
intuition; subst; inversion Hstep; subst; clear Hstep; auto.
+ inversion H0; subst; clear H0. auto.
+ inversion H0; subst; clear H0.
+ inversion H0; subst; clear H0. auto.
Qed.
Definition counter_valuation_x_ge_5 (v : valuation) :=
exists x,
lookup "x" v = Some x /\
x >= 5.
Definition counter_programs_x_ge_5 (s : valuation * cmd) :=
let (v, c) := s in
c = counter \/
(c = (Skip;;
while 1 loop
"x" <- "x" + 1
done) /\ counter_valuation_x_ge_5 v) \/
(c = (while 1 loop
"x" <- "x" + 1
done) /\ counter_valuation_x_ge_5 v) \/
(c = ("x" <- "x" + 1;;
while 1 loop
"x" <- "x" + 1
done) /\ counter_valuation_x_ge_5 v).
Lemma counter_programs_x_ge_5_invariant :
is_invariant counter_sys counter_programs_x_ge_5.
Proof.
invariant_induction_boilerplate.
- auto.
- destruct s1 as [v1 c1], s2 as [v2 c2].
unfold counter_valuation_x_ge_5 in *.
intuition; subst; inversion Hstep; subst; clear Hstep; auto.
+ inversion H0; subst; clear H0. cbn. eauto 10.
+ inversion H0; subst; clear H0.
+ simpl in *. discriminate.
+ inversion H0; subst; clear H0.
destruct H1 as [x [Hlook Hx]]. cbn. rewrite Hlook. right. left.
split; auto. eexists. split; auto. lia.
Qed.
Theorem counter_ge_5_invariant :
is_invariant counter_sys counter_ge_5.
Proof.
apply invariant_implies with (P := counter_programs_x_ge_5).
- apply counter_programs_x_ge_5_invariant.
- unfold counter_programs_x_ge_5, counter_ge_5.
intros [v c] Hinv.
intuition.
Qed.
Definition factorial_sys (input : nat) : trsys (valuation * cmd) :=
cmd_to_trsys [("input", input)] factorial.
Fixpoint fact (n : nat) : nat :=
match n with
| O => 1
| S n' => fact n' * S n'
end.
Definition factorial_safe (input : nat) (s : valuation * cmd) : Prop :=
let (v, c) := s in
c = Skip ->
lookup "output" v = Some (fact input).
Theorem factorial_safe_invariant :
forall input,
is_invariant (factorial_sys input) (factorial_safe input).
Proof.
Abort.
Definition factorial_after_step_one :=
Skip;;
"acc" <- 1;;
while "n" loop
"acc" <- "acc" * "n";;
"n" <- "n" - 1
done;;
"output" <- "acc".
Definition factorial_after_step_two :=
"acc" <- 1;;
while "n" loop
"acc" <- "acc" * "n";;
"n" <- "n" - 1
done;;
"output" <- "acc".
Definition factorial_after_step_three :=
Skip;;
while "n" loop
"acc" <- "acc" * "n";;
"n" <- "n" - 1
done;;
"output" <- "acc".
Definition factorial_top_of_loop :=
while "n" loop
"acc" <- "acc" * "n";;
"n" <- "n" - 1
done;;
"output" <- "acc".
Definition factorial_body_start :=
"acc" <- "acc" * "n";;
"n" <- "n" - 1;;
while "n" loop
"acc" <- "acc" * "n";;
"n" <- "n" - 1
done;;
"output" <- "acc".
Definition factorial_body_after_step_one :=
Skip;;
"n" <- "n" - 1;;
while "n" loop
"acc" <- "acc" * "n";;
"n" <- "n" - 1
done;;
"output" <- "acc".
Definition factorial_body_after_step_two :=
"n" <- "n" - 1;;
while "n" loop
"acc" <- "acc" * "n";;
"n" <- "n" - 1
done;;
"output" <- "acc".
Definition factorial_after_loop :=
Skip;;
"output" <- "acc".
Definition factorial_last_step :=
"output" <- "acc".
Definition factorial_loop_invariant input v :=
exists n acc,
lookup "n" v = Some n /\
lookup "acc" v = Some acc /\
fact n * acc = fact input.
Definition factorial_body_invariant input v :=
exists n acc,
lookup "n" v = Some (S n) /\
lookup "acc" v = Some acc /\
fact (S n) * acc = fact input.
Definition factorial_body_invariant_after_step input v :=
exists n acc,
lookup "n" v = Some (S n) /\
lookup "acc" v = Some acc /\
fact n * acc = fact input.
Definition factorial_inv (input : nat) (s : valuation * cmd) : Prop :=
let (v, c) := s in
(c = factorial /\ lookup "input" v = Some input) \/
(c = factorial_after_step_one /\ lookup "n" v = Some input) \/
(c = factorial_after_step_two /\ lookup "n" v = Some input) \/
(c = factorial_after_step_three /\ factorial_loop_invariant input v) \/
(c = factorial_top_of_loop /\ factorial_loop_invariant input v) \/
(c = factorial_body_start /\ factorial_body_invariant input v) \/
(c = factorial_body_after_step_one /\ factorial_body_invariant_after_step input v) \/
(c = factorial_body_after_step_two /\ factorial_body_invariant_after_step input v) \/
(c = factorial_after_loop /\ lookup "acc" v = Some (fact input)) \/
(c = factorial_last_step /\ lookup "acc" v = Some (fact input)) \/
(c = Skip /\ lookup "output" v = Some (fact input)).
Ltac invc H := inversion H; subst; clear H.
Lemma factorial_inv_invariant :
forall input,
is_invariant (factorial_sys input) (factorial_inv input).
Proof.
invariant_induction_boilerplate.
- auto.
- unfold factorial_loop_invariant, factorial_body_invariant.
unfold factorial_body_invariant_after_step.
destruct s1 as [v1 c1], s2 as [v2 c2].
intuition idtac; subst.
+ invc Hstep. invc H0. invc H2. invc H0.
cbn [eval_arith].
rewrite H1.
auto.
+ invc Hstep. invc H0. invc H2. invc H0. auto.
+ invc Hstep. invc H0. invc H2.
right. right. right. left. split; [reflexivity|].
exists input, 1.
cbn. split; auto. split; auto. lia.
+ destruct H1 as [n [acc [? []]]].
invc Hstep. invc H3. invc H4.
eauto 20.
+ destruct H1 as [n [acc [? []]]].
invc Hstep. invc H3.
-- right. right. right. right. right. left. split; [reflexivity|].
cbn in *. rewrite H in *.
destruct n; [congruence|]. (* note: destruct before exists *)
eauto.
-- right. right. right. right. right. right. right. right. left. split; [reflexivity|].
cbn in *. rewrite H in *. subst n.
cbn in *. rewrite H0, <- H1. f_equal. lia.
+ destruct H1 as [n [acc [? []]]].
invc Hstep. invc H3. invc H4. invc H3.
right. right. right. right. right. right. left. split; [reflexivity|].
cbn. rewrite H, H0. eexists. eexists. split; eauto. split; eauto.
rewrite <- H1. cbn. lia.
+ destruct H1 as [n [acc [? []]]].
invc Hstep. invc H3. invc H4. invc H3.
eauto 15.
+ destruct H1 as [n [acc [? []]]].
invc Hstep. invc H3. invc H4.
right. right. right. left. split; [reflexivity|].
cbn. rewrite H. cbn. rewrite Nat.sub_0_r. eauto.
+ invc Hstep. invc H1. invc H0.
auto 20.
+ invc Hstep.
right. right. right. right. right. right. right. right. right. right.
split; auto.
cbn. rewrite H1. auto.
+ invc Hstep.
Qed.
Ltac invert_one_step :=
match goal with
| [ H : step _ _ |- _ ] => invc H
end.
Ltac invert_steps :=
repeat invert_one_step.
Ltac magic_select_case :=
repeat match goal with
| [ |- _ \/ _ ] => (left; split; [reflexivity|]) || right
| _ => try split; [reflexivity|]
end.
Ltac break_up_hyps :=
repeat match goal with
| [ H : exists _, _ |- _ ] => destruct H
| [ H : _ /\ _ |- _ ] => destruct H
end.
Ltac find_rewrites :=
repeat match goal with
| [ H : _ = _ |- _ ] => rewrite H in *
end.
Lemma factorial_inv_invariant_again :
forall input,
is_invariant (factorial_sys input) (factorial_inv input).
Proof.
invariant_induction_boilerplate.
- auto.
- destruct s1 as [v1 c1], s2 as [v2 c2].
fold (factorial_inv input (v2, c2)).
intuition; subst; invert_steps;
unfold factorial_inv;
unfold factorial_loop_invariant, factorial_body_invariant in *;
unfold factorial_body_invariant_after_step in *;
magic_select_case;
break_up_hyps;
cbn in *;
find_rewrites;
eauto 20.
+ eexists. eexists.
split; eauto. split; eauto. lia.
+ destruct x; [congruence|]. (* note: destruct before exists *)
eauto.
+ subst.
cbn in *. rewrite <- H1. f_equal. lia.
+ eexists. eexists. split; eauto. split; eauto.
rewrite <- H1. cbn. lia.
+ eexists. eexists. split; eauto. split; eauto.
cbn. rewrite <- H1. f_equal. f_equal. lia.
Qed.
Theorem factorial_safe_invariant :
forall input,
is_invariant (factorial_sys input) (factorial_safe input).
Proof.
intros input.
apply invariant_implies with (P := factorial_inv input).
- apply factorial_inv_invariant.
- unfold factorial_inv, factorial_safe.
intros [v c] Hinv Hfinal.
subst.
intuition; discriminate.
Qed.
Lemma decompose_sequence_execution :
forall v v' c1 c2 c',
trc step (v, c1;; c2) (v', c') ->
exists v1' c1',
trc step (v, c1) (v1', c1') /\
(c' = (c1';; c2) \/
(c1' = Skip /\ trc step (v1', c2) (v', c'))).
Proof.
intros v v' c1 c2 c' Hstep.
induction Hstep.
- (* wait... what is x??? *)
Restart.
intros v v' c1 c2 c' Hstep.
remember (v, c1;;c2) as s.
remember (v', c') as s'.
revert v c1 c2 v' c' Heqs Heqs'.
induction Hstep; intros v c1 c2 v' c' ? ?; subst.
- invc Heqs'. eexists. eexists. split. constructor. auto.
- invc H.
+ specialize (IHHstep v'0 c1' c2 v' c' eq_refl eq_refl).
destruct IHHstep as [v1' [c1'0 [Hstep' Hc']]].
eexists. eexists.
split. eapply trc_front; eauto.
intuition.
+ eexists. eexists. split. apply trc_refl.
auto.
Qed.
Lemma trc_seq_l_trc :
forall v1 c1 v2 c2 c3,
trc step (v1, c1) (v2, c2) ->
trc step (v1, c1;;c3) (v2, c2;;c3).
Proof.
intros v1 c1 v2 c2 c3 Hstep.
remember (v1, c1) as s1.
remember (v2, c2) as s2.
revert v1 c1 v2 c2 c3 Heqs1 Heqs2.
induction Hstep; intros v1 c1 v2 c2 c3 ? ?; subst.
- invc Heqs2. econstructor.
- destruct y as [v1' c1'].
specialize (IHHstep v1' c1' v2 c2 c3 eq_refl eq_refl).
eapply trc_front. apply StepSeqLStep. eauto. eauto.
Qed.
Inductive trc_backward {A} (R : A -> A -> Prop) : A -> A -> Prop :=
| trcb_refl :
forall x,
trc_backward R x x
| trcb_back :
forall x y z,
trc_backward R x y ->
R y z ->
trc_backward R x z.
Lemma trc_back :
forall {A} (R : A -> A -> Prop) x y,
trc R x y ->
forall z,
R y z ->
trc R x z.
Proof.
(* On HW3 *)
Admitted.
Lemma trcb_front :
forall {A} (R : A -> A -> Prop) y z,
trc_backward R y z ->
forall x,
R x y ->
trc_backward R x z.
Proof.
(* Very similar to previous lemma. *)
Admitted.
Lemma trc_implies_trc_backward :
forall A (R : A -> A -> Prop) x y,
trc R x y ->
trc_backward R x y.
Proof.
intros A R x y Htrc.
induction Htrc.
- constructor.
- eapply trcb_front; eauto.
Qed.
Lemma trc_backward_implies_trc :
forall A (R : A -> A -> Prop) x y,
trc_backward R x y ->
trc R x y.
Proof.
intros A R x y Htrcb.
induction Htrcb.
- constructor.
- eapply trc_back; eauto.
Qed.
Lemma trc_reverse_ind :
forall A (R : A -> A -> Prop) (P : A -> A -> Prop),
(forall x, P x x) ->
(forall x y z, trc R x y -> R y z -> P x y -> P x z) ->
forall x y,
trc R x y ->
P x y.
Proof.
intros A R P Hbase Hind x y H.
apply trc_implies_trc_backward in H.
induction H.
- apply Hbase.
- eapply Hind; eauto.
apply trc_backward_implies_trc.
auto.
Qed.
Definition loop_runs_to (e : arith) (c : cmd) (v1 v2 : valuation) :=
eval_arith e v1 <> 0 /\
trc step (v1, c) (v2, Skip).
Ltac prepare_induct_step H :=
match type of H with
| step (?v, ?c) (?v', ?c') =>
let s := fresh "s" in
let Heqs := fresh "Heqs" in
let s' := fresh "s'" in
let Heqs' := fresh "Heqs'" in
remember (v, c) as s eqn:Heqs;
remember (v', c') as s' eqn:Heqs';
revert Heqs Heqs';
try revert c';
try revert v';
try revert c;
try revert v
end.
Ltac induct_step H :=
prepare_induct_step H;
induction H; intros; subst.
Ltac prepare_induct_trc_step H :=
match type of H with
| trc step (?v, ?c) (?v', ?c') =>
let s := fresh "s" in
let Heqs := fresh "Heqs" in
let s' := fresh "s'" in
let Heqs' := fresh "Heqs'" in
remember (v, c) as s eqn:Heqs;
remember (v', c') as s' eqn:Heqs';
revert Heqs Heqs';
try revert c';
try revert v';
try revert c;
try revert v
end.
Ltac induct_trc_step H :=
prepare_induct_trc_step H;
induction H; intros; subst.
Lemma decompose_while_execution :
forall v v' e c c',
trc step (v, while e loop c done) (v', c') ->
exists v1,
trc (loop_runs_to e c) v v1 /\
((c' = Skip /\ v' = v1 /\ eval_arith e v' = 0) \/
(c' = (while e loop c done) /\ v' = v1) \/
(eval_arith e v1 <> 0 /\ exists c1', trc step (v1, c) (v', c1') /\ c' = (c1' ;; while e loop c done))).
Proof.
intros v v' e c c' Htrc.
prepare_induct_trc_step Htrc.
revert e c.
induction Htrc using trc_reverse_ind; intros v e c v' c' ? ?; subst.
- invc Heqs'. (* eexists. split.
+ apply trc_refl.
+ auto. *)
eauto 10 using trc_refl.
- destruct y as [v2 c2].
specialize (IHHtrc v e c v2 c2 eq_refl eq_refl).
destruct IHHtrc as [v1 [Htrc1 IH]].
destruct IH as [[? [? He]]|[[? ?]|[He [c1' [Hc ?]]]]]; subst.
+ invc H.
+ invc H.
* eexists. split; eauto.
right. right. split; auto.
eexists. split; eauto. constructor.
* eauto 10.
+ invc H.
* eexists. split; eauto.
right. right. split; auto.
eexists. split; [|reflexivity].
eapply trc_back; eauto.
* exists v'. split.
-- eapply trc_back; eauto. split; auto.
-- auto.
Qed.
Fixpoint strength_reduction (e : arith) : arith :=
match e with
| Const _ => e
| Var _ => e
| Plus e1 e2 => Plus (strength_reduction e1) (strength_reduction e2)
| Minus e1 e2 => Minus (strength_reduction e1) (strength_reduction e2)
| Times (Const 2) e2 =>
let e2' := strength_reduction e2 in
Plus e2' e2'
| Times e1 e2 => Times (strength_reduction e1) (strength_reduction e2)
end.
Fixpoint cmd_xform_arith (f : arith -> arith) (c : cmd) : cmd :=
match c with
| Skip => Skip
| Assign x e => Assign x (f e)
| Sequence c1 c2 => Sequence (cmd_xform_arith f c1) (cmd_xform_arith f c2)
| If e c1 c2 => If (f e) (cmd_xform_arith f c1) (cmd_xform_arith f c2)
| While e c => While (f e) (cmd_xform_arith f c)
end.
Lemma cmd_xform_arith_equiv_step :
forall f,
(forall e v, eval_arith (f e) v = eval_arith e v) ->
forall v c v' c',
step (v, c) (v', c') ->
step (v, cmd_xform_arith f c) (v', cmd_xform_arith f c').
Proof.
intros f Hf v c v' c' Hstep.
induct_step Hstep; invc Heqs; invc Heqs'; simpl; constructor;
try rewrite Hf; auto.
Qed.
Theorem cmd_xform_arith_equiv :
forall f,
(forall e v, eval_arith e v = eval_arith (f e) v) ->
forall v c v' c',
trc step (v, c) (v', c') ->
trc step (v, cmd_xform_arith f c) (v', cmd_xform_arith f c').
Proof.
intros f Hf v c v' c' Htrc.
induct_trc_step Htrc.
- invc Heqs'. constructor.
- destruct y as [v1 c1].
eapply cmd_xform_arith_equiv_step in H; eauto.
econstructor; eauto.
Qed.
End Imp.
|
Formal statement is: lemma real_vector_eq_affinity: "m \<noteq> 0 \<Longrightarrow> y = m *\<^sub>R x + c \<longleftrightarrow> inverse m *\<^sub>R y - (inverse m *\<^sub>R c) = x" for x :: "'a::real_vector" Informal statement is: If $m \neq 0$, then $y = mx + c$ if and only if $\frac{1}{m}y - \frac{1}{m}c = x$.
|
"""Tool for interfacing to Fast Downward (FD) planner, for deterministic
problems. Based on `run_det_baselines.py` from `../det-baselines/` (but with
some changes)."""
import argparse
import contextlib
import os
import os.path as osp
import re
import shutil
import subprocess
import time
import uuid
import numpy as np
from asnets.pddl_utils import extract_domain_problem, hlist_to_sexprs, \
replace_init_state
from asnets.state_reprs import sample_next_state, get_init_cstate
THIS_DIR = osp.dirname(osp.abspath(__file__))
ABOVE_DIR = osp.abspath(osp.join(THIS_DIR, '..'))
FD_DIR = osp.join(ABOVE_DIR, 'fd')
FD_PATH = osp.join(FD_DIR, 'fast-downward.py')
PLAN_BN = 'plan.out'
STDOUT_BN = 'stdout.txt'
STDERR_BN = 'stderr.txt'
CMDLINE_BN = 'cmdline.txt'
def has_fd():
return osp.exists(FD_PATH)
def try_install_fd():
# If necessary, installs Fast Downward per
# http://www.fast-downward.org/ObtainingAndRunningFastDownward
# TODO: make this less racy; should be okay to call it from several
# processes at once.
if not has_fd():
print("Installing FD")
if not osp.exists(FD_DIR):
subprocess.run(
# this is a fairly recent version of FD (June 2019)
[
"hg", "clone", "http://hg.fast-downward.org", "fd", "-u",
"98c4bdb9cee9"
],
check=True,
cwd=ABOVE_DIR)
subprocess.run(["python", "build.py", "-j16"],
check=True,
cwd=FD_DIR)
def get_plan_file_path(root_dir, base_name):
"""Get path to best plan file from an FD planner. Generally the plan file
path will be either `root_dir + '/' + basename` (for non-anytime planners)
or `root_dir + '/' + basename + '.' + str(stage_num)` for anytime planners.
In the latter case we want to get the plan file with the highest
stage_num!"""
file_names = os.listdir(root_dir)
if base_name in file_names:
return osp.join(root_dir, base_name)
names_nums = []
for file_name in file_names:
if file_name.startswith(base_name):
name_str, num_str = file_name.rsplit('.', 1)
# the name should be something like `<basename>.3` (for third
# stage, in this case)
assert name_str == base_name, "can't handle name '%s' in '%s'" \
% (file_name, root_dir)
file_num = int(num_str)
names_nums.append((file_num, file_name))
_, latest_plan = max(names_nums)
return osp.join(root_dir, latest_plan)
def _make_problem_txt(planner_exts):
# returns domain_as_text, domain_name, problem_as_text, problem_name
return extract_domain_problem(planner_exts.pddl_files,
planner_exts.problem_name)
class FDTimeout(Exception):
"""Exception class for when Fast Downward times out on a problem."""
pass
# regex to scrape the domain or problem names out of a (P)PDDL file
_NAME_RE = re.compile(
r'^\s*\(\s*define\s+\((?:domain|problem)\s+([^\s\)]+)\s*\)')
def _name_from_txt(pddl_txt):
"""Takes a PDDL declaration & figures out name of the corresponding
domain/problem. Assumes no comments & only one domain/problem in the
string!"""
# (starting with a very simple solution; if this doesn't work, then I'll
# have to try running pddl_txt through the functions for
# parsing/stringifying in pddl_utils.py)
name, = _NAME_RE.findall(pddl_txt)
return name
def run_fd_raw(planner,
domain_txt,
problem_txt,
result_dir,
*,
timeout_s=None,
cost_bound=None,
mem_limit_mb=None):
"""Runs FD in a given directory & then returns path to directory."""
assert has_fd(), \
"Couldn't find Fast Downward. Use try_install_fd() before using this."
# now setup output dir & write problem text
os.makedirs(result_dir, exist_ok=True)
domain_path = osp.join(result_dir, 'domain.pddl')
problem_path = osp.join(result_dir, 'problem.pddl')
with open(domain_path, 'w') as dom_fp, open(problem_path, 'w') as prob_fp:
dom_fp.write(domain_txt)
prob_fp.write(problem_txt)
cost_bound_s = 'infinity' if cost_bound is None else str(cost_bound)
del cost_bound # so that I don't accidentally use it
# figure out where FD is and run it
cmdline = ["python", FD_PATH]
if timeout_s is not None:
assert timeout_s >= 1, "can't have <1s time limit (got %s)" % timeout_s
cmdline.extend(["--overall-time-limit", "%ds" % timeout_s])
if mem_limit_mb is not None:
assert mem_limit_mb >= 1, "can't have <1MB memory limit (got %s)" \
% mem_limit_mb
cmdline.extend(["--overall-memory-limit", "%dM" % mem_limit_mb])
cmdline.extend(['--plan-file', PLAN_BN])
def make_wlama_args(w):
# flags for LAMA's WA* thing using a specific W (the last ~3 or so
# stages of LAMA are like this)
assert isinstance(w, int) and w > 0
return [
"--evaluator", "ff=ff()", "--evaluator",
"hlm=lmcount(lm_rhw(reasonable_orders=true),pref=true)",
"--search",
"lazy_wastar([ff,hlm],preferred=[ff,hlm],w={w},bound={bound})".
format(w=w, bound=cost_bound_s)
]
# set planner flags appropriately
if planner == 'lama-2011':
# This is not quite real LAMA-2011 preset because it only supports unit
# costs (like the ASNet trainer, which I also need to fix). It should
# be sufficient for our benchmark problems though.
cost_prefs_bound = "[hff,hlm],preferred=[hff,hlm],bound={bound}" \
.format(bound=cost_bound_s)
cmdline.extend([
domain_path, problem_path, "--evaluator",
"hlm=lmcount(lm_rhw(reasonable_orders=true),pref={pref})".format(
pref=True), "--evaluator", "hff=ff()", "--search",
("iterated([lazy_greedy({cost_prefs}),"
"lazy_wastar({cost_prefs},w=5),lazy_wastar({cost_prefs},w=3),"
"lazy_wastar({cost_prefs},w=2),lazy_wastar({cost_prefs},w=1)],"
"repeat_last=true,continue_on_fail=true,bound={bound})").format(
cost_prefs=cost_prefs_bound, bound=cost_bound_s)
])
elif planner == 'lama-first':
# LAMA-first:
# fast-downward.py --alias lama-first ${dom} ${prob}
cmdline.extend([
domain_path, problem_path, "--evaluator",
("hlm=lmcount(lm_factory=lm_rhw(reasonable_orders=true),"
"transform=adapt_costs(one),pref=false)"), "--evaluator",
"hff=ff(transform=adapt_costs(one))", "--search",
("lazy_greedy([hff,hlm],preferred=[hff,hlm],cost_type=one,"
"reopen_closed=false,bound={bound})").format(bound=cost_bound_s)
])
elif planner == 'lama-w5':
# the second (i.e fourth-last) stage of LAMA-2011 (lazy WA* with W=5)
cmdline.extend([
domain_path,
problem_path,
*make_wlama_args(5),
])
elif planner == 'lama-w3':
# the third (also third-last) stage of LAMA-2011 (lazy WA* with W=3)
cmdline.extend([
domain_path,
problem_path,
*make_wlama_args(3),
])
elif planner == 'lama-w2':
# the second-last stage of LAMA-2011 (lazy WA* with W=2)
cmdline.extend([
domain_path,
problem_path,
*make_wlama_args(2),
])
elif planner == 'lama-w1':
# One step of the last stage of LAMA-2011 (lazy A*, so W=1). Note that
# there is no *real* "last stage" of LAMA, since it keeps applying the
# final stage search engine with tighter & tighter upper bounds on cost
# until it runs out of time or something like that (using iterated
# search). That means that it ends up with much better solutions than
# you can get in just one application of the planner!
cmdline.extend([
domain_path,
problem_path,
*make_wlama_args(1),
])
elif planner == 'astar-lmcut':
# A* with LM-cut:
# fast-downward.py ${dom} ${prob} --search "astar(lmcut())"
# (similar template for astar or gbf with other heuristics)
cmdline.extend([
domain_path, problem_path, "--search",
"astar(lmcut(),bound={bound})".format(bound=cost_bound_s)
])
elif planner == 'astar-lmcount':
# inadmissible variant of above
cmdline.extend([
domain_path, problem_path, "--search",
"astar(lmcount(lm_rhw()),bound={bound})".format(bound=cost_bound_s)
])
elif planner == 'astar-hadd':
cmdline.extend([
domain_path, problem_path, "--search",
"astar(add(),bound={bound})".format(bound=cost_bound_s)
])
elif planner == 'gbf-lmcut':
# gbf = greedy best first (if this works well then finding a
# generalised policy may be trivial for ASNets, using only action
# landmarks!)
cmdline.extend([
domain_path, problem_path, "--search",
"eager(single(lmcut()),bound={bound})".format(bound=cost_bound_s)
])
elif planner == 'gbf-hadd':
cmdline.extend([
domain_path, problem_path, "--search",
"eager(single(add()),bound={bound})".format(bound=cost_bound_s)
])
else:
raise ValueError("Unknown planner '%s'" % planner)
# write command line to a text file so we can play back later if this fails
cmdline_path = osp.join(result_dir, CMDLINE_BN)
with open(cmdline_path, 'w') as cmdline_fp:
cmdline_fp.write('\n'.join(cmdline))
cmdline_fp.write('\n')
# run FD, writing stderr/stdout to appropriate files
out_path = osp.join(result_dir, STDOUT_BN)
err_path = osp.join(result_dir, STDERR_BN)
with open(out_path, 'w') as out_fp, open(err_path, 'w') as err_fp:
rv = subprocess.Popen(cmdline,
cwd=result_dir,
stdout=out_fp,
stderr=err_fp,
universal_newlines=True)
rv.wait()
return rv
def run_fd_or_timeout(planner, domain_txt, problem_txt, *, timeout_s=None):
"""Takes a planner name recognised by FD (e.g `"lama-2011"`), a path to a
PDDL domain, and a path to a PDDL problem, then produces a plan as list of
state strings (or None, in case of failure to reach goal)."""
domain_name = _name_from_txt(domain_txt)
problem_name = _name_from_txt(domain_txt)
dname = '%s:%s:%s' % (planner, domain_name, problem_name)
guid = uuid.uuid1().hex
result_dir = osp.join('/tmp', 'fd-results-%s-%s' % (dname, guid))
run_fd_raw(planner=planner,
domain_txt=domain_txt,
problem_txt=problem_txt,
result_dir=result_dir,
timeout_s=timeout_s)
# could use rv.returncode to check success, but that is sometimes
# nonzero even when the planner manages to find a rough plan :(
with open(osp.join(result_dir, STDOUT_BN), 'r') as stdout_fp:
out_text = stdout_fp.read()
with open(osp.join(result_dir, STDERR_BN), 'r') as stderr_fp:
err_text = stderr_fp.read()
with open(osp.join(result_dir, CMDLINE_BN), 'r') as cmdline_fp:
cmdline = cmdline_fp.read()
# Check whether search was successful or not. If it was not, return None;
# if it was, return plan (as list of string-formatted action names, minus
# parens).
if 'Search stopped without finding a solution.' in out_text:
rv = None
elif (("Driver aborting after translate" in out_text
or "Driver aborting after search" in out_text)
and "Solution found." not in out_text):
# timeout
raise FDTimeout("FD appears to have timed out during search")
else:
assert 'Solution found.' in out_text, \
"Bad stdout for cmd %s, ret code %r. Here is stdout:\n\n%s\n\n" \
"Here is stderr:\n\n%s\n\n" \
% (cmdline, getattr(rv, 'returncode', None), out_text, err_text)
plan_path = get_plan_file_path(result_dir, PLAN_BN)
with open(plan_path, 'r') as out_plan_fp:
plan = []
for line in out_plan_fp:
line = line.strip()
if line.startswith(';'):
continue
assert line.startswith('(') and line.endswith(')')
# strip parens (so we can use act_ident_to_mdpsim_act during
# playback of solution)
action = line[1:-1]
plan.append(action)
rv = plan
# clean up output dir (we don't want to clean up in case of exception,
# since output dir can be helpful)
shutil.rmtree(result_dir)
return rv
def _simulate_plan(init_cstate, plan_strs, planner_exts):
"""Simulate a plan to obtain a sequence of states. Will include all states
visited by the plan in the order the are encountered, including initial
state and goal state. Only works for deterministic problems, obviously!"""
cstates = [init_cstate]
costs = []
for action_str in plan_strs:
this_state = cstates[-1]
assert not this_state.is_terminal
action_id \
= planner_exts.problem_meta.act_unique_id_to_index(action_str)
next_state, cost = sample_next_state(cstates[-1], action_id,
planner_exts)
costs.append(cost)
cstates.append(next_state)
assert cstates[-1].is_terminal
return cstates, costs
class FDQValueCache(object):
"""Cache of Q-values computed by calling FD repeatedly for the same
problem."""
def __init__(self,
planner_exts,
*,
planner='astar-hadd',
timeout_s=1800):
# maps each state to a value computed via FD (states are represented by
# tuples of true prop names, in no-paren format)
self.planner_exts = planner_exts
self.state_value_cache = {}
self.best_action_cache = {}
pddl_files = planner_exts.pddl_files
problem_name = planner_exts.problem_name
domain_hlist, domain_name, problem_hlist, problem_name_pddl = \
extract_domain_problem(pddl_files, problem_name)
assert problem_name == problem_name_pddl, \
"name mismatch ('%r' != '%r')" % (problem_name, problem_name_pddl)
self._domain_source = hlist_to_sexprs(domain_hlist)
self._problem_hlist = problem_hlist
self._domain_name = domain_name
self._problem_name = problem_name
self._planner_name = planner
self._timeout_s = timeout_s
self._fd_blacklist = set()
def _run_fd_with_blacklist(self, *args, **kwargs):
ident_tup = (args, tuple(sorted(kwargs)))
if ident_tup in self._fd_blacklist:
raise FDTimeout("this state previously caused planner timeout")
try:
return run_fd_or_timeout(*args, **kwargs)
except FDTimeout:
self._fd_blacklist.add(ident_tup)
raise
def compute_state_value_action(self, cstate):
"""Compute state value under V* (assumes the given planner is optimal,
which it possibly is not) and also the action recommended by FD (may be
None if no plan available). Caller may want to handle FDTimeout."""
tup_state = cstate.to_fd_proplist()
if tup_state in self.state_value_cache:
return self.state_value_cache[tup_state], \
self.best_action_cache[tup_state]
if cstate.is_terminal:
cost = 0 if cstate.is_goal else None
self.state_value_cache[tup_state] = cost
self.best_action_cache[tup_state] = None
return cost, None
# *_source is a string containing PDDL, *_hlist is the AST for the PDDL
problem_hlist = replace_init_state(self._problem_hlist, tup_state)
problem_source = hlist_to_sexprs(problem_hlist)
plan = self._run_fd_with_blacklist(self._planner_name,
self._domain_source,
problem_source,
timeout_s=self._timeout_s)
if plan is None:
# couldn't find a plan
self.state_value_cache[tup_state] = None
self.best_action_cache[tup_state] = None
return None, None
# visit all states except the last
visited_states, step_costs \
= _simulate_plan(cstate, plan, self.planner_exts)
costs_to_goal = np.cumsum(step_costs[::-1])[::-1]
visited_states = visited_states[:-1]
assert len(visited_states) == len(plan), \
"%d visited states, but %d actions in plan" \
% (len(visited_states), len(plan))
states_acts_costs = zip(visited_states, plan, costs_to_goal)
for this_cstate, this_act, cost_to_goal in states_acts_costs:
this_tup_state = this_cstate.to_fd_proplist()
if this_tup_state in self.state_value_cache:
old_val = self.state_value_cache[this_tup_state]
if cost_to_goal > old_val:
continue
self.state_value_cache[this_tup_state] = cost_to_goal
self.best_action_cache[this_tup_state] = this_act
return self.state_value_cache[tup_state], \
self.best_action_cache[this_tup_state]
def compute_state_value(self, cstate):
value, _ = self.compute_state_value_action(cstate)
return value
def compute_q_values(self, cstate, act_strs):
"""Compute Q-values for each action applicable in the current state.
Caller may want to handle FDTimeout."""
q_values = []
for act_str in act_strs:
# expecting mdpsim format (for whatever reason)
assert act_str[0] == '(' and act_str[-1] == ')'
act_strip = act_str[1:-1]
action_id = self.planner_exts.problem_meta \
.act_unique_id_to_index(act_strip)
is_enabled = cstate.acts_enabled[action_id][1]
if not is_enabled:
q_values.append(None)
continue
next_state, cost = sample_next_state(cstate, action_id,
self.planner_exts)
next_state_value = self.compute_state_value(next_state)
if next_state_value is None:
# this action leads to a dead end
q_values.append(None)
else:
q_value = cost + next_state_value
q_values.append(q_value)
return q_values
def compute_policy_envelope(self, cstate):
"""Compute the 'optimal policy envelope' for a given `Canonical State`.
Here `optimal policy envelope` really just means 'sequence of
non-terminal states visited on the way to the goal'; this is a simpler
notion than the notion of 'policy envelope' for a probabilistic
problem. Caller may want to handle FDTimeout."""
# warm up the value cache
state_value = self.compute_state_value(cstate)
if state_value is None:
return []
envelope = []
while not cstate.is_terminal:
envelope.append(cstate)
best_act_str = self.best_action_cache[cstate.to_fd_proplist()]
action_id = self.planner_exts.problem_meta \
.act_unique_id_to_index(best_act_str)
cstate, _ = sample_next_state(cstate, action_id, self.planner_exts)
envelope.append(cstate)
assert len(envelope) < 10000, \
"envelope way too big, is there an infinite loop here?"
return envelope
@contextlib.contextmanager
def _timer(task_name):
start = time.time()
yield
elapsed = time.time() - start
print('[timer] %s took %fs' % (task_name, elapsed))
def _demo_main():
# quick demo of what this file does
# (exists in part to test its functionality)
from asnets.supervised import PlannerExtensions
# install FD first
try_install_fd()
parser = argparse.ArgumentParser()
parser.add_argument(
'pddl_files',
nargs='+',
help='path to relevant PDDL files (domain, problem, etc.)')
args = parser.parse_args()
problem_name_re = re.compile(
r'^\s*\(\s*define\s+\(problem\s+([^\s\)]+)\s*\)')
for file_path in args.pddl_files[::-1]:
with open(file_path, 'r') as fp:
contents = fp.read()
matches = problem_name_re.findall(contents)
if matches:
problem_name = matches[0]
break
else:
raise ValueError("Could not find problem name in PDDL files: %s" %
', '.join(args.pddl_files))
planner_exts = PlannerExtensions(args.pddl_files, problem_name)
value_cache = FDQValueCache(planner_exts)
init_state = get_init_cstate(planner_exts)
with _timer('Getting first set of values'):
init_value = value_cache.compute_state_value(init_state)
print('The value of the initial state is', init_value)
all_act_strs = [
'(%s)' % ba.unique_ident for ba, _ in init_state.acts_enabled
]
enabled_act_strs = [
'(%s)' % ba.unique_ident for ba, enabled in init_state.acts_enabled
if enabled
]
with _timer('Getting Q-values for %d actions' % len(enabled_act_strs)):
q_values = value_cache.compute_q_values(init_state, enabled_act_strs)
print('Q-values for initial state are', q_values)
q_values_all = value_cache.compute_q_values(init_state, all_act_strs)
print('Q-values for *all* actions are', q_values_all)
policy_envelope = value_cache.compute_policy_envelope(init_state)
print('FD policy envelope for initial state is', [
' '.join('(%s)' % p for p in s.to_fd_proplist())
for s in policy_envelope
])
if __name__ == '__main__':
_demo_main()
|
There are two versions of the song " You Only Live Twice " , sung by Nancy Sinatra , one directly from the movie soundtrack , and a second one for record release arranged by Billy Strange . The movie soundtrack song is widely recognised for its striking opening bars and oriental flavour , and was far more popular on radio . The record release made No. 44 on the Billboard charts in the USA , No. 11 in UK . Both versions of the title song are available on CD .
|
-- {-# OPTIONS -v import:10 -v scope:10 #-}
module Issue1078 where
import Common.Level
import Issue1078.A
import Issue1078.B
-- Was: weird scope error in Issue1078.B
-- Should give error:
-- You tried to load Issue1078/B.agda
-- which defines the module Issue1078.A. However, according to the
-- include path this module should be defined in Issue1078/A.agda.
|
using BHAtp
ProjDir = @__DIR__
isdir(joinpath(ProjDir, "tp0")) && rm(joinpath(ProjDir, "tp0"), recursive=true)
isdir(joinpath(ProjDir, "tp")) && rm(joinpath(ProjDir, "tp"), recursive=true)
isdir(joinpath(ProjDir, "plots")) && rm(joinpath(ProjDir, "plots"), recursive=true)
ProjName = split(ProjDir, "/")[end]
bhaj = BHAJ(ProjName, ProjDir)
bhaj.ratio = 1.7
segs = [
# Element type, Material, Length, OD, ID, fc
(:bit, :steel, 0.00, 2.75, 9.0, 0.0),
(:collar, :steel, 45.00, 2.75, 7.0, 0.0),
(:stabilizer, :steel, 0.00, 2.75, 9.0, 0.0),
(:pipe, :steel, 30.00, 2.75, 7.0, 0.0),
(:stabilizer, :steel, 0.00, 2.75, 9.0, 0.0),
(:pipe, :steel, 90.00, 2.75, 7.0, 0.0),
(:stabilizer, :steel, 0.00, 2.75, 9.0, 0.0),
(:pipe, :steel, 100.00, 2.75, 7.0, 0.0)
]
traj = [
# Heading, Diameter
( 60.0, 9.0)
]
wobs = 20:10:40
incls = 20:10:40 # Or e.g. incls = [5 10 20 30 40 45 50]
@time bhaj(segs, traj, wobs, incls)
println()
display("Fetch tp=0, wob=40, incl@bit=20 solution:")
df,df_tp = show_solution(ProjDir, 40, 20, show=false, tp=false)
df[:,[2; 5:6; 9:12]] |> display
println()
println("Fetch wob=40, incl@bit=20 solution:")
df,df_tp = show_solution(ProjDir, 40, 20, show=false);
df[:,[2; 5:6; 9:12]] |> display
println()
show_tp(ProjDir, wobs, incls) |> display
|
# # Tutorials
# A suite of concrete examples are provided here as a guidance for constructing experiments.
# ## Balance Law
# An introduction on components within a balance law is provided.
# ## Atmos
# Showcase drivers for atmospheric modelling in GCM, single stack, and LES simulations are provided.
# - Dry Idealzed GCM: The Held-Suarez configuration is used as a guidance to create a driver that runs a simple GCM simulation.
# - Single Element Stack: The Burgers Equations with a passive tracer is used as a guidance to run the simulation on a single element stack.
# - LES Experiment: The dry rising bubble case is used as a quigance in creating an LES driver.
# - Topography: Experiments of dry flow over prescirbe topography (Agnesi mountain) are provided for:
# * Linear Hydrostatic Mountain
# * Linear Non-Hydrostatic Mountain
# ## Ocean
# A showcase for Ocean model is still under construction.
# ## Land
# Examples are provided in constructing balance law and solving for fundemental equations in land modelling.
# - Heat: A tutorial shows how to create a HeatModel to solve the heat equation and visualize the outputs.
# - Soil: Examples of solving fundemental equations in the soil model are provided.
# * Hydraulic Functions: a tutorial to specify the hydraulic function in the Richard's equation.
# * Soil Heat Equations: a tutorial for solving the heat equation in the soil.
# * Coupled Water and Heat: a tutorial for solving interactive heat and wateri in the soil model.
# ## Numerics (need to be moved to How-to-Guide)
# - System Solvers: Two numerical methods to solve the linear system Ax=b are provided.
# * Conjugate Gradient
# * Batched Generalized Minimal Residual
# - DG Methods
# * Filters
# ## Diagnostics
# A diagnostic tool that can
# - generate statistics for MPIStateArrays
# - validate with reference values
# for debugging purposes.
|
{-# OPTIONS --rewriting --allow-unsolved-metas #-}
open import Agda.Builtin.Equality using (_≡_)
open import Agda.Builtin.Equality.Rewrite
postulate
cast : (A B : Set) → A → B
cast-rew : (A : Set) (x : A) → cast A A x ≡ x
{-# REWRITE cast-rew #-}
postulate
A : Set
x y : A
data D (B : A → Set) (b : B y) : Set where
con : cast (B x) (B y) ? ≡ b → D B b
record R (B : A → Set) (b : B y) : Set where
field
eq : cast (B x) (B y) ? ≡ b
|
MODULE invar
! Module to store the AHOT input variables
IMPLICIT NONE
SAVE
! Parallel initialization
INTEGER :: isize, irank
! Title
CHARACTER(80) :: title
! Problem Size Specifications
INTEGER :: lambda, meth, qdord, qdtyp, nxt, nyt, npx, npy, ng, nm
REAL*8, DIMENSION(:), ALLOCATABLE :: dx, dy
! Problem size per block
INTEGER :: nx, ny
! Cell materials
INTEGER, DIMENSION(:,:), ALLOCATABLE :: mat
! Iteration Controls
REAL*8 :: err, tolr
INTEGER :: bitmx, itmx, iall
! Solution check frequency
REAL*8 :: tchk
INTEGER :: ichk
! Extra variables derived from input
INTEGER :: apo, order, ordsq
REAL*8, DIMENSION(:,:), ALLOCATABLE :: ssum
! Angular quadrature input
REAL*8, DIMENSION(:,:), ALLOCATABLE :: ang
REAL*8, DIMENSION(:), ALLOCATABLE :: w
! Boundary Conditions by quadrant (quadrants 1-4 same as basic trig. quadrants)
INTEGER :: q1bc, q2bc, q3bc, q4bc
REAL*8, DIMENSION(:), ALLOCATABLE :: psi1, psi2, psi3, psi4
! Cross section input
REAL*8, DIMENSION(:,:), ALLOCATABLE :: sigt
REAL*8, DIMENSION(:,:,:), ALLOCATABLE :: sigs
! Source data
REAL*8, DIMENSION(:,:,:,:,:), ALLOCATABLE :: s
! Editing data
INTEGER :: momp, pmoaf
! Parallel Topology setup
INTEGER :: allcomm, xcomm, ycomm, nrank, xrank, yrank
INTEGER, DIMENSION(:), ALLOCATABLE :: nxvec, nyvec
! Solution methodology
INTEGER :: itmflag
! Print the matrix
INTEGER :: matrix
END MODULE
|
Malaria : During the early 1940s , quinine was the chief anti @-@ malarial drug . Made from the bark of the South American cinchona tree , quinine was in short supply during the war , so scientists began searching for an alternative treatment . The test subjects allowed themselves to be bitten by malarial mosquitoes and when the fever reached its peak in three to four days , were given experimental treatments . At the University of Minnesota , twelve CPS men underwent tests to determine the recovery period for those infected with malaria . This research documented the debilitating effects of the disease and the amount of time required for a complete recovery .
|
[STATEMENT]
lemma fold_max_ge: "b \<le> a \<Longrightarrow> (b::nat) \<le> fold (\<lambda>x m. if m \<le> x then x else m) ys a"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. b \<le> a \<Longrightarrow> b \<le> fold (\<lambda>x m. if m \<le> x then x else m) ys a
[PROOF STEP]
by (induction ys arbitrary: a b) auto
|
{-# OPTIONS --without-K --safe #-}
module Categories.Category.Unbundled.Properties where
-- The Obj-unbundled Category is equivalent (as a type) to the
-- usual kind. Quite straightforward and because of η, the proofs are just refl.
open import Data.Product using (Σ; _,_)
open import Level
open import Function using (_↔_; mk↔′)
open import Relation.Binary.PropositionalEquality using (refl)
open import Categories.Category.Core using (Category)
open import Categories.Category.Unbundled renaming (Category to Unb-Cat)
private
variable
o ℓ e : Level
unpack : Category o ℓ e → Σ (Set o) (λ Obj → Unb-Cat Obj ℓ e)
unpack C = C.Obj , record { C }
where module C = Category C
unpack′ : (C : Category o ℓ e) → Unb-Cat (Category.Obj C) ℓ e
unpack′ C = record { C }
where module C = Category C
pack : Σ (Set o) (λ Obj → Unb-Cat Obj ℓ e) → Category o ℓ e
pack (o , uc) = record { Obj = o; UC }
where module UC = Unb-Cat uc
pack′ : {Obj : Set o} → Unb-Cat Obj ℓ e → Category o ℓ e
pack′ {Obj = o} uc = record { Obj = o; UC }
where module UC = Unb-Cat uc
equiv : (Category o ℓ e) ↔ (Σ (Set o) (λ Obj → Unb-Cat Obj ℓ e))
equiv = mk↔′ unpack pack (λ _ → refl) λ _ → refl
|
[STATEMENT]
lemma hypext_power_Hyperdual_parts:
"(*h* (\<lambda>x. x ^ n)) (a *\<^sub>H ba + b *\<^sub>H e1 + c *\<^sub>H e2 + d *\<^sub>H e12) =
a ^ n *\<^sub>H ba + (of_nat n * b * a ^ (n - 1)) *\<^sub>H e1 + (of_nat n * c * a ^ (n - 1)) *\<^sub>H e2 +
(d * (of_nat n * a ^ (n - 1)) + b * c * (of_nat n * of_nat (n - 1) * a ^ (n - 2))) *\<^sub>H e12"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (*h* (\<lambda>x. x ^ n)) (a *\<^sub>H ba + b *\<^sub>H e1 + c *\<^sub>H e2 + d *\<^sub>H e12) = a ^ n *\<^sub>H ba + (of_nat n * b * a ^ (n - 1)) *\<^sub>H e1 + (of_nat n * c * a ^ (n - 1)) *\<^sub>H e2 + (d * (of_nat n * a ^ (n - 1)) + b * c * (of_nat n * of_nat (n - 1) * a ^ (n - 2))) *\<^sub>H e12
[PROOF STEP]
by (simp add: Hyperdual_eq [symmetric] hypext_power_Hyperdual)
|
(* Verify simple double floating add. *)
Require Import VST.floyd.proofauto.
Require Import Step0.step0.
Require Import compcert.lib.Floats.
(* The next line is "boilerplate", always required after importing an AST. *)
Instance CompSpecs : compspecs. make_compspecs prog. Defined.
Definition Vprog : varspecs. mk_varspecs prog. Defined.
(* In this section we abstract over the semantics of the function that
computes the delta.
*)
Section XD_Abstract.
Variable delta : float -> float.
Definition oneStep0 (input: float) : float :=
let xd := delta input in
Float.add input xd.
Definition xdp_spec :=
WITH xf: float
PRE [ _x OF tdouble]
PROP ()
LOCAL (temp _x (Vfloat xf))
SEP ()
POST [ tdouble ]
PROP()
LOCAL (temp ret_temp (Vfloat (delta xf)))
SEP().
Definition xdp_type :=
(tptr (Tfunction (Tcons tdouble Tnil) tdouble cc_default)).
Definition step0_spec :=
DECLARE _step0
WITH x: float, xdp: val
PRE [ _x OF tdouble,
_xdp OF xdp_type]
PROP( )
LOCAL(temp _x (Vfloat x); temp _xdp xdp)
SEP (func_ptr' xdp_spec xdp)
POST [ tdouble ]
PROP()
LOCAL(temp ret_temp (Vfloat (oneStep0 x)))
SEP (func_ptr' xdp_spec xdp).
Definition Gprog : funspecs :=
ltac:(with_library prog [ step0_spec ]).
Lemma body_step0: semax_body Vprog Gprog f_step0 step0_spec.
Proof.
start_function.
forward_call x.
forward.
forward.
Qed.
End XD_Abstract.
|
import logging
import os.path
import networkx as nx
import numpy as np
import re
import selfies as sf
import sys
import time
import torch
from rdkit import Chem
from torch.utils.data import Dataset
from typing import Dict, List, Tuple
from utils.chem_utils import ATOM_FDIM, BOND_FDIM, get_atom_features_sparse, get_bond_features
from utils.rxn_graphs import RxnGraph
def tokenize_selfies_from_smiles(smi: str) -> str:
encoded_selfies = sf.encoder(smi)
tokens = list(sf.split_selfies(encoded_selfies))
assert encoded_selfies == "".join(tokens)
return " ".join(tokens)
def tokenize_smiles(smi: str) -> str:
pattern = r"(\[[^\]]+]|Br?|Cl?|N|O|S|P|F|I|b|c|n|o|s|p|\(|\)|\.|=|#|-|\+|\\|\/|:|~|@|\?|>|\*|\$|\%[0-9]{2}|[0-9])"
regex = re.compile(pattern)
tokens = [token for token in regex.findall(smi)]
assert smi == "".join(tokens), f"Tokenization mismatch. smi: {smi}, tokens: {tokens}"
return " ".join(tokens)
def canonicalize_smiles(smiles, remove_atom_number=False, trim=True, suppress_warning=False):
cano_smiles = ""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
cano_smiles = ""
else:
if trim and mol.GetNumHeavyAtoms() < 2:
if not suppress_warning:
logging.info(f"Problematic smiles: {smiles}, setting it to 'CC'")
cano_smiles = "CC" # TODO: hardcode to ignore
else:
if remove_atom_number:
[a.ClearProp('molAtomMapNumber') for a in mol.GetAtoms()]
cano_smiles = Chem.MolToSmiles(mol, isomericSmiles=True)
return cano_smiles
def len2idx(lens) -> np.ndarray:
# end_indices = np.cumsum(np.concatenate(lens, axis=0))
end_indices = np.cumsum(lens)
start_indices = np.concatenate([[0], end_indices[:-1]], axis=0)
indices = np.stack([start_indices, end_indices], axis=1)
return indices
class S2SBatch:
def __init__(self,
src_token_ids: torch.Tensor,
src_lengths: torch.Tensor,
tgt_token_ids: torch.Tensor,
tgt_lengths: torch.Tensor):
self.src_token_ids = src_token_ids
self.src_lengths = src_lengths
self.tgt_token_ids = tgt_token_ids
self.tgt_lengths = tgt_lengths
self.size = len(src_lengths)
def to(self, device):
self.src_token_ids = self.src_token_ids.to(device)
self.src_lengths = self.src_lengths.to(device)
self.tgt_token_ids = self.tgt_token_ids.to(device)
self.tgt_lengths = self.tgt_lengths.to(device)
def pin_memory(self):
self.src_token_ids = self.src_token_ids.pin_memory()
self.src_lengths = self.src_lengths.pin_memory()
self.tgt_token_ids = self.tgt_token_ids.pin_memory()
self.tgt_lengths = self.tgt_lengths.pin_memory()
return self
def log_tensor_shape(self):
logging.info(f"src_token_ids: {self.src_token_ids.shape}, "
f"src_lengths: {self.src_lengths}, "
f"tgt_token_ids: {self.tgt_token_ids.shape}, "
f"tgt_lengths: {self.tgt_lengths}")
class S2SDataset(Dataset):
def __init__(self, args, file: str):
self.args = args
self.src_token_ids = []
self.src_lens = []
self.tgt_token_ids = []
self.tgt_lens = []
self.data_indices = []
self.batch_sizes = []
self.batch_starts = []
self.batch_ends = []
logging.info(f"Loading preprocessed features from {file}")
feat = np.load(file)
for attr in ["src_token_ids", "src_lens", "tgt_token_ids", "tgt_lens"]:
setattr(self, attr, feat[attr])
assert len(self.src_token_ids) == len(self.src_lens) == len(self.tgt_token_ids) == len(self.tgt_lens), \
f"Lengths of source and target mismatch!"
self.data_size = len(self.src_token_ids)
self.data_indices = np.arange(self.data_size)
logging.info(f"Loaded and initialized S2SDataset, size: {self.data_size}")
def sort(self):
start = time.time()
logging.info(f"Calling S2SDataset.sort()")
sys.stdout.flush()
self.data_indices = np.argsort(self.src_lens + self.tgt_lens)
logging.info(f"Done, time: {time.time() - start: .2f} s")
sys.stdout.flush()
def shuffle_in_bucket(self, bucket_size: int):
start = time.time()
logging.info(f"Calling S2SDataset.shuffle_in_bucket()")
sys.stdout.flush()
for i in range(0, self.data_size, bucket_size):
np.random.shuffle(self.data_indices[i:i+bucket_size])
logging.info(f"Done, time: {time.time() - start: .2f} s")
sys.stdout.flush()
def batch(self, batch_type: str, batch_size: int):
start = time.time()
logging.info(f"Calling S2SDataset.batch()")
sys.stdout.flush()
self.batch_sizes = []
if batch_type == "samples":
raise NotImplementedError
elif batch_type == "atoms":
raise NotImplementedError
elif batch_type == "tokens":
sample_size = 0
max_batch_src_len = 0
max_batch_tgt_len = 0
for data_idx in self.data_indices:
src_len = self.src_lens[data_idx]
tgt_len = self.tgt_lens[data_idx]
max_batch_src_len = max(src_len, max_batch_src_len)
max_batch_tgt_len = max(tgt_len, max_batch_tgt_len)
while self.args.enable_amp and not max_batch_src_len % 8 == 0: # for amp
max_batch_src_len += 1
while self.args.enable_amp and not max_batch_tgt_len % 8 == 0: # for amp
max_batch_tgt_len += 1
if (max_batch_src_len + max_batch_tgt_len) * (sample_size + 1) <= batch_size:
sample_size += 1
elif self.args.enable_amp and not sample_size % 8 == 0:
sample_size += 1
else:
self.batch_sizes.append(sample_size)
sample_size = 1
max_batch_src_len = src_len
max_batch_tgt_len = tgt_len
while self.args.enable_amp and not max_batch_src_len % 8 == 0: # for amp
max_batch_src_len += 1
while self.args.enable_amp and not max_batch_tgt_len % 8 == 0: # for amp
max_batch_tgt_len += 1
# lastly
self.batch_sizes.append(sample_size)
self.batch_sizes = np.array(self.batch_sizes)
assert np.sum(self.batch_sizes) == self.data_size, \
f"Size mismatch! Data size: {self.data_size}, sum batch sizes: {np.sum(self.batch_sizes)}"
self.batch_ends = np.cumsum(self.batch_sizes)
self.batch_starts = np.concatenate([[0], self.batch_ends[:-1]])
else:
raise ValueError(f"batch_type {batch_type} not supported!")
logging.info(f"Done, time: {time.time() - start: .2f} s, total batches: {self.__len__()}")
sys.stdout.flush()
def __getitem__(self, index: int) -> S2SBatch:
batch_start = self.batch_starts[index]
batch_end = self.batch_ends[index]
data_indices = self.data_indices[batch_start:batch_end]
# collating, essentially
src_token_ids = self.src_token_ids[data_indices]
src_lengths = self.src_lens[data_indices]
tgt_token_ids = self.tgt_token_ids[data_indices]
tgt_lengths = self.tgt_lens[data_indices]
src_token_ids = src_token_ids[:, :max(src_lengths)]
tgt_token_ids = tgt_token_ids[:, :max(tgt_lengths)]
src_token_ids = torch.as_tensor(src_token_ids, dtype=torch.long)
tgt_token_ids = torch.as_tensor(tgt_token_ids, dtype=torch.long)
src_lengths = torch.tensor(src_lengths, dtype=torch.long)
tgt_lengths = torch.tensor(tgt_lengths, dtype=torch.long)
s2s_batch = S2SBatch(
src_token_ids=src_token_ids,
src_lengths=src_lengths,
tgt_token_ids=tgt_token_ids,
tgt_lengths=tgt_lengths
)
# s2s_batch.log_tensor_shape()
return s2s_batch
def __len__(self):
return len(self.batch_sizes)
class G2SBatch:
def __init__(self,
fnode: torch.Tensor,
fmess: torch.Tensor,
agraph: torch.Tensor,
bgraph: torch.Tensor,
atom_scope: List,
bond_scope: List,
tgt_token_ids: torch.Tensor,
tgt_lengths: torch.Tensor,
distances: torch.Tensor = None):
self.fnode = fnode
self.fmess = fmess
self.agraph = agraph
self.bgraph = bgraph
self.atom_scope = atom_scope
self.bond_scope = bond_scope
self.tgt_token_ids = tgt_token_ids
self.tgt_lengths = tgt_lengths
self.distances = distances
self.size = len(tgt_lengths)
def to(self, device):
self.fnode = self.fnode.to(device)
self.fmess = self.fmess.to(device)
self.agraph = self.agraph.to(device)
self.bgraph = self.bgraph.to(device)
self.tgt_token_ids = self.tgt_token_ids.to(device)
self.tgt_lengths = self.tgt_lengths.to(device)
if self.distances is not None:
self.distances = self.distances.to(device)
def pin_memory(self):
self.fnode = self.fnode.pin_memory()
self.fmess = self.fmess.pin_memory()
self.agraph = self.agraph.pin_memory()
self.bgraph = self.bgraph.pin_memory()
self.tgt_token_ids = self.tgt_token_ids.pin_memory()
self.tgt_lengths = self.tgt_lengths.pin_memory()
if self.distances is not None:
self.distances = self.distances.pin_memory()
return self
def log_tensor_shape(self):
logging.info(f"fnode: {self.fnode.shape}, "
f"fmess: {self.fmess.shape}, "
f"tgt_token_ids: {self.tgt_token_ids.shape}, "
f"tgt_lengths: {self.tgt_lengths}")
class G2SDataset(Dataset):
def __init__(self, args, file: str):
self.args = args
self.a_scopes = []
self.b_scopes = []
self.a_features = []
self.b_features = []
self.a_graphs = []
self.b_graphs = []
self.a_scopes_lens = []
self.b_scopes_lens = []
self.a_features_lens = []
self.b_features_lens = []
self.src_token_ids = [] # loaded but not batched
self.src_lens = []
self.tgt_token_ids = []
self.tgt_lens = []
self.data_indices = []
self.batch_sizes = []
self.batch_starts = []
self.batch_ends = []
self.vocab = load_vocab(args.vocab_file)
self.vocab_tokens = [k for k, v in sorted(self.vocab.items(), key=lambda tup: tup[1])]
logging.info(f"Loading preprocessed features from {file}")
feat = np.load(file)
for attr in ["a_scopes", "b_scopes", "a_features", "b_features", "a_graphs", "b_graphs",
"a_scopes_lens", "b_scopes_lens", "a_features_lens", "b_features_lens",
"src_token_ids", "src_lens", "tgt_token_ids", "tgt_lens"]:
setattr(self, attr, feat[attr])
# mask out chiral tag (as UNSPECIFIED)
self.a_features[:, 6] = 2
assert len(self.a_scopes_lens) == len(self.b_scopes_lens) == \
len(self.a_features_lens) == len(self.b_features_lens) == \
len(self.src_token_ids) == len(self.src_lens) == \
len(self.tgt_token_ids) == len(self.tgt_lens), \
f"Lengths of source and target mismatch!"
self.a_scopes_indices = len2idx(self.a_scopes_lens)
self.b_scopes_indices = len2idx(self.b_scopes_lens)
self.a_features_indices = len2idx(self.a_features_lens)
self.b_features_indices = len2idx(self.b_features_lens)
del self.a_scopes_lens, self.b_scopes_lens, self.a_features_lens, self.b_features_lens
self.data_size = len(self.src_token_ids)
self.data_indices = np.arange(self.data_size)
logging.info(f"Loaded and initialized G2SDataset, size: {self.data_size}")
def sort(self):
if self.args.verbose:
start = time.time()
logging.info(f"Calling G2SDataset.sort()")
sys.stdout.flush()
self.data_indices = np.argsort(self.src_lens)
logging.info(f"Done, time: {time.time() - start: .2f} s")
sys.stdout.flush()
else:
self.data_indices = np.argsort(self.src_lens)
def shuffle_in_bucket(self, bucket_size: int):
if self.args.verbose:
start = time.time()
logging.info(f"Calling G2SDataset.shuffle_in_bucket()")
sys.stdout.flush()
for i in range(0, self.data_size, bucket_size):
np.random.shuffle(self.data_indices[i:i+bucket_size])
logging.info(f"Done, time: {time.time() - start: .2f} s")
sys.stdout.flush()
else:
for i in range(0, self.data_size, bucket_size):
np.random.shuffle(self.data_indices[i:i + bucket_size])
def batch(self, batch_type: str, batch_size: int):
start = time.time()
logging.info(f"Calling G2SDataset.batch()")
sys.stdout.flush()
self.batch_sizes = []
if batch_type == "samples":
raise NotImplementedError
elif batch_type == "atoms":
raise NotImplementedError
elif batch_type.startswith("tokens"):
sample_size = 0
max_batch_src_len = 0
max_batch_tgt_len = 0
for data_idx in self.data_indices:
src_len = self.src_lens[data_idx]
tgt_len = self.tgt_lens[data_idx]
max_batch_src_len = max(src_len, max_batch_src_len)
max_batch_tgt_len = max(tgt_len, max_batch_tgt_len)
while self.args.enable_amp and not max_batch_src_len % 8 == 0: # for amp
max_batch_src_len += 1
while self.args.enable_amp and not max_batch_tgt_len % 8 == 0: # for amp
max_batch_tgt_len += 1
if batch_type == "tokens" and \
max_batch_src_len * (sample_size + 1) <= batch_size:
sample_size += 1
elif batch_type == "tokens_sum" and \
(max_batch_src_len + max_batch_tgt_len) * (sample_size + 1) <= batch_size:
sample_size += 1
elif self.args.enable_amp and not sample_size % 8 == 0:
sample_size += 1
else:
self.batch_sizes.append(sample_size)
sample_size = 1
max_batch_src_len = src_len
max_batch_tgt_len = tgt_len
while self.args.enable_amp and not max_batch_src_len % 8 == 0: # for amp
max_batch_src_len += 1
while self.args.enable_amp and not max_batch_tgt_len % 8 == 0: # for amp
max_batch_tgt_len += 1
'''
sample_size = 0
max_batch_src_len = 0
for data_idx in self.data_indices:
src_len = self.src_lens[data_idx]
max_batch_src_len = max(src_len, max_batch_src_len)
while self.args.enable_amp and not max_batch_src_len % 8 == 0: # for amp
max_batch_src_len += 1
if max_batch_src_len * (sample_size + 1) <= batch_size:
sample_size += 1
elif self.args.enable_amp and not sample_size % 8 == 0:
sample_size += 1
else:
self.batch_sizes.append(sample_size)
sample_size = 1
max_batch_src_len = src_len
while self.args.enable_amp and not max_batch_src_len % 8 == 0: # for amp
max_batch_src_len += 1
'''
# lastly
self.batch_sizes.append(sample_size)
self.batch_sizes = np.array(self.batch_sizes)
assert np.sum(self.batch_sizes) == self.data_size, \
f"Size mismatch! Data size: {self.data_size}, sum batch sizes: {np.sum(self.batch_sizes)}"
self.batch_ends = np.cumsum(self.batch_sizes)
self.batch_starts = np.concatenate([[0], self.batch_ends[:-1]])
else:
raise ValueError(f"batch_type {batch_type} not supported!")
logging.info(f"Done, time: {time.time() - start: .2f} s, total batches: {self.__len__()}")
sys.stdout.flush()
def __getitem__(self, index: int) -> G2SBatch:
batch_index = index
batch_start = self.batch_starts[batch_index]
batch_end = self.batch_ends[batch_index]
data_indices = self.data_indices[batch_start:batch_end]
# collating, essentially
# source (graph)
graph_features = []
a_lengths = []
for data_index in data_indices:
start, end = self.a_scopes_indices[data_index]
a_scope = self.a_scopes[start:end]
a_length = a_scope[-1][0] + a_scope[-1][1] - a_scope[0][0]
start, end = self.b_scopes_indices[data_index]
b_scope = self.b_scopes[start:end]
start, end = self.a_features_indices[data_index]
a_feature = self.a_features[start:end]
a_graph = self.a_graphs[start:end]
start, end = self.b_features_indices[data_index]
b_feature = self.b_features[start:end]
b_graph = self.b_graphs[start:end]
graph_feature = (a_scope, b_scope, a_feature, b_feature, a_graph, b_graph)
graph_features.append(graph_feature)
a_lengths.append(a_length)
fnode, fmess, agraph, bgraph, atom_scope, bond_scope = collate_graph_features(graph_features)
# target (seq)
tgt_token_ids = self.tgt_token_ids[data_indices]
tgt_lengths = self.tgt_lens[data_indices]
tgt_token_ids = tgt_token_ids[:, :max(tgt_lengths)]
tgt_token_ids = torch.as_tensor(tgt_token_ids, dtype=torch.long)
tgt_lengths = torch.tensor(tgt_lengths, dtype=torch.long)
distances = None
if self.args.compute_graph_distance:
distances = collate_graph_distances(self.args, graph_features, a_lengths)
"""
logging.info("--------------------src_tokens--------------------")
for data_index in data_indices:
smi = "".join(self.vocab_tokens[src_token_id] for src_token_id in self.src_token_ids[data_index])
logging.info(smi)
logging.info("--------------------distances--------------------")
logging.info(f"{distances}")
exit(0)
"""
g2s_batch = G2SBatch(
fnode=fnode,
fmess=fmess,
agraph=agraph,
bgraph=bgraph,
atom_scope=atom_scope,
bond_scope=bond_scope,
tgt_token_ids=tgt_token_ids,
tgt_lengths=tgt_lengths,
distances=distances
)
# g2s_batch.log_tensor_shape()
return g2s_batch
def __len__(self):
return len(self.batch_sizes)
def get_graph_from_smiles(smi: str):
mol = Chem.MolFromSmiles(smi)
rxn_graph = RxnGraph(reac_mol=mol)
return rxn_graph
def get_graph_features_from_smi(_args):
i, smi, use_rxn_class = _args
assert isinstance(smi, str) and isinstance(use_rxn_class, bool)
if i > 0 and i % 10000 == 0:
logging.info(f"Processing {i}th SMILES")
atom_features = []
bond_features = []
edge_dict = {}
if not smi.strip():
smi = "CC" # hardcode to ignore
graph = get_graph_from_smiles(smi).reac_mol
mol = graph.mol
assert mol.GetNumAtoms() == len(graph.G_dir)
G = nx.convert_node_labels_to_integers(graph.G_dir, first_label=0)
# node iteration to get sparse atom features
for v, attr in G.nodes(data="label"):
atom_feat = get_atom_features_sparse(mol.GetAtomWithIdx(v),
use_rxn_class=use_rxn_class,
rxn_class=graph.rxn_class)
atom_features.append(atom_feat)
a_graphs = [[] for _ in range(len(atom_features))]
# edge iteration to get (dense) bond features
for u, v, attr in G.edges(data='label'):
bond_feat = get_bond_features(mol.GetBondBetweenAtoms(u, v))
bond_feat = [u, v] + bond_feat
bond_features.append(bond_feat)
eid = len(edge_dict)
edge_dict[(u, v)] = eid
a_graphs[v].append(eid)
b_graphs = [[] for _ in range(len(bond_features))]
# second edge iteration to get neighboring edges (after edge_dict is updated fully)
for bond_feat in bond_features:
u, v = bond_feat[:2]
eid = edge_dict[(u, v)]
for w in G.predecessors(u):
if not w == v:
b_graphs[eid].append(edge_dict[(w, u)])
# padding
for a_graph in a_graphs:
while len(a_graph) < 11: # OH MY GOODNESS... Fe can be bonded to 10...
a_graph.append(1e9)
for b_graph in b_graphs:
while len(b_graph) < 11: # OH MY GOODNESS... Fe can be bonded to 10...
b_graph.append(1e9)
a_scopes = np.array(graph.atom_scope, dtype=np.int32)
a_scopes_lens = a_scopes.shape[0]
b_scopes = np.array(graph.bond_scope, dtype=np.int32)
b_scopes_lens = b_scopes.shape[0]
a_features = np.array(atom_features, dtype=np.int32)
a_features_lens = a_features.shape[0]
b_features = np.array(bond_features, dtype=np.int32)
b_features_lens = b_features.shape[0]
a_graphs = np.array(a_graphs, dtype=np.int32)
b_graphs = np.array(b_graphs, dtype=np.int32)
return a_scopes, a_scopes_lens, b_scopes, b_scopes_lens, \
a_features, a_features_lens, b_features, b_features_lens, a_graphs, b_graphs
def collate_graph_features(graph_features: List[Tuple], directed: bool = True, use_rxn_class: bool = False) \
-> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, List[np.ndarray], List[np.ndarray]]:
if directed:
padded_features = get_atom_features_sparse(Chem.Atom("*"), use_rxn_class=use_rxn_class, rxn_class=0)
fnode = [np.array(padded_features)]
fmess = [np.zeros(shape=[1, 2 + BOND_FDIM], dtype=np.int32)]
agraph = [np.zeros(shape=[1, 11], dtype=np.int32)]
bgraph = [np.zeros(shape=[1, 11], dtype=np.int32)]
n_unique_bonds = 1
edge_offset = 1
atom_scope, bond_scope = [], []
for bid, graph_feature in enumerate(graph_features):
a_scope, b_scope, atom_features, bond_features, a_graph, b_graph = graph_feature
a_scope = a_scope.copy()
b_scope = b_scope.copy()
atom_features = atom_features.copy()
bond_features = bond_features.copy()
a_graph = a_graph.copy()
b_graph = b_graph.copy()
atom_offset = len(fnode)
bond_offset = n_unique_bonds
n_unique_bonds += int(bond_features.shape[0] / 2) # This should be correct?
a_scope[:, 0] += atom_offset
b_scope[:, 0] += bond_offset
atom_scope.append(a_scope)
bond_scope.append(b_scope)
# node iteration is reduced to an extend
fnode.extend(atom_features)
# edge iteration is reduced to an append
bond_features[:, :2] += atom_offset
fmess.append(bond_features)
a_graph += edge_offset
a_graph[a_graph >= 999999999] = 0 # resetting padding edge to point towards edge 0
agraph.append(a_graph)
b_graph += edge_offset
b_graph[b_graph >= 999999999] = 0 # resetting padding edge to point towards edge 0
bgraph.append(b_graph)
edge_offset += bond_features.shape[0]
# densification
fnode = np.stack(fnode, axis=0)
fnode_one_hot = np.zeros([fnode.shape[0], sum(ATOM_FDIM)], dtype=np.float32)
for i in range(len(ATOM_FDIM) - 1):
fnode[:, i+1:] += ATOM_FDIM[i] # cumsum, essentially
for i, feat in enumerate(fnode): # Looks vectorizable?
# fnode_one_hot[i, feat[feat < 9999]] = 1
fnode_one_hot[i, feat[feat < sum(ATOM_FDIM)]] = 1
fnode = torch.as_tensor(fnode_one_hot, dtype=torch.float)
fmess = torch.as_tensor(np.concatenate(fmess, axis=0), dtype=torch.float)
agraph = np.concatenate(agraph, axis=0)
column_idx = np.argwhere(np.all(agraph[..., :] == 0, axis=0))
agraph = agraph[:, :column_idx[0, 0] + 1] # drop trailing columns of 0, leaving only 1 last column of 0
bgraph = np.concatenate(bgraph, axis=0)
column_idx = np.argwhere(np.all(bgraph[..., :] == 0, axis=0))
bgraph = bgraph[:, :column_idx[0, 0] + 1] # drop trailing columns of 0, leaving only 1 last column of 0
agraph = torch.as_tensor(agraph, dtype=torch.long)
bgraph = torch.as_tensor(bgraph, dtype=torch.long)
else:
raise NotImplementedError
return fnode, fmess, agraph, bgraph, atom_scope, bond_scope
def collate_graph_distances(args, graph_features: List[Tuple], a_lengths: List[int]) -> torch.Tensor:
max_len = max(a_lengths)
distances = []
for bid, (graph_feature, a_length) in enumerate(zip(graph_features, a_lengths)):
_, _, _, bond_features, _, _ = graph_feature
bond_features = bond_features.copy()
# compute adjacency
adjacency = np.zeros((a_length, a_length), dtype=np.int32)
for bond_feature in bond_features:
u, v = bond_feature[:2]
adjacency[u, v] = 1
# compute graph distance
distance = adjacency.copy()
shortest_paths = adjacency.copy()
path_length = 2
stop_counter = 0
non_zeros = 0
while 0 in distance:
shortest_paths = np.matmul(shortest_paths, adjacency)
shortest_paths = path_length * (shortest_paths > 0)
new_distance = distance + (distance == 0) * shortest_paths
# if np.count_nonzero(new_distance) == np.count_nonzero(distance):
if np.count_nonzero(new_distance) <= non_zeros:
stop_counter += 1
else:
non_zeros = np.count_nonzero(new_distance)
stop_counter = 0
if args.task == "reaction_prediction" and stop_counter == 3:
break
distance = new_distance
path_length += 1
# bucket
distance[(distance > 8) & (distance < 15)] = 8
distance[distance >= 15] = 9
if args.task == "reaction_prediction":
distance[distance == 0] = 10
# reset diagonal
np.fill_diagonal(distance, 0)
# padding
if args.task == "reaction_prediction":
padded_distance = np.ones((max_len, max_len), dtype=np.int32) * 11
else:
padded_distance = np.ones((max_len, max_len), dtype=np.int32) * 10
padded_distance[:a_length, :a_length] = distance
distances.append(padded_distance)
distances = np.stack(distances)
distances = torch.as_tensor(distances, dtype=torch.long)
return distances
def make_vocab(fns: Dict[str, List[Tuple[str, str]]], vocab_file: str, tokenized=True):
assert tokenized, f"Vocab can only be made from tokenized files"
logging.info(f"Making vocab from {fns}")
vocab = {}
for phase, file_list in fns.items():
for src_file, tgt_file in file_list:
for fn in [src_file, tgt_file]:
with open(fn, "r") as f:
for line in f:
tokens = line.strip().split()
for token in tokens:
if token in vocab:
vocab[token] += 1
else:
vocab[token] = 1
logging.info(f"Saving vocab into {vocab_file}")
with open(vocab_file, "w") as of:
of.write("_PAD\n_UNK\n_SOS\n_EOS\n")
for token, count in vocab.items():
of.write(f"{token}\t{count}\n")
def load_vocab(vocab_file: str) -> Dict[str, int]:
if os.path.exists(vocab_file):
logging.info(f"Loading vocab from {vocab_file}")
else:
vocab_file = "./preprocessed/default_vocab_smiles.txt"
logging.info(f"Vocab file invalid, loading default vocab from {vocab_file}")
vocab = {}
with open(vocab_file, "r") as f:
for i, line in enumerate(f):
token = line.strip().split("\t")[0]
vocab[token] = i
return vocab
def data_util_test():
pass
if __name__ == "__main__":
data_util_test()
|
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
import os
import numpy as np
from src.model_utils.config import config
def cal_acc():
'''caculate accuracy'''
bs = config.batch_size
label_path = os.path.join(config.pre_result_path, "label_bs" + str(bs) + ".npy")
file_num = len(os.listdir(config.post_result_path))
acc_sum, sample_num = 0, 0
label_list = np.load(label_path)
for i in range(file_num):
f = os.path.join(config.post_result_path, "c3d_bs" + str(bs) + "_" + str(i) + "_0.bin")
predictions = np.fromfile(f, np.float32).reshape(bs, config.num_classes)
label = label_list[i]
acc = np.sum(np.argmax(predictions, 1) == label[:, -1])
batch_size = label.shape[0]
acc_sum += acc
sample_num += batch_size
accuracy_top1 = acc_sum / sample_num
print('eval result: top_1 {:.3f}%'.format(accuracy_top1 * 100))
if __name__ == '__main__':
cal_acc()
|
<a href="https://colab.research.google.com/github/alexmascension/ANMI/blob/main/notebook/T4.ipynb" target="_parent"></a>
# Tema 4: Aproximación de funciones
```python
!pip install -r https://raw.githubusercontent.com/alexmascension/ANMI/main/requirements.txt
```
```python
from sympy import *
from sympy.matrices import Matrix as mat
from sympy.matrices import randMatrix
from sympy import symbols
import sympy
import numpy as np
from scipy.linalg import orth
from matplotlib import pyplot as plt
import matplotlib as mpl
mpl.rcParams['figure.dpi'] = 150
```
```python
from anmi.genericas import norma_p_func, norma_inf_func
from anmi.T4 import metodo_ruffini
from anmi.T4 import producto_deriv, producto_asecas, producto_escalar_peso, metodo_gram, gram_schmidt_f, polinomios_orto_peso
from anmi.T4 import producto_escalar_trigono, coefs_fourier, coefs_fourier_discr, serie_fourier
from anmi.T4 import polinomios_bernstein
```
```python
x, y, z, a, lambda_ = symbols('x'), symbols('y'), symbols('z'), symbols('a'), symbols('lambda')
```
El objetivo de la aproximación de funciones es encontrar una función de caracteristicas menores o con términos más fáciles para computar, que se aproxime a una función dada en un intervalo o conjunto de puntos determinado. A nivel computacional, también es más eficiente y estable poder emplear cierto tipo de funciones de aproximación.
## Representación anidada (algoritmo de Horner) / Método de Ruffini
Si tenemos un polinomio $p(x) = a_0 + a_1x + a_2x^2+\cdots+a_nx^n$, entonces podemos hacer el polinomio más compacto, en la forma $p(x) = q_1(q_2(\cdots(q_n(x)))$, tal que $q_i(x) = a_{i-1} + a_i(x)$.
```python
help(metodo_ruffini)
```
```python
poli_1 = Poly(x**3 - x**2 + 2*x - 5)
```
```python
metodo_ruffini(poli_1, 1)
```
## Aproximación de funciones
Si $f$ es una función en un espacio vectorial $V$ podemos definir una norma $||\;\;||$, que es una aplicación que cumple:
* $||f|| = 0 \iff f = 0$
* $||\lambda f|| = |\lambda|\,||f||$
* $||f + g|| \le ||f|| + ||g||$
Si fijamos un subespacio $U \subset V$, podemos buscar una función $g\in U$ tal que sea la más similar.
Si queremos medir la distancia entre 2 funciones, hay múltiples opciones:
* Norma 2: $||f||_2 = \left( \int_a^bf(x)^2 dx \right)^\frac{1}{2}$
* Norma p: $||f||_p = \left( \int_a^b |f(x)|^p dx \right)^\frac{1}{p}$
* Norma inf: $||f||_{\inf} = \max_{x \in [a,b]} |f(x)|$
```python
f = x
g1 = sin(x)
g2 = 1 - cos(x)
```
```python
norma_p_func(f - g1, p=2, a=0, b=2*pi)
```
```python
norma_inf_func(f - g1, a=0, b=2*pi)
```
```python
norma_p_func(f - g2, p=2, a=0, b=2*pi)
```
```python
norma_inf_func(f - g2, a=0, b=2*pi)
```
### Aproximación por mínimos cuadrados (continua y discreta)
Para la aproximación definimos el producto escalar como una aplicación $\langle\,,\rangle \; :\,V \times V \rightarrow \mathbb{R}^+$ que verifica:
* $\langle f, f\rangle = \iff f = 0$
* $\langle f, g\rangle =\langle g, f\rangle$
* $\langle\alpha f+\mu g, h\rangle = \alpha\langle f, h\rangle + \mu \langle g, h\rangle$
La norma se define como $||f|| = \langle f, f\rangle^{\frac{1}{2}}$.
Una forma de producto escalar es, por ejemplo:
$$\langle f, g \rangle = \int_a^b f(x)g(x) dx$$
Esa forma puede aplicarse de forma discreta (para un conjunto discreto $I = \{x_1, x_2, \cdots, x_m\}$ como :
$$\langle f, g \rangle = \sum_{i \in I} f(i)g(i)$$
En la aproximación de mínimos cuadrados deseamos encontrar, para una base $\{\phi_0, \cdots, \phi_n\}$ de $U$, un vector $\alpha$ que minimice una función de coste $J(\alpha) = ||f - \sum_0^n \alpha_i\phi_i||^2$. Para ello se emplea el método de Gram, que consiste en encontrar la solución a
$$G\alpha = \bar{f}$$
donde $G_{ij} = \langle\phi_i, \phi_j\rangle$ y $\bar{f}_i = \langle f, \phi_i\rangle$ en un producto escalar definido arbitrariamente.
**IMPORTANTE**
Si la base $U$ es ortonormal, la matriz de Gram es la identidad y, en este caso, la mejor aproximación a $f$ es
$$g = \sum_{i=0}^n \langle f, \phi_i \rangle \phi_i$$
```python
help(producto_deriv)
help(producto_asecas)
```
```python
help(metodo_gram)
```
#### Ejercicio 33
```python
U = [S(1), x, x ** 2] # S(1) lo hacemos porque hacer 1.diff da error por ser int.
f = E ** x
dict_prod_deriv = metodo_gram(f, U, var=x, func_producto=producto_deriv, a=0, b=1)
```
```python
dict_prod_deriv['poly']
```
```python
dict_prod_deriv['G']
```
```python
dict_prod_deriv['f_bar']
```
```python
dict_prod_deriv['alpha']
```
Ahora con una versión discreta en los puntos 0, 0.2, 0.4, 0.6, 0.8, 1:
```python
U = [S(1), x, x ** 2] # S(1) lo hacemos porque hacer 1.diff da error por ser int.
f = E ** x
dict_prod_deriv_discreto = metodo_gram(f, U, var=x, func_producto=producto_deriv, I = [0, 0.2, 0.4, 0.6, 0.8, 1])
```
```python
dict_prod_deriv_discreto['poly']
```
```python
dict_prod_deriv_discreto['G']
```
```python
dict_prod_deriv_discreto['f_bar']
```
```python
dict_prod_deriv_discreto['alpha']
```
Ahora la versión continua pero con la función $\langle f, g \rangle = \int_a^b f(x)g(x) dx$
```python
U = [S(1), x, x ** 2] # S(1) lo hacemos porque hacer 1.diff da error por ser int.
f = E ** x
dict_prod_asecas = metodo_gram(f, U, var=x, func_producto=producto_asecas, a=0, b=1)
```
```python
dict_prod_asecas['poly']
```
```python
x_range = np.linspace(0, 1, 100)
y_real = [(E ** x).subs(x, i) for i in x_range]
y_prod_deriv = [dict_prod_deriv['poly'].subs(x, i) for i in x_range]
y_prod_discreto = [dict_prod_deriv_discreto['poly'].subs(x, i) for i in x_range]
y_prod_asecas = [dict_prod_asecas['poly'].subs(x, i) for i in x_range]
plt.plot(x_range, y_real, label='real')
plt.plot(x_range, y_prod_deriv, label="fg + f'g' continuo")
plt.plot(x_range, y_prod_discreto, label="fg + f'g' discreto")
plt.plot(x_range, y_prod_asecas, label="fg")
plt.legend()
```
#### Ejercicio 34
En el ejercicio piden usar la base $\{1, x\}$. Nosotros lo hacemos con $\{1, x, x^2, x^3, x^4, x^5\}$, que da una representación más real de la aproximación.
Calculamos la versión continua
```python
U = [S(1), x, x ** 2, x ** 3, x ** 4] # S(1) lo hacemos porque hacer 1.diff da error por ser int.
f = cos(pi * x)/2 + sin(pi/2 * x)/3
dict_prod_continuo = metodo_gram(f, U, var=x, func_producto=producto_asecas, a=-1, b=1)
```
```python
dict_prod_continuo['poly']
```
```python
dict_prod_continuo['G']
```
```python
dict_prod_continuo['f_bar']
```
```python
dict_prod_continuo['alpha']
```
Y ahora la discreta
```python
dict_prod_discreto = metodo_gram(f, U, var=x, func_producto=producto_asecas, I=[-1, 0, 1])
```
```python
dict_prod_discreto['poly']
```
```python
dict_prod_discreto['G']
```
```python
dict_prod_discreto['f_bar']
```
```python
dict_prod_discreto['alpha']
```
Repetimos el proceso, por curiosidad, pero con el producto escalar fg + f'g'
```python
dict_prod_continuo_deriv = metodo_gram(f, U, var=x, func_producto=producto_deriv, a=-1, b=1)
dict_prod_discreto_deriv = metodo_gram(f, U, var=x, func_producto=producto_deriv, I=[-1, 0, 1])
```
```python
dict_prod_continuo_deriv['poly']
```
```python
dict_prod_discreto_deriv['poly']
```
```python
x_range = np.linspace(-1, 1, 100)
y_real = [f.subs(x, i) for i in x_range]
y_prod_continuo = [dict_prod_continuo['poly'].subs(x, i) for i in x_range]
y_prod_discreto = [dict_prod_discreto['poly'].subs(x, i) for i in x_range]
y_prod_continuo_deriv = [dict_prod_continuo_deriv['poly'].subs(x, i) for i in x_range]
y_prod_discreto_deriv = [dict_prod_discreto_deriv['poly'].subs(x, i) for i in x_range]
plt.plot(x_range, y_real, label='real')
plt.plot(x_range, y_prod_continuo, label="fg continuo")
plt.plot(x_range, y_prod_discreto, label="fg discreto")
plt.plot(x_range, y_prod_continuo_deriv, label="fg + f'g' continuo")
plt.plot(x_range, y_prod_discreto_deriv, label="fg + f'g' discreto")
plt.legend()
```
Si nos fijamos, la aproximación con el método discreto es bastante mala, al no encontrar una inversa adecuada.
```python
help(gram_schmidt_f)
```
#### Ejemplo 23
```python
gram_schmidt_f([S(1), x, x ** 2, x ** 3, x ** 4, x ** 5, x ** 6], x, prod_esc=producto_asecas)
```
#### Ejercicio 35
```python
I = [-1, 0, 1, 2]
U_GS = gram_schmidt_f([S(1), x, x ** 2], x, prod_esc=producto_asecas, I=I)
```
```python
for i in U_GS:
print(i)
```
```python
f = sin(pi/2 * x)
dict_prod_discreto = metodo_gram(f, U_GS, var=x, func_producto=producto_asecas, I=I)
```
```python
dict_prod_discreto['poly']
```
### Aproximación con peso
Para las anteriores definiciones podemos tomar un producto escalar
$$\langle f, g \rangle = \int_a^b f(x)g(x)\omega(x) dx$$
Donde $\omega(x)$ es una función positiva en $(a,b)$
Se puede construir la sucesión de polinomios
$$p_0(x) = 1$$
$$p_1(x) = x - a_1$$
$$p_2(x) = (x - a_2)p_1(x) - b_2p_0(x)$$
$$\cdots$$
$$p_n(x) = (x - a_n)p_{n-1}(x) - b_np_{n-2}(x)$$
Con
$$a_n = \frac{\langle xp_{n-1},p_{n-1}\rangle}{\langle p_{n-1},p_{n-1}\rangle}$$
$$b_n = \frac{\langle xp_{n-1},p_{n-2}\rangle}{\langle p_{n-2},p_{n-2}\rangle}$$
```python
help(polinomios_orto_peso)
```
#### Polinomios de Legendre
Los polinomios de Legendre surgen de la aplicación del método descrito anteriormente para la base $\mathcal{P}(n) = \{1, x, x^2, \cdots, x^n\}$.
```python
# La base para los polinomios tiene que ser ortogonal porque si no los polinomios no son ortogonales entre si!
base = [S(1), x, x**2, x**3, x**4, x**5, x**6]
base_ortogonal = gram_schmidt_f(base, var=x, prod_esc=producto_asecas, a=-1, b=1)
base_legendre = polinomios_orto_peso(base_ortogonal, w=S(1), var=x, a=-1, b=1)
```
```python
base_legendre
```
```python
x_range = np.linspace(-1, 1, 100)
for p in base_legendre['p']:
plt.plot(x_range, [p.subs(x, i)/abs(p.subs(x, -1)) for i in x_range], label=S(1)/abs(p.subs(x, -1)))
plt.legend(bbox_to_anchor=(1, 0.5))
```
Ahora probamos a resolver algun problema asociado. Por ejemplo, vamos a aproximar sin(x) en [0, 2 * pi]
```python
base = [S(1), x, x**2, x**3]
base_ortogonal = gram_schmidt_f(base, var=x, prod_esc=producto_asecas, a=0, b=2*pi)
base_legendre = polinomios_orto_peso(base_ortogonal, w=S(1), var=x, a=0, b=2*pi)
```
```python
f = sin(x)
U_GS_base = metodo_gram(f, base, var=x, func_producto=producto_escalar_peso, a=0, b=2*pi, w=S(1))
U_GS_ortogonal = metodo_gram(f, base_ortogonal, var=x, func_producto=producto_escalar_peso, a=0, b=2*pi, w=S(1))
U_GS_legendre = metodo_gram(f, base_legendre['p'], var=x, func_producto=producto_escalar_peso, a=0, b=2*pi, w=S(1))
```
```python
expand(U_GS_base['poly'])
```
```python
expand(U_GS_ortogonal['poly'])
```
```python
expand(U_GS_legendre['poly'])
```
Los polinomios son técnicamente los mismos. Sin embargo, las matrices de Gram son mucho más convenientes para la base ortogonal / de legendre.
```python
U_GS_base['G']
```
```python
U_GS_ortogonal['G']
```
```python
U_GS_legendre['G']
```
Ahora vamos a hacer la aproximación gráfica para las funciones $\sin(x)$ y $\ln(x)$
```python
x_range = np.linspace(0, 2 * np.pi, 100)
base = [S(1), x, x**2, x**3, x**4, x**5, x**6, x**7]
f = sin(x)
plt.plot(x_range, [sin(x).subs(x,i) for i in x_range], label='real')
for i in range(3, 8, 2):
base_sub = base[:i]
U_GS_base = metodo_gram(f, base_sub, var=x, func_producto=producto_escalar_peso, a=0, b=2*pi, w=S(1))
plt.plot(x_range, [U_GS_base['poly'].subs(x,i) for i in x_range], label=f'poly_{i}')
plt.legend(bbox_to_anchor=(1, 0.5))
```
```python
x_range = np.linspace(0.01, 2, 100)
base = [S(1), x, x**2, x**3, x**4, x**5, x**6, x**7,]
f = ln(x)/ln(2)
plt.plot(x_range, [f.subs(x,i) for i in x_range], label='real')
for i in range(3, 8, 2):
base_sub = base[:i]
U_GS_base = metodo_gram(f, base_sub, var=x, func_producto=producto_escalar_peso, a=0.01, b=2, w=S(1))
plt.plot(x_range, [U_GS_base['poly'].subs(x,i) for i in x_range], label=f'poly_{i}')
plt.legend(bbox_to_anchor=(1.5, 0.3))
```
Vemos que una aproximación polinomial de log es bastante buena también!
### Polinomios de Chebyshev
Los polinomios de Chevysheb responden a la ecuación $T_n = \cos(n \arccos(x))$. En base a las propiedades trigonométricas, estos polinomios también responden a la forma:
$$T_0 = 1, \;\; T_1 = x$$
$$T_n = 2xT_{n-1} - T_{n-2}$$
En el intervalo [-1, 1]. Fuera de él la expresión T_n da valores complejos, aunque la parte real de esos valores se aproxima mucho a la forma polinomial.
Estos polinomios son ortogonales en el intervalo [-1, 1] estableciendo $\omega(x) = \frac{1}{\sqrt{1-x^2}}$:
$$\int_{-1}^{1} T_nT_m \frac{1}{\sqrt{1-x^2}} dx = \begin{cases}
0 & n\neq m \\
\pi & n = m = 0 \\
\pi/2 & n = m \neq 0
\end {cases}$$
```python
# Aqui los generamos iterativamente
t0 = S(1)
t1 = x
t2 = expand(2 * x * t1 - t0)
t3 = expand(2 * x * t2 - t1)
t4 = expand(2 * x * t3 - t2)
t5 = expand(2 * x * t4 - t3)
t5
```
```python
# También podemos usar la función de sympy
chebyshevt_poly(5)
```
```python
T5 = cos(5 * acos(x))
```
```python
x_range = np.linspace(-3, 3, 1000)
y_t5 = [t5.subs(x, i) for i in x_range]
y_T5 = [re(T5.subs(x, i)) for i in x_range]
plt.plot(x_range, y_t5, label='t5')
plt.plot(x_range, y_T5, label="T5")
plt.legend()
```
Vemos que ambos polinomios son iguales
Ahora vamos a comprobar la ortogonalidad de los polinomios usando el peso adecuado, u otro peso
```python
producto_escalar_peso(chebyshevt_poly(3, x), chebyshevt_poly(5, x), x, w=S(1),a=-1, b=1)
```
```python
producto_escalar_peso(chebyshevt_poly(3, x), chebyshevt_poly(5, x), x, w=1/sqrt(1 - x**2),a=-1, b=1)
```
Vemos que si no añadimos el peso $\omega(x)$ el resultado de la integral no es 0.
```python
producto_escalar_peso(chebyshevt_poly(0, x), chebyshevt_poly(0, x), x, w=1/sqrt(1 - x**2),a=-1, b=1)
```
```python
producto_escalar_peso(chebyshevt_poly(1, x), chebyshevt_poly(1, x), x, w=1/sqrt(1 - x**2),a=-1, b=1)
```
```python
producto_escalar_peso(chebyshevt_poly(3, x), chebyshevt_poly(3, x), x, w=1/sqrt(1 - x**2),a=-1, b=1)
```
```python
producto_escalar_peso(chebyshevt_poly(5, x), chebyshevt_poly(5, x), x, w=1/sqrt(1 - x**2),a=-1, b=1)
```
Para dos polinomios iguales, los resultados son los esperados
### Aproximación trigonométrica (series de Fourier)
La aproximación trigonométrica considera el siguiente producto escalar:
$$\langle f, g\rangle = \frac{1}{2\pi}\int_{-\pi}^{\pi}f(x)g(x)dx$$
Si en el método de Gram consideramos los polinomios trigonométricos $\{1, \cos(x), \sin(x), \cdots, \cos(nx), \sin(nx)\}$ tenemos que $\langle f, g\rangle$ para la base $\mathcal{U}$ es:
$$\int_{-\pi}^{\pi} \cos(kx)\sin(jx)dx = 0$$
$$\int_{-\pi}^{\pi} \cos(kx)\cos(jx)dx = \int_{-\pi}^{\pi} \cos(kx)\cos(jx)dx =
\begin{cases}0 & k\neq j \\ \pi & k=j>1 \\ 2\pi & k = j = 0\end{cases}$$
Así, la matriz a resolver es:
$$\begin{bmatrix}
2\pi & 0 & 0 & \cdots & 0 & 0 \\
0 & \pi & 0 & \cdots & 0 & 0 \\
0 & 0 & \pi & \cdots & 0 & 0 \\
\vdots & \vdots & \vdots & \ddots & \vdots & \vdots \\
0 & 0 & 0 & \cdots & \pi & 0 \\
0 & 0 & 0 & \cdots & 0 & \pi \\
\end{bmatrix}
\begin{bmatrix}
a_0 \\
a_1 \\
b_1 \\
\vdots \\
a_n \\
b_n \\
\end{bmatrix}
=
\begin{bmatrix}
\langle f, 1 \rangle \\
\langle f, \cos(x) \rangle \\
\langle f, \sin(x) \rangle \\
\vdots \\
\langle f, \cos(nx) \rangle \\
\langle f, \sin(nx) \rangle \\
\end{bmatrix}
$$
Luego
$$
\begin{bmatrix}
a_0 \\
a_1 \\
b_1 \\
\vdots \\
a_n \\
b_n \\
\end{bmatrix}
=
\begin{bmatrix}
\frac{1}{2\pi} & 0 & 0 & \cdots & 0 & 0 \\
0 & \frac{1}{\pi} & 0 & \cdots & 0 & 0 \\
0 & 0 & \frac{1}{\pi} & \cdots & 0 & 0 \\
\vdots & \vdots & \vdots & \ddots & \vdots & \vdots \\
0 & 0 & 0 & \cdots & \frac{1}{\pi} & 0 \\
0 & 0 & 0 & \cdots & 0 & \frac{1}{\pi} \\
\end{bmatrix}
\begin{bmatrix}
\langle f, 1 \rangle \\
\langle f, \cos(x) \rangle \\
\langle f, \sin(x) \rangle \\
\vdots \\
\langle f, \cos(nx) \rangle \\
\langle f, \sin(nx) \rangle \\
\end{bmatrix} =
\begin{bmatrix}
\frac{1}{2\pi}\langle f, 1 \rangle \\
\frac{1}{\pi}\langle f, \cos(x) \rangle \\
\frac{1}{\pi}\langle f, \sin(x) \rangle \\
\vdots \\
\frac{1}{\pi}\langle f, \cos(nx) \rangle \\
\frac{1}{\pi}\langle f, \sin(nx) \rangle \\
\end{bmatrix}
$$
Así, los coeficientes quedan definidos como:
$$a_k = \frac{1}{\pi} \int_{-\pi}^{\pi} f(x) \cos(kx) dx$$
$$b_k = \frac{1}{\pi} \int_{-\pi}^{\pi} f(x) \sin(kx) dx$$
Si combinamos los coeficientes con los elementos de $\mathcal{U}$ tenemos que el polinomio óptimo es, hasta grado $n$:
$$g_n(x) = \frac{a_0}{2} + \sum_{k=1}^n a_k\cos(kx) + b_k\sin(kx)$$
```python
help(producto_escalar_trigono)
```
#### EJERCICIO 36
```python
base = [S(1), cos(x), sin(x)]
m_gram = zeros(3, 3)
f_base = zeros(3, 1)
for i in range(3):
for j in range(3):
m_gram[i, j] = producto_escalar_trigono(base[i], base[j], x)
f_base[i, 0] = producto_escalar_trigono(x, base[i], x)
```
```python
m_gram # Se ve que la base es ortogonal
```
```python
f_base
```
```python
# Resolvemos la matriz de Gram
g = ((m_gram ** -1 * f_base).T * mat([base]).T)[0]
g
```
```python
help(coefs_fourier)
help(coefs_fourier_discr)
help(serie_fourier)
```
#### EJEMPLO 25 ($f(x) = e^x$)
En este ejercicio vamos a calcular la expansión de Fourier para órdenes 3, 6 y 15. Comprobamos que en orden 6 la aproximación es mejor, pero en los extremos del intervalo la aproximación empeora, tal y como se comenta en el texto base.
```python
f = E ** x
```
```python
coefs_fourier(f, var=x, I=[-pi, pi], n_coefs=6)
```
```python
serie_f_3 = expand(serie_fourier(f, x, [-pi, pi], n_coefs=3))
serie_f_6 = expand(serie_fourier(f, x, [-pi, pi], n_coefs=6))
serie_f_15 = expand(serie_fourier(f, x, [-pi, pi], n_coefs=15))
```
```python
x_range = np.linspace(-np.pi, np.pi, 300)
real = [(f).subs(x, i) for i in x_range]
f3 = [serie_f_3.subs(x, i) for i in x_range]
f6 = [serie_f_6.subs(x, i) for i in x_range]
f15 = [serie_f_15.subs(x, i) for i in x_range]
plt.plot(x_range, real, label="E**x")
plt.plot(x_range, f3, label='f3')
plt.plot(x_range, f6, label="f6")
plt.plot(x_range, f15, label="f15")
plt.legend()
```
Las series de Fourier también admiten un caso discreto. En este caso, si dividimos el intervalo $[a,b]$ en $2m$ (asumimos $m$ hasta $[a, \frac{a+b}{2}]$ y otros $m$ hasta $[\frac{a+b}{2}, b]$), para el caso discreto los coeficientes $a_k$ y $b_k$ se redefinen como:
$$a_k = \frac{1}{m}\sum_{i=0}^{2m-1}f(x_i)\cos(kx_i)$$
$$b_k = \frac{1}{m}\sum_{i=0}^{2m-1}f(x_i)\sin(kx_i)$$
que, por simplificar, sería una media de $m$ valores en el intervalo, en lugar de la integral. Cuanto más grande sea $m$, más se van a parecer los coeficientes del caso discreto al continuo.
Ahora hacemos el caso discreto para m=6
```python
serie_f_6_m_3 = expand(serie_fourier(f, x, [-np.pi, np.pi], n_coefs=6, discreto=True, m=3))
```
```python
serie_f_6_m_10 = expand(serie_fourier(f, x, [-np.pi, np.pi], n_coefs=6, discreto=True, m=10))
```
```python
serie_f_6_m_20 = expand(serie_fourier(f, x, [-np.pi, np.pi], n_coefs=6, discreto=True, m=20))
```
```python
serie_f_6_m_50 = expand(serie_fourier(f, x, [-np.pi, np.pi], n_coefs=6, discreto=True, m=50))
```
```python
x_range = np.linspace(-np.pi, np.pi, 300)
real = [(f).subs(x, i) for i in x_range]
f6m3 = [serie_f_6_m_3.subs(x, i) for i in x_range]
f6m10 = [serie_f_6_m_10.subs(x, i) for i in x_range]
f6m20 = [serie_f_6_m_20.subs(x, i) for i in x_range]
f6m50 = [serie_f_6_m_50.subs(x, i) for i in x_range]
f6 = [serie_f_6.subs(x, i) for i in x_range]
plt.plot(x_range, real, label="E**x")
plt.plot(x_range, f6, label='f6')
plt.plot(x_range, f6m3, label="f6disc-m3")
plt.plot(x_range, f6m10, label="f6disc-m10")
plt.plot(x_range, f6m20, label="f6disc-m20")
plt.plot(x_range, f6m50, label="f6disc-m50")
plt.legend()
```
#### EJEMPLO 25 ($f(x) = x$)
```python
f = x
```
```python
coefs_fourier(f, x, [-pi, pi], n_coefs=6)
```
```python
serie_f_3 = expand(serie_fourier(f, x, [-pi, pi], n_coefs=3))
serie_f_6 = expand(serie_fourier(f, x, [-pi, pi], n_coefs=6))
serie_f_15 = expand(serie_fourier(f, x, [-pi, pi], n_coefs=15))
```
```python
x_range = np.linspace(-np.pi, np.pi, 300)
real = [(f).subs(x, i) for i in x_range]
f3 = [serie_f_3.subs(x, i) for i in x_range]
f6 = [serie_f_6.subs(x, i) for i in x_range]
f15 = [serie_f_15.subs(x, i) for i in x_range]
plt.plot(x_range, real, label="x")
plt.plot(x_range, f3, label='f3')
plt.plot(x_range, f6, label="f6")
plt.plot(x_range, f15, label="f15")
plt.legend()
```
Ahora hacemos el caso discreto para m=6
```python
serie_f_6_m_5 = expand(serie_fourier(f, x, [-np.pi, np.pi], n_coefs=6, discreto=True, m=5))
```
```python
serie_f_6_m_10 = expand(serie_fourier(f, x, [-np.pi, np.pi], n_coefs=6, discreto=True, m=10))
```
```python
serie_f_6_m_20 = expand(serie_fourier(f, x, [-np.pi, np.pi], n_coefs=6, discreto=True, m=20))
```
```python
serie_f_6_m_50 = expand(serie_fourier(f, x, [-np.pi, np.pi], n_coefs=6, discreto=True, m=50))
```
```python
x_range = np.linspace(-np.pi, np.pi, 300)
real = [(f).subs(x, i) for i in x_range]
f6m5 = [serie_f_6_m_5.subs(x, i) for i in x_range]
f6m10 = [serie_f_6_m_10.subs(x, i) for i in x_range]
f6m20 = [serie_f_6_m_20.subs(x, i) for i in x_range]
f6m50 = [serie_f_6_m_50.subs(x, i) for i in x_range]
f6 = [serie_f_6.subs(x, i) for i in x_range]
plt.plot(x_range, real, label="x")
plt.plot(x_range, f6, label='f6')
plt.plot(x_range, f6m5, label="f6disc-m3")
plt.plot(x_range, f6m10, label="f6disc-m10")
plt.plot(x_range, f6m20, label="f6disc-m20")
plt.plot(x_range, f6m50, label="f6disc-m50")
plt.legend()
```
#### EJEMPLO 25 ($f(x) = x^2$)
```python
f = x ** 2
```
```python
coefs_fourier(f, x, [-pi, pi], n_coefs=6)
```
```python
N(2*pi**2/3)
```
```python
coefs_fourier_discr(f, x, [-np.pi, np.pi], n_coefs=6, m=100)
```
```python
serie_f_3 = expand(serie_fourier(f, x, [-pi, pi], n_coefs=3))
serie_f_6 = expand(serie_fourier(f, x, [-pi, pi], n_coefs=6))
serie_f_15 = expand(serie_fourier(f, x, [-pi, pi], n_coefs=15))
```
```python
x_range = np.linspace(-np.pi, np.pi, 300)
real = [(f).subs(x, i) for i in x_range]
f3 = [serie_f_3.subs(x, i) for i in x_range]
f6 = [serie_f_6.subs(x, i) for i in x_range]
f15 = [serie_f_15.subs(x, i) for i in x_range]
plt.plot(x_range, real, label="x^2")
plt.plot(x_range, f3, label='f3')
plt.plot(x_range, f6, label="f6")
plt.plot(x_range, f15, label="f15")
plt.legend()
```
Ahora hacemos el caso discreto para m=6
```python
serie_f_6_m_3 = expand(serie_fourier(f, x, [-np.pi, np.pi], n_coefs=6, discreto=True, m=3))
```
```python
serie_f_6_m_10 = expand(serie_fourier(f, x, [-np.pi, np.pi], n_coefs=6, discreto=True, m=10))
```
```python
serie_f_6_m_20 = expand(serie_fourier(f, x, [-np.pi, np.pi], n_coefs=6, discreto=True, m=20))
```
```python
serie_f_6_m_50 = expand(serie_fourier(f, x, [-np.pi, np.pi], n_coefs=6, discreto=True, m=50))
```
```python
x_range = np.linspace(-np.pi, np.pi, 300)
real = [(f).subs(x, i) for i in x_range]
f6m3 = [serie_f_6_m_3.subs(x, i) for i in x_range]
f6m10 = [serie_f_6_m_10.subs(x, i) for i in x_range]
f6m20 = [serie_f_6_m_20.subs(x, i) for i in x_range]
f6m50 = [serie_f_6_m_50.subs(x, i) for i in x_range]
f6 = [serie_f_6.subs(x, i) for i in x_range]
plt.plot(x_range, real, label="x^2")
plt.plot(x_range, f6, label='f6')
plt.plot(x_range, f6m3, label="f6disc-m3")
plt.plot(x_range, f6m10, label="f6disc-m10")
plt.plot(x_range, f6m20, label="f6disc-m20")
plt.plot(x_range, f6m50, label="f6disc-m50")
plt.legend()
```
### Aproximación uniforme (Polinomios de Bernstein)
Otro modo de realizar aproximaciones a funciones es empleando la aproximación uniforme. El tma de Weierstrass indica que para $f$ continua en un intervalo cerrado y acotado $I$, para todo $\epsilon > 0$ existe un polinomio $p$ tal que $||f-p||_\infty < \epsilon$.
Para $I = [0, 1]$, el conjunto de polinomios de grado $n$ que satisface esa condición son los polinomios de Bernstein:
$$B_{n,f}(x) = \sum_{i = 0}^n f\left(\frac{i}{n}\right) {n \choose i} x^i(1-x)^{n-i}$$
Para $I = [a, b]$, hay que realizar el cambio de variable $x = (b-a)t + a$ para $t \in [0,1]$. Con ello, definimos $g(t)$ y tenemos el polinomio
$$B_{n,f}(t) = \sum_{i = 0}^n g\left(\frac{i}{n}\right) {n \choose i} t^i(1-t)^{n-i}$$
Que después reconvertimos a $x$ aplicando el cambio $t = \frac{x - a}{b - a}$
```python
help(polinomios_bernstein)
```
#### EJERCICIO 38
```python
f = abs(x)
```
```python
polinomios_bernstein(f, x, I=[-1, 1], grado=1)
```
```python
polinomios_bernstein(f, x, I=[-1, 1], grado=2)
```
```python
polinomios_bernstein(f, x, I=[-1, 1], grado=3)
```
```python
polinomios_bernstein(f, x, I=[-1, 1], grado=4)
```
```python
polinomios_bernstein(f, x, I=[-1, 1], grado=5)
```
```python
polinomios_bernstein(f, x, I=[-1, 1], grado=6)
```
```python
polinomios_bernstein(f, x, I=[-1, 1], grado=7)
```
```python
polinomios_bernstein(f, x, I=[-1, 1], grado=8)
```
Vemos que los polinomios se repiten por paridad. Esto tiene sentido porque los polinomios solo pueden tener coeficientes pares, ya que abs(x) siempre es positivo.
Vamos a plotear los polinomios hasta un grado alto.
```python
x_range = np.linspace(-1, 1, 300)
real = [(f).subs(x, i) for i in x_range]
B2 = [polinomios_bernstein(f, x, I=[-1, 1], grado=2).subs(x, i) for i in x_range]
B6 = [polinomios_bernstein(f, x, I=[-1, 1], grado=6).subs(x, i) for i in x_range]
B10 = [polinomios_bernstein(f, x, I=[-1, 1], grado=10).subs(x, i) for i in x_range]
B100 = [polinomios_bernstein(f, x, I=[-1, 1], grado=100).subs(x, i) for i in x_range]
plt.plot(x_range, real, label="abs(x)")
plt.plot(x_range, B2, label='B2')
plt.plot(x_range, B6, label='B6')
plt.plot(x_range, B10, label='B10')
plt.plot(x_range, B100, label='B100')
plt.legend()
```
Vemos que la curva se acerca cada vez más a abs(x).
#### EJEMPLO 26
```python
f = E**(3*x) * sin(pi * x)
f
```
```python
polinomios_bernstein(f, x, I=[0, 1], grado=1)
```
```python
polinomios_bernstein(f, x, I=[0, 1], grado=2)
```
```python
polinomios_bernstein(f, x, I=[0, 1], grado=3)
```
```python
polinomios_bernstein(f, x, I=[0, 1], grado=4)
```
Vemos que los polinomios se repiten por paridad. Esto tiene sentido porque los polinomios solo pueden tener coeficientes pares, ya que abs(x) siempre es positivo.
Vamos a plotear los polinomios hasta un grado alto.
```python
x_range = np.linspace(0, 1, 300)
real = [(f).subs(x, i) for i in x_range]
B2 = [polinomios_bernstein(f, x, I=[0, 1], grado=2).subs(x, i) for i in x_range]
B4 = [polinomios_bernstein(f, x, I=[0, 1], grado=4).subs(x, i) for i in x_range]
B8 = [polinomios_bernstein(f, x, I=[0, 1], grado=8).subs(x, i) for i in x_range]
B16 = [polinomios_bernstein(f, x, I=[0, 1], grado=16).subs(x, i) for i in x_range]
B32 = [polinomios_bernstein(f, x, I=[0, 1], grado=32).subs(x, i) for i in x_range]
plt.plot(x_range, real, label="f")
plt.plot(x_range, B2, label='B2')
plt.plot(x_range, B4, label='B4')
plt.plot(x_range, B8, label='B8')
plt.plot(x_range, B16, label='B16')
plt.plot(x_range, B32, label='B32')
plt.legend()
```
Ahora vamos a plotear el error entre la función real y la aproximación. Vemos que conforme el polinomio es más complejo, más se acerca a la función, pero también salen artefactos en la computación.
```python
x_range = np.linspace(0, 1, 300)
real = [(f).subs(x, i) for i in x_range]
B2 = [polinomios_bernstein(f, x, I=[0, 1], grado=2).subs(x, i) for i in x_range]
B4 = [polinomios_bernstein(f, x, I=[0, 1], grado=4).subs(x, i) for i in x_range]
B8 = [polinomios_bernstein(f, x, I=[0, 1], grado=8).subs(x, i) for i in x_range]
B16 = [polinomios_bernstein(f, x, I=[0, 1], grado=16).subs(x, i) for i in x_range]
B32 = [polinomios_bernstein(f, x, I=[0, 1], grado=32).subs(x, i) for i in x_range]
plt.plot(x_range, np.array(real) - np.array(B2), label="2")
plt.plot(x_range, np.array(real) - np.array(B4), label="4")
plt.plot(x_range, np.array(real) - np.array(B8), label="8")
plt.plot(x_range, np.array(real) - np.array(B32), label="32")
plt.legend()
```
## Ejercicios
### Ejercicio 40
Determinar la mejor aproximación de $x^3$ en $\mathcal{P}_2$ usando el producto escalar de Chebyshev.
Recordemos el producto escalar de Chebyshev:
$$\langle f, g\rangle = \int_{-1}^{1} f(x)g(x) \frac{1}{\sqrt{1-x^2}} dx$$
```python
help(metodo_gram)
```
```python
U = [sqrt(1/pi) * chebyshevt_poly(0, x), sqrt(2/pi) * chebyshevt_poly(1, x), sqrt(2/pi) * chebyshevt_poly(2, x)] # S(1) lo hacemos porque hacer 1.diff da error por ser int.
f = x ** 3
dict_prod_deriv = metodo_gram(f, U, var=x, func_producto=producto_escalar_peso, a=-1, b=1, w=1/sqrt(1 - x**2))
```
```python
dict_prod_deriv['G']
```
```python
dict_prod_deriv['alpha']
```
```python
dict_prod_deriv['f_bar']
```
```python
dict_prod_deriv['poly']
```
### Ejercicio 41
Aplicar el procedimiento de orto-normalización de Gram-Schmidt a la base $\{1, x, x^2\}$ respecto el producto escalar.
$$\langle f, g \rangle = \frac{1}{2}\int_0^1(1+3x^2)f(x)g(x)dx$$
Aplicamos el procedimiento. En este caso los pasos a seguir serían:
$$p_0(x) = 1$$
$$p_1(x) = x - \frac{\langle p_0, x\rangle}{\langle p_0, p_0\rangle}p_0$$
$$p_2(x) = x^2 - \frac{\langle p_0, x^2\rangle}{\langle p_0, p_0\rangle}p_0 -
\frac{\langle p_1, x^2\rangle}{\langle p_1, p_1\rangle}p_1$$
Después habría que, para ortonormalizar, aplicar:
$$p_i := \frac{p_i}{\langle p_i, p_i\rangle}$$
```python
p0 = S(1)
p0
```
```python
p1 = x - producto_escalar_peso(p0, x, w=(1 + 3*x**2)/2, a=0, b=1) / producto_escalar_peso(p0, p0, w=(1 + 3*x**2)/2, a=0, b=1) * p0
p1
```
```python
p1_norm = p1 / sqrt(producto_escalar_peso(p1, p1, w=(1 + 3*x**2)/2, a=0, b=1))
p1_norm
```
```python
p2 = x**2 - producto_escalar_peso(p0, x**2, w=(1 + 3*x**2)/2, a=0, b=1) / producto_escalar_peso(p0, p0, w=(1 + 3*x**2)/2, a=0, b=1) * p0 - \
producto_escalar_peso(p1, x**2, w=(1 + 3*x**2)/2, a=0, b=1) / producto_escalar_peso(p1, p1, w=(1 + 3*x**2)/2, a=0, b=1) * p1
p2
```
```python
p2_norm = p2 / sqrt(producto_escalar_peso(p2, p2, w=(1 + 3*x**2)/2, a=0, b=1))
p2_norm
```
### Ejercicio 42
Hallar la recta que mejor aproxima la gráfica de la función $y = \frac{x}{1+x^2}$ con la norma inducida por el producto escalar
$$\langle f, g \rangle = \int_0^5f(x)g(x)dx$$
Usando una base de polinomios ortonormales.
El primer punto es transformar la base $\{1, x\}$, que conforma las posibles rectas, en una base ortonormal para ese producto escalar. Para ello empleamos el procedimiento de Gram Schmidt.
```python
f = x/(1 + x**2)
```
```python
U_ortogonal = gram_schmidt_f(base=[S(1), x], var=x, prod_esc=producto_asecas, a=0, b=5)
U_ortogonal
```
```python
p0 = U_ortogonal[0] / sqrt(producto_asecas(U_ortogonal[0], U_ortogonal[0], a=0, b=5))
p0
```
```python
producto_asecas(p0, p0, a=0, b=5)
```
```python
p1 = U_ortogonal[1] / sqrt(producto_asecas(U_ortogonal[1], U_ortogonal[1], a=0, b=5))
p1
```
```python
producto_asecas(p1, p1, a=0, b=5)
```
Ahora que tenemos la base de polinomios ortonormales vamos a desarrollar por el método de Gram, por comprobar la ortonormalidad.
```python
dict_gram = metodo_gram(f=f, U = [p0, p1], var=x, func_producto=producto_asecas, a=0, b=5)
dict_gram['G']
```
```python
dict_gram['alpha']
```
```python
dict_gram['f_bar']
```
```python
dict_gram['poly']
```
```python
x_vals = np.linspace(0, 5, 100)
y_vals = [dict_gram['poly'].subs(x, i) for i in x_vals]
plt.plot(x_vals, [f.subs(x, i) for i in x_vals])
plt.plot(x_vals, y_vals)
```
### Ejercicio 43
Hallar la recta que mejor aproxima la función $y = \frac{x}{1+x^2}$ con el producto discreto $\langle f, g \rangle = f(0)g(0)+f(2)g(2) + f(3)g(3) + f(5)g(5)$ usando una base de polinomios ortogonales.
Los polinomios ortonormales de la seccion anterior no nos son válidos porque en este caso el producto ha cambiado. Por ello tenemos que generar una nueva base.
```python
U_ortogonal_disc = gram_schmidt_f(base=[S(1), x], var=x, prod_esc=producto_asecas, a=0, b=5, I=[0, 2, 3, 5])
U_ortogonal_disc
```
```python
p0_disc = U_ortogonal_disc[0] / sqrt(producto_asecas(U_ortogonal_disc[0], U_ortogonal_disc[0], a=0, b=5, I=[0, 2, 3, 5]))
p0_disc
```
```python
producto_asecas(p0_disc, p0_disc, a=0, b=5, I=[0, 2, 3, 5])
```
```python
p1_disc = U_ortogonal_disc[1] / sqrt(producto_asecas(U_ortogonal_disc[1], U_ortogonal_disc[1], a=0, b=5, I=[0, 2, 3, 5]))
p1_disc
```
```python
producto_asecas(p1_disc, p1_disc, a=0, b=5, I=[0, 2, 3, 5])
```
```python
dict_gram_disc = metodo_gram(f=f, U = [p0_disc, p1_disc], var=x, func_producto=producto_asecas, a=0, b=5, I=[0, 2, 3, 5])
dict_gram_disc['G']
```
```python
dict_gram_disc['alpha']
```
```python
dict_gram_disc['f_bar']
```
```python
dict_gram_disc['poly']
```
```python
x_vals = np.linspace(0, 5, 100)
y_vals = [dict_gram['poly'].subs(x, i) for i in x_vals]
y_vals_disc = [dict_gram_disc['poly'].subs(x, i) for i in x_vals]
plt.plot(x_vals, [f.subs(x, i) for i in x_vals])
plt.plot(x_vals, y_vals, label='cont')
plt.plot(x_vals, y_vals_disc, label='disc')
plt.legend()
```
```python
x_vals = np.linspace(0, 5, 100)
y_vals = [(f - dict_gram['poly']).subs(x, i) for i in x_vals]
y_vals_disc = [(f - dict_gram_disc['poly']).subs(x, i) for i in x_vals]
plt.plot(x_vals, y_vals, label='cont')
plt.plot(x_vals, y_vals_disc, label='disc')
plt.legend()
```
Vemos que en el caso continuo la mayor diferencia está en 0, y es cercana a 0.4, y en el caso discreto está en 1, y es cercana a 0.3. Vamos a hallar esas diferencias explicitamente.
Ahora vamos a hallar las normas $\vert\vert f - g \vert\vert_\infty$ para la versión discreta y continua
```python
# Continua
max_x = [N(i) for i in solve((dict_gram['poly'] - (x/(1+x**2))).diff(x), x)]
max_x
```
```python
N(abs((dict_gram['poly'] - (x/(1+x**2))).subs(x, max_x[1])))
```
```python
N(abs((dict_gram['poly'] - (x/(1+x**2))).subs(x, max_x[3])))
```
```python
N((dict_gram['poly'] - (x/(1+x**2))).subs(x, 0))
```
El valor más cercano dentro de $[0, 5]$ es 1.09, pero es menor que el valor en 0. Así que el valor máximo es en 0.
```python
# Discreta
max_x = [N(i) for i in solve((dict_gram_disc['poly'] - (x/(1+x**2))).diff(x), x)]
max_x
```
```python
N(abs((dict_gram_disc['poly'] - (x/(1+x**2))).subs(x, max_x[1])))
```
En el caso discreto el valor máximo está en $x\sim0.94$ y es $0.32$.
Así, la mayor diferencia está para el caso continuo (en base a la norma uniforme).
Sin embargo, si tomamos la diferencia de áreas, el área de diferencia es mayor para la discreta, que *falla* más a lo largo de la función.
```python
Integral(abs(dict_gram['poly'] - (x/(1+x**2))), (x, 0, 5)).evalf()
```
```python
Integral(abs(dict_gram_disc['poly'] - (x/(1+x**2))), (x, 0, 5)).evalf()
```
### Ejercicio 44
Construir los cuatro primeros polinomios de grado creciente, de coeficiente principal igual a 1, que sean ortogonales respecto al producto escalar
$$\langle f, g\rangle = \int_{-1}^{1} \vert x\vert f(x)g(x) dx$$
Para esto recurrimos al Tma 14, que indica que si $\omega$ es una función positiva en el intervalo (en este caso lo es), se cumple que se pueden generar los polinomios por recurrencia.
```python
U = [S(1), x, x**2, x**3]
```
```python
help(polinomios_orto_peso)
```
```python
base_legendre = polinomios_orto_peso(U, w=abs(x), var=x, a=-1, b=1)
```
```python
base_legendre
```
```python
U_ortogonal_disc = gram_schmidt_f(base=U, var=x, prod_esc=producto_escalar_peso, w=abs(x), a=-1, b=1)
U_ortogonal_disc
```
```python
Vemos que la base de polinomios es la misma.
```
```python
producto_escalar_peso(f=U_ortogonal_disc[1], g=U_ortogonal_disc[2], w=abs(x), a=-1, b=1)
```
```python
producto_escalar_peso(f=U_ortogonal_disc[3], g=U_ortogonal_disc[2], w=abs(x), a=-1, b=1)
```
### Ejercicio 45
Determinar la mejor aproximación a la función $f(x) = e^x$ en $\mathcal{P}_2$ usando la norma asociada al siguiente producto escalar
$$\langle f, g \rangle = \int_0^1 (f(x)g(x) + f'(x)g'(x)) dx$$
Vamos a usar el método de Gram directamente
```python
U = [S(1), x, x**2]
f = E ** x
```
```python
dict_prod_continuo = metodo_gram(f, U, var=x, func_producto=producto_deriv,a=0, b=1)
```
```python
expand(dict_prod_continuo['poly'])
```
```python
dict_prod_continuo['G']
```
```python
dict_prod_continuo['f_bar']
```
```python
dict_prod_continuo['alpha']
```
Y ahora vamos a buscar una base ortonormal y repetir el método
```python
base_ortogonal = gram_schmidt_f(U, var=x, prod_esc=producto_deriv,a=0, b=1)
base_ortogonal
```
```python
base_ortonormal = [i / sqrt(producto_deriv(i, i, a=0, b = 1)) for i in base_ortogonal]
base_ortonormal
```
```python
dict_prod_continuo_ortonormal = metodo_gram(f, base_ortonormal, var=x, func_producto=producto_deriv,a=0, b=1)
```
```python
dict_prod_continuo_ortonormal['poly']
```
```python
dict_prod_continuo_ortonormal['G']
```
```python
dict_prod_continuo_ortonormal['f_bar']
```
```python
dict_prod_continuo_ortonormal['alpha']
```
```python
N(dict_prod_continuo['poly'])
```
```python
x_vals = np.linspace(0, 1, 100)
y_vals = [dict_prod_continuo['poly'].subs(x, i) for i in x_vals]
plt.plot(x_vals, [f.subs(x, i) for i in x_vals])
plt.plot(x_vals, y_vals)
```
|
A simply connected open set is a connected open set with the following properties: The winding number of any closed path in the set is zero. The contour integral of any holomorphic function over any closed path in the set is zero. Any holomorphic function on the set has a primitive. Any holomorphic function on the set that is nonzero on the set has a logarithm. Any holomorphic function on the set that is nonzero on the set has a square root. The set is biholomorphic to the open unit disc. The set is homeomorphic to the open unit disc.
|
Require Import Crypto.Specific.Framework.RawCurveParameters.
Require Import Crypto.Util.LetIn.
(***
Modulus : 2^383 - 421
Base: 47.875
***)
Definition curve : CurveParameters :=
{|
sz := 8%nat;
base := 47 + 7/8;
bitwidth := 64;
s := 2^383;
c := [(1, 421)];
carry_chains := Some [seq 0 (pred 8); [0; 1]]%nat;
a24 := None;
coef_div_modulus := Some 2%nat;
goldilocks := None;
karatsuba := None;
montgomery := false;
freeze := Some true;
ladderstep := false;
mul_code := None;
square_code := None;
upper_bound_of_exponent_loose := None;
upper_bound_of_exponent_tight := None;
allowable_bit_widths := None;
freeze_extra_allowable_bit_widths := None;
modinv_fuel := None
|}.
Ltac extra_prove_mul_eq _ := idtac.
Ltac extra_prove_square_eq _ := idtac.
|
(*
Copyright (C) 2017 M.A.L. Marques
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*)
(* type: gga_vxc *)
(* prefix:
gga_x_lb_params *params;
assert(p->params != NULL);
params = (gga_x_lb_params * )(p->params);
*)
lb_f0 := (rs, z, x) -> -my_piecewise3(x < 300,
params_a_beta*x^2/(1 + 3*params_a_beta*x*arcsinh(params_a_gamma*x)),
x/(3*log(2*params_a_gamma*x))):
lb_f := (rs, z, x) -> (params_a_alpha*(4/3)*LDA_X_FACTOR + lb_f0(rs, z, x))*n_spin(rs, z)^(1/3):
f := (rs, z, xt, xs0, xs1) -> lb_f(rs, z, xs0):
|
! smtp.f90
!
! Example that shows how to send an e-mail via SMTP with SSL encryption using
! libcurl. Based on the following C implementation:
!
! https://curl.haxx.se/libcurl/c/smtp-ssl.html
!
! Author: Philipp Engel
! Licence: ISC
module callback_smtp
use, intrinsic :: iso_c_binding
implicit none
private
public :: upload_callback
! Client data for `upload_callback()`.
type, public :: upload_type
character(len=512), allocatable :: payload(:)
integer :: index
end type upload_type
interface
! void *memcpy(void *dest, const void *src, size_t n)
function c_memcpy(dest, src, n) bind(c, name='memcpy')
import :: c_ptr, c_size_t
type(c_ptr), intent(in), value :: dest
type(c_ptr), intent(in), value :: src
integer(kind=c_size_t), intent(in), value :: n
type(c_ptr) :: c_memcpy
end function c_memcpy
! size_t strlen(const char *s)
function c_strlen(s) bind(c, name='strlen')
import :: c_char, c_size_t
character(kind=c_char), intent(in) :: s
integer(c_size_t) :: c_strlen
end function c_strlen
end interface
contains
! static size_t callback(void *ptr, size_t size, size_t nmemb, void *data)
function upload_callback(ptr, sze, nmemb, data) bind(c)
!! Callback function for `CURLOPT_READFUNCTION` that copies the payload
!! of the given `data` ptr (derived type `upload_type`) chunk-wise to
!! `ptr` and returns the byte count.
type(c_ptr), intent(in), value :: ptr
integer(kind=c_size_t), intent(in), value :: sze
integer(kind=c_size_t), intent(in), value :: nmemb
type(c_ptr), intent(in), value :: data
integer(kind=c_size_t) :: upload_callback
integer(kind=c_size_t) :: n
type(upload_type), pointer :: upload
type(c_ptr) :: tmp
upload_callback = int(0, kind=c_size_t)
if (sze == 0 .or. nmemb == 0 .or. sze * nmemb < 1) return
if (.not. c_associated(data)) return
! Get upload data.
call c_f_pointer(data, upload)
if (.not. allocated(upload%payload)) return
! Check if upload of payload is complete.
if (upload%index >= size(upload%payload)) return
! Copy payload to given C pointer.
upload%index = upload%index + 1
n = c_strlen(upload%payload(upload%index))
tmp = c_memcpy(ptr, c_loc(upload%payload(upload%index)), n)
! Return the copied bytes.
upload_callback = n
end function upload_callback
end module callback_smtp
program main
use, intrinsic :: iso_c_binding
use :: curl
use :: callback_smtp
implicit none
character(len=*), parameter :: CRLF = achar(13) // achar(10) // c_null_char
character(len=*), parameter :: FROM = '<[email protected]>' ! Sender of mail.
character(len=*), parameter :: TO = '<[email protected]>' ! Mail receiver.
character(len=*), parameter :: CC = '<[email protected]>' ! CC mail receiver.
character(len=*), parameter :: SUBJECT = 'A message from Fortran' ! Mail subject.
character(len=*), parameter :: URL = 'smtps://example.com' ! SMTP server (SSL).
character(len=*), parameter :: USERNAME = '[email protected]' ! SMTP user name.
character(len=*), parameter :: PASSWORD = 'secret' ! SMTP password.
type(c_ptr) :: curl_ptr
type(c_ptr) :: list_ptr
type(upload_type), target :: upload
integer :: rc
allocate (upload%payload(8))
upload%payload(1) = 'Date: ' // rfc2822() // CRLF
upload%payload(2) = 'To: ' // TO // CRLF
upload%payload(3) = 'From: ' // FROM // CRLF
upload%payload(4) = 'Cc: ' // CC // CRLF
upload%payload(5) = 'Subject: ' // SUBJECT // CRLF
upload%payload(6) = CRLF
upload%payload(7) = 'Hello, from Fortran!' // CRLF
upload%payload(8) = CRLF
upload%index = 0
curl_ptr = curl_easy_init()
if (c_associated(curl_ptr)) then
! Add recipients.
list_ptr = curl_slist_append(c_null_ptr, TO // c_null_char)
list_ptr = curl_slist_append(list_ptr, CC // c_null_char)
! Set curl options.
rc = curl_easy_setopt(curl_ptr, CURLOPT_URL, URL // c_null_char)
rc = curl_easy_setopt(curl_ptr, CURLOPT_USERNAME, USERNAME // c_null_char)
rc = curl_easy_setopt(curl_ptr, CURLOPT_PASSWORD, PASSWORD // c_null_char)
rc = curl_easy_setopt(curl_ptr, CURLOPT_SSL_VERIFYPEER, int(1, kind=8))
rc = curl_easy_setopt(curl_ptr, CURLOPT_SSL_VERIFYHOST, int(1, kind=8))
rc = curl_easy_setopt(curl_ptr, CURLOPT_MAIL_FROM, FROM // c_null_char)
rc = curl_easy_setopt(curl_ptr, CURLOPT_MAIL_RCPT, list_ptr)
rc = curl_easy_setopt(curl_ptr, CURLOPT_READDATA, c_loc(upload))
rc = curl_easy_setopt(curl_ptr, CURLOPT_READFUNCTION, c_funloc(upload_callback))
rc = curl_easy_setopt(curl_ptr, CURLOPT_UPLOAD, int(1, kind=8))
rc = curl_easy_setopt(curl_ptr, CURLOPT_VERBOSE, int(1, kind=8))
! Send e-mail.
if (curl_easy_perform(curl_ptr) /= CURLE_OK) then
print '(a)', 'Error: curl_easy_perform() failed'
end if
call curl_slist_free_all(list_ptr)
call curl_easy_cleanup(curl_ptr)
end if
contains
function rfc2822()
! Returns current time and date in RFC 2822 format:
!
! https://www.ietf.org/rfc/rfc2822.txt
!
! Example: `Thu, 01 Sep 2016 10:11:12 -0500`.
character(len=3), parameter :: days(7) = [ 'Sun', 'Mon', 'Thu', 'Wed', 'Thu', 'Fri', 'Sat' ]
character(len=3), parameter :: months(12) = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', &
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
character(len=*), parameter :: dt_fmt = '(a, ", ", i0.2, " ", a, " ", i4, " ", ' // &
'i0.2, ":", i0.2, ":", i0.2, " ", a)'
character(len=31) :: rfc2822
character(len=5) :: z
integer(kind=8) :: dt(8), w
call date_and_time(zone=z, values=dt)
w = 1 + modulo(dt(1) + int((dt(1) - 1) / 4) - int((dt(1) - 1) / 100) + int((dt(1) - 1) / 400), &
int(7, kind=8))
write (rfc2822, dt_fmt) days(w), dt(3), months(dt(2)), dt(1), dt(5), dt(6), dt(7), z
end function rfc2822
end program main
|
(* Title: HOL/Auth/n_g2kAbsAfter_lemma_inv__77_on_rules.thy
Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
*)
header{*The n_g2kAbsAfter Protocol Case Study*}
theory n_g2kAbsAfter_lemma_inv__77_on_rules imports n_g2kAbsAfter_lemma_on_inv__77
begin
section{*All lemmas on causal relation between inv__77*}
lemma lemma_inv__77_on_rules:
assumes b1: "r \<in> rules N" and b2: "(f=inv__77 )"
shows "invHoldForRule s f r (invariants N)"
proof -
have c1: "(\<exists> d. d\<le>N\<and>r=n_n_Store_i1 d)\<or>
(\<exists> d. d\<le>N\<and>r=n_n_AStore_i1 d)\<or>
(r=n_n_SendReqS_j1 )\<or>
(r=n_n_SendReqEI_i1 )\<or>
(r=n_n_SendReqES_i1 )\<or>
(r=n_n_RecvReq_i1 )\<or>
(r=n_n_SendInvE_i1 )\<or>
(r=n_n_SendInvS_i1 )\<or>
(r=n_n_SendInvAck_i1 )\<or>
(r=n_n_RecvInvAck_i1 )\<or>
(r=n_n_SendGntS_i1 )\<or>
(r=n_n_SendGntE_i1 )\<or>
(r=n_n_RecvGntS_i1 )\<or>
(r=n_n_RecvGntE_i1 )\<or>
(r=n_n_ASendReqIS_j1 )\<or>
(r=n_n_ASendReqSE_j1 )\<or>
(r=n_n_ASendReqEI_i1 )\<or>
(r=n_n_ASendReqES_i1 )\<or>
(r=n_n_SendReqEE_i1 )\<or>
(r=n_n_ARecvReq_i1 )\<or>
(r=n_n_ASendInvE_i1 )\<or>
(r=n_n_ASendInvS_i1 )\<or>
(r=n_n_ASendInvAck_i1 )\<or>
(r=n_n_ARecvInvAck_i1 )\<or>
(r=n_n_ASendGntS_i1 )\<or>
(r=n_n_ASendGntE_i1 )\<or>
(r=n_n_ARecvGntS_i1 )\<or>
(r=n_n_ARecvGntE_i1 )"
apply (cut_tac b1, auto) done
moreover {
assume d1: "(\<exists> d. d\<le>N\<and>r=n_n_Store_i1 d)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_Store_i1Vsinv__77) done
}
moreover {
assume d1: "(\<exists> d. d\<le>N\<and>r=n_n_AStore_i1 d)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_AStore_i1Vsinv__77) done
}
moreover {
assume d1: "(r=n_n_SendReqS_j1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendReqS_j1Vsinv__77) done
}
moreover {
assume d1: "(r=n_n_SendReqEI_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendReqEI_i1Vsinv__77) done
}
moreover {
assume d1: "(r=n_n_SendReqES_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendReqES_i1Vsinv__77) done
}
moreover {
assume d1: "(r=n_n_RecvReq_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_RecvReq_i1Vsinv__77) done
}
moreover {
assume d1: "(r=n_n_SendInvE_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendInvE_i1Vsinv__77) done
}
moreover {
assume d1: "(r=n_n_SendInvS_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendInvS_i1Vsinv__77) done
}
moreover {
assume d1: "(r=n_n_SendInvAck_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendInvAck_i1Vsinv__77) done
}
moreover {
assume d1: "(r=n_n_RecvInvAck_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_RecvInvAck_i1Vsinv__77) done
}
moreover {
assume d1: "(r=n_n_SendGntS_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendGntS_i1Vsinv__77) done
}
moreover {
assume d1: "(r=n_n_SendGntE_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendGntE_i1Vsinv__77) done
}
moreover {
assume d1: "(r=n_n_RecvGntS_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_RecvGntS_i1Vsinv__77) done
}
moreover {
assume d1: "(r=n_n_RecvGntE_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_RecvGntE_i1Vsinv__77) done
}
moreover {
assume d1: "(r=n_n_ASendReqIS_j1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendReqIS_j1Vsinv__77) done
}
moreover {
assume d1: "(r=n_n_ASendReqSE_j1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendReqSE_j1Vsinv__77) done
}
moreover {
assume d1: "(r=n_n_ASendReqEI_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendReqEI_i1Vsinv__77) done
}
moreover {
assume d1: "(r=n_n_ASendReqES_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendReqES_i1Vsinv__77) done
}
moreover {
assume d1: "(r=n_n_SendReqEE_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_SendReqEE_i1Vsinv__77) done
}
moreover {
assume d1: "(r=n_n_ARecvReq_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ARecvReq_i1Vsinv__77) done
}
moreover {
assume d1: "(r=n_n_ASendInvE_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendInvE_i1Vsinv__77) done
}
moreover {
assume d1: "(r=n_n_ASendInvS_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendInvS_i1Vsinv__77) done
}
moreover {
assume d1: "(r=n_n_ASendInvAck_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendInvAck_i1Vsinv__77) done
}
moreover {
assume d1: "(r=n_n_ARecvInvAck_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ARecvInvAck_i1Vsinv__77) done
}
moreover {
assume d1: "(r=n_n_ASendGntS_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendGntS_i1Vsinv__77) done
}
moreover {
assume d1: "(r=n_n_ASendGntE_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ASendGntE_i1Vsinv__77) done
}
moreover {
assume d1: "(r=n_n_ARecvGntS_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ARecvGntS_i1Vsinv__77) done
}
moreover {
assume d1: "(r=n_n_ARecvGntE_i1 )"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_n_ARecvGntE_i1Vsinv__77) done
}
ultimately show "invHoldForRule s f r (invariants N)"
by satx
qed
end
|
(* Title: HOL/Auth/n_flash_lemma_on_inv__20.thy
Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
*)
header{*The n_flash Protocol Case Study*}
theory n_flash_lemma_on_inv__20 imports n_flash_base
begin
section{*All lemmas on causal relation between inv__20 and some rule r*}
lemma n_PI_Remote_PutXVsinv__20:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_PI_Remote_PutX dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_PI_Remote_PutX dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__20 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') dst) ''CacheState'')) (Const CACHE_E))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_PI_Remote_ReplaceVsinv__20:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_Replace src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_Replace src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__20 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_PutVsinv__20:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__20 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_Put_HomeVsinv__20:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__20 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_PutXVsinv__20:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__20 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_PutX_HomeVsinv__20:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__20 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_PutVsinv__20:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Put dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Put dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__20 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "((formEval (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''InvMarked'')) (Const true)) s))\<or>((formEval (neg (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''InvMarked'')) (Const true))) s))" by auto
moreover {
assume c1: "((formEval (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''InvMarked'')) (Const true)) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (neg (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''InvMarked'')) (Const true))) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately have "invHoldForRule s f r (invariants N)" by satx
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_PutXVsinv__20:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_PutX dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_PutX dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__20 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Field (Ident ''Sta'') ''WbMsg'') ''Cmd'')) (Const WB_Wb))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_InvVsinv__20:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Inv dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Inv dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__20 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_WbVsinv__20:
assumes a1: "(r=n_NI_Wb )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__20 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Local_Get_Get__part__1Vsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_GetVsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_Get src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_PutX_9__part__0Vsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX__part__0Vsinv__20:
assumes a1: "r=n_PI_Local_GetX_PutX__part__0 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_StoreVsinv__20:
assumes a1: "\<exists> src data. src\<le>N\<and>data\<le>N\<and>r=n_Store src data" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_PutX_5Vsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_GetX__part__1Vsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_3Vsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_3 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_PutX_8_Home_NODE_GetVsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__1Vsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_1Vsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_1 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_GetX__part__1Vsinv__20:
assumes a1: "r=n_PI_Local_GetX_GetX__part__1 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_GetX__part__0Vsinv__20:
assumes a1: "r=n_PI_Local_GetX_GetX__part__0 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_Store_HomeVsinv__20:
assumes a1: "\<exists> data. data\<le>N\<and>r=n_Store_Home data" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_PutX_3Vsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_ReplaceVsinv__20:
assumes a1: "r=n_PI_Local_Replace " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_Nak__part__1Vsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Nak__part__1Vsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Get__part__0Vsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_existsVsinv__20:
assumes a1: "\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_InvAck_exists src pp" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_Nak__part__2Vsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Put_HeadVsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_PutXVsinv__20:
assumes a1: "r=n_PI_Local_PutX " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Nak__part__2Vsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_GetX__part__0Vsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_PutX_6Vsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_PutVsinv__20:
assumes a1: "r=n_PI_Local_Get_Put " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_ShWbVsinv__20:
assumes a1: "r=n_NI_ShWb N " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX_HeadVld__part__0Vsinv__20:
assumes a1: "r=n_PI_Local_GetX_PutX_HeadVld__part__0 N " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_PutX_11Vsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_ReplaceVsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Replace src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_PutX_1Vsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_PutX_8_HomeVsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_GetX_Nak_HomeVsinv__20:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_Nak_Home dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_PutX_7__part__0Vsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_PutXAcksDoneVsinv__20:
assumes a1: "r=n_NI_Local_PutXAcksDone " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_GetX_NakVsinv__20:
assumes a1: "\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_NakVsinv__20:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Nak dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_PutX_9__part__1Vsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_GetXVsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_GetX src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX__part__1Vsinv__20:
assumes a1: "r=n_PI_Local_GetX_PutX__part__1 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_Get_Nak_HomeVsinv__20:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Nak_Home dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_PutX_10Vsinv__20:
assumes a1: "\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_PutX_8Vsinv__20:
assumes a1: "\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_PutVsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_PutX_8_NODE_GetVsinv__20:
assumes a1: "\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_PutX_2Vsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_Nak__part__0Vsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_exists_HomeVsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_exists_Home src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Replace_HomeVsinv__20:
assumes a1: "r=n_NI_Replace_Home " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_PutVsinv__20:
assumes a1: "r=n_NI_Local_Put " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_PutX_7__part__1Vsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_Get_NakVsinv__20:
assumes a1: "\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Nak_ClearVsinv__20:
assumes a1: "r=n_NI_Nak_Clear " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Put_DirtyVsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_Get_Nak__part__0Vsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_GetVsinv__20:
assumes a1: "r=n_PI_Local_Get_Get " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Nak_HomeVsinv__20:
assumes a1: "r=n_NI_Nak_Home " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_PutX_10_HomeVsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_2Vsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_2 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX_HeadVld__part__1Vsinv__20:
assumes a1: "r=n_PI_Local_GetX_PutX_HeadVld__part__1 N " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_FAckVsinv__20:
assumes a1: "r=n_NI_FAck " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_PutX_4Vsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__0Vsinv__20:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__20 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
end
|
function d = AngDiff(x, y)
%ANGDIFF Compute angle difference accurately
%
% D = ANGDIFF(X, Y) computes Y - X, reduces the result to (-180,180] and
% rounds the result. X and Y must be in [-180,180]. X and Y can be any
% compatible shapes.
[d, t] = sumx(-x, y);
c = (d - 180) + t > 0;
d(c) = (d(c) - 360) + t(c);
c = (d + 180) + t <= 0;
d(c) = (d(c) + 360) + t(c);
end
|
Require Import VST.floyd.base.
Require Import VST.floyd.val_lemmas.
Require Import VST.floyd.typecheck_lemmas.
Require Import compcert.cfrontend.Ctypes.
Definition const_only_isUnOpResultType {CS: compspecs} op (typeof_a:type) valueof_a ty : bool :=
match op with
| Cop.Onotbool => match typeof_a with
| Tint _ _ _
| Tlong _ _
| Tfloat _ _ => is_int_type ty
| Tpointer _ _ =>
if Archi.ptr64
then match valueof_a with
| Vlong v =>
andb (negb (eqb_type (typeof_a) int_or_ptr_type))
(andb (is_int_type ty) (Z.eqb 0 (Int64.unsigned v)))
| _ => false
end
else match valueof_a with
| Vint v =>
andb (negb (eqb_type typeof_a int_or_ptr_type))
(andb (is_int_type ty) (Z.eqb 0 (Int.unsigned v)))
| _ => false
end
| _ => false
end
| Cop.Onotint => match Cop.classify_notint (typeof_a) with
| Cop.notint_default => false
| Cop.notint_case_i _ => (is_int32_type ty)
| Cop.notint_case_l _ => (is_long_type ty)
end
| Cop.Oneg => match Cop.classify_neg (typeof_a) with
| Cop.neg_case_i sg =>
andb (is_int32_type ty)
match (typeof_a) with
| Tint _ Signed _ =>
match valueof_a with
| Vint v => negb (Z.eqb (Int.signed v) Int.min_signed)
| _ => false
end
| Tlong Signed _ =>
match valueof_a with
| Vlong v => negb (Z.eqb (Int64.signed v) Int64.min_signed)
| _ => false
end
| _ => true
end
| Cop.neg_case_f => is_float_type ty
| Cop.neg_case_s => is_single_type ty
| _ => false
end
| Cop.Oabsfloat =>match Cop.classify_neg (typeof_a) with
| Cop.neg_case_i sg => is_float_type ty
| Cop.neg_case_l _ => is_float_type ty
| Cop.neg_case_f => is_float_type ty
| Cop.neg_case_s => is_float_type ty
| _ => false
end
end.
(* TODO: binarithType would better be bool type *)
Definition const_only_isBinOpResultType {CS: compspecs} op typeof_a1 valueof_a1 typeof_a2 valueof_a2 ty : bool :=
match op with
| Cop.Oadd =>
match Cop.classify_add (typeof_a1) (typeof_a2) with
| Cop.add_case_pi t _ | Cop.add_case_pl t =>
andb
(andb
(andb (match valueof_a1 with Vptr _ _ => true | _ => false end) (complete_type cenv_cs t))
(negb (eqb_type (typeof_a1) int_or_ptr_type)))
(is_pointer_type ty)
| Cop.add_case_ip _ t | Cop.add_case_lp t =>
andb
(andb
(andb (match valueof_a2 with Vptr _ _ => true | _ => false end) (complete_type cenv_cs t))
(negb (eqb_type (typeof_a2) int_or_ptr_type)))
(is_pointer_type ty)
| Cop.add_default => false
end
| _ => false (* TODO *)
end.
Definition const_only_isCastResultType {CS: compspecs} (t1 t2: type) (valueof_a: val) : bool :=
is_neutral_cast t1 t2 ||
match t1, t2 with
| Tint _ _ _, Tlong _ _ => true
| _, _ => false
end.
Fixpoint const_only_eval_expr {cs: compspecs} (e: Clight.expr): option val :=
match e with
| Econst_int i (Tint I32 _ _) => Some (Vint i)
| Econst_int _ _ => None
| Econst_long i ty => None
| Econst_float f (Tfloat F64 _) => Some (Vfloat f)
| Econst_float _ _ => None
| Econst_single f (Tfloat F32 _) => Some (Vsingle f)
| Econst_single _ _ => None
| Etempvar id ty => None
| Evar _ _ => None
| Eaddrof a ty => None
| Eunop op a ty =>
match const_only_eval_expr a with
| Some v => if const_only_isUnOpResultType op (typeof a) v ty
then Some (eval_unop op (typeof a) v)
else None
| None => None
end
| Ebinop op a1 a2 ty =>
match (const_only_eval_expr a1), (const_only_eval_expr a2) with
| Some v1, Some v2 =>
if const_only_isBinOpResultType op (typeof a1) v1 (typeof a2) v2 ty
then Some (eval_binop op (typeof a1) (typeof a2) v1 v2)
else None
| _, _ => None
end
| Ecast a ty =>
match const_only_eval_expr a with
| Some v => if const_only_isCastResultType (typeof a) ty v
then Some (eval_cast (typeof a) ty v)
else None
| None => None
end
| Ederef a ty => None
| Efield a i ty => None
| Esizeof t t0 =>
if andb (complete_type cenv_cs t) (eqb_type t0 size_t)
then Some (Vptrofs (Ptrofs.repr (sizeof t)))
else None
| Ealignof t t0 =>
if andb (complete_type cenv_cs t) (eqb_type t0 size_t)
then Some (Vptrofs (Ptrofs.repr (alignof t)))
else None
end.
Lemma const_only_isUnOpResultType_spec: forall {cs: compspecs} rho u e t P,
const_only_isUnOpResultType u (typeof e) (eval_expr e rho) t = true ->
P |-- denote_tc_assert (isUnOpResultType u e t) rho.
Proof.
intros.
unfold isUnOpResultType.
unfold const_only_isUnOpResultType in H.
destruct u.
+ destruct (typeof e);
try solve [inv H | rewrite H; exact (@prop_right mpred _ True _ I)].
rewrite !denote_tc_assert_andp.
match goal with
| |- context [denote_tc_assert (tc_test_eq ?a ?b)] =>
change (denote_tc_assert (tc_test_eq a b)) with (expr2.denote_tc_assert (tc_test_eq a b))
end.
rewrite binop_lemmas2.denote_tc_assert_test_eq'.
simpl expr2.denote_tc_assert.
unfold_lift. simpl.
unfold tc_int_or_ptr_type.
destruct Archi.ptr64 eqn:HH.
- destruct (eval_expr e rho); try solve [inv H].
rewrite !andb_true_iff in H.
destruct H as [? [? ?]].
rewrite H, H0.
rewrite Z.eqb_eq in H1.
apply andp_right; [exact (@prop_right mpred _ True _ I) |].
apply andp_right; [exact (@prop_right mpred _ True _ I) |].
simpl.
rewrite HH.
change (P |-- (!! (i = Int64.zero)) && (!! (Int64.zero = Int64.zero)))%logic.
apply andp_right; apply prop_right; auto.
rewrite <- (Int64.repr_unsigned i), <- H1.
auto.
- destruct (eval_expr e rho); try solve [inv H].
rewrite !andb_true_iff in H.
destruct H as [? [? ?]].
rewrite H, H0.
rewrite Z.eqb_eq in H1.
apply andp_right; [exact (@prop_right mpred _ True _ I) |].
apply andp_right; [exact (@prop_right mpred _ True _ I) |].
simpl.
rewrite HH.
change (P |-- (!! (i = Int.zero)) && (!! (Int.zero = Int.zero)))%logic.
apply andp_right; apply prop_right; auto.
rewrite <- (Int.repr_unsigned i), <- H1.
auto.
+ destruct (Cop.classify_notint (typeof e));
try solve [inv H | rewrite H; exact (@prop_right mpred _ True _ I)].
+ destruct (Cop.classify_neg (typeof e));
try solve [inv H | rewrite H; exact (@prop_right mpred _ True _ I)].
rewrite !andb_true_iff in H.
destruct H.
rewrite H; simpl.
destruct (typeof e) as [| ? [|] | [|] | | | | | |];
try solve [exact (@prop_right mpred _ True _ I)].
- simpl.
unfold_lift.
unfold denote_tc_nosignedover.
destruct (eval_expr e rho); try solve [inv H0].
rewrite negb_true_iff in H0.
rewrite Z.eqb_neq in H0.
apply prop_right.
change (Int.signed Int.zero) with 0.
rep_lia.
- simpl.
unfold_lift.
unfold denote_tc_nosignedover.
destruct (typeof e) as [ | _ [ | ] _ | | | | | | | ];
destruct (eval_expr e rho); try solve [inv H0];
rewrite negb_true_iff in H0;
rewrite Z.eqb_neq in H0;
apply prop_right;
change (Int64.signed Int64.zero) with 0;
rep_lia.
+ destruct (Cop.classify_neg (typeof e)); try solve [inv H | rewrite H; exact (@prop_right mpred _ True _ I)].
Qed.
Lemma const_only_isBinOpResultType_spec: forall {cs: compspecs} rho b e1 e2 t P,
const_only_isBinOpResultType b (typeof e1) (eval_expr e1 rho) (typeof e2) (eval_expr e2 rho) t = true ->
P |-- denote_tc_assert (isBinOpResultType b e1 e2 t) rho.
Proof.
intros.
unfold isBinOpResultType.
unfold const_only_isBinOpResultType in H.
destruct b.
+ destruct (Cop.classify_add (typeof e1) (typeof e2)).
- rewrite !denote_tc_assert_andp; simpl.
unfold_lift.
unfold tc_int_or_ptr_type, denote_tc_isptr.
destruct (eval_expr e1 rho); inv H.
rewrite !andb_true_iff in H1.
destruct H1 as [[? ?] ?].
rewrite H, H0, H1.
simpl.
repeat apply andp_right; apply prop_right; auto.
- rewrite !denote_tc_assert_andp; simpl.
unfold_lift.
unfold tc_int_or_ptr_type, denote_tc_isptr.
destruct (eval_expr e1 rho); inv H.
rewrite !andb_true_iff in H1.
destruct H1 as [[? ?] ?].
rewrite H, H0, H1.
simpl.
repeat apply andp_right; apply prop_right; auto.
- rewrite !denote_tc_assert_andp; simpl.
unfold_lift.
unfold tc_int_or_ptr_type, denote_tc_isptr.
destruct (eval_expr e2 rho); inv H.
rewrite !andb_true_iff in H1.
destruct H1 as [[? ?] ?].
rewrite H, H0, H1.
simpl.
repeat apply andp_right; apply prop_right; auto.
- rewrite !denote_tc_assert_andp; simpl.
unfold_lift.
unfold tc_int_or_ptr_type, denote_tc_isptr.
destruct (eval_expr e2 rho); inv H.
rewrite !andb_true_iff in H1.
destruct H1 as [[? ?] ?].
rewrite H, H0, H1.
simpl.
repeat apply andp_right; apply prop_right; auto.
- inv H.
+ inv H.
+ inv H.
+ inv H.
+ inv H.
+ inv H.
+ inv H.
+ inv H.
+ inv H.
+ inv H.
+ inv H.
+ inv H.
+ inv H.
+ inv H.
+ inv H.
+ inv H.
Qed.
Lemma const_only_isCastResultType_spec: forall {cs: compspecs} rho e t P,
const_only_isCastResultType (typeof e) t (eval_expr e rho) = true ->
P |-- denote_tc_assert (isCastResultType (typeof e) t e) rho.
Proof.
intros.
unfold const_only_isCastResultType in H.
rewrite orb_true_iff in H.
destruct H.
apply neutral_isCastResultType; auto.
destruct (typeof e); inv H.
destruct t; inv H1.
simpl. apply TT_right.
Qed.
Lemma const_only_eval_expr_eq: forall {cs: compspecs} rho e v,
const_only_eval_expr e = Some v ->
eval_expr e rho = v.
Proof.
intros.
revert v H; induction e; try solve [intros; inv H; auto].
+ intros.
simpl in *.
destruct t as [| [| | |] | | | | | | |]; inv H.
auto.
+ intros.
simpl in *.
destruct t as [| | | [|] | | | | |]; inv H.
auto.
+ intros.
simpl in *.
destruct t as [| | | [|] | | | | |]; inv H.
auto.
+ intros.
simpl in *.
unfold option_map in H.
destruct (const_only_eval_expr e); inv H.
destruct (const_only_isUnOpResultType u (typeof e) v0 t); inv H1.
specialize (IHe _ eq_refl).
unfold_lift.
rewrite IHe; auto.
+ intros.
simpl in *.
unfold option_map in H.
destruct (const_only_eval_expr e1); inv H.
destruct (const_only_eval_expr e2); inv H1.
destruct (const_only_isBinOpResultType b (typeof e1) v0 (typeof e2) v1 t); inv H0.
specialize (IHe1 _ eq_refl).
specialize (IHe2 _ eq_refl).
unfold_lift.
rewrite IHe1, IHe2; auto.
+ intros.
simpl in *.
unfold option_map in H.
destruct (const_only_eval_expr e); inv H.
destruct (const_only_isCastResultType (typeof e) t v0) eqn:?H; inv H1.
unfold_lift. erewrite IHe by reflexivity. auto.
+ intros.
simpl in *.
destruct (complete_type cenv_cs t); inv H.
destruct (eqb_type t0 size_t); inv H1.
auto.
+ intros.
simpl in *.
destruct (complete_type cenv_cs t); inv H.
destruct (eqb_type t0 size_t); inv H1.
auto.
Qed.
Lemma const_only_eval_expr_tc: forall {cs: compspecs} Delta e v P,
const_only_eval_expr e = Some v ->
P |-- tc_expr Delta e.
Proof.
intros.
intro rho.
revert v H; induction e; try solve [intros; inv H].
+ intros.
inv H.
destruct t as [| [| | |] | | | | | | |]; inv H1.
exact (@prop_right mpred _ True _ I).
+ intros.
inv H.
destruct t as [| | | [|] | | | | |]; inv H1.
exact (@prop_right mpred _ True _ I).
+ intros.
inv H.
destruct t as [| | | [|] | | | | |]; inv H1.
exact (@prop_right mpred _ True _ I).
+ intros.
unfold tc_expr in *.
simpl in *.
unfold option_map in H.
destruct (const_only_eval_expr e) eqn:HH; inv H.
specialize (IHe _ eq_refl).
unfold_lift.
rewrite denote_tc_assert_andp; simpl; apply andp_right; auto.
apply const_only_isUnOpResultType_spec.
apply (const_only_eval_expr_eq rho) in HH.
rewrite HH.
destruct (const_only_isUnOpResultType u (typeof e) v0 t); inv H1; auto.
+ intros.
unfold tc_expr in *.
simpl in *.
unfold option_map in H.
destruct (const_only_eval_expr e1) eqn:HH1; inv H.
destruct (const_only_eval_expr e2) eqn:HH2; inv H1.
specialize (IHe1 _ eq_refl).
specialize (IHe2 _ eq_refl).
unfold_lift.
rewrite !denote_tc_assert_andp; simpl; repeat apply andp_right; auto.
apply const_only_isBinOpResultType_spec.
apply (const_only_eval_expr_eq rho) in HH1.
apply (const_only_eval_expr_eq rho) in HH2.
rewrite HH1, HH2.
destruct (const_only_isBinOpResultType b (typeof e1) v0 (typeof e2) v1 t); inv H0; auto.
+ intros.
unfold tc_expr in *.
simpl in *.
unfold option_map in H.
destruct (const_only_eval_expr e) eqn:HH; inv H.
destruct (const_only_isCastResultType (typeof e) t v0) eqn:?H; inv H1.
rewrite denote_tc_assert_andp.
simpl.
apply andp_right; eauto.
apply const_only_isCastResultType_spec; auto.
+ intros.
inv H.
unfold tc_expr.
simpl typecheck_expr.
simpl.
destruct (complete_type cenv_cs t && eqb_type t0 size_t) eqn:HH; inv H1.
rewrite andb_true_iff in HH.
unfold tuint in HH; destruct HH.
rewrite H, H0.
exact (@prop_right mpred _ True _ I).
+ intros.
inv H.
unfold tc_expr.
simpl typecheck_expr.
simpl.
destruct (complete_type cenv_cs t && eqb_type t0 size_t) eqn:HH; inv H1.
rewrite andb_true_iff in HH.
unfold tuint in HH; destruct HH.
rewrite H, H0.
exact (@prop_right mpred _ True _ I).
Qed.
|
Formal statement is: lemma (in finite_measure) emeasure_real: "\<exists>r. 0 \<le> r \<and> emeasure M A = ennreal r" Informal statement is: If $M$ is a finite measure space, then the measure of any set $A$ is a nonnegative real number.
|
### A Pluto.jl notebook ###
# v0.17.2
using Markdown
using InteractiveUtils
# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).
macro bind(def, element)
quote
local iv = try Base.loaded_modules[Base.PkgId(Base.UUID("6e696c72-6542-2067-7265-42206c756150"), "AbstractPlutoDingetjes")].Bonds.initial_value catch; b -> missing; end
local el = $(esc(element))
global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)
el
end
end
# ╔═╡ e7666210-a660-11eb-3e0d-7d9aec9a9f9e
begin
#try
using PlutoUI
using Plots
using Plots.PlotMeasures
using LaTeXStrings
using Markdown
using HypertextLiteral
#using Images
#using LinearAlgebra
#using SparseArrays
#using SpecialFunctions
#using StatsBase
using Random
#using Distributions
md"""
### Packages
All needed Packages available :) """
#catch
# using Pkg;
# Pkg.activate(mktempdir())
# Pkg.add("PlutoUI")
# Pkg.add("Plots")
# Pkg.add("LaTeXStrings")
# Pkg.add("Markdown")
# Pkg.add("Images")
# Pkg.add("Random")
#Pkg.add("LinearAlgebra")
#Pkg.add("SparseArrays")
#Pkg.add("SpecialFunctions")
#Pkg.add("StatsBase")
#Pkg.add("Distributions")
# using PlutoUI, Plots, LaTeXStrings, Markdown, Images, Plots.PlotMeasures, Random
#using LinearAlgebra
#using SparseArrays
#using StatsBase
#using Random
# md"""
### Packages
# Some Package sources not added, this will take approx. 3 minutes"""
# end
end
# ╔═╡ ec784992-f4af-4ece-bf72-555960a054ca
html"""<div style="display: flex; justify-content: center;">
<div notthestyle="position: relative; right: 0; top: 0; z-index: 300;">
<iframe src="https://www.youtube.com/embed/ABbv9g5kTdI" width=600 height=375 frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>"""
# ╔═╡ 8f919de1-356f-4e42-9f7e-5d29092ed80f
md"""
## Bayesian reasoning
The lighttower located at the unknown coordinates $(a|b)$ randomly emits light in all polar directions $\varphi$ measured to the perpendicular to the beach. The light hits the beach if the angle $\varphi$ of emitted light is in the interval $\varphi \in [-\pi/2, \pi/2]$. See the sketch below for a detailed definition of the used variables.
The location $x$ on the beach is given by
$x = \tan(\varphi)\cdot b + a$
"""
# ╔═╡ fd94fab8-c4c4-454e-9f5b-c0f1178143b3
begin
md"""
## Derivation of the Likelihood and Posterior
So let's derive the Likelihood to spot a flash on the coastline position ``x``:
We know, that the lightsource 🔦 of the lighthouse is constantly rotating so all angles are equally probable independent of the actual position of the lighthouse:
``p(\varphi|a,b) = p(\varphi) = \frac{1}{2\pi}``
Then we know the relation between angle (``\varphi``), position of the lighthouse ``(a,b)`` and the coastline position ``x`` to spot a flash on the beach:
``x = a + b \cdot \tan(\varphi), \quad `` for ``\varphi \in [-\pi/2, \pi/2]``
So we are looking for the probability
``p(x|a,b)``
and can use the transformation law:
$p(x|a,b) = p\big(\varphi(x)|a,b\big) \cdot \left\lvert \frac{d\varphi(x)}{dx}\right\rvert$
With ``\frac{d\varphi(x)}{dx} = \frac{b}{b+(x-a)^2}`` and ``p(\varphi(x)) = \frac{1}{\pi}`` (we have to restrict the angle of ``\varphi`` to the halfplane to hit the coastline) we obtain the following Likelihood:
$p(x|a,b) = \frac{1}{\pi} \frac{b}{b^2 + (x-a)^2}$
For the posterior
$p(a,b|x) = \frac{1}{Z} p(x|a,b) \cdot p(a,b)$
we can assume a flat prior ``p(a,b)``.
"""
end
# ╔═╡ d3f023b1-8a57-4690-b8d6-afbe2ff50d5e
begin
a_slider = @bind a Scrubbable(-4:0.1:4, default= 1)
b_slider = @bind b Scrubbable(0.1:0.1:4, default= 3)
phi_slider = @bind φ Scrubbable(-pi/2:pi/120:pi/2, default= -3*pi/10)
fix_beach_box = @bind fix_beach CheckBox()
flashes = @bind generate_flash CounterButton("Generate Flashes")
md"""
## The program
### Define sliders and general checkboxes and buttons
"""
end
# ╔═╡ 3c1cc3af-11f9-44ac-b07f-69704c4841c4
@htl("""<div class="hide-me">
$(
md"""
Angle of the emitted light ``\varphi``: $(phi_slider)
Horizontal distance of the lighthouse from the origin ``a``: $(a_slider)
Perpendicular distance of the lighthouse from the coastline ``b``: $(b_slider)
Fix beach length 👉 $(fix_beach_box)
"""
)
</div>""")
# ╔═╡ ed56b559-ea17-41c7-8fe5-6ae9440fd5b5
begin
rng = MersenneTwister(1 + (generate_flash % 10 ) + Int(round((φ+2) * 100)))
md" ### Define random number seed"
end
# ╔═╡ b2dc9f9b-9f57-4ca8-82ef-9c6a3915d6d0
begin
show_flash_box = @bind show_flashes CheckBox()
md" ### CheckBox show flash"
end
# ╔═╡ 656ac69b-4cf5-440b-a894-83a7a80f42f0
begin
show_calculation_box = @bind show_calculation CheckBox(default=false)
md" ### Define start calculation Checkbox"
end
# ╔═╡ 936ccc78-8720-46b5-91eb-8d23f8699c99
@htl("""<div class="hide-me-not">
$(
md"""
Deactivate Calcuation to change position of the lighthouse: 👉 $(show_calculation_box)
"""
)
</div>""")
# ╔═╡ bbb80420-ccae-48e7-a943-8aae332cb254
if show_calculation
html"""
<style>
.hide-me {
display: none;
}
</style>
"""
else
html"""
<style>
.hide-me-not {
display: none;
}
</style>
"""
end
# ╔═╡ a61337a8-e197-4a7b-817d-012a5c1c0f17
begin
rand_phi = (rand(rng,100) .- 0.5) * pi
x_new = tan.(rand_phi).*b .+ a
md" ### Generate new sample of flash points"
end
# ╔═╡ 51b1234a-9808-4dad-a588-f61db077767f
begin
range_a = -5:0.01:5
range_b = 0.1:0.01:5
p = zeros(length(range_b), length(range_a))
lighttower = (0,0)
if show_calculation
for i = 1:length(range_a), j=1:length(range_b)
a_temp = range_a[i]
b_temp = range_b[j]
p[j,i] = 1/pi * prod(b_temp ./(b_temp^2 .+ (x_new .- a_temp).^2))
end
p = p./sum(p);
end
index = findall(p .== maximum(p))[1]
lighttower = (range_a[index[2]], range_b[index[1]])
md""" ### Calculation of the Likelihood"""
end
# ╔═╡ b8942536-020b-4c8e-a875-b5aba3034d42
begin
#a = 1
x = a+b*tan(φ)
if fix_beach
beach_length = 10
else
beach_length = maximum([4, abs(x)])
end
a_dist = abs(a) > 0.10 ? 0.05 : 0
a_dist_y = 0.15
b_dist = beach_length/30
# plot light ray
plot([x,a], [0,b], linestyle = :solid, linewidth = 2, color = :yellow, label=false,
size = (640,320),
labelfontsize = 15,
tickfontsize = 13,
legendfontsize = 11,
bottom_margin =5mm,
left_margin = 5mm,
right_margin = 5mm,
titlefontsize = 12,
#foreground_color_grid = :black,
#foreground_color_xticks = :black,
background_color = :transparent,
#foreground_color_axis = :black,
#foreground_color_text = :black,
#foreground_color_border = :black,
foreground_color = :black,
fontfamily="Computer Modern")
plot!([x,a], [0,b], linestyle = :dash, linewidth = 2, color = :yellow3, label="Light")
# plot beach
plot!([-beach_length,beach_length], [0,0], color = :black, linewidth = 3, label=false, ylim=[0,4])
# plot perpendicular
plot!([a,a], [0,b], color=:black, linewidth = 2, linestyle = :dash,label = false)
# plot lighthouse
plot!([a], [b], markercolor=:red, marker=:o,linealpha = 0,markersize = 8, label="Lighttower")
# plot distance b
plot!(b_dist .+ [a,a,NaN,a,a], [a_dist_y,b-a_dist_y,NaN,b-a_dist_y,a_dist_y], color = :red, linewidth = 2.5, linestyle = :solid, label="\$b\$",arrow = true)
annotate!(a+2*b_dist, b/2,text("\${b}\$", :red))
#plot distance a
plot!([sign(a)*a_dist,a-sign(a)*a_dist, NaN,a-sign(a)*a_dist,sign(a)*a_dist], [a_dist_y,a_dist_y, NaN, a_dist_y,a_dist_y], color=:green, linewidth = 2.5, linestyle = :solid, label= "\$a\$", arrow = true)
annotate!((a+b_dist/2)/2,2*a_dist_y,text("\${a}\$", :green, :center))
# plot varphi
varphi = atan((x-a)/b)
pl_angle =sign(varphi).* (0:0.01:abs(varphi))
rad = 1
annotate!(a + sin(varphi/2)*2*rad/3, b-cos(varphi/2)*2*rad/3,"\$\\varphi\$")
plot!([a .+ sin.(pl_angle)*rad], [b.-cos.(pl_angle)*rad], label =false)
# plot x
annotate!(x,-2*a_dist_y, "\$x\$")
if show_flashes
plot!(x_new, zeros(size(x_new)), marker= :o, color = :orange,markeralpha = 0.4, linealpha = 0, label= "Flashes")
end
if show_calculation
heatmap!(range_a, range_b, p, alpha = 0.4,
title="The lighttower is most likely located at "*string(lighttower))
end
plot!([x,x], [-a_dist_y, a_dist_y]./2, linewidth = 3, color= :black, label = false, xlim = [-beach_length, beach_length])
end
# ╔═╡ ca076585-03b6-4381-b730-e32c7a30446e
if show_calculation
heatmap(range_a, range_b, p,
title="The lighttower is most likely located at "*string(lighttower), colorbar_ticks = (0, "0"))
#clim=(0,0.00006)
end
# ╔═╡ 16938d4f-6f25-4924-8bdf-b0eb638a6c4f
begin
claire = "https://raw.githubusercontent.com/Captain-Bayes/images/main/claire_100px.gif"
makabe = "https://raw.githubusercontent.com/Captain-Bayes/images/main/makeba_100px.gif"
bayes = "https://raw.githubusercontent.com/Captain-Bayes/images/main/bayes_100px.gif"
bernoulli = "https://raw.githubusercontent.com/Captain-Bayes/images/main/Bernoulli_wet.gif"
island = "https://raw.githubusercontent.com/Captain-Bayes/images/main/Turtle_island_with_ship.png"
map = "https://raw.githubusercontent.com/Captain-Bayes/images/main/Fishground_map.png"
frogfish_image = "https://raw.githubusercontent.com/Captain-Bayes/images/main/frogfish_green_full.gif"
venn = "https://raw.githubusercontent.com/Captain-Bayes/images/main/venn_100px.gif"
angles_view = "https://raw.githubusercontent.com/Captain-Bayes/images/main/Gipfel_angles.png"
mountain_view = "https://raw.githubusercontent.com/Captain-Bayes/images/main/Gipfel_view.png"
image_of_data = "https://raw.githubusercontent.com/Captain-Bayes/images/main/Daten_brett.png"
diagram_of_data = "https://raw.githubusercontent.com/Captain-Bayes/images/main/Diagram.png"
treasure_map = "https://raw.githubusercontent.com/Captain-Bayes/images/main/Treasure_map_2.png"
lighthouse_image = "https://raw.githubusercontent.com/Captain-Bayes/images/main/lighthouse_problem_draft.png"
lighthouse_gif = "https://raw.githubusercontent.com/Captain-Bayes/images/main/Lighthouse.gif"
lyra = "https://raw.githubusercontent.com/Captain-Bayes/images/main/lyra_100px.gif"
md"""Images"""
end
# ╔═╡ 6c070606-1411-40fc-b6cd-8f27f052136b
md"""
# The lighthouse problem
$(Resource(lighthouse_gif, :width=>600))
$(Resource(lyra, :width=>150))
> *It tell you from my observations I know, there must be a lighthouse somewhere over the sea. Have a look at my data!*
> *Watch the **video** below for the full story:*
"""
#$(Resource(treasure_map, :width=>500))
# ╔═╡ 5fc032bb-990d-424e-a256-ef2979980606
begin
xx = [4.73, 0.45, -1.73, 1.09, 2.19, 0.12, 1.31, 1.00,
1.32, 1.07, 0.86, -0.49, -2.59, 1.73, 2.11, 1.61,
4.98, 1.71, 2.23,-57.20, 0.96, 1.25, -1.56, 2.45,
1.19, 2.17,-10.66, 1.91, -4.16, 1.92, 0.10, 1.98,
-2.51, 5.55, -0.47, 1.91, 0.95, -0.78, -0.84, 1.72,
-0.01, 1.48, 2.70, 1.21, 4.41, -4.79, 1.33, 0.81,
0.20, 1.58, 1.29, 16.19, 2.75, -2.38, -1.79, 6.50,
-18.53, 0.72, 0.94, 3.64, 1.94, -0.11, 1.57, 0.57]
md"""
## The data:
$(Resource(lyra, :width=>100))
*Click on the Checkbox 👉 $(show_flash_box) to see the position of the 100 flashes which I recorded. You can start a new observation by pressing the Button $(flashes)*.
> *Captain Bayes, can you help me to find the position of the lighthouse?*
"""
end
# ╔═╡ 6dd8c883-dac4-4a31-b5ae-09ec067ba852
begin
md"""
*For sure Lyra, below you can find the __derivation__ how I perform this calculation.*
*Just tick the checkbox to __start the calculation__ 👉 $(show_calculation_box)*
$(Resource(bayes, :width=>100))
"""
end
# ╔═╡ 7bf32131-f749-41da-9923-2970f1487f7e
begin
almost(text, headline=md"Almost there!") = Markdown.MD(Markdown.Admonition("warning", string(headline), [text]));
#brown
correct(text=md"Great! You got the right answer!", headline=md"Got it!") = Markdown.MD(Markdown.Admonition("correct", string(headline), [text]));
#green
keep_working(text=md"The answer is not quite right.", headline=md"Keep working on it!") = Markdown.MD(Markdown.Admonition("danger", string(headline), [text]));
#red
hint(text, headline=md"Hint") = Markdown.MD(Markdown.Admonition("hint", string(headline), [text]));
#blue
md"definition of boxes"
end
# ╔═╡ 5d349d39-c688-4431-b056-aa11d69376e9
function sr(variable, dig = 2; add_sign = false)
# string and round - converts a variable into a string with the predifined precission - to be extended to scientific and other formats
if dig == 0
st = string(round(Int, variable))
else
st = string(round(variable, digits = dig))
end
if add_sign
st = (variable < 0 ? "" : "+") * st
end
return st
end
# ╔═╡ 1760c093-96c9-4ed9-8f4d-2c2ff3bfda5c
TableOfContents()
# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
HypertextLiteral = "ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2"
LaTeXStrings = "b964fa9f-0449-5b57-a5c2-d3ea65f4040f"
Markdown = "d6f4376e-aef5-505a-96c1-9c027394607a"
Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
[compat]
HypertextLiteral = "~0.9.3"
LaTeXStrings = "~1.3.0"
Plots = "~1.23.6"
PlutoUI = "~0.7.20"
"""
# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised
[[AbstractPlutoDingetjes]]
deps = ["Pkg"]
git-tree-sha1 = "0bc60e3006ad95b4bb7497698dd7c6d649b9bc06"
uuid = "6e696c72-6542-2067-7265-42206c756150"
version = "1.1.1"
[[Adapt]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "84918055d15b3114ede17ac6a7182f68870c16f7"
uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"
version = "3.3.1"
[[ArgTools]]
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"
[[Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"
[[Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
[[Bzip2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "19a35467a82e236ff51bc17a3a44b69ef35185a2"
uuid = "6e34b625-4abd-537c-b88f-471c36dfa7a0"
version = "1.0.8+0"
[[Cairo_jll]]
deps = ["Artifacts", "Bzip2_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "JLLWrappers", "LZO_jll", "Libdl", "Pixman_jll", "Pkg", "Xorg_libXext_jll", "Xorg_libXrender_jll", "Zlib_jll", "libpng_jll"]
git-tree-sha1 = "f2202b55d816427cd385a9a4f3ffb226bee80f99"
uuid = "83423d85-b0ee-5818-9007-b63ccbeb887a"
version = "1.16.1+0"
[[ChainRulesCore]]
deps = ["Compat", "LinearAlgebra", "SparseArrays"]
git-tree-sha1 = "f885e7e7c124f8c92650d61b9477b9ac2ee607dd"
uuid = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
version = "1.11.1"
[[ChangesOfVariables]]
deps = ["LinearAlgebra", "Test"]
git-tree-sha1 = "9a1d594397670492219635b35a3d830b04730d62"
uuid = "9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0"
version = "0.1.1"
[[ColorSchemes]]
deps = ["ColorTypes", "Colors", "FixedPointNumbers", "Random"]
git-tree-sha1 = "a851fec56cb73cfdf43762999ec72eff5b86882a"
uuid = "35d6a980-a343-548e-a6ea-1d62b119f2f4"
version = "3.15.0"
[[ColorTypes]]
deps = ["FixedPointNumbers", "Random"]
git-tree-sha1 = "024fe24d83e4a5bf5fc80501a314ce0d1aa35597"
uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f"
version = "0.11.0"
[[Colors]]
deps = ["ColorTypes", "FixedPointNumbers", "Reexport"]
git-tree-sha1 = "417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40"
uuid = "5ae59095-9a9b-59fe-a467-6f913c188581"
version = "0.12.8"
[[Compat]]
deps = ["Base64", "Dates", "DelimitedFiles", "Distributed", "InteractiveUtils", "LibGit2", "Libdl", "LinearAlgebra", "Markdown", "Mmap", "Pkg", "Printf", "REPL", "Random", "SHA", "Serialization", "SharedArrays", "Sockets", "SparseArrays", "Statistics", "Test", "UUIDs", "Unicode"]
git-tree-sha1 = "dce3e3fea680869eaa0b774b2e8343e9ff442313"
uuid = "34da2185-b29b-5c13-b0c7-acf172513d20"
version = "3.40.0"
[[CompilerSupportLibraries_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae"
[[Contour]]
deps = ["StaticArrays"]
git-tree-sha1 = "9f02045d934dc030edad45944ea80dbd1f0ebea7"
uuid = "d38c429a-6771-53c6-b99e-75d170b6e991"
version = "0.5.7"
[[DataAPI]]
git-tree-sha1 = "cc70b17275652eb47bc9e5f81635981f13cea5c8"
uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a"
version = "1.9.0"
[[DataStructures]]
deps = ["Compat", "InteractiveUtils", "OrderedCollections"]
git-tree-sha1 = "7d9d316f04214f7efdbb6398d545446e246eff02"
uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
version = "0.18.10"
[[DataValueInterfaces]]
git-tree-sha1 = "bfc1187b79289637fa0ef6d4436ebdfe6905cbd6"
uuid = "e2d170a0-9d28-54be-80f0-106bbe20a464"
version = "1.0.0"
[[Dates]]
deps = ["Printf"]
uuid = "ade2ca70-3891-5945-98fb-dc099432e06a"
[[DelimitedFiles]]
deps = ["Mmap"]
uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab"
[[Distributed]]
deps = ["Random", "Serialization", "Sockets"]
uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b"
[[DocStringExtensions]]
deps = ["LibGit2"]
git-tree-sha1 = "b19534d1895d702889b219c382a6e18010797f0b"
uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae"
version = "0.8.6"
[[Downloads]]
deps = ["ArgTools", "LibCURL", "NetworkOptions"]
uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6"
[[EarCut_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "3f3a2501fa7236e9b911e0f7a588c657e822bb6d"
uuid = "5ae413db-bbd1-5e63-b57d-d24a61df00f5"
version = "2.2.3+0"
[[Expat_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "b3bfd02e98aedfa5cf885665493c5598c350cd2f"
uuid = "2e619515-83b5-522b-bb60-26c02a35a201"
version = "2.2.10+0"
[[FFMPEG]]
deps = ["FFMPEG_jll"]
git-tree-sha1 = "b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8"
uuid = "c87230d0-a227-11e9-1b43-d7ebe4e7570a"
version = "0.4.1"
[[FFMPEG_jll]]
deps = ["Artifacts", "Bzip2_jll", "FreeType2_jll", "FriBidi_jll", "JLLWrappers", "LAME_jll", "Libdl", "Ogg_jll", "OpenSSL_jll", "Opus_jll", "Pkg", "Zlib_jll", "libass_jll", "libfdk_aac_jll", "libvorbis_jll", "x264_jll", "x265_jll"]
git-tree-sha1 = "d8a578692e3077ac998b50c0217dfd67f21d1e5f"
uuid = "b22a6f82-2f65-5046-a5b2-351ab43fb4e5"
version = "4.4.0+0"
[[FixedPointNumbers]]
deps = ["Statistics"]
git-tree-sha1 = "335bfdceacc84c5cdf16aadc768aa5ddfc5383cc"
uuid = "53c48c17-4a7d-5ca2-90c5-79b7896eea93"
version = "0.8.4"
[[Fontconfig_jll]]
deps = ["Artifacts", "Bzip2_jll", "Expat_jll", "FreeType2_jll", "JLLWrappers", "Libdl", "Libuuid_jll", "Pkg", "Zlib_jll"]
git-tree-sha1 = "21efd19106a55620a188615da6d3d06cd7f6ee03"
uuid = "a3f928ae-7b40-5064-980b-68af3947d34b"
version = "2.13.93+0"
[[Formatting]]
deps = ["Printf"]
git-tree-sha1 = "8339d61043228fdd3eb658d86c926cb282ae72a8"
uuid = "59287772-0a20-5a39-b81b-1366585eb4c0"
version = "0.4.2"
[[FreeType2_jll]]
deps = ["Artifacts", "Bzip2_jll", "JLLWrappers", "Libdl", "Pkg", "Zlib_jll"]
git-tree-sha1 = "87eb71354d8ec1a96d4a7636bd57a7347dde3ef9"
uuid = "d7e528f0-a631-5988-bf34-fe36492bcfd7"
version = "2.10.4+0"
[[FriBidi_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91"
uuid = "559328eb-81f9-559d-9380-de523a88c83c"
version = "1.0.10+0"
[[GLFW_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libglvnd_jll", "Pkg", "Xorg_libXcursor_jll", "Xorg_libXi_jll", "Xorg_libXinerama_jll", "Xorg_libXrandr_jll"]
git-tree-sha1 = "0c603255764a1fa0b61752d2bec14cfbd18f7fe8"
uuid = "0656b61e-2033-5cc2-a64a-77c0f6c09b89"
version = "3.3.5+1"
[[GR]]
deps = ["Base64", "DelimitedFiles", "GR_jll", "HTTP", "JSON", "Libdl", "LinearAlgebra", "Pkg", "Printf", "Random", "Serialization", "Sockets", "Test", "UUIDs"]
git-tree-sha1 = "30f2b340c2fff8410d89bfcdc9c0a6dd661ac5f7"
uuid = "28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71"
version = "0.62.1"
[[GR_jll]]
deps = ["Artifacts", "Bzip2_jll", "Cairo_jll", "FFMPEG_jll", "Fontconfig_jll", "GLFW_jll", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Libtiff_jll", "Pixman_jll", "Pkg", "Qt5Base_jll", "Zlib_jll", "libpng_jll"]
git-tree-sha1 = "fd75fa3a2080109a2c0ec9864a6e14c60cca3866"
uuid = "d2c73de3-f751-5644-a686-071e5b155ba9"
version = "0.62.0+0"
[[GeometryBasics]]
deps = ["EarCut_jll", "IterTools", "LinearAlgebra", "StaticArrays", "StructArrays", "Tables"]
git-tree-sha1 = "58bcdf5ebc057b085e58d95c138725628dd7453c"
uuid = "5c1252a2-5f33-56bf-86c9-59e7332b4326"
version = "0.4.1"
[[Gettext_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Libiconv_jll", "Pkg", "XML2_jll"]
git-tree-sha1 = "9b02998aba7bf074d14de89f9d37ca24a1a0b046"
uuid = "78b55507-aeef-58d4-861c-77aaff3498b1"
version = "0.21.0+0"
[[Glib_jll]]
deps = ["Artifacts", "Gettext_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Libiconv_jll", "Libmount_jll", "PCRE_jll", "Pkg", "Zlib_jll"]
git-tree-sha1 = "7bf67e9a481712b3dbe9cb3dac852dc4b1162e02"
uuid = "7746bdde-850d-59dc-9ae8-88ece973131d"
version = "2.68.3+0"
[[Graphite2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "344bf40dcab1073aca04aa0df4fb092f920e4011"
uuid = "3b182d85-2403-5c21-9c21-1e1f0cc25472"
version = "1.3.14+0"
[[Grisu]]
git-tree-sha1 = "53bb909d1151e57e2484c3d1b53e19552b887fb2"
uuid = "42e2da0e-8278-4e71-bc24-59509adca0fe"
version = "1.0.2"
[[HTTP]]
deps = ["Base64", "Dates", "IniFile", "Logging", "MbedTLS", "NetworkOptions", "Sockets", "URIs"]
git-tree-sha1 = "0fa77022fe4b511826b39c894c90daf5fce3334a"
uuid = "cd3eb016-35fb-5094-929b-558a96fad6f3"
version = "0.9.17"
[[HarfBuzz_jll]]
deps = ["Artifacts", "Cairo_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "Graphite2_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Pkg"]
git-tree-sha1 = "8a954fed8ac097d5be04921d595f741115c1b2ad"
uuid = "2e76f6c2-a576-52d4-95c1-20adfe4de566"
version = "2.8.1+0"
[[Hyperscript]]
deps = ["Test"]
git-tree-sha1 = "8d511d5b81240fc8e6802386302675bdf47737b9"
uuid = "47d2ed2b-36de-50cf-bf87-49c2cf4b8b91"
version = "0.0.4"
[[HypertextLiteral]]
git-tree-sha1 = "2b078b5a615c6c0396c77810d92ee8c6f470d238"
uuid = "ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2"
version = "0.9.3"
[[IOCapture]]
deps = ["Logging", "Random"]
git-tree-sha1 = "f7be53659ab06ddc986428d3a9dcc95f6fa6705a"
uuid = "b5f81e59-6552-4d32-b1f0-c071b021bf89"
version = "0.2.2"
[[IniFile]]
deps = ["Test"]
git-tree-sha1 = "098e4d2c533924c921f9f9847274f2ad89e018b8"
uuid = "83e8ac13-25f8-5344-8a64-a9f2b223428f"
version = "0.5.0"
[[InteractiveUtils]]
deps = ["Markdown"]
uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240"
[[InverseFunctions]]
deps = ["Test"]
git-tree-sha1 = "a7254c0acd8e62f1ac75ad24d5db43f5f19f3c65"
uuid = "3587e190-3f89-42d0-90ee-14403ec27112"
version = "0.1.2"
[[IrrationalConstants]]
git-tree-sha1 = "7fd44fd4ff43fc60815f8e764c0f352b83c49151"
uuid = "92d709cd-6900-40b7-9082-c6be49f344b6"
version = "0.1.1"
[[IterTools]]
git-tree-sha1 = "05110a2ab1fc5f932622ffea2a003221f4782c18"
uuid = "c8e1da08-722c-5040-9ed9-7db0dc04731e"
version = "1.3.0"
[[IteratorInterfaceExtensions]]
git-tree-sha1 = "a3f24677c21f5bbe9d2a714f95dcd58337fb2856"
uuid = "82899510-4779-5014-852e-03e436cf321d"
version = "1.0.0"
[[JLLWrappers]]
deps = ["Preferences"]
git-tree-sha1 = "642a199af8b68253517b80bd3bfd17eb4e84df6e"
uuid = "692b3bcd-3c85-4b1f-b108-f13ce0eb3210"
version = "1.3.0"
[[JSON]]
deps = ["Dates", "Mmap", "Parsers", "Unicode"]
git-tree-sha1 = "8076680b162ada2a031f707ac7b4953e30667a37"
uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6"
version = "0.21.2"
[[JpegTurbo_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "d735490ac75c5cb9f1b00d8b5509c11984dc6943"
uuid = "aacddb02-875f-59d6-b918-886e6ef4fbf8"
version = "2.1.0+0"
[[LAME_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "f6250b16881adf048549549fba48b1161acdac8c"
uuid = "c1c5ebd0-6772-5130-a774-d5fcae4a789d"
version = "3.100.1+0"
[[LZO_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "e5b909bcf985c5e2605737d2ce278ed791b89be6"
uuid = "dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac"
version = "2.10.1+0"
[[LaTeXStrings]]
git-tree-sha1 = "f2355693d6778a178ade15952b7ac47a4ff97996"
uuid = "b964fa9f-0449-5b57-a5c2-d3ea65f4040f"
version = "1.3.0"
[[Latexify]]
deps = ["Formatting", "InteractiveUtils", "LaTeXStrings", "MacroTools", "Markdown", "Printf", "Requires"]
git-tree-sha1 = "a8f4f279b6fa3c3c4f1adadd78a621b13a506bce"
uuid = "23fbe1c1-3f47-55db-b15f-69d7ec21a316"
version = "0.15.9"
[[LibCURL]]
deps = ["LibCURL_jll", "MozillaCACerts_jll"]
uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21"
[[LibCURL_jll]]
deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"]
uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0"
[[LibGit2]]
deps = ["Base64", "NetworkOptions", "Printf", "SHA"]
uuid = "76f85450-5226-5b5a-8eaa-529ad045b433"
[[LibSSH2_jll]]
deps = ["Artifacts", "Libdl", "MbedTLS_jll"]
uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8"
[[Libdl]]
uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb"
[[Libffi_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "0b4a5d71f3e5200a7dff793393e09dfc2d874290"
uuid = "e9f186c6-92d2-5b65-8a66-fee21dc1b490"
version = "3.2.2+1"
[[Libgcrypt_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libgpg_error_jll", "Pkg"]
git-tree-sha1 = "64613c82a59c120435c067c2b809fc61cf5166ae"
uuid = "d4300ac3-e22c-5743-9152-c294e39db1e4"
version = "1.8.7+0"
[[Libglvnd_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll", "Xorg_libXext_jll"]
git-tree-sha1 = "7739f837d6447403596a75d19ed01fd08d6f56bf"
uuid = "7e76a0d4-f3c7-5321-8279-8d96eeed0f29"
version = "1.3.0+3"
[[Libgpg_error_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "c333716e46366857753e273ce6a69ee0945a6db9"
uuid = "7add5ba3-2f88-524e-9cd5-f83b8a55f7b8"
version = "1.42.0+0"
[[Libiconv_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "42b62845d70a619f063a7da093d995ec8e15e778"
uuid = "94ce4f54-9a6c-5748-9c1c-f9c7231a4531"
version = "1.16.1+1"
[[Libmount_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "9c30530bf0effd46e15e0fdcf2b8636e78cbbd73"
uuid = "4b2f31a3-9ecc-558c-b454-b3730dcb73e9"
version = "2.35.0+0"
[[Libtiff_jll]]
deps = ["Artifacts", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Pkg", "Zlib_jll", "Zstd_jll"]
git-tree-sha1 = "340e257aada13f95f98ee352d316c3bed37c8ab9"
uuid = "89763e89-9b03-5906-acba-b20f662cd828"
version = "4.3.0+0"
[[Libuuid_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "7f3efec06033682db852f8b3bc3c1d2b0a0ab066"
uuid = "38a345b3-de98-5d2b-a5d3-14cd9215e700"
version = "2.36.0+0"
[[LinearAlgebra]]
deps = ["Libdl"]
uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
[[LogExpFunctions]]
deps = ["ChainRulesCore", "ChangesOfVariables", "DocStringExtensions", "InverseFunctions", "IrrationalConstants", "LinearAlgebra"]
git-tree-sha1 = "be9eef9f9d78cecb6f262f3c10da151a6c5ab827"
uuid = "2ab3a3ac-af41-5b50-aa03-7779005ae688"
version = "0.3.5"
[[Logging]]
uuid = "56ddb016-857b-54e1-b83d-db4d58db5568"
[[MacroTools]]
deps = ["Markdown", "Random"]
git-tree-sha1 = "3d3e902b31198a27340d0bf00d6ac452866021cf"
uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09"
version = "0.5.9"
[[Markdown]]
deps = ["Base64"]
uuid = "d6f4376e-aef5-505a-96c1-9c027394607a"
[[MbedTLS]]
deps = ["Dates", "MbedTLS_jll", "Random", "Sockets"]
git-tree-sha1 = "1c38e51c3d08ef2278062ebceade0e46cefc96fe"
uuid = "739be429-bea8-5141-9913-cc70e7f3736d"
version = "1.0.3"
[[MbedTLS_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1"
[[Measures]]
git-tree-sha1 = "e498ddeee6f9fdb4551ce855a46f54dbd900245f"
uuid = "442fdcdd-2543-5da2-b0f3-8c86c306513e"
version = "0.3.1"
[[Missings]]
deps = ["DataAPI"]
git-tree-sha1 = "bf210ce90b6c9eed32d25dbcae1ebc565df2687f"
uuid = "e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28"
version = "1.0.2"
[[Mmap]]
uuid = "a63ad114-7e13-5084-954f-fe012c677804"
[[MozillaCACerts_jll]]
uuid = "14a3606d-f60d-562e-9121-12d972cd8159"
[[NaNMath]]
git-tree-sha1 = "bfe47e760d60b82b66b61d2d44128b62e3a369fb"
uuid = "77ba4419-2d1f-58cd-9bb1-8ffee604a2e3"
version = "0.3.5"
[[NetworkOptions]]
uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908"
[[Ogg_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "7937eda4681660b4d6aeeecc2f7e1c81c8ee4e2f"
uuid = "e7412a2a-1a6e-54c0-be00-318e2571c051"
version = "1.3.5+0"
[[OpenSSL_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "15003dcb7d8db3c6c857fda14891a539a8f2705a"
uuid = "458c3c95-2e84-50aa-8efc-19380b2a3a95"
version = "1.1.10+0"
[[Opus_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "51a08fb14ec28da2ec7a927c4337e4332c2a4720"
uuid = "91d4177d-7536-5919-b921-800302f37372"
version = "1.3.2+0"
[[OrderedCollections]]
git-tree-sha1 = "85f8e6578bf1f9ee0d11e7bb1b1456435479d47c"
uuid = "bac558e1-5e72-5ebc-8fee-abe8a469f55d"
version = "1.4.1"
[[PCRE_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "b2a7af664e098055a7529ad1a900ded962bca488"
uuid = "2f80f16e-611a-54ab-bc61-aa92de5b98fc"
version = "8.44.0+0"
[[Parsers]]
deps = ["Dates"]
git-tree-sha1 = "ae4bbcadb2906ccc085cf52ac286dc1377dceccc"
uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0"
version = "2.1.2"
[[Pixman_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "b4f5d02549a10e20780a24fce72bea96b6329e29"
uuid = "30392449-352a-5448-841d-b1acce4e97dc"
version = "0.40.1+0"
[[Pkg]]
deps = ["Artifacts", "Dates", "Downloads", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"]
uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f"
[[PlotThemes]]
deps = ["PlotUtils", "Requires", "Statistics"]
git-tree-sha1 = "a3a964ce9dc7898193536002a6dd892b1b5a6f1d"
uuid = "ccf2f8ad-2431-5c83-bf29-c5338b663b6a"
version = "2.0.1"
[[PlotUtils]]
deps = ["ColorSchemes", "Colors", "Dates", "Printf", "Random", "Reexport", "Statistics"]
git-tree-sha1 = "b084324b4af5a438cd63619fd006614b3b20b87b"
uuid = "995b91a9-d308-5afd-9ec6-746e21dbc043"
version = "1.0.15"
[[Plots]]
deps = ["Base64", "Contour", "Dates", "Downloads", "FFMPEG", "FixedPointNumbers", "GR", "GeometryBasics", "JSON", "Latexify", "LinearAlgebra", "Measures", "NaNMath", "PlotThemes", "PlotUtils", "Printf", "REPL", "Random", "RecipesBase", "RecipesPipeline", "Reexport", "Requires", "Scratch", "Showoff", "SparseArrays", "Statistics", "StatsBase", "UUIDs", "UnicodeFun"]
git-tree-sha1 = "0d185e8c33401084cab546a756b387b15f76720c"
uuid = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
version = "1.23.6"
[[PlutoUI]]
deps = ["AbstractPlutoDingetjes", "Base64", "Dates", "Hyperscript", "HypertextLiteral", "IOCapture", "InteractiveUtils", "JSON", "Logging", "Markdown", "Random", "Reexport", "UUIDs"]
git-tree-sha1 = "1e0cb51e0ccef0afc01aab41dc51a3e7f781e8cb"
uuid = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
version = "0.7.20"
[[Preferences]]
deps = ["TOML"]
git-tree-sha1 = "00cfd92944ca9c760982747e9a1d0d5d86ab1e5a"
uuid = "21216c6a-2e73-6563-6e65-726566657250"
version = "1.2.2"
[[Printf]]
deps = ["Unicode"]
uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7"
[[Qt5Base_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "Fontconfig_jll", "Glib_jll", "JLLWrappers", "Libdl", "Libglvnd_jll", "OpenSSL_jll", "Pkg", "Xorg_libXext_jll", "Xorg_libxcb_jll", "Xorg_xcb_util_image_jll", "Xorg_xcb_util_keysyms_jll", "Xorg_xcb_util_renderutil_jll", "Xorg_xcb_util_wm_jll", "Zlib_jll", "xkbcommon_jll"]
git-tree-sha1 = "ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8"
uuid = "ea2cea3b-5b76-57ae-a6ef-0a8af62496e1"
version = "5.15.3+0"
[[REPL]]
deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"]
uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb"
[[Random]]
deps = ["Serialization"]
uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
[[RecipesBase]]
git-tree-sha1 = "a4425fe1cde746e278fa895cc69e3113cb2614f6"
uuid = "3cdcf5f2-1ef4-517c-9805-6587b60abb01"
version = "1.2.0"
[[RecipesPipeline]]
deps = ["Dates", "NaNMath", "PlotUtils", "RecipesBase"]
git-tree-sha1 = "7ad0dfa8d03b7bcf8c597f59f5292801730c55b8"
uuid = "01d81517-befc-4cb6-b9ec-a95719d0359c"
version = "0.4.1"
[[Reexport]]
git-tree-sha1 = "45e428421666073eab6f2da5c9d310d99bb12f9b"
uuid = "189a3867-3050-52da-a836-e630ba90ab69"
version = "1.2.2"
[[Requires]]
deps = ["UUIDs"]
git-tree-sha1 = "4036a3bd08ac7e968e27c203d45f5fff15020621"
uuid = "ae029012-a4dd-5104-9daa-d747884805df"
version = "1.1.3"
[[SHA]]
uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce"
[[Scratch]]
deps = ["Dates"]
git-tree-sha1 = "0b4b7f1393cff97c33891da2a0bf69c6ed241fda"
uuid = "6c6a2e73-6563-6170-7368-637461726353"
version = "1.1.0"
[[Serialization]]
uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b"
[[SharedArrays]]
deps = ["Distributed", "Mmap", "Random", "Serialization"]
uuid = "1a1011a3-84de-559e-8e89-a11a2f7dc383"
[[Showoff]]
deps = ["Dates", "Grisu"]
git-tree-sha1 = "91eddf657aca81df9ae6ceb20b959ae5653ad1de"
uuid = "992d4aef-0814-514b-bc4d-f2e9a6c4116f"
version = "1.0.3"
[[Sockets]]
uuid = "6462fe0b-24de-5631-8697-dd941f90decc"
[[SortingAlgorithms]]
deps = ["DataStructures"]
git-tree-sha1 = "b3363d7460f7d098ca0912c69b082f75625d7508"
uuid = "a2af1166-a08f-5f64-846c-94a0d3cef48c"
version = "1.0.1"
[[SparseArrays]]
deps = ["LinearAlgebra", "Random"]
uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
[[StaticArrays]]
deps = ["LinearAlgebra", "Random", "Statistics"]
git-tree-sha1 = "3c76dde64d03699e074ac02eb2e8ba8254d428da"
uuid = "90137ffa-7385-5640-81b9-e52037218182"
version = "1.2.13"
[[Statistics]]
deps = ["LinearAlgebra", "SparseArrays"]
uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
[[StatsAPI]]
git-tree-sha1 = "0f2aa8e32d511f758a2ce49208181f7733a0936a"
uuid = "82ae8749-77ed-4fe6-ae5f-f523153014b0"
version = "1.1.0"
[[StatsBase]]
deps = ["DataAPI", "DataStructures", "LinearAlgebra", "LogExpFunctions", "Missings", "Printf", "Random", "SortingAlgorithms", "SparseArrays", "Statistics", "StatsAPI"]
git-tree-sha1 = "2bb0cb32026a66037360606510fca5984ccc6b75"
uuid = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91"
version = "0.33.13"
[[StructArrays]]
deps = ["Adapt", "DataAPI", "StaticArrays", "Tables"]
git-tree-sha1 = "2ce41e0d042c60ecd131e9fb7154a3bfadbf50d3"
uuid = "09ab397b-f2b6-538f-b94a-2f83cf4a842a"
version = "0.6.3"
[[TOML]]
deps = ["Dates"]
uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76"
[[TableTraits]]
deps = ["IteratorInterfaceExtensions"]
git-tree-sha1 = "c06b2f539df1c6efa794486abfb6ed2022561a39"
uuid = "3783bdb8-4a98-5b6b-af9a-565f29a5fe9c"
version = "1.0.1"
[[Tables]]
deps = ["DataAPI", "DataValueInterfaces", "IteratorInterfaceExtensions", "LinearAlgebra", "TableTraits", "Test"]
git-tree-sha1 = "fed34d0e71b91734bf0a7e10eb1bb05296ddbcd0"
uuid = "bd369af6-aec1-5ad0-b16a-f7cc5008161c"
version = "1.6.0"
[[Tar]]
deps = ["ArgTools", "SHA"]
uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e"
[[Test]]
deps = ["InteractiveUtils", "Logging", "Random", "Serialization"]
uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
[[URIs]]
git-tree-sha1 = "97bbe755a53fe859669cd907f2d96aee8d2c1355"
uuid = "5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4"
version = "1.3.0"
[[UUIDs]]
deps = ["Random", "SHA"]
uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4"
[[Unicode]]
uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5"
[[UnicodeFun]]
deps = ["REPL"]
git-tree-sha1 = "53915e50200959667e78a92a418594b428dffddf"
uuid = "1cfade01-22cf-5700-b092-accc4b62d6e1"
version = "0.4.1"
[[Wayland_jll]]
deps = ["Artifacts", "Expat_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Pkg", "XML2_jll"]
git-tree-sha1 = "3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23"
uuid = "a2964d1f-97da-50d4-b82a-358c7fce9d89"
version = "1.19.0+0"
[[Wayland_protocols_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "66d72dc6fcc86352f01676e8f0f698562e60510f"
uuid = "2381bf8a-dfd0-557d-9999-79630e7b1b91"
version = "1.23.0+0"
[[XML2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libiconv_jll", "Pkg", "Zlib_jll"]
git-tree-sha1 = "1acf5bdf07aa0907e0a37d3718bb88d4b687b74a"
uuid = "02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a"
version = "2.9.12+0"
[[XSLT_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libgcrypt_jll", "Libgpg_error_jll", "Libiconv_jll", "Pkg", "XML2_jll", "Zlib_jll"]
git-tree-sha1 = "91844873c4085240b95e795f692c4cec4d805f8a"
uuid = "aed1982a-8fda-507f-9586-7b0439959a61"
version = "1.1.34+0"
[[Xorg_libX11_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libxcb_jll", "Xorg_xtrans_jll"]
git-tree-sha1 = "5be649d550f3f4b95308bf0183b82e2582876527"
uuid = "4f6342f7-b3d2-589e-9d20-edeb45f2b2bc"
version = "1.6.9+4"
[[Xorg_libXau_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "4e490d5c960c314f33885790ed410ff3a94ce67e"
uuid = "0c0b7dd1-d40b-584c-a123-a41640f87eec"
version = "1.0.9+4"
[[Xorg_libXcursor_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXfixes_jll", "Xorg_libXrender_jll"]
git-tree-sha1 = "12e0eb3bc634fa2080c1c37fccf56f7c22989afd"
uuid = "935fb764-8cf2-53bf-bb30-45bb1f8bf724"
version = "1.2.0+4"
[[Xorg_libXdmcp_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "4fe47bd2247248125c428978740e18a681372dd4"
uuid = "a3789734-cfe1-5b06-b2d0-1dd0d9d62d05"
version = "1.1.3+4"
[[Xorg_libXext_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll"]
git-tree-sha1 = "b7c0aa8c376b31e4852b360222848637f481f8c3"
uuid = "1082639a-0dae-5f34-9b06-72781eeb8cb3"
version = "1.3.4+4"
[[Xorg_libXfixes_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll"]
git-tree-sha1 = "0e0dc7431e7a0587559f9294aeec269471c991a4"
uuid = "d091e8ba-531a-589c-9de9-94069b037ed8"
version = "5.0.3+4"
[[Xorg_libXi_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXext_jll", "Xorg_libXfixes_jll"]
git-tree-sha1 = "89b52bc2160aadc84d707093930ef0bffa641246"
uuid = "a51aa0fd-4e3c-5386-b890-e753decda492"
version = "1.7.10+4"
[[Xorg_libXinerama_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXext_jll"]
git-tree-sha1 = "26be8b1c342929259317d8b9f7b53bf2bb73b123"
uuid = "d1454406-59df-5ea1-beac-c340f2130bc3"
version = "1.1.4+4"
[[Xorg_libXrandr_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXext_jll", "Xorg_libXrender_jll"]
git-tree-sha1 = "34cea83cb726fb58f325887bf0612c6b3fb17631"
uuid = "ec84b674-ba8e-5d96-8ba1-2a689ba10484"
version = "1.5.2+4"
[[Xorg_libXrender_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll"]
git-tree-sha1 = "19560f30fd49f4d4efbe7002a1037f8c43d43b96"
uuid = "ea2f1a96-1ddc-540d-b46f-429655e07cfa"
version = "0.9.10+4"
[[Xorg_libpthread_stubs_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "6783737e45d3c59a4a4c4091f5f88cdcf0908cbb"
uuid = "14d82f49-176c-5ed1-bb49-ad3f5cbd8c74"
version = "0.1.0+3"
[[Xorg_libxcb_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "XSLT_jll", "Xorg_libXau_jll", "Xorg_libXdmcp_jll", "Xorg_libpthread_stubs_jll"]
git-tree-sha1 = "daf17f441228e7a3833846cd048892861cff16d6"
uuid = "c7cfdc94-dc32-55de-ac96-5a1b8d977c5b"
version = "1.13.0+3"
[[Xorg_libxkbfile_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll"]
git-tree-sha1 = "926af861744212db0eb001d9e40b5d16292080b2"
uuid = "cc61e674-0454-545c-8b26-ed2c68acab7a"
version = "1.1.0+4"
[[Xorg_xcb_util_image_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xcb_util_jll"]
git-tree-sha1 = "0fab0a40349ba1cba2c1da699243396ff8e94b97"
uuid = "12413925-8142-5f55-bb0e-6d7ca50bb09b"
version = "0.4.0+1"
[[Xorg_xcb_util_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libxcb_jll"]
git-tree-sha1 = "e7fd7b2881fa2eaa72717420894d3938177862d1"
uuid = "2def613f-5ad1-5310-b15b-b15d46f528f5"
version = "0.4.0+1"
[[Xorg_xcb_util_keysyms_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xcb_util_jll"]
git-tree-sha1 = "d1151e2c45a544f32441a567d1690e701ec89b00"
uuid = "975044d2-76e6-5fbe-bf08-97ce7c6574c7"
version = "0.4.0+1"
[[Xorg_xcb_util_renderutil_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xcb_util_jll"]
git-tree-sha1 = "dfd7a8f38d4613b6a575253b3174dd991ca6183e"
uuid = "0d47668e-0667-5a69-a72c-f761630bfb7e"
version = "0.3.9+1"
[[Xorg_xcb_util_wm_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xcb_util_jll"]
git-tree-sha1 = "e78d10aab01a4a154142c5006ed44fd9e8e31b67"
uuid = "c22f9ab0-d5fe-5066-847c-f4bb1cd4e361"
version = "0.4.1+1"
[[Xorg_xkbcomp_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libxkbfile_jll"]
git-tree-sha1 = "4bcbf660f6c2e714f87e960a171b119d06ee163b"
uuid = "35661453-b289-5fab-8a00-3d9160c6a3a4"
version = "1.4.2+4"
[[Xorg_xkeyboard_config_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xkbcomp_jll"]
git-tree-sha1 = "5c8424f8a67c3f2209646d4425f3d415fee5931d"
uuid = "33bec58e-1273-512f-9401-5d533626f822"
version = "2.27.0+4"
[[Xorg_xtrans_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "79c31e7844f6ecf779705fbc12146eb190b7d845"
uuid = "c5fb5394-a638-5e4d-96e5-b29de1b5cf10"
version = "1.4.0+3"
[[Zlib_jll]]
deps = ["Libdl"]
uuid = "83775a58-1f1d-513f-b197-d71354ab007a"
[[Zstd_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "cc4bf3fdde8b7e3e9fa0351bdeedba1cf3b7f6e6"
uuid = "3161d3a3-bdf6-5164-811a-617609db77b4"
version = "1.5.0+0"
[[libass_jll]]
deps = ["Artifacts", "Bzip2_jll", "FreeType2_jll", "FriBidi_jll", "HarfBuzz_jll", "JLLWrappers", "Libdl", "Pkg", "Zlib_jll"]
git-tree-sha1 = "5982a94fcba20f02f42ace44b9894ee2b140fe47"
uuid = "0ac62f75-1d6f-5e53-bd7c-93b484bb37c0"
version = "0.15.1+0"
[[libfdk_aac_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "daacc84a041563f965be61859a36e17c4e4fcd55"
uuid = "f638f0a6-7fb0-5443-88ba-1cc74229b280"
version = "2.0.2+0"
[[libpng_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Zlib_jll"]
git-tree-sha1 = "94d180a6d2b5e55e447e2d27a29ed04fe79eb30c"
uuid = "b53b4c65-9356-5827-b1ea-8c7a1a84506f"
version = "1.6.38+0"
[[libvorbis_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Ogg_jll", "Pkg"]
git-tree-sha1 = "c45f4e40e7aafe9d086379e5578947ec8b95a8fb"
uuid = "f27f6e37-5d2b-51aa-960f-b287f2bc3b7a"
version = "1.3.7+0"
[[nghttp2_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d"
[[p7zip_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0"
[[x264_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "4fea590b89e6ec504593146bf8b988b2c00922b2"
uuid = "1270edf5-f2f9-52d2-97e9-ab00b5d0237a"
version = "2021.5.5+0"
[[x265_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "ee567a171cce03570d77ad3a43e90218e38937a9"
uuid = "dfaa095f-4041-5dcd-9319-2fabd8486b76"
version = "3.5.0+0"
[[xkbcommon_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Wayland_jll", "Wayland_protocols_jll", "Xorg_libxcb_jll", "Xorg_xkeyboard_config_jll"]
git-tree-sha1 = "ece2350174195bb31de1a63bea3a41ae1aa593b6"
uuid = "d8fb68d0-12a3-5cfd-a85a-d49703b185fd"
version = "0.9.1+5"
"""
# ╔═╡ Cell order:
# ╟─6c070606-1411-40fc-b6cd-8f27f052136b
# ╟─ec784992-f4af-4ece-bf72-555960a054ca
# ╟─8f919de1-356f-4e42-9f7e-5d29092ed80f
# ╟─3c1cc3af-11f9-44ac-b07f-69704c4841c4
# ╟─936ccc78-8720-46b5-91eb-8d23f8699c99
# ╟─b8942536-020b-4c8e-a875-b5aba3034d42
# ╟─5fc032bb-990d-424e-a256-ef2979980606
# ╟─6dd8c883-dac4-4a31-b5ae-09ec067ba852
# ╟─ca076585-03b6-4381-b730-e32c7a30446e
# ╟─fd94fab8-c4c4-454e-9f5b-c0f1178143b3
# ╟─d3f023b1-8a57-4690-b8d6-afbe2ff50d5e
# ╟─bbb80420-ccae-48e7-a943-8aae332cb254
# ╟─ed56b559-ea17-41c7-8fe5-6ae9440fd5b5
# ╟─b2dc9f9b-9f57-4ca8-82ef-9c6a3915d6d0
# ╟─656ac69b-4cf5-440b-a894-83a7a80f42f0
# ╟─a61337a8-e197-4a7b-817d-012a5c1c0f17
# ╟─51b1234a-9808-4dad-a588-f61db077767f
# ╟─e7666210-a660-11eb-3e0d-7d9aec9a9f9e
# ╟─16938d4f-6f25-4924-8bdf-b0eb638a6c4f
# ╟─7bf32131-f749-41da-9923-2970f1487f7e
# ╟─5d349d39-c688-4431-b056-aa11d69376e9
# ╠═1760c093-96c9-4ed9-8f4d-2c2ff3bfda5c
# ╟─00000000-0000-0000-0000-000000000001
# ╟─00000000-0000-0000-0000-000000000002
|
module Polymorphic where
import Data.Complex
import Data.Ratio
import Prelude hiding (product)
stringLength :: String -> Int
stringLength x = case x of
[] -> 0
['a',_] -> 1
_:xs -> 1 + stringLength xs
integerListLength :: [Integer] -> Int
integerListLength n = case n of
[] -> 0
_:xs -> 1 + integerListLength xs
-- | A polymorphic length function
polymorphicLength :: [a] -> Int
polymorphicLength list = case list of
[] -> 0
_ : xs -> 1 + polymorphicLength xs
-- | A polymorphic reverse function
reverseOf :: [a] -> [a]
reverseOf n = case n of
[] -> []
x:xs -> reverseOf xs ++ [x]
-- | A polymorphic isPalindrome function
isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome list = list == reverseOf list
-- | A polymorphic list equality function
listEqual :: (Eq a) => [a] -> [a] -> Bool
listEqual list1 list2 = case (list1,list2) of
([],[] )-> True
([],_) -> False
(_,[]) -> False
(x:xs,y:ys) -> (x==y) && (xs `listEqual` ys)
isMonotonicallyIncreasing :: (Ord a) => [a] -> Bool
isMonotonicallyIncreasing list = case list of
[] -> True
i1:i2:is
|i1<=i2 -> isMonotonicallyIncreasing (i2:is)
|otherwise -> False
[_] -> True
normaliseVector :: (Floating a) => [a] -> [a]
normaliseVector vector = divideByScalar vector (norm vector)
divideByScalar :: (Fractional a) =>[a] -> a -> [a]
divideByScalar vector' scalar = case vector' of
[] -> []
f: fs -> (f / scalar): divideByScalar fs scalar
norm :: (Floating a) => [a] -> a
norm vector' = sqrt(sumSqr vector')
where
sumSqr :: (Num a)=> [a] -> a
sumSqr vector'' = case vector'' of
[] -> 0
f: fs -> f*f + sumSqr fs
reallyPolymorphicLength :: (Integral b) => [a] -> b
reallyPolymorphicLength list = case list of
[] -> 0
_: xs -> 1 + reallyPolymorphicLength xs
printLargestAsString :: (Ord a, Show a) => [a] -> String
printLargestAsString list =
"The largest element in the list is " ++ show (maximum list)
rationalZero :: Ratio Integer
floatZero :: Float
doubleZero :: Double
complexZero :: Complex Double
rationalZero = 0
floatZero = 0.0
doubleZero = 0.0
complexZero = mkPolar 0.0 0.0
product :: (Num a, Eq a) => a -> a -> a
product x y = case y of
0->0
1->x
_->x+product x(y-1)
|
You can get EZ-Builder Robot Control Software and try this out yourself.
Not a programmer? No problem! The EZ-Builder application allows non-programmers to easily build robots using advanced functions of the EZ-B Robot Controller. It is a Microsoft Windows application that gives you remote and scripting control of your custom robot design. Within the application, you add Controls that mimic your robot’s configuration. There are many controls for speakers, iRobot Roomba, HBridge, Servos, Cameras, Voice Recognition, Joysticks and more! There is even an easy scripting language so you may create short animations, interactions or initialization routines for your robot.
Using a Dremel, hot glue gun, screw drivers and various other tools, you can begin modifying the toy shell to fit your servos. For wheels or mobility, use continuous rotation modified servos. For arms and neck, use a standard servo. To allow your robot to see for object detection, use a Sharp IR Distance Sensor or a HC-SR04 Ultrasonic Ping Sensor.
My younger son is interested in robotics and waited patiently for about four years to be old enough to use the Mindstorm robotic toy. He was very excited once he got it but found that it was not as hands on as he had hoped. Since he is still relatively young for the age requirement I think he bit off more than he could chew for an 11 year old. As he gets older I want to help him to explore the world of robotics more fully. It is a very exciting field to play in.
The Wall-e is so much like the real guy in the movie. very cool!
Robots have always fascinated me and I always wanted to build one. Will be checking out this software when I have the time.
This is a nice video. I like it. I am very interested in robotics. It is awesome how modern robots can move and to some really nice work. I think i will try to programm my own robots with this control software. I hope it will be great to look at.
It never crossed my mind that creating a wall-e robot is very easy. Although I can get my hands on tools and materials to create the robot, the fact that I have no idea on how to program a robot stops me to do so. I really appreciate the video and thank you for posting this. I will make sure to try this out and see if I can make my most favorite robot (this will be my first time to create one; so wish me luck).
|
/* movstat/gsl_movstat.h
*
* Copyright (C) 2018 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_MOVSTAT_H__
#define __GSL_MOVSTAT_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef enum
{
GSL_MOVSTAT_END_PADZERO,
GSL_MOVSTAT_END_PADVALUE,
GSL_MOVSTAT_END_TRUNCATE
} gsl_movstat_end_t;
/* accumulator struct
* size - return number of bytes needed for accumulator with maximum of n elements
* init - initialize accumulator state
* insert - insert a single sample into accumulator; if there are already n
* samples in accumulator, oldest sample is overwritten
* delete_oldest - delete oldest sample from accumulator
* get - return accumulated value
*/
typedef struct
{
size_t (*size) (const size_t n);
int (*init) (const size_t n, void * vstate);
int (*insert) (const double x, void * vstate);
int (*delete_oldest) (void * vstate);
int (*get) (void * params, double * result, const void * vstate);
} gsl_movstat_accum;
typedef struct
{
double (* function) (const size_t n, double x[], void * params);
void * params;
} gsl_movstat_function;
#define GSL_MOVSTAT_FN_EVAL(F,n,x) (*((F)->function))((n),(x),(F)->params)
/* workspace for moving window statistics */
typedef struct
{
size_t H; /* number of previous samples in window */
size_t J; /* number of after samples in window */
size_t K; /* window size K = H + J + 1 */
double *work; /* workspace, size K */
void *state; /* state workspace for various accumulators */
size_t state_size; /* bytes allocated for 'state' */
} gsl_movstat_workspace;
/* alloc.c */
GSL_FUN gsl_movstat_workspace *gsl_movstat_alloc(const size_t K);
GSL_FUN gsl_movstat_workspace *gsl_movstat_alloc2(const size_t H, const size_t J);
GSL_FUN gsl_movstat_workspace *gsl_movstat_alloc_with_size(const size_t accum_state_size, const size_t H, const size_t J);
GSL_FUN void gsl_movstat_free(gsl_movstat_workspace * w);
/* apply.c */
GSL_FUN int gsl_movstat_apply_accum(const gsl_movstat_end_t endtype, const gsl_vector * x,
const gsl_movstat_accum * accum, void * accum_params,
gsl_vector * y, gsl_vector * z,
gsl_movstat_workspace * w);
GSL_FUN int gsl_movstat_apply(const gsl_movstat_end_t endtype, const gsl_movstat_function * F,
const gsl_vector * x, gsl_vector * y, gsl_movstat_workspace * w);
/* fill.c */
GSL_FUN size_t gsl_movstat_fill(const gsl_movstat_end_t endtype, const gsl_vector * x, const size_t idx,
const size_t H, const size_t J, double * window);
GSL_FUN int gsl_movstat_mean(const gsl_movstat_end_t endtype, const gsl_vector * x, gsl_vector * y, gsl_movstat_workspace * w);
GSL_FUN int gsl_movstat_variance(const gsl_movstat_end_t endtype, const gsl_vector * x, gsl_vector * y, gsl_movstat_workspace * w);
GSL_FUN int gsl_movstat_sd(const gsl_movstat_end_t endtype, const gsl_vector * x, gsl_vector * y, gsl_movstat_workspace * w);
GSL_FUN int gsl_movstat_median(const gsl_movstat_end_t endtype, const gsl_vector * x, gsl_vector * y, gsl_movstat_workspace * w);
GSL_FUN int gsl_movstat_min(const gsl_movstat_end_t endtype, const gsl_vector * x, gsl_vector * y, gsl_movstat_workspace * w);
GSL_FUN int gsl_movstat_max(const gsl_movstat_end_t endtype, const gsl_vector * x, gsl_vector * y, gsl_movstat_workspace * w);
GSL_FUN int gsl_movstat_minmax(const gsl_movstat_end_t endtype, const gsl_vector * x, gsl_vector * y_min, gsl_vector * y_max, gsl_movstat_workspace * w);
GSL_FUN int gsl_movstat_mad0(const gsl_movstat_end_t endtype, const gsl_vector * x, gsl_vector * xmedian,
gsl_vector * xmad, gsl_movstat_workspace * w);
GSL_FUN int gsl_movstat_mad(const gsl_movstat_end_t endtype, const gsl_vector * x, gsl_vector * xmedian,
gsl_vector * xmad, gsl_movstat_workspace * w);
GSL_FUN int gsl_movstat_qqr(const gsl_movstat_end_t endtype, const gsl_vector * x, const double q,
gsl_vector * xqqr, gsl_movstat_workspace * w);
GSL_FUN int gsl_movstat_Sn(const gsl_movstat_end_t endtype, const gsl_vector * x,
gsl_vector * xscale, gsl_movstat_workspace * w);
GSL_FUN int gsl_movstat_Qn(const gsl_movstat_end_t endtype, const gsl_vector * x,
gsl_vector * xscale, gsl_movstat_workspace * w);
GSL_FUN int gsl_movstat_sum(const gsl_movstat_end_t endtype, const gsl_vector * x, gsl_vector * y, gsl_movstat_workspace * w);
/* accumulator variables */
GSL_VAR const gsl_movstat_accum * gsl_movstat_accum_mad;
GSL_VAR const gsl_movstat_accum * gsl_movstat_accum_max;
GSL_VAR const gsl_movstat_accum * gsl_movstat_accum_mean;
GSL_VAR const gsl_movstat_accum * gsl_movstat_accum_median;
GSL_VAR const gsl_movstat_accum * gsl_movstat_accum_min;
GSL_VAR const gsl_movstat_accum * gsl_movstat_accum_minmax;
GSL_VAR const gsl_movstat_accum * gsl_movstat_accum_sd;
GSL_VAR const gsl_movstat_accum * gsl_movstat_accum_Sn;
GSL_VAR const gsl_movstat_accum * gsl_movstat_accum_sum;
GSL_VAR const gsl_movstat_accum * gsl_movstat_accum_Qn;
GSL_VAR const gsl_movstat_accum * gsl_movstat_accum_qqr;
GSL_VAR const gsl_movstat_accum * gsl_movstat_accum_userfunc;
GSL_VAR const gsl_movstat_accum * gsl_movstat_accum_variance;
__END_DECLS
#endif /* __GSL_MOVSTAT_H__ */
|
REBOL []
do %rugby.r
code: {add1: func [ n [number!]][n + 1]}
do get-rugby-service http://localhost:8002
extend-env [add1] code
|
# Copyright (c) 2018-2021, Carnegie Mellon University
# See LICENSE for details
Class(ISumn, ISum, rec(
abbrevs := [ (dom, expr) -> Checked(IsPosIntSym(dom), IsSPL(expr), [dom, expr]) ],
new := meth(self, domain, expr)
local res;
# ??? if domain = 1 then return SubstBottomUp(expr, var, e->V(0));
res := SPL(WithBases(self, rec(_children := [expr], domain := domain)));
res.dimensions := res.dims();
return res;
end,
#-----------------------------------------------------------------------
unrolledChildren := self >> Error("not implemented"),
# List(listRange(self.domain), u ->
# SubstBottomUp(Copy(self._children[1]), self.var, e->V(u))),
#-----------------------------------------------------------------------
rChildren := self >> [self.domain, self._children[1]],
rSetChild := meth(self, n, what)
if n=1 then self.domain := what;
elif n=2 then self._children[1] := what;
else Error("<n> must be in [1,2]"); fi;
end,
#-----------------------------------------------------------------------
print := (self,i,is) >> Print(self.name, "(", self.domain, ",\n",
Blanks(i+is), self._children[1].print(i+is, is), "\n", Blanks(i), ")"),
#-----------------------------------------------------------------------
sums := self >> let(base := self.__bases__[1],
base(self.var, self.domain, self._children[1].sums())),
));
Tensor.sumsn := meth(self)
local ch, col_prods, row_prods, col_prods_rev, row_prods_rev, i, c,
cp1, cp2, rp1, rp2, cols, rows, prod, term, scat, gath;
if self.isPermutation() then return
Prm(ApplyFunc(self.fTensor, List(self.children(), c->c.sums().func)));
elif ForAll(self.children(), x->ObjId(x)=Diag) then return
Diag(ApplyFunc(diagTensor, List(self.children(), c->c.element)));
fi;
ch := self.children();
col_prods := ScanL(ch, (x,y)->x*Cols(y), 1);
col_prods_rev := Drop(ScanR(ch, (x,y)->x*Cols(y), 1), 1);
#row_prods := ScanL(ch, (x,y)->x*Rows(y), 1);
#row_prods_rev := DropLast(ScanR(ch, (x,y)->x*Rows(y), 1), 1);
prod := [];
for i in [1..Length(ch)] do
c := ch[i];
if not IsIdentitySPL(c) then
[cp1, cp2] := [col_prods[i], col_prods_rev[i]];
#[rp1, rp2] := [row_prods[i], row_prods_rev[i]];
[rows, cols] := Dimensions(c);
[scat, gath] := [[cp2], [cp2]];
if cp2 <> 1 then
Add(scat, 1);
Add(gath, 1); fi;
if cp1 <> 1 then
Add(scat, cp2*rows);
Add(gath, cp2*cols); fi;
term := Scat(HH(cp1*rows*cp2, rows, 0, scat)) *
c.sums() *
Gath(HH(cp1*cols*cp2, cols, 0, gath));
if cp2 <> 1 then term := ISumn(cp2, term); fi;
if cp1 <> 1 then term := ISumn(cp1, term); fi;
Add(prod, term);
fi;
od;
return Compose(prod);
end;
IterDirectSum.sumsn := self >> let(A := self.child(1),
ISumn(self.domain,
Scat(HH(Rows(self), Rows(A), 0, [1, Rows(A)])) *
# spiral.sigma.SumsSPL( # NOTE: subst to ind -- potentially unsafe! (other loops!)
SubstVars(Copy(A), rec((self.var.id) := ind(self.var.range, 1))).sums() *
Gath(HH(Cols(self), Cols(A), 0, [1, Cols(A)]))));
RowTensor.sumsn := self >> let(A := self.child(1),
ISumn(self.isize,
Scat(HH(Rows(self), Rows(A), 0, [1, Rows(A)])) *
# spiral.sigma.SumsSPL(A) *
A.sums() *
Gath(HH(Cols(self), Cols(A), 0, [1, Cols(A) - self.overlap]))));
|
/* rng/knuthran2.c
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/*
* This generator is taken from
*
* Donald E. Knuth
* The Art of Computer Programming
* Volume 2
* Third Edition
* Addison-Wesley
* Page 108
*
* This implementation copyright (C) 2001 Carlo Perassi
* and (C) 2003 Heiko Bauke.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>
#include "schrage.c"
#define AA1 271828183UL
#define AA2 1833324378UL /* = -314159269 mod (2 ^ 31 -1) */
#define MM 0x7fffffffUL /* 2 ^ 31 - 1 */
#define CEIL_SQRT_MM 46341UL /* sqrt(2 ^ 31 - 1) */
static inline unsigned long int ran_get (void *vstate);
static double ran_get_double (void *vstate);
static void ran_set (void *state, unsigned long int s);
typedef struct
{
unsigned long int x0;
unsigned long int x1;
}
ran_state_t;
static inline unsigned long int
ran_get (void *vstate)
{
ran_state_t *state = (ran_state_t *) vstate;
const unsigned long int xtmp = state->x1;
state->x1 = schrage_mult (AA1, state->x1, MM, CEIL_SQRT_MM)
+ schrage_mult (AA2, state->x0, MM, CEIL_SQRT_MM);
if (state->x1 >= MM)
state->x1 -= MM;
state->x0 = xtmp;
return state->x1;
}
static double
ran_get_double (void *vstate)
{
ran_state_t *state = (ran_state_t *) vstate;
return ran_get (state) / 2147483647.0;
}
static void
ran_set (void *vstate, unsigned long int s)
{
ran_state_t *state = (ran_state_t *) vstate;
if ((s % MM) == 0)
s = 1; /* default seed is 1 */
state->x0 = s % MM;
state->x1 = s % MM;
return;
}
static const gsl_rng_type ran_type = {
"knuthran2", /* name */
MM - 1L, /* RAND_MAX */
0, /* RAND_MIN */
sizeof (ran_state_t),
&ran_set,
&ran_get,
&ran_get_double
};
const gsl_rng_type *gsl_rng_knuthran2 = &ran_type;
|
[STATEMENT]
lemma wbalanced_bal_list[simp]: "n \<le> length xs \<Longrightarrow> wbalanced (bal_list n xs)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. n \<le> length xs \<Longrightarrow> wbalanced (bal_list n xs)
[PROOF STEP]
by(simp add: bal_list_def) (metis prod.collapse wbalanced_bal)
|
From mathcomp Require Import all_ssreflect.
From RegLang Require Import setoid_leq misc nfa dfa minimization languages regexp.
From RegMatch Require Import regexp regmatch.
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Section RegLangExp.
Variable char : eqType.
Lemma r_eq_dec (e1 e2 : r char) : {e1 = e2} + {e1 <> e2}.
Proof. decide equality; apply: eq_comparable. Qed.
Definition r_eqMixin := EqMixin (compareP r_eq_dec).
Canonical Structure re_eqType := EqType _ r_eqMixin.
Fixpoint regexp2r (r0 : regexp char) : r char :=
match r0 with
| Void => r_zero
| Eps => r_unit
| Atom c' => r_char c'
| Star r' => r_star (regexp2r r')
| Plus r1 r2 => r_plus (regexp2r r1) (regexp2r r2)
| Conc r1 r2 => r_times (regexp2r r1) (regexp2r r2)
end.
Fixpoint r2regexp (r : r char) : regexp char :=
match r with
| r_zero => Void
| r_unit => Eps
| r_char c' => Atom c'
| r_star r' => Star (r2regexp r')
| r_plus r1 r2 => Plus (r2regexp r1) (r2regexp r2)
| r_times r1 r2 => Conc (r2regexp r1) (r2regexp r2)
end.
Fixpoint re_stars (e : regexp char) : nat :=
match e with
| Star s => (re_stars s).+1
| Plus s t => ((re_stars s)+(re_stars t)).+1
| Conc s t => ((re_stars s)+(re_stars t)).+1
| _ => 0
end.
Lemma cancel_re_regexp : cancel r2regexp regexp2r.
Proof.
rewrite /cancel.
elim => //=.
- move => r IH r' IH'.
by rewrite IH IH'.
- move => r IH r' IH'.
by rewrite IH IH'.
- move => r IH.
by rewrite IH.
Qed.
Lemma cancel_regexp_re : cancel regexp2r r2regexp.
Proof.
rewrite /cancel.
elim => //=.
- move => r IH.
by rewrite IH.
- move => r IH r' IH'.
by rewrite IH IH'.
- move => r IH r' IH'.
by rewrite IH IH'.
Qed.
Lemma regexp_re_in : forall (r : r char) (w : seq char), s_in_regexp_lang _ w r -> w \in re_lang (r2regexp r).
Proof.
move => r w H.
remember r as r0.
remember w as w0.
revert r w Heqr0 Heqw0.
induction H => //=.
- move => r w H_eq H_eq'.
subst.
by rewrite inE.
- move => r w H_eq H_eq'.
subst.
apply/plusP; left.
exact: IHs_in_regexp_lang.
- move => r w H_eq H_eq'.
subst.
apply/plusP; right.
exact: IHs_in_regexp_lang.
- move => r w H_eq H_eq'.
subst.
apply/concP.
exists s5, s'.
split => //.
split.
* exact: IHs_in_regexp_lang1.
* exact: IHs_in_regexp_lang2.
- move => r' w H_eq H_eq'.
subst.
apply/star_cat.
* exact: IHs_in_regexp_lang1.
* exact: IHs_in_regexp_lang2.
Qed.
Lemma regexp_re_in' : forall (r : regexp char) (w : seq char), s_in_regexp_lang _ w (regexp2r r) -> w \in re_lang r.
Proof.
move => r w H.
remember (regexp2r r) as r0.
remember w as w0.
revert r w Heqr0 Heqw0.
induction H => //=.
- move => r w H_eq H_eq'.
subst.
by destruct r.
- move => r w H_eq H_eq'.
subst.
destruct r => //.
rewrite /= in H_eq.
injection H_eq => H_eq'.
subst.
by rewrite inE.
- move => r w H_eq H_eq'.
subst.
destruct r => //.
rewrite /= in H_eq.
injection H_eq => H_eq1 H_eq2.
subst.
apply/plusP.
left.
by apply (IHs_in_regexp_lang _ w).
- move => r w H_eq H_eq'.
subst.
destruct r => //.
rewrite /= in H_eq.
injection H_eq => H_eq1 H_eq2.
subst.
apply/plusP.
right.
by apply (IHs_in_regexp_lang _ w).
- move => r w H_eq H_eq'.
subst.
destruct r => //.
rewrite /= in H_eq.
injection H_eq => H_eq1 H_eq2.
subst.
apply/concP.
exists s5, s'.
split => //.
split.
* exact: IHs_in_regexp_lang1.
* exact: IHs_in_regexp_lang2.
- move => r' w H_eq H_eq'.
subst.
by destruct r'.
- move => r' w H_eq H_eq'.
subst.
destruct r' => //.
rewrite /= in H_eq.
injection H_eq => H_eq'.
subst.
apply/star_cat.
* exact: IHs_in_regexp_lang1.
* rewrite -/(re_lang _).
have ->: star (re_lang r') = re_lang (Star r') by [].
exact: IHs_in_regexp_lang2.
Qed.
Lemma re_lang_ind : forall (char : eqType) (P : seq char -> regexp char -> Prop),
P [::] Eps ->
(forall c' : char, P [:: c'] (Atom c')) ->
(forall (w : seq char) (r1 r2 : regexp char), w \in (re_lang r1) -> P w r1 -> P w (Plus r1 r2)) ->
(forall (w : seq char) (r1 r2 : regexp char), w \in (re_lang r2) -> P w r2 -> P w (Plus r1 r2)) ->
(forall (w1 w2 : seq char) (r1 r2 : regexp char),
w1 \in (re_lang r1) -> P w1 r1 -> w2 \in (re_lang r2) -> P w2 r2 -> P (w1 ++ w2) (Conc r1 r2)) ->
(forall r : regexp char, P [::] (Star r)) ->
(forall (w1 w2 : seq char) (r :regexp char),
w1 \in (re_lang r) -> P w1 r -> w2 \in (re_lang (Star r)) -> P w2 (Star r) -> P (w1 ++ w2) (Star r)) ->
forall (w : seq char) (r : regexp char), w \in (re_lang r) -> P w r.
Proof.
move => c0 P H_e H_a H_p1 H_p2 H_c H_s1 H_s2.
move => w r.
elim: r w => //=.
- by case.
- move => c' w.
rewrite inE /=.
move/eqP => H_eq.
subst.
exact: H_a.
- move => r IH w.
move/starP => [vv H_vv] H_f.
subst.
move/allP: H_vv.
move => IH'.
elim: vv IH' => //=.
move => w0 vv' IH' H_in.
have H_in_vv: w0 \in w0 :: vv'.
rewrite inE.
apply/orP.
by left.
have H_in_vv' := H_in _ H_in_vv.
move/andP: H_in_vv' => [H_not_in_vv H_in_vv'].
apply H_s2 => //.
* exact: IH.
* apply/starI.
move => w H_w.
rewrite -/(re_lang _).
have H_w_in: w \in w0 :: vv'.
rewrite inE.
apply/orP.
by right.
apply H_in in H_w_in.
move: H_w_in.
by move/andP => [H_w_in H_w_in'].
* apply: IH'.
move => w' H_w'.
apply: H_in.
rewrite inE.
apply/orP.
by right.
- move => r1 IH1 r2 IH2.
move => w.
move/plusP => [H_rp1|H_rp2].
* apply: H_p1 => //.
exact: IH1.
* apply: H_p2 => //.
exact: IH2.
- move => r1 IH1 r2 IH2.
move => w.
move/concP => [w1 [w2 [H_eq [H_w1 H_w2]]]].
subst.
apply: H_c => //.
* exact: IH1.
* exact: IH2.
Qed.
Lemma regexp_in_re : forall (r : regexp char) (w : seq char), w \in re_lang r -> s_in_regexp_lang _ w (regexp2r r).
Proof.
move => r w H_st.
remember r as r0.
remember w as w0.
move: H_st r w Heqr0 Heqw0.
elim/re_lang_ind => //=.
- move => r w H_eq H_eq'.
subst.
exact: s_in_regexp_lang_unit.
- move => c' r w H_eq H_eq'.
subst.
exact: s_in_regexp_lang_char.
- move => w r1 r2 H_in IH r' w1 H_eq H_eq'.
subst.
apply: s_in_regexp_lang_plus_1.
exact: IH.
- move => w r1 r2 H_in IH r' w1 H_eq H_eq'.
subst.
apply: s_in_regexp_lang_plus_2.
exact: IH.
- move => w1 w2 r1 r2 H_in1 IH1 H_in2 IH2 r w H_eq H_eq'.
subst.
apply s_in_regexp_lang_times.
* exact: IH1.
* exact: IH2.
- move => r r2 w H_eq H_eq'.
subst.
exact: s_in_regexp_lang_star_1.
- move => w1 w2 r H_in1 IH1 H_in2 IH2 r1 w H_eq H_eq'.
subst.
apply s_in_regexp_lang_star_2.
* exact: IH1.
* exact: IH2.
Qed.
Definition residuals_re (r : regexp char) (c : char) (l : seq (regexp char)) :=
(forall r', r' \in l -> (forall w, w \in re_lang r' -> w \in residual c (re_lang r))) /\
(forall w, w \in residual c (re_lang r) -> exists r', r' \in l /\ w \in re_lang r').
Definition residuals_t (r : regexp char) (c : char) :=
{ l : seq (regexp char) | residuals_re r c l }.
Lemma s_in_regexp_c_lang_residual : forall r w c',
s_in_regexp_c_lang char w (regexp2r r) c' ->
w \in residual c' (re_lang r).
Proof.
move => r w c' H_c.
inversion H_c; subst.
rewrite /= in H.
by apply regexp_re_in'.
Qed.
Lemma residual_s_in_regexp_c_lang : forall r w c',
w \in residual c' (re_lang r) ->
s_in_regexp_c_lang char w (regexp2r r) c'.
Proof.
move => r w c' H_c.
apply s_in_regexp_c_lang_cs.
rewrite /=.
by apply regexp_in_re.
Qed.
Definition residuals : forall (r : regexp char) (c : char), residuals_t r c.
refine
(fun r c =>
match regexps_no_c (@eq_comparable char) (regexp2r r, c) with
| exist l H_l => exist _ (map r2regexp l) _
end).
split.
- move => r' H_in /= w H_w.
rewrite /residual.
rewrite inE.
move: H_l => [H_l H_l'] {H_l'}.
rewrite /= in H_l.
apply s_in_regexp_c_lang_residual.
apply regexp_in_re in H_w.
apply (H_l (regexp2r r')) => //.
move: H_in.
move/mapP => [r0 H_in] H_eq.
rewrite H_eq {H_eq}.
rewrite cancel_re_regexp.
move: H_in.
clear.
elim: l => //.
move => r' l IH.
rewrite inE.
move/orP => [H_in|H_in].
* by left; move/eqP: H_in.
* right; exact: IH.
- move => w /= H_in.
apply residual_s_in_regexp_c_lang in H_in.
move: H_l => [H_l' H_l] {H_l'}.
rewrite /= in H_l.
apply H_l in H_in.
move: H_in => [r' [H_in H_r']].
exists (r2regexp r').
split; last exact: regexp_re_in.
apply List.in_split in H_in.
rewrite /= in H_in.
move: H_in => [l1 [l2 H_eq]].
rewrite H_eq /=.
rewrite map_cat mem_cat.
apply/orP.
right.
rewrite inE.
apply/orP.
by left.
Defined.
Definition accept' : forall (r : regexp char) (w : seq char), {w \in re_lang r}+{w \notin re_lang r}.
refine
(fun r w =>
match accept (@eq_comparable char) (regexp2r r, w) with
| left H_l => left _
| right H_r => right _
end).
- exact: regexp_re_in'.
- apply/negP.
move => H_acc.
case: H_r.
exact: regexp_in_re.
Defined.
End RegLangExp.
|
lemma irreducibleD: "irreducible p \<Longrightarrow> p = a * b \<Longrightarrow> a dvd 1 \<or> b dvd 1"
|
from skimage.feature import peak_local_max
import numpy as np
import concurrent.futures
def get_all_peaks(heatmap, threshold):
"""
extracts peaks from the heatmap
:param heatmap: h x w x m
:param threshold:
:return: [
[ (x,y,score), (x,y,score),... ] # Nose
...
]
"""
# TODO: this function is slow ~0.3 seconds per call
_, _, n_joints = heatmap.shape
peaks = []
for i in range(n_joints):
hm = heatmap[:,:,i]
local_peaks = peak_local_max(hm, threshold_abs=threshold)
found_peaks = []
for x,y in local_peaks:
found_peaks.append((y,x,hm[x,y]))
peaks.append(np.array(found_peaks))
return peaks
def request_peaks(heatmaps, cid, cam, threshold):
"""
:param cid:
:param cam:
:return:
"""
hm = heatmaps[cid]
peaks = get_all_peaks(hm, threshold)
# -- undistort peaks --
peaks_undist = []
for joint in peaks:
if len(joint) > 0:
peaks_undist.append(cam.undistort_points(joint))
else:
peaks_undist.append([])
assert len(peaks) == len(peaks_undist)
return peaks, peaks_undist
class Candidates2D:
"""
Generates 2D candidates for the heatmaps
for the original image and for the undistorted
one
"""
def __init__(self, heatmaps, Calib, threshold=0.1):
"""
n camera views, m joint types
:param heatmaps: np.array: n x h x w x m
:param Calib:
:param threshold:
"""
n, h, w, m = heatmaps.shape
assert n == len(Calib)
self.n_cameras = n
self.n_joints = m
self.peaks2d = [None] * n
self.peaks2d_undistorted = [None] * n
with concurrent.futures.ThreadPoolExecutor(max_workers=n) as executor:
#with concurrent.futures.ProcessPoolExecutor(max_workers=n) as executor:
futures_to_peaks = {
executor.submit(request_peaks, heatmaps, cid, cam, threshold): cid \
for cid, cam in enumerate(Calib)}
for future in concurrent.futures.as_completed(futures_to_peaks):
cid = futures_to_peaks[future]
peaks, peaks_undist = future.result()
self.peaks2d[cid] = peaks
self.peaks2d_undistorted[cid] = peaks_undist
|
module PCA.PCA
( PCA (..)
, covariance
, eigenValues
, eigenVectors
, inputData
, finalData
, makePCA
, restoredData
, meanMatrix
) where
import Universum hiding (All, Vector, transpose)
import PCA.Types
import Control.Lens (makeLenses)
import Data.Array.Repa
import Data.Array.Repa.Repr.ForeignPtr
import Numeric.LinearAlgebra.Repa hiding (Matrix, Vector)
data PCA = PCA
{ _inputData :: Matrix D Double
, _covariance :: Covariance Double
, _eigenVectors :: EigenVectors Double
, _eigenValues :: Vector F Double
, _finalData :: Matrix D Double
, _restoredData :: Matrix D Double
, _meanMatrix :: Matrix D Double
}
makeLenses ''PCA
makePCA
:: Int
-> Matrix D Double
-> PCA
makePCA desiredDimensions input =
let _inputData = input
-- get dimension
(Z :. yInp :. _) = extent input
(meanVec, _covariance) = meanCovS input
_meanMatrix = extend (Z :. yInp :. All) meanVec
adjustInput'@(ADelayed (Z :. _ :. _) _) = input -^ _meanMatrix
(_eigenValues, eigenVec) = eigSH _covariance
eigenVecD@(ADelayed (Z :. y :. x) f) = transpose eigenVec
-- leave only n desired eigenvectors
eigenVectors' =
if desiredDimensions >= y
then eigenVecD
else ADelayed (Z :. desiredDimensions :. x) f
-- colunmns are eigenvectors
_eigenVectors = transpose eigenVectors'
-- data in new eigenvectors space
finalData' = runIdentity $ eigenVectors' `mulP` transpose adjustInput'
_finalData = transpose finalData'
-- restore to the original space
restoredDataWOMean = transpose $ pinvS eigenVectors' `mul` finalData'
-- add mean
_restoredData = restoredDataWOMean +^ _meanMatrix
in PCA{..}
|
using SimpleHeatmaps
using Test
@testset "SimpleHeatmaps.jl" begin
# Write your own tests here.
end
|
module Mod
export
fn : Nat -> Nat
fn x = S x
|
make_icosahedron_complex := proc()
global icosahedron_complex,dodecahedron_complex;
local IC,DC,tau,vI,vD,i;
IC := table():
DC := table():
IC["vertices"] := [seq(i,i=1..12)];
DC["vertices"] := [seq(i,i=1..20)];
IC["faces"] := [
[ 1, 2, 9], [ 1, 2,11], [ 1, 5, 6], [ 1, 5, 9], [ 1, 6,11],
[ 2, 7, 8], [ 2, 7, 9], [ 2, 8,11], [ 3, 4,10], [ 3, 4,12],
[ 3, 5, 6], [ 3, 5,10], [ 3, 6,12], [ 4, 7, 8], [ 4, 7,10],
[ 4, 8,12], [ 5, 9,10], [ 6,11,12], [ 7, 9,10], [ 8,11,12]
];
IC["edges"] := {op(map(op,map(f -> [[f[1],f[2]],[f[1],f[3]],[f[2],f[3]]],IC["faces"])))};
IC["edges"] := sort([op(IC["edges"])]);
IC["max_simplices"] := IC["faces"];
tau := (1+sqrt(5))/2;
IC["embedding_dim"] := 3;
vI := table([
1 = [ 0, 1, tau],
2 = [ 0, -1, tau],
3 = [ 0, 1,-tau],
4 = [ 0, -1,-tau],
5 = [ 1, tau, 0],
6 = [ -1, tau, 0],
7 = [ 1,-tau, 0],
8 = [ -1,-tau, 0],
9 = [ tau, 0, 1],
10 = [ tau, 0, -1],
11 = [-tau, 0, 1],
12 = [-tau, 0, -1]
]):
for i from 1 to 12 do vI[i] := simplify(rationalize(vI[i] /~ tau^2)); od;
IC["embedding"] := eval(vI);
IC["normalised_embedding"] := table([
seq(i = evalf(vI[i] /~ sqrt(5-2*sqrt(5))),i = 1..12)
]);
IC["edge_centres"] :=
map(e -> (vI[e[1]] +~ vI[e[2]]) /~ 2,IC["edges"]);
IC["face_centres"] :=
map(f -> (vI[f[1]] +~ vI[f[2]] +~ vI[f[3]]) /~ 3, IC["faces"]);
`plot/simplicial_complex`(IC);
icosahedron_complex := eval(IC);
dodecahedron_complex := eval(DC);
return eval(IC);
end:
make_icosahedron_complex():
icosphere_complex := proc(n::nonnegint)
local T,T0,E,v,x,i,j;
T := eval(icosahedron_complex);
for i from 1 to n do
T0 := eval(T);
T := eval(`triangular_subdivision/simplicial_complex`(T0));
T0 := eval(T);
T := eval(`condense/simplicial_complex`(T0));
E := T["embedding"];
for v in T["vertices"] do
x := E[v];
x := evalf(x /~ sqrt(add(x[j]^2,j=1..3)));
E[v] := x;
od:
od:
return eval(T):
end:
|
(* This Isabelle theory is produced using the TIP tool offered at the following website:
https://github.com/tip-org/tools
This file was originally provided as part of TIP benchmark at the following website:
https://github.com/tip-org/benchmarks
Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly
to make it compatible with Isabelle2017.*)
theory TIP_sort_nat_MSortBUSorts
imports "../../Test_Base"
begin
datatype 'a list = nil2 | cons2 "'a" "'a list"
datatype Nat = Z | S "Nat"
fun map :: "('a => 'b) => 'a list => 'b list" where
"map f (nil2) = nil2"
| "map f (cons2 y xs) = cons2 (f y) (map f xs)"
fun le :: "Nat => Nat => bool" where
"le (Z) y = True"
| "le (S z) (Z) = False"
| "le (S z) (S x2) = le z x2"
fun lmerge :: "Nat list => Nat list => Nat list" where
"lmerge (nil2) y = y"
| "lmerge (cons2 z x2) (nil2) = cons2 z x2"
| "lmerge (cons2 z x2) (cons2 x3 x4) =
(if le z x3 then cons2 z (lmerge x2 (cons2 x3 x4)) else
cons2 x3 (lmerge (cons2 z x2) x4))"
fun pairwise :: "(Nat list) list => (Nat list) list" where
"pairwise (nil2) = nil2"
| "pairwise (cons2 xs (nil2)) = cons2 xs (nil2)"
| "pairwise (cons2 xs (cons2 ys xss)) =
cons2 (lmerge xs ys) (pairwise xss)"
(*fun did not finish the proof*)
function mergingbu :: "(Nat list) list => Nat list" where
"mergingbu (nil2) = nil2"
| "mergingbu (cons2 xs (nil2)) = xs"
| "mergingbu (cons2 xs (cons2 z x2)) =
mergingbu (pairwise (cons2 xs (cons2 z x2)))"
by pat_completeness auto
fun msortbu :: "Nat list => Nat list" where
"msortbu x = mergingbu (map (% (y :: Nat) => cons2 y (nil2)) x)"
fun ordered :: "Nat list => bool" where
"ordered (nil2) = True"
| "ordered (cons2 y (nil2)) = True"
| "ordered (cons2 y (cons2 y2 xs)) =
((le y y2) & (ordered (cons2 y2 xs)))"
theorem property0 :
"ordered (msortbu xs)"
oops
end
|
Formal statement is: lemma open_halfspace_gt: "open {x. inner a x > b}" Informal statement is: The set of points $x$ such that $a \cdot x > b$ is open.
|
# This file contains the necessary ingredients to create a PackageManager for BinDeps
using BinDeps
import BinDeps: PackageManager, can_use, package_available, libdir, generate_steps, LibraryDependency, provider
import Base: show
mutable struct HB <: PackageManager
packages
end
show(io::IO, hb::HB) = write(io, "Homebrew Bottles ",
join(isa(hb.packages, AbstractString) ? [hb.packages] : hb.packages,", "))
# Only return true on Darwin platforms
can_use(::Type{HB}) = Sys.KERNEL == :Darwin
function package_available(p::HB)
!can_use(HB) && return false
pkgs = p.packages
if isa(pkgs, AbstractString)
pkgs = [pkgs]
end
# For each package, see if we can get info about it. If not, fail out
for pkg in pkgs
try
info(pkg)
catch
return false
end
end
return true
end
libdir(p::HB, dep) = joinpath(brew_prefix, "lib")
provider(::Type{HB}, packages::Vector{T}; opts...) where {T <: AbstractString} = HB(packages)
function generate_steps(dep::LibraryDependency, p::HB, opts)
pkgs = p.packages
if isa(pkgs, AbstractString)
pkgs = [pkgs]
end
()->install(pkgs)
end
function install(pkgs)
for pkg in pkgs
add(pkg)
end
end
|
import unittest
import numpy as np
import periodictable as pt
from interferences.util.mz import process_window
class TestProcessWindow(unittest.TestCase):
def test_floats(self):
window = (0.1, 10.0)
pw = process_window(window)
self.assertTrue(all([isinstance(v, (float, int)) for v in pw]))
def test_isotope_string(self):
window = ("Ca[40]", 0.05)
pw = process_window(window)
self.assertTrue(all([isinstance(v, (float, int)) for v in pw]))
def test_element_string(self):
window = ("Ca", 0.05)
pw = process_window(window)
self.assertTrue(all([isinstance(v, (float, int)) for v in pw]))
def test_isotope_object(self):
window = (pt.Ca.add_isotope(40), 0.05)
pw = process_window(window)
self.assertTrue(all([isinstance(v, (float, int)) for v in pw]))
def test_element_object(self):
window = (pt.Ca, 0.05)
pw = process_window(window)
self.assertTrue(all([isinstance(v, (float, int)) for v in pw]))
if __name__ == "__main__":
unittest.main()
|
%GETSTRUCTURINGELEMENT Returns a structuring element of the specified size and shape for morphological operations
%
% elem = cv.getStructuringElement('OptionName', optionValue, ...)
%
% ## Output
% * __elem__ Output structuring element of specified shape and size.
%
% ## Options
% * __Shape__ Element shape, default 'Rect'. Could be one of:
% * __Rect__ a rectangular structuring element: `E(i,j)=1`
% * __Cross__ a cross-shaped structuring element: `E(i,j)=1` if
% `i=Anchor(2)` or `j=Anchor(1)`, `E(i,j)=0` otherwise.
% * __Ellipse__ an elliptic structuring element, that is, a filled ellipse
% inscribed into the rectangle `[0, 0, KSize(1), KSize(2)]`.
% * __KSize__ Size of the structuring element `[w,h]`. default [3,3].
% * __Anchor__ Anchor position within the element. The default value (-1,-1)
% means that the anchor is at the center. Note that only the shape of a
% cross-shaped element depends on the anchor position. In other cases the
% anchor just regulates how much the result of the morphological operation
% is shifted.
%
% The function constructs and returns the structuring element that can be
% further passed to cv.erode, cv.dilate or cv.morphologyEx. But you can also
% construct an arbitrary binary mask yourself and use it as the structuring
% element.
%
% See also: cv.sepFilter2D, cv.getDerivKernels, cv.getGaussianKernel
%
|
State Before: α : Type u_1
inst✝ : LinearOrderedAddCommGroup α
hα : Archimedean α
p : α
hp : 0 < p
a✝ b✝ c : α
n : ℤ
a b : α
⊢ toIocDiv hp (a - p) b = toIocDiv hp a b + 1 State After: no goals Tactic: simpa only [one_zsmul] using toIocDiv_sub_zsmul' hp a b 1
|
The 2012 – 13 season was York City 's first season back in the Football League , having won the Conference Premier play @-@ offs in 2011 – 12 after eights years in the Football Conference . Manager Gary Mills was sacked in March 2013 following an 11 @-@ match run without a victory , and was replaced by former Northern Ireland manager Nigel Worthington . Despite being in the relegation zone with three matches remaining , Worthington led the team to safety from relegation after a 1 – 0 win away to Dagenham & Redbridge on the final day of the season . York finished the season in 17th @-@ place in the 2012 – 13 League Two table .
|
// This file is auto-generated, don't edit it. Thanks.
#include <alibabacloud/ess_20140828.hpp>
#include <alibabacloud/endpoint_util.hpp>
#include <alibabacloud/open_api.hpp>
#include <alibabacloud/open_api_util.hpp>
#include <boost/any.hpp>
#include <boost/throw_exception.hpp>
#include <darabonba/core.hpp>
#include <darabonba/util.hpp>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
using namespace Alibabacloud_Ess20140828;
Alibabacloud_Ess20140828::Client::Client(const shared_ptr<Alibabacloud_OpenApi::Config>& config) : Alibabacloud_OpenApi::Client(config) {
_endpointRule = make_shared<string>("regional");
_endpointMap = make_shared<map<string, string>>(map<string, string>({
{"cn-qingdao", "ess.aliyuncs.com"},
{"cn-beijing", "ess.aliyuncs.com"},
{"cn-hangzhou", "ess.aliyuncs.com"},
{"cn-shanghai", "ess.aliyuncs.com"},
{"cn-shenzhen", "ess.aliyuncs.com"},
{"cn-hongkong", "ess.aliyuncs.com"},
{"ap-southeast-1", "ess.aliyuncs.com"},
{"us-west-1", "ess.aliyuncs.com"},
{"us-east-1", "ess.aliyuncs.com"},
{"cn-shanghai-finance-1", "ess.aliyuncs.com"},
{"cn-shenzhen-finance-1", "ess.aliyuncs.com"},
{"cn-north-2-gov-1", "ess.aliyuncs.com"},
{"ap-northeast-2-pop", "ess.ap-northeast-1.aliyuncs.com"},
{"cn-beijing-finance-1", "ess.aliyuncs.com"},
{"cn-beijing-finance-pop", "ess.aliyuncs.com"},
{"cn-beijing-gov-1", "ess.aliyuncs.com"},
{"cn-beijing-nu16-b01", "ess.aliyuncs.com"},
{"cn-edge-1", "ess.aliyuncs.com"},
{"cn-fujian", "ess.aliyuncs.com"},
{"cn-haidian-cm12-c01", "ess.aliyuncs.com"},
{"cn-hangzhou-bj-b01", "ess.aliyuncs.com"},
{"cn-hangzhou-finance", "ess.aliyuncs.com"},
{"cn-hangzhou-internal-prod-1", "ess.aliyuncs.com"},
{"cn-hangzhou-internal-test-1", "ess.aliyuncs.com"},
{"cn-hangzhou-internal-test-2", "ess.aliyuncs.com"},
{"cn-hangzhou-internal-test-3", "ess.aliyuncs.com"},
{"cn-hangzhou-test-306", "ess.aliyuncs.com"},
{"cn-hongkong-finance-pop", "ess.aliyuncs.com"},
{"cn-qingdao-nebula", "ess.aliyuncs.com"},
{"cn-shanghai-et15-b01", "ess.aliyuncs.com"},
{"cn-shanghai-et2-b01", "ess.aliyuncs.com"},
{"cn-shanghai-inner", "ess.aliyuncs.com"},
{"cn-shanghai-internal-test-1", "ess.aliyuncs.com"},
{"cn-shenzhen-inner", "ess.aliyuncs.com"},
{"cn-shenzhen-st4-d01", "ess.aliyuncs.com"},
{"cn-shenzhen-su18-b01", "ess.aliyuncs.com"},
{"cn-wuhan", "ess.aliyuncs.com"},
{"cn-yushanfang", "ess.aliyuncs.com"},
{"cn-zhangbei-na61-b01", "ess.aliyuncs.com"},
{"cn-zhangjiakou-na62-a01", "ess.aliyuncs.com"},
{"cn-zhengzhou-nebula-1", "ess.aliyuncs.com"},
{"eu-west-1-oxs", "ess.ap-northeast-1.aliyuncs.com"},
{"rus-west-1-pop", "ess.ap-northeast-1.aliyuncs.com"}
})
);
checkConfig(config);
_endpoint = make_shared<string>(getEndpoint(make_shared<string>("ess"), _regionId, _endpointRule, _network, _suffix, _endpointMap, _endpoint));
};
string Alibabacloud_Ess20140828::Client::getEndpoint(shared_ptr<string> productId,
shared_ptr<string> regionId,
shared_ptr<string> endpointRule,
shared_ptr<string> network,
shared_ptr<string> suffix,
shared_ptr<map<string, string>> endpointMap,
shared_ptr<string> endpoint) {
if (!Darabonba_Util::Client::empty(endpoint)) {
return *endpoint;
}
if (!Darabonba_Util::Client::isUnset<map<string, string>>(endpointMap) && !Darabonba_Util::Client::empty(make_shared<string>((*endpointMap)[regionId]))) {
return (*endpointMap)[regionId];
}
return Alibabacloud_EndpointUtil::Client::getEndpointRules(productId, regionId, endpointRule, network, suffix);
}
AttachAlbServerGroupsResponse Alibabacloud_Ess20140828::Client::attachAlbServerGroupsWithOptions(shared_ptr<AttachAlbServerGroupsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return AttachAlbServerGroupsResponse(doRPCRequest(make_shared<string>("AttachAlbServerGroups"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
AttachAlbServerGroupsResponse Alibabacloud_Ess20140828::Client::attachAlbServerGroups(shared_ptr<AttachAlbServerGroupsRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return attachAlbServerGroupsWithOptions(request, runtime);
}
AttachDBInstancesResponse Alibabacloud_Ess20140828::Client::attachDBInstancesWithOptions(shared_ptr<AttachDBInstancesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return AttachDBInstancesResponse(doRPCRequest(make_shared<string>("AttachDBInstances"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
AttachDBInstancesResponse Alibabacloud_Ess20140828::Client::attachDBInstances(shared_ptr<AttachDBInstancesRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return attachDBInstancesWithOptions(request, runtime);
}
AttachInstancesResponse Alibabacloud_Ess20140828::Client::attachInstancesWithOptions(shared_ptr<AttachInstancesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return AttachInstancesResponse(doRPCRequest(make_shared<string>("AttachInstances"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
AttachInstancesResponse Alibabacloud_Ess20140828::Client::attachInstances(shared_ptr<AttachInstancesRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return attachInstancesWithOptions(request, runtime);
}
AttachLoadBalancersResponse Alibabacloud_Ess20140828::Client::attachLoadBalancersWithOptions(shared_ptr<AttachLoadBalancersRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return AttachLoadBalancersResponse(doRPCRequest(make_shared<string>("AttachLoadBalancers"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
AttachLoadBalancersResponse Alibabacloud_Ess20140828::Client::attachLoadBalancers(shared_ptr<AttachLoadBalancersRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return attachLoadBalancersWithOptions(request, runtime);
}
AttachVServerGroupsResponse Alibabacloud_Ess20140828::Client::attachVServerGroupsWithOptions(shared_ptr<AttachVServerGroupsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return AttachVServerGroupsResponse(doRPCRequest(make_shared<string>("AttachVServerGroups"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
AttachVServerGroupsResponse Alibabacloud_Ess20140828::Client::attachVServerGroups(shared_ptr<AttachVServerGroupsRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return attachVServerGroupsWithOptions(request, runtime);
}
CompleteLifecycleActionResponse Alibabacloud_Ess20140828::Client::completeLifecycleActionWithOptions(shared_ptr<CompleteLifecycleActionRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return CompleteLifecycleActionResponse(doRPCRequest(make_shared<string>("CompleteLifecycleAction"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
CompleteLifecycleActionResponse Alibabacloud_Ess20140828::Client::completeLifecycleAction(shared_ptr<CompleteLifecycleActionRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return completeLifecycleActionWithOptions(request, runtime);
}
CreateAlarmResponse Alibabacloud_Ess20140828::Client::createAlarmWithOptions(shared_ptr<CreateAlarmRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return CreateAlarmResponse(doRPCRequest(make_shared<string>("CreateAlarm"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
CreateAlarmResponse Alibabacloud_Ess20140828::Client::createAlarm(shared_ptr<CreateAlarmRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return createAlarmWithOptions(request, runtime);
}
CreateLifecycleHookResponse Alibabacloud_Ess20140828::Client::createLifecycleHookWithOptions(shared_ptr<CreateLifecycleHookRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return CreateLifecycleHookResponse(doRPCRequest(make_shared<string>("CreateLifecycleHook"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
CreateLifecycleHookResponse Alibabacloud_Ess20140828::Client::createLifecycleHook(shared_ptr<CreateLifecycleHookRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return createLifecycleHookWithOptions(request, runtime);
}
CreateNotificationConfigurationResponse Alibabacloud_Ess20140828::Client::createNotificationConfigurationWithOptions(shared_ptr<CreateNotificationConfigurationRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return CreateNotificationConfigurationResponse(doRPCRequest(make_shared<string>("CreateNotificationConfiguration"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
CreateNotificationConfigurationResponse Alibabacloud_Ess20140828::Client::createNotificationConfiguration(shared_ptr<CreateNotificationConfigurationRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return createNotificationConfigurationWithOptions(request, runtime);
}
CreateScalingConfigurationResponse Alibabacloud_Ess20140828::Client::createScalingConfigurationWithOptions(shared_ptr<CreateScalingConfigurationRequest> tmpReq, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(tmpReq);
shared_ptr<CreateScalingConfigurationShrinkRequest> request = make_shared<CreateScalingConfigurationShrinkRequest>();
Alibabacloud_OpenApiUtil::Client::convert(tmpReq, request);
if (!Darabonba_Util::Client::isUnset<map<string, boost::any>>(tmpReq->schedulerOptions)) {
request->schedulerOptionsShrink = make_shared<string>(Alibabacloud_OpenApiUtil::Client::arrayToStringWithSpecifiedStyle(tmpReq->schedulerOptions, make_shared<string>("SchedulerOptions"), make_shared<string>("json")));
}
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return CreateScalingConfigurationResponse(doRPCRequest(make_shared<string>("CreateScalingConfiguration"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
CreateScalingConfigurationResponse Alibabacloud_Ess20140828::Client::createScalingConfiguration(shared_ptr<CreateScalingConfigurationRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return createScalingConfigurationWithOptions(request, runtime);
}
CreateScalingGroupResponse Alibabacloud_Ess20140828::Client::createScalingGroupWithOptions(shared_ptr<CreateScalingGroupRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return CreateScalingGroupResponse(doRPCRequest(make_shared<string>("CreateScalingGroup"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
CreateScalingGroupResponse Alibabacloud_Ess20140828::Client::createScalingGroup(shared_ptr<CreateScalingGroupRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return createScalingGroupWithOptions(request, runtime);
}
CreateScalingRuleResponse Alibabacloud_Ess20140828::Client::createScalingRuleWithOptions(shared_ptr<CreateScalingRuleRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return CreateScalingRuleResponse(doRPCRequest(make_shared<string>("CreateScalingRule"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
CreateScalingRuleResponse Alibabacloud_Ess20140828::Client::createScalingRule(shared_ptr<CreateScalingRuleRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return createScalingRuleWithOptions(request, runtime);
}
CreateScheduledTaskResponse Alibabacloud_Ess20140828::Client::createScheduledTaskWithOptions(shared_ptr<CreateScheduledTaskRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return CreateScheduledTaskResponse(doRPCRequest(make_shared<string>("CreateScheduledTask"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
CreateScheduledTaskResponse Alibabacloud_Ess20140828::Client::createScheduledTask(shared_ptr<CreateScheduledTaskRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return createScheduledTaskWithOptions(request, runtime);
}
DeactivateScalingConfigurationResponse Alibabacloud_Ess20140828::Client::deactivateScalingConfigurationWithOptions(shared_ptr<DeactivateScalingConfigurationRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return DeactivateScalingConfigurationResponse(doRPCRequest(make_shared<string>("DeactivateScalingConfiguration"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
DeactivateScalingConfigurationResponse Alibabacloud_Ess20140828::Client::deactivateScalingConfiguration(shared_ptr<DeactivateScalingConfigurationRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return deactivateScalingConfigurationWithOptions(request, runtime);
}
DeleteAlarmResponse Alibabacloud_Ess20140828::Client::deleteAlarmWithOptions(shared_ptr<DeleteAlarmRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return DeleteAlarmResponse(doRPCRequest(make_shared<string>("DeleteAlarm"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
DeleteAlarmResponse Alibabacloud_Ess20140828::Client::deleteAlarm(shared_ptr<DeleteAlarmRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return deleteAlarmWithOptions(request, runtime);
}
DeleteLifecycleHookResponse Alibabacloud_Ess20140828::Client::deleteLifecycleHookWithOptions(shared_ptr<DeleteLifecycleHookRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return DeleteLifecycleHookResponse(doRPCRequest(make_shared<string>("DeleteLifecycleHook"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
DeleteLifecycleHookResponse Alibabacloud_Ess20140828::Client::deleteLifecycleHook(shared_ptr<DeleteLifecycleHookRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return deleteLifecycleHookWithOptions(request, runtime);
}
DeleteNotificationConfigurationResponse Alibabacloud_Ess20140828::Client::deleteNotificationConfigurationWithOptions(shared_ptr<DeleteNotificationConfigurationRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return DeleteNotificationConfigurationResponse(doRPCRequest(make_shared<string>("DeleteNotificationConfiguration"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
DeleteNotificationConfigurationResponse Alibabacloud_Ess20140828::Client::deleteNotificationConfiguration(shared_ptr<DeleteNotificationConfigurationRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return deleteNotificationConfigurationWithOptions(request, runtime);
}
DeleteScalingConfigurationResponse Alibabacloud_Ess20140828::Client::deleteScalingConfigurationWithOptions(shared_ptr<DeleteScalingConfigurationRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return DeleteScalingConfigurationResponse(doRPCRequest(make_shared<string>("DeleteScalingConfiguration"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
DeleteScalingConfigurationResponse Alibabacloud_Ess20140828::Client::deleteScalingConfiguration(shared_ptr<DeleteScalingConfigurationRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return deleteScalingConfigurationWithOptions(request, runtime);
}
DeleteScalingGroupResponse Alibabacloud_Ess20140828::Client::deleteScalingGroupWithOptions(shared_ptr<DeleteScalingGroupRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return DeleteScalingGroupResponse(doRPCRequest(make_shared<string>("DeleteScalingGroup"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
DeleteScalingGroupResponse Alibabacloud_Ess20140828::Client::deleteScalingGroup(shared_ptr<DeleteScalingGroupRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return deleteScalingGroupWithOptions(request, runtime);
}
DeleteScalingRuleResponse Alibabacloud_Ess20140828::Client::deleteScalingRuleWithOptions(shared_ptr<DeleteScalingRuleRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return DeleteScalingRuleResponse(doRPCRequest(make_shared<string>("DeleteScalingRule"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
DeleteScalingRuleResponse Alibabacloud_Ess20140828::Client::deleteScalingRule(shared_ptr<DeleteScalingRuleRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return deleteScalingRuleWithOptions(request, runtime);
}
DeleteScheduledTaskResponse Alibabacloud_Ess20140828::Client::deleteScheduledTaskWithOptions(shared_ptr<DeleteScheduledTaskRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return DeleteScheduledTaskResponse(doRPCRequest(make_shared<string>("DeleteScheduledTask"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
DeleteScheduledTaskResponse Alibabacloud_Ess20140828::Client::deleteScheduledTask(shared_ptr<DeleteScheduledTaskRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return deleteScheduledTaskWithOptions(request, runtime);
}
DescribeAlarmsResponse Alibabacloud_Ess20140828::Client::describeAlarmsWithOptions(shared_ptr<DescribeAlarmsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return DescribeAlarmsResponse(doRPCRequest(make_shared<string>("DescribeAlarms"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
DescribeAlarmsResponse Alibabacloud_Ess20140828::Client::describeAlarms(shared_ptr<DescribeAlarmsRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return describeAlarmsWithOptions(request, runtime);
}
DescribeLifecycleActionsResponse Alibabacloud_Ess20140828::Client::describeLifecycleActionsWithOptions(shared_ptr<DescribeLifecycleActionsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return DescribeLifecycleActionsResponse(doRPCRequest(make_shared<string>("DescribeLifecycleActions"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
DescribeLifecycleActionsResponse Alibabacloud_Ess20140828::Client::describeLifecycleActions(shared_ptr<DescribeLifecycleActionsRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return describeLifecycleActionsWithOptions(request, runtime);
}
DescribeLifecycleHooksResponse Alibabacloud_Ess20140828::Client::describeLifecycleHooksWithOptions(shared_ptr<DescribeLifecycleHooksRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return DescribeLifecycleHooksResponse(doRPCRequest(make_shared<string>("DescribeLifecycleHooks"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
DescribeLifecycleHooksResponse Alibabacloud_Ess20140828::Client::describeLifecycleHooks(shared_ptr<DescribeLifecycleHooksRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return describeLifecycleHooksWithOptions(request, runtime);
}
DescribeLimitationResponse Alibabacloud_Ess20140828::Client::describeLimitationWithOptions(shared_ptr<DescribeLimitationRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return DescribeLimitationResponse(doRPCRequest(make_shared<string>("DescribeLimitation"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
DescribeLimitationResponse Alibabacloud_Ess20140828::Client::describeLimitation(shared_ptr<DescribeLimitationRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return describeLimitationWithOptions(request, runtime);
}
DescribeNotificationConfigurationsResponse Alibabacloud_Ess20140828::Client::describeNotificationConfigurationsWithOptions(shared_ptr<DescribeNotificationConfigurationsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return DescribeNotificationConfigurationsResponse(doRPCRequest(make_shared<string>("DescribeNotificationConfigurations"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
DescribeNotificationConfigurationsResponse Alibabacloud_Ess20140828::Client::describeNotificationConfigurations(shared_ptr<DescribeNotificationConfigurationsRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return describeNotificationConfigurationsWithOptions(request, runtime);
}
DescribeNotificationTypesResponse Alibabacloud_Ess20140828::Client::describeNotificationTypesWithOptions(shared_ptr<DescribeNotificationTypesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return DescribeNotificationTypesResponse(doRPCRequest(make_shared<string>("DescribeNotificationTypes"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
DescribeNotificationTypesResponse Alibabacloud_Ess20140828::Client::describeNotificationTypes(shared_ptr<DescribeNotificationTypesRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return describeNotificationTypesWithOptions(request, runtime);
}
DescribeRegionsResponse Alibabacloud_Ess20140828::Client::describeRegionsWithOptions(shared_ptr<DescribeRegionsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return DescribeRegionsResponse(doRPCRequest(make_shared<string>("DescribeRegions"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
DescribeRegionsResponse Alibabacloud_Ess20140828::Client::describeRegions(shared_ptr<DescribeRegionsRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return describeRegionsWithOptions(request, runtime);
}
DescribeScalingActivitiesResponse Alibabacloud_Ess20140828::Client::describeScalingActivitiesWithOptions(shared_ptr<DescribeScalingActivitiesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return DescribeScalingActivitiesResponse(doRPCRequest(make_shared<string>("DescribeScalingActivities"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
DescribeScalingActivitiesResponse Alibabacloud_Ess20140828::Client::describeScalingActivities(shared_ptr<DescribeScalingActivitiesRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return describeScalingActivitiesWithOptions(request, runtime);
}
DescribeScalingActivityDetailResponse Alibabacloud_Ess20140828::Client::describeScalingActivityDetailWithOptions(shared_ptr<DescribeScalingActivityDetailRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return DescribeScalingActivityDetailResponse(doRPCRequest(make_shared<string>("DescribeScalingActivityDetail"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
DescribeScalingActivityDetailResponse Alibabacloud_Ess20140828::Client::describeScalingActivityDetail(shared_ptr<DescribeScalingActivityDetailRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return describeScalingActivityDetailWithOptions(request, runtime);
}
DescribeScalingConfigurationsResponse Alibabacloud_Ess20140828::Client::describeScalingConfigurationsWithOptions(shared_ptr<DescribeScalingConfigurationsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return DescribeScalingConfigurationsResponse(doRPCRequest(make_shared<string>("DescribeScalingConfigurations"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
DescribeScalingConfigurationsResponse Alibabacloud_Ess20140828::Client::describeScalingConfigurations(shared_ptr<DescribeScalingConfigurationsRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return describeScalingConfigurationsWithOptions(request, runtime);
}
DescribeScalingInstancesResponse Alibabacloud_Ess20140828::Client::describeScalingInstancesWithOptions(shared_ptr<DescribeScalingInstancesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return DescribeScalingInstancesResponse(doRPCRequest(make_shared<string>("DescribeScalingInstances"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
DescribeScalingInstancesResponse Alibabacloud_Ess20140828::Client::describeScalingInstances(shared_ptr<DescribeScalingInstancesRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return describeScalingInstancesWithOptions(request, runtime);
}
DescribeScalingRulesResponse Alibabacloud_Ess20140828::Client::describeScalingRulesWithOptions(shared_ptr<DescribeScalingRulesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return DescribeScalingRulesResponse(doRPCRequest(make_shared<string>("DescribeScalingRules"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
DescribeScalingRulesResponse Alibabacloud_Ess20140828::Client::describeScalingRules(shared_ptr<DescribeScalingRulesRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return describeScalingRulesWithOptions(request, runtime);
}
DescribeScheduledTasksResponse Alibabacloud_Ess20140828::Client::describeScheduledTasksWithOptions(shared_ptr<DescribeScheduledTasksRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return DescribeScheduledTasksResponse(doRPCRequest(make_shared<string>("DescribeScheduledTasks"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
DescribeScheduledTasksResponse Alibabacloud_Ess20140828::Client::describeScheduledTasks(shared_ptr<DescribeScheduledTasksRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return describeScheduledTasksWithOptions(request, runtime);
}
DetachAlbServerGroupsResponse Alibabacloud_Ess20140828::Client::detachAlbServerGroupsWithOptions(shared_ptr<DetachAlbServerGroupsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return DetachAlbServerGroupsResponse(doRPCRequest(make_shared<string>("DetachAlbServerGroups"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
DetachAlbServerGroupsResponse Alibabacloud_Ess20140828::Client::detachAlbServerGroups(shared_ptr<DetachAlbServerGroupsRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return detachAlbServerGroupsWithOptions(request, runtime);
}
DetachDBInstancesResponse Alibabacloud_Ess20140828::Client::detachDBInstancesWithOptions(shared_ptr<DetachDBInstancesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return DetachDBInstancesResponse(doRPCRequest(make_shared<string>("DetachDBInstances"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
DetachDBInstancesResponse Alibabacloud_Ess20140828::Client::detachDBInstances(shared_ptr<DetachDBInstancesRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return detachDBInstancesWithOptions(request, runtime);
}
DetachInstancesResponse Alibabacloud_Ess20140828::Client::detachInstancesWithOptions(shared_ptr<DetachInstancesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return DetachInstancesResponse(doRPCRequest(make_shared<string>("DetachInstances"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
DetachInstancesResponse Alibabacloud_Ess20140828::Client::detachInstances(shared_ptr<DetachInstancesRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return detachInstancesWithOptions(request, runtime);
}
DetachLoadBalancersResponse Alibabacloud_Ess20140828::Client::detachLoadBalancersWithOptions(shared_ptr<DetachLoadBalancersRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return DetachLoadBalancersResponse(doRPCRequest(make_shared<string>("DetachLoadBalancers"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
DetachLoadBalancersResponse Alibabacloud_Ess20140828::Client::detachLoadBalancers(shared_ptr<DetachLoadBalancersRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return detachLoadBalancersWithOptions(request, runtime);
}
DetachVServerGroupsResponse Alibabacloud_Ess20140828::Client::detachVServerGroupsWithOptions(shared_ptr<DetachVServerGroupsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return DetachVServerGroupsResponse(doRPCRequest(make_shared<string>("DetachVServerGroups"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
DetachVServerGroupsResponse Alibabacloud_Ess20140828::Client::detachVServerGroups(shared_ptr<DetachVServerGroupsRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return detachVServerGroupsWithOptions(request, runtime);
}
DisableAlarmResponse Alibabacloud_Ess20140828::Client::disableAlarmWithOptions(shared_ptr<DisableAlarmRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return DisableAlarmResponse(doRPCRequest(make_shared<string>("DisableAlarm"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
DisableAlarmResponse Alibabacloud_Ess20140828::Client::disableAlarm(shared_ptr<DisableAlarmRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return disableAlarmWithOptions(request, runtime);
}
DisableScalingGroupResponse Alibabacloud_Ess20140828::Client::disableScalingGroupWithOptions(shared_ptr<DisableScalingGroupRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return DisableScalingGroupResponse(doRPCRequest(make_shared<string>("DisableScalingGroup"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
DisableScalingGroupResponse Alibabacloud_Ess20140828::Client::disableScalingGroup(shared_ptr<DisableScalingGroupRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return disableScalingGroupWithOptions(request, runtime);
}
EnableAlarmResponse Alibabacloud_Ess20140828::Client::enableAlarmWithOptions(shared_ptr<EnableAlarmRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return EnableAlarmResponse(doRPCRequest(make_shared<string>("EnableAlarm"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
EnableAlarmResponse Alibabacloud_Ess20140828::Client::enableAlarm(shared_ptr<EnableAlarmRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return enableAlarmWithOptions(request, runtime);
}
EnableScalingGroupResponse Alibabacloud_Ess20140828::Client::enableScalingGroupWithOptions(shared_ptr<EnableScalingGroupRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return EnableScalingGroupResponse(doRPCRequest(make_shared<string>("EnableScalingGroup"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
EnableScalingGroupResponse Alibabacloud_Ess20140828::Client::enableScalingGroup(shared_ptr<EnableScalingGroupRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return enableScalingGroupWithOptions(request, runtime);
}
EnterStandbyResponse Alibabacloud_Ess20140828::Client::enterStandbyWithOptions(shared_ptr<EnterStandbyRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return EnterStandbyResponse(doRPCRequest(make_shared<string>("EnterStandby"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
EnterStandbyResponse Alibabacloud_Ess20140828::Client::enterStandby(shared_ptr<EnterStandbyRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return enterStandbyWithOptions(request, runtime);
}
ExecuteScalingRuleResponse Alibabacloud_Ess20140828::Client::executeScalingRuleWithOptions(shared_ptr<ExecuteScalingRuleRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return ExecuteScalingRuleResponse(doRPCRequest(make_shared<string>("ExecuteScalingRule"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
ExecuteScalingRuleResponse Alibabacloud_Ess20140828::Client::executeScalingRule(shared_ptr<ExecuteScalingRuleRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return executeScalingRuleWithOptions(request, runtime);
}
ExitStandbyResponse Alibabacloud_Ess20140828::Client::exitStandbyWithOptions(shared_ptr<ExitStandbyRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return ExitStandbyResponse(doRPCRequest(make_shared<string>("ExitStandby"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
ExitStandbyResponse Alibabacloud_Ess20140828::Client::exitStandby(shared_ptr<ExitStandbyRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return exitStandbyWithOptions(request, runtime);
}
ListTagKeysResponse Alibabacloud_Ess20140828::Client::listTagKeysWithOptions(shared_ptr<ListTagKeysRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return ListTagKeysResponse(doRPCRequest(make_shared<string>("ListTagKeys"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
ListTagKeysResponse Alibabacloud_Ess20140828::Client::listTagKeys(shared_ptr<ListTagKeysRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return listTagKeysWithOptions(request, runtime);
}
ListTagResourcesResponse Alibabacloud_Ess20140828::Client::listTagResourcesWithOptions(shared_ptr<ListTagResourcesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return ListTagResourcesResponse(doRPCRequest(make_shared<string>("ListTagResources"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
ListTagResourcesResponse Alibabacloud_Ess20140828::Client::listTagResources(shared_ptr<ListTagResourcesRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return listTagResourcesWithOptions(request, runtime);
}
ListTagValuesResponse Alibabacloud_Ess20140828::Client::listTagValuesWithOptions(shared_ptr<ListTagValuesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return ListTagValuesResponse(doRPCRequest(make_shared<string>("ListTagValues"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
ListTagValuesResponse Alibabacloud_Ess20140828::Client::listTagValues(shared_ptr<ListTagValuesRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return listTagValuesWithOptions(request, runtime);
}
ModifyAlarmResponse Alibabacloud_Ess20140828::Client::modifyAlarmWithOptions(shared_ptr<ModifyAlarmRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return ModifyAlarmResponse(doRPCRequest(make_shared<string>("ModifyAlarm"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
ModifyAlarmResponse Alibabacloud_Ess20140828::Client::modifyAlarm(shared_ptr<ModifyAlarmRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return modifyAlarmWithOptions(request, runtime);
}
ModifyLifecycleHookResponse Alibabacloud_Ess20140828::Client::modifyLifecycleHookWithOptions(shared_ptr<ModifyLifecycleHookRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return ModifyLifecycleHookResponse(doRPCRequest(make_shared<string>("ModifyLifecycleHook"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
ModifyLifecycleHookResponse Alibabacloud_Ess20140828::Client::modifyLifecycleHook(shared_ptr<ModifyLifecycleHookRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return modifyLifecycleHookWithOptions(request, runtime);
}
ModifyNotificationConfigurationResponse Alibabacloud_Ess20140828::Client::modifyNotificationConfigurationWithOptions(shared_ptr<ModifyNotificationConfigurationRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return ModifyNotificationConfigurationResponse(doRPCRequest(make_shared<string>("ModifyNotificationConfiguration"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
ModifyNotificationConfigurationResponse Alibabacloud_Ess20140828::Client::modifyNotificationConfiguration(shared_ptr<ModifyNotificationConfigurationRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return modifyNotificationConfigurationWithOptions(request, runtime);
}
ModifyScalingConfigurationResponse Alibabacloud_Ess20140828::Client::modifyScalingConfigurationWithOptions(shared_ptr<ModifyScalingConfigurationRequest> tmpReq, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(tmpReq);
shared_ptr<ModifyScalingConfigurationShrinkRequest> request = make_shared<ModifyScalingConfigurationShrinkRequest>();
Alibabacloud_OpenApiUtil::Client::convert(tmpReq, request);
if (!Darabonba_Util::Client::isUnset<map<string, boost::any>>(tmpReq->schedulerOptions)) {
request->schedulerOptionsShrink = make_shared<string>(Alibabacloud_OpenApiUtil::Client::arrayToStringWithSpecifiedStyle(tmpReq->schedulerOptions, make_shared<string>("SchedulerOptions"), make_shared<string>("json")));
}
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return ModifyScalingConfigurationResponse(doRPCRequest(make_shared<string>("ModifyScalingConfiguration"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
ModifyScalingConfigurationResponse Alibabacloud_Ess20140828::Client::modifyScalingConfiguration(shared_ptr<ModifyScalingConfigurationRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return modifyScalingConfigurationWithOptions(request, runtime);
}
ModifyScalingGroupResponse Alibabacloud_Ess20140828::Client::modifyScalingGroupWithOptions(shared_ptr<ModifyScalingGroupRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return ModifyScalingGroupResponse(doRPCRequest(make_shared<string>("ModifyScalingGroup"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
ModifyScalingGroupResponse Alibabacloud_Ess20140828::Client::modifyScalingGroup(shared_ptr<ModifyScalingGroupRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return modifyScalingGroupWithOptions(request, runtime);
}
ModifyScalingRuleResponse Alibabacloud_Ess20140828::Client::modifyScalingRuleWithOptions(shared_ptr<ModifyScalingRuleRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return ModifyScalingRuleResponse(doRPCRequest(make_shared<string>("ModifyScalingRule"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
ModifyScalingRuleResponse Alibabacloud_Ess20140828::Client::modifyScalingRule(shared_ptr<ModifyScalingRuleRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return modifyScalingRuleWithOptions(request, runtime);
}
ModifyScheduledTaskResponse Alibabacloud_Ess20140828::Client::modifyScheduledTaskWithOptions(shared_ptr<ModifyScheduledTaskRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return ModifyScheduledTaskResponse(doRPCRequest(make_shared<string>("ModifyScheduledTask"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
ModifyScheduledTaskResponse Alibabacloud_Ess20140828::Client::modifyScheduledTask(shared_ptr<ModifyScheduledTaskRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return modifyScheduledTaskWithOptions(request, runtime);
}
RebalanceInstancesResponse Alibabacloud_Ess20140828::Client::rebalanceInstancesWithOptions(shared_ptr<RebalanceInstancesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return RebalanceInstancesResponse(doRPCRequest(make_shared<string>("RebalanceInstances"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
RebalanceInstancesResponse Alibabacloud_Ess20140828::Client::rebalanceInstances(shared_ptr<RebalanceInstancesRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return rebalanceInstancesWithOptions(request, runtime);
}
RecordLifecycleActionHeartbeatResponse Alibabacloud_Ess20140828::Client::recordLifecycleActionHeartbeatWithOptions(shared_ptr<RecordLifecycleActionHeartbeatRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return RecordLifecycleActionHeartbeatResponse(doRPCRequest(make_shared<string>("RecordLifecycleActionHeartbeat"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
RecordLifecycleActionHeartbeatResponse Alibabacloud_Ess20140828::Client::recordLifecycleActionHeartbeat(shared_ptr<RecordLifecycleActionHeartbeatRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return recordLifecycleActionHeartbeatWithOptions(request, runtime);
}
RemoveInstancesResponse Alibabacloud_Ess20140828::Client::removeInstancesWithOptions(shared_ptr<RemoveInstancesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return RemoveInstancesResponse(doRPCRequest(make_shared<string>("RemoveInstances"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
RemoveInstancesResponse Alibabacloud_Ess20140828::Client::removeInstances(shared_ptr<RemoveInstancesRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return removeInstancesWithOptions(request, runtime);
}
ResumeProcessesResponse Alibabacloud_Ess20140828::Client::resumeProcessesWithOptions(shared_ptr<ResumeProcessesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return ResumeProcessesResponse(doRPCRequest(make_shared<string>("ResumeProcesses"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
ResumeProcessesResponse Alibabacloud_Ess20140828::Client::resumeProcesses(shared_ptr<ResumeProcessesRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return resumeProcessesWithOptions(request, runtime);
}
ScaleWithAdjustmentResponse Alibabacloud_Ess20140828::Client::scaleWithAdjustmentWithOptions(shared_ptr<ScaleWithAdjustmentRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return ScaleWithAdjustmentResponse(doRPCRequest(make_shared<string>("ScaleWithAdjustment"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
ScaleWithAdjustmentResponse Alibabacloud_Ess20140828::Client::scaleWithAdjustment(shared_ptr<ScaleWithAdjustmentRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return scaleWithAdjustmentWithOptions(request, runtime);
}
SetGroupDeletionProtectionResponse Alibabacloud_Ess20140828::Client::setGroupDeletionProtectionWithOptions(shared_ptr<SetGroupDeletionProtectionRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return SetGroupDeletionProtectionResponse(doRPCRequest(make_shared<string>("SetGroupDeletionProtection"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
SetGroupDeletionProtectionResponse Alibabacloud_Ess20140828::Client::setGroupDeletionProtection(shared_ptr<SetGroupDeletionProtectionRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return setGroupDeletionProtectionWithOptions(request, runtime);
}
SetInstanceHealthResponse Alibabacloud_Ess20140828::Client::setInstanceHealthWithOptions(shared_ptr<SetInstanceHealthRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return SetInstanceHealthResponse(doRPCRequest(make_shared<string>("SetInstanceHealth"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
SetInstanceHealthResponse Alibabacloud_Ess20140828::Client::setInstanceHealth(shared_ptr<SetInstanceHealthRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return setInstanceHealthWithOptions(request, runtime);
}
SetInstancesProtectionResponse Alibabacloud_Ess20140828::Client::setInstancesProtectionWithOptions(shared_ptr<SetInstancesProtectionRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return SetInstancesProtectionResponse(doRPCRequest(make_shared<string>("SetInstancesProtection"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
SetInstancesProtectionResponse Alibabacloud_Ess20140828::Client::setInstancesProtection(shared_ptr<SetInstancesProtectionRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return setInstancesProtectionWithOptions(request, runtime);
}
SuspendProcessesResponse Alibabacloud_Ess20140828::Client::suspendProcessesWithOptions(shared_ptr<SuspendProcessesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return SuspendProcessesResponse(doRPCRequest(make_shared<string>("SuspendProcesses"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
SuspendProcessesResponse Alibabacloud_Ess20140828::Client::suspendProcesses(shared_ptr<SuspendProcessesRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return suspendProcessesWithOptions(request, runtime);
}
TagResourcesResponse Alibabacloud_Ess20140828::Client::tagResourcesWithOptions(shared_ptr<TagResourcesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return TagResourcesResponse(doRPCRequest(make_shared<string>("TagResources"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
TagResourcesResponse Alibabacloud_Ess20140828::Client::tagResources(shared_ptr<TagResourcesRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return tagResourcesWithOptions(request, runtime);
}
UntagResourcesResponse Alibabacloud_Ess20140828::Client::untagResourcesWithOptions(shared_ptr<UntagResourcesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return UntagResourcesResponse(doRPCRequest(make_shared<string>("UntagResources"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
UntagResourcesResponse Alibabacloud_Ess20140828::Client::untagResources(shared_ptr<UntagResourcesRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return untagResourcesWithOptions(request, runtime);
}
VerifyAuthenticationResponse Alibabacloud_Ess20140828::Client::verifyAuthenticationWithOptions(shared_ptr<VerifyAuthenticationRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return VerifyAuthenticationResponse(doRPCRequest(make_shared<string>("VerifyAuthentication"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}
VerifyAuthenticationResponse Alibabacloud_Ess20140828::Client::verifyAuthentication(shared_ptr<VerifyAuthenticationRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return verifyAuthenticationWithOptions(request, runtime);
}
VerifyUserResponse Alibabacloud_Ess20140828::Client::verifyUserWithOptions(shared_ptr<VerifyUserRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
Darabonba_Util::Client::validateModel(request);
shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
{"body", boost::any(Darabonba_Util::Client::toMap(request))}
}));
return VerifyUserResponse(doRPCRequest(make_shared<string>("VerifyUser"), make_shared<string>("2014-08-28"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("none"), req, runtime));
}
VerifyUserResponse Alibabacloud_Ess20140828::Client::verifyUser(shared_ptr<VerifyUserRequest> request) {
shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
return verifyUserWithOptions(request, runtime);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.