Datasets:
AI4M
/

text
stringlengths
0
3.34M
lemma holomorphic_periodic_fixpoint: assumes holf: "f holomorphic_on UNIV" and "p \<noteq> 0" and per: "\<And>z. f(z + p) = f z" obtains x where "f x = x"
[GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R ⊢ 4 * b₈ W = b₂ W * b₆ W - b₄ W ^ 2 [PROOFSTEP] simp only [b₂, b₄, b₆, b₈] [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R ⊢ 4 * (W.a₁ ^ 2 * W.a₆ + 4 * W.a₂ * W.a₆ - W.a₁ * W.a₃ * W.a₄ + W.a₂ * W.a₃ ^ 2 - W.a₄ ^ 2) = (W.a₁ ^ 2 + 4 * W.a₂) * (W.a₃ ^ 2 + 4 * W.a₆) - (2 * W.a₄ + W.a₁ * W.a₃) ^ 2 [PROOFSTEP] ring1 [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R ⊢ 1728 * Δ W = c₄ W ^ 3 - c₆ W ^ 2 [PROOFSTEP] simp only [b₂, b₄, b₆, b₈, c₄, c₆, Δ] [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R ⊢ 1728 * (-(W.a₁ ^ 2 + 4 * W.a₂) ^ 2 * (W.a₁ ^ 2 * W.a₆ + 4 * W.a₂ * W.a₆ - W.a₁ * W.a₃ * W.a₄ + W.a₂ * W.a₃ ^ 2 - W.a₄ ^ 2) - 8 * (2 * W.a₄ + W.a₁ * W.a₃) ^ 3 - 27 * (W.a₃ ^ 2 + 4 * W.a₆) ^ 2 + 9 * (W.a₁ ^ 2 + 4 * W.a₂) * (2 * W.a₄ + W.a₁ * W.a₃) * (W.a₃ ^ 2 + 4 * W.a₆)) = ((W.a₁ ^ 2 + 4 * W.a₂) ^ 2 - 24 * (2 * W.a₄ + W.a₁ * W.a₃)) ^ 3 - (-(W.a₁ ^ 2 + 4 * W.a₂) ^ 3 + 36 * (W.a₁ ^ 2 + 4 * W.a₂) * (2 * W.a₄ + W.a₁ * W.a₃) - 216 * (W.a₃ ^ 2 + 4 * W.a₆)) ^ 2 [PROOFSTEP] ring1 [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R ⊢ c₄ (ofJ0 R) = 0 [PROOFSTEP] rw [ofJ0, c₄, b₂, b₄] [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R ⊢ ({ a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₁ ^ 2 + 4 * { a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₂) ^ 2 - 24 * (2 * { a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₄ + { a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₁ * { a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₃) = 0 [PROOFSTEP] norm_num1 [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R ⊢ Δ (ofJ0 R) = -27 [PROOFSTEP] rw [ofJ0, Δ, b₂, b₄, b₆, b₈] [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R ⊢ -({ a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₁ ^ 2 + 4 * { a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₂) ^ 2 * ({ a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₁ ^ 2 * { a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₆ + 4 * { a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₂ * { a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₆ - { a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₁ * { a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₃ * { a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₄ + { a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₂ * { a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₃ ^ 2 - { a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₄ ^ 2) - 8 * (2 * { a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₄ + { a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₁ * { a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₃) ^ 3 - 27 * ({ a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₃ ^ 2 + 4 * { a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₆) ^ 2 + 9 * ({ a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₁ ^ 2 + 4 * { a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₂) * (2 * { a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₄ + { a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₁ * { a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₃) * ({ a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₃ ^ 2 + 4 * { a₁ := 0, a₂ := 0, a₃ := 1, a₄ := 0, a₆ := 0 }.a₆) = -27 [PROOFSTEP] norm_num1 [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R ⊢ c₄ (ofJ1728 R) = -48 [PROOFSTEP] rw [ofJ1728, c₄, b₂, b₄] [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R ⊢ ({ a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₁ ^ 2 + 4 * { a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₂) ^ 2 - 24 * (2 * { a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₄ + { a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₁ * { a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₃) = -48 [PROOFSTEP] norm_num1 [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R ⊢ Δ (ofJ1728 R) = -64 [PROOFSTEP] rw [ofJ1728, Δ, b₂, b₄, b₆, b₈] [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R ⊢ -({ a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₁ ^ 2 + 4 * { a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₂) ^ 2 * ({ a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₁ ^ 2 * { a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₆ + 4 * { a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₂ * { a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₆ - { a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₁ * { a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₃ * { a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₄ + { a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₂ * { a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₃ ^ 2 - { a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₄ ^ 2) - 8 * (2 * { a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₄ + { a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₁ * { a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₃) ^ 3 - 27 * ({ a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₃ ^ 2 + 4 * { a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₆) ^ 2 + 9 * ({ a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₁ ^ 2 + 4 * { a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₂) * (2 * { a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₄ + { a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₁ * { a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₃) * ({ a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₃ ^ 2 + 4 * { a₁ := 0, a₂ := 0, a₃ := 0, a₄ := 1, a₆ := 0 }.a₆) = -64 [PROOFSTEP] norm_num1 [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R j : R ⊢ c₄ (ofJ j) = j * (j - 1728) ^ 3 [PROOFSTEP] simp only [ofJ, c₄, b₂, b₄] [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R j : R ⊢ ((j - 1728) ^ 2 + 4 * 0) ^ 2 - 24 * (2 * (-36 * (j - 1728) ^ 3) + (j - 1728) * 0) = j * (j - 1728) ^ 3 [PROOFSTEP] ring1 [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R j : R ⊢ Δ (ofJ j) = j ^ 2 * (j - 1728) ^ 9 [PROOFSTEP] simp only [ofJ, Δ, b₂, b₄, b₆, b₈] [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R j : R ⊢ -((j - 1728) ^ 2 + 4 * 0) ^ 2 * ((j - 1728) ^ 2 * -(j - 1728) ^ 5 + 4 * 0 * -(j - 1728) ^ 5 - (j - 1728) * 0 * (-36 * (j - 1728) ^ 3) + 0 * 0 ^ 2 - (-36 * (j - 1728) ^ 3) ^ 2) - 8 * (2 * (-36 * (j - 1728) ^ 3) + (j - 1728) * 0) ^ 3 - 27 * (0 ^ 2 + 4 * -(j - 1728) ^ 5) ^ 2 + 9 * ((j - 1728) ^ 2 + 4 * 0) * (2 * (-36 * (j - 1728) ^ 3) + (j - 1728) * 0) * (0 ^ 2 + 4 * -(j - 1728) ^ 5) = j ^ 2 * (j - 1728) ^ 9 [PROOFSTEP] ring1 [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R C✝ C' C'' C : VariableChange R ⊢ comp id C = C [PROOFSTEP] simp only [comp, id, zero_add, zero_mul, mul_zero, one_mul] [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R C✝ C' C'' C : VariableChange R ⊢ comp C id = C [PROOFSTEP] simp only [comp, id, add_zero, mul_zero, one_mul, mul_one, one_pow, Units.val_one] [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R C✝ C' C'' C : VariableChange R ⊢ comp (inv C) C = id [PROOFSTEP] rw [comp, id, inv] [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R C✝ C' C'' C : VariableChange R ⊢ { u := { u := C.u⁻¹, r := -C.r * ↑C.u⁻¹ ^ 2, s := -C.s * ↑C.u⁻¹, t := (C.r * C.s - C.t) * ↑C.u⁻¹ ^ 3 }.u * C.u, r := { u := C.u⁻¹, r := -C.r * ↑C.u⁻¹ ^ 2, s := -C.s * ↑C.u⁻¹, t := (C.r * C.s - C.t) * ↑C.u⁻¹ ^ 3 }.r * ↑C.u ^ 2 + C.r, s := ↑C.u * { u := C.u⁻¹, r := -C.r * ↑C.u⁻¹ ^ 2, s := -C.s * ↑C.u⁻¹, t := (C.r * C.s - C.t) * ↑C.u⁻¹ ^ 3 }.s + C.s, t := { u := C.u⁻¹, r := -C.r * ↑C.u⁻¹ ^ 2, s := -C.s * ↑C.u⁻¹, t := (C.r * C.s - C.t) * ↑C.u⁻¹ ^ 3 }.t * ↑C.u ^ 3 + { u := C.u⁻¹, r := -C.r * ↑C.u⁻¹ ^ 2, s := -C.s * ↑C.u⁻¹, t := (C.r * C.s - C.t) * ↑C.u⁻¹ ^ 3 }.r * C.s * ↑C.u ^ 2 + C.t } = { u := 1, r := 0, s := 0, t := 0 } [PROOFSTEP] ext [GOAL] case u.a R : Type u inst✝ : CommRing R W : WeierstrassCurve R C✝ C' C'' C : VariableChange R ⊢ ↑{ u := { u := C.u⁻¹, r := -C.r * ↑C.u⁻¹ ^ 2, s := -C.s * ↑C.u⁻¹, t := (C.r * C.s - C.t) * ↑C.u⁻¹ ^ 3 }.u * C.u, r := { u := C.u⁻¹, r := -C.r * ↑C.u⁻¹ ^ 2, s := -C.s * ↑C.u⁻¹, t := (C.r * C.s - C.t) * ↑C.u⁻¹ ^ 3 }.r * ↑C.u ^ 2 + C.r, s := ↑C.u * { u := C.u⁻¹, r := -C.r * ↑C.u⁻¹ ^ 2, s := -C.s * ↑C.u⁻¹, t := (C.r * C.s - C.t) * ↑C.u⁻¹ ^ 3 }.s + C.s, t := { u := C.u⁻¹, r := -C.r * ↑C.u⁻¹ ^ 2, s := -C.s * ↑C.u⁻¹, t := (C.r * C.s - C.t) * ↑C.u⁻¹ ^ 3 }.t * ↑C.u ^ 3 + { u := C.u⁻¹, r := -C.r * ↑C.u⁻¹ ^ 2, s := -C.s * ↑C.u⁻¹, t := (C.r * C.s - C.t) * ↑C.u⁻¹ ^ 3 }.r * C.s * ↑C.u ^ 2 + C.t }.u = ↑{ u := 1, r := 0, s := 0, t := 0 }.u [PROOFSTEP] dsimp only [GOAL] case r R : Type u inst✝ : CommRing R W : WeierstrassCurve R C✝ C' C'' C : VariableChange R ⊢ { u := { u := C.u⁻¹, r := -C.r * ↑C.u⁻¹ ^ 2, s := -C.s * ↑C.u⁻¹, t := (C.r * C.s - C.t) * ↑C.u⁻¹ ^ 3 }.u * C.u, r := { u := C.u⁻¹, r := -C.r * ↑C.u⁻¹ ^ 2, s := -C.s * ↑C.u⁻¹, t := (C.r * C.s - C.t) * ↑C.u⁻¹ ^ 3 }.r * ↑C.u ^ 2 + C.r, s := ↑C.u * { u := C.u⁻¹, r := -C.r * ↑C.u⁻¹ ^ 2, s := -C.s * ↑C.u⁻¹, t := (C.r * C.s - C.t) * ↑C.u⁻¹ ^ 3 }.s + C.s, t := { u := C.u⁻¹, r := -C.r * ↑C.u⁻¹ ^ 2, s := -C.s * ↑C.u⁻¹, t := (C.r * C.s - C.t) * ↑C.u⁻¹ ^ 3 }.t * ↑C.u ^ 3 + { u := C.u⁻¹, r := -C.r * ↑C.u⁻¹ ^ 2, s := -C.s * ↑C.u⁻¹, t := (C.r * C.s - C.t) * ↑C.u⁻¹ ^ 3 }.r * C.s * ↑C.u ^ 2 + C.t }.r = { u := 1, r := 0, s := 0, t := 0 }.r [PROOFSTEP] dsimp only [GOAL] case s R : Type u inst✝ : CommRing R W : WeierstrassCurve R C✝ C' C'' C : VariableChange R ⊢ { u := { u := C.u⁻¹, r := -C.r * ↑C.u⁻¹ ^ 2, s := -C.s * ↑C.u⁻¹, t := (C.r * C.s - C.t) * ↑C.u⁻¹ ^ 3 }.u * C.u, r := { u := C.u⁻¹, r := -C.r * ↑C.u⁻¹ ^ 2, s := -C.s * ↑C.u⁻¹, t := (C.r * C.s - C.t) * ↑C.u⁻¹ ^ 3 }.r * ↑C.u ^ 2 + C.r, s := ↑C.u * { u := C.u⁻¹, r := -C.r * ↑C.u⁻¹ ^ 2, s := -C.s * ↑C.u⁻¹, t := (C.r * C.s - C.t) * ↑C.u⁻¹ ^ 3 }.s + C.s, t := { u := C.u⁻¹, r := -C.r * ↑C.u⁻¹ ^ 2, s := -C.s * ↑C.u⁻¹, t := (C.r * C.s - C.t) * ↑C.u⁻¹ ^ 3 }.t * ↑C.u ^ 3 + { u := C.u⁻¹, r := -C.r * ↑C.u⁻¹ ^ 2, s := -C.s * ↑C.u⁻¹, t := (C.r * C.s - C.t) * ↑C.u⁻¹ ^ 3 }.r * C.s * ↑C.u ^ 2 + C.t }.s = { u := 1, r := 0, s := 0, t := 0 }.s [PROOFSTEP] dsimp only [GOAL] case t R : Type u inst✝ : CommRing R W : WeierstrassCurve R C✝ C' C'' C : VariableChange R ⊢ { u := { u := C.u⁻¹, r := -C.r * ↑C.u⁻¹ ^ 2, s := -C.s * ↑C.u⁻¹, t := (C.r * C.s - C.t) * ↑C.u⁻¹ ^ 3 }.u * C.u, r := { u := C.u⁻¹, r := -C.r * ↑C.u⁻¹ ^ 2, s := -C.s * ↑C.u⁻¹, t := (C.r * C.s - C.t) * ↑C.u⁻¹ ^ 3 }.r * ↑C.u ^ 2 + C.r, s := ↑C.u * { u := C.u⁻¹, r := -C.r * ↑C.u⁻¹ ^ 2, s := -C.s * ↑C.u⁻¹, t := (C.r * C.s - C.t) * ↑C.u⁻¹ ^ 3 }.s + C.s, t := { u := C.u⁻¹, r := -C.r * ↑C.u⁻¹ ^ 2, s := -C.s * ↑C.u⁻¹, t := (C.r * C.s - C.t) * ↑C.u⁻¹ ^ 3 }.t * ↑C.u ^ 3 + { u := C.u⁻¹, r := -C.r * ↑C.u⁻¹ ^ 2, s := -C.s * ↑C.u⁻¹, t := (C.r * C.s - C.t) * ↑C.u⁻¹ ^ 3 }.r * C.s * ↑C.u ^ 2 + C.t }.t = { u := 1, r := 0, s := 0, t := 0 }.t [PROOFSTEP] dsimp only [GOAL] case u.a R : Type u inst✝ : CommRing R W : WeierstrassCurve R C✝ C' C'' C : VariableChange R ⊢ ↑(C.u⁻¹ * C.u) = ↑1 [PROOFSTEP] exact C.u.inv_mul [GOAL] case r R : Type u inst✝ : CommRing R W : WeierstrassCurve R C✝ C' C'' C : VariableChange R ⊢ -C.r * ↑C.u⁻¹ ^ 2 * ↑C.u ^ 2 + C.r = 0 [PROOFSTEP] linear_combination (norm := ring1) -C.r * pow_mul_pow_eq_one 2 C.u.inv_mul [GOAL] case a R : Type u inst✝ : CommRing R W : WeierstrassCurve R C✝ C' C'' C : VariableChange R ⊢ -C.r * ↑C.u⁻¹ ^ 2 * ↑C.u ^ 2 + C.r - 0 - (-C.r * (↑C.u⁻¹ ^ 2 * ↑C.u ^ 2) - -C.r * 1) = 0 [PROOFSTEP] ring1 [GOAL] case s R : Type u inst✝ : CommRing R W : WeierstrassCurve R C✝ C' C'' C : VariableChange R ⊢ ↑C.u * (-C.s * ↑C.u⁻¹) + C.s = 0 [PROOFSTEP] linear_combination (norm := ring1) -C.s * C.u.inv_mul [GOAL] case a R : Type u inst✝ : CommRing R W : WeierstrassCurve R C✝ C' C'' C : VariableChange R ⊢ ↑C.u * (-C.s * ↑C.u⁻¹) + C.s - 0 - (-C.s * (↑C.u⁻¹ * ↑C.u) - -C.s * 1) = 0 [PROOFSTEP] ring1 [GOAL] case t R : Type u inst✝ : CommRing R W : WeierstrassCurve R C✝ C' C'' C : VariableChange R ⊢ (C.r * C.s - C.t) * ↑C.u⁻¹ ^ 3 * ↑C.u ^ 3 + -C.r * ↑C.u⁻¹ ^ 2 * C.s * ↑C.u ^ 2 + C.t = 0 [PROOFSTEP] linear_combination (norm := ring1) (C.r * C.s - C.t) * pow_mul_pow_eq_one 3 C.u.inv_mul + -C.r * C.s * pow_mul_pow_eq_one 2 C.u.inv_mul [GOAL] case a R : Type u inst✝ : CommRing R W : WeierstrassCurve R C✝ C' C'' C : VariableChange R ⊢ (C.r * C.s - C.t) * ↑C.u⁻¹ ^ 3 * ↑C.u ^ 3 + -C.r * ↑C.u⁻¹ ^ 2 * C.s * ↑C.u ^ 2 + C.t - 0 - ((C.r * C.s - C.t) * (↑C.u⁻¹ ^ 3 * ↑C.u ^ 3) + -C.r * C.s * (↑C.u⁻¹ ^ 2 * ↑C.u ^ 2) - ((C.r * C.s - C.t) * 1 + -C.r * C.s * 1)) = 0 [PROOFSTEP] ring1 [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R C✝ C'✝ C''✝ C C' C'' : VariableChange R ⊢ comp (comp C C') C'' = comp C (comp C' C'') [PROOFSTEP] ext [GOAL] case u.a R : Type u inst✝ : CommRing R W : WeierstrassCurve R C✝ C'✝ C''✝ C C' C'' : VariableChange R ⊢ ↑(comp (comp C C') C'').u = ↑(comp C (comp C' C'')).u [PROOFSTEP] simp only [comp, Units.val_mul] [GOAL] case r R : Type u inst✝ : CommRing R W : WeierstrassCurve R C✝ C'✝ C''✝ C C' C'' : VariableChange R ⊢ (comp (comp C C') C'').r = (comp C (comp C' C'')).r [PROOFSTEP] simp only [comp, Units.val_mul] [GOAL] case s R : Type u inst✝ : CommRing R W : WeierstrassCurve R C✝ C'✝ C''✝ C C' C'' : VariableChange R ⊢ (comp (comp C C') C'').s = (comp C (comp C' C'')).s [PROOFSTEP] simp only [comp, Units.val_mul] [GOAL] case t R : Type u inst✝ : CommRing R W : WeierstrassCurve R C✝ C'✝ C''✝ C C' C'' : VariableChange R ⊢ (comp (comp C C') C'').t = (comp C (comp C' C'')).t [PROOFSTEP] simp only [comp, Units.val_mul] [GOAL] case u.a R : Type u inst✝ : CommRing R W : WeierstrassCurve R C✝ C'✝ C''✝ C C' C'' : VariableChange R ⊢ ↑C.u * ↑C'.u * ↑C''.u = ↑C.u * (↑C'.u * ↑C''.u) [PROOFSTEP] ring1 [GOAL] case r R : Type u inst✝ : CommRing R W : WeierstrassCurve R C✝ C'✝ C''✝ C C' C'' : VariableChange R ⊢ (C.r * ↑C'.u ^ 2 + C'.r) * ↑C''.u ^ 2 + C''.r = C.r * (↑C'.u * ↑C''.u) ^ 2 + (C'.r * ↑C''.u ^ 2 + C''.r) [PROOFSTEP] ring1 [GOAL] case s R : Type u inst✝ : CommRing R W : WeierstrassCurve R C✝ C'✝ C''✝ C C' C'' : VariableChange R ⊢ ↑C''.u * (↑C'.u * C.s + C'.s) + C''.s = ↑C'.u * ↑C''.u * C.s + (↑C''.u * C'.s + C''.s) [PROOFSTEP] ring1 [GOAL] case t R : Type u inst✝ : CommRing R W : WeierstrassCurve R C✝ C'✝ C''✝ C C' C'' : VariableChange R ⊢ (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) * ↑C''.u ^ 3 + (C.r * ↑C'.u ^ 2 + C'.r) * C''.s * ↑C''.u ^ 2 + C''.t = C.t * (↑C'.u * ↑C''.u) ^ 3 + C.r * (↑C''.u * C'.s + C''.s) * (↑C'.u * ↑C''.u) ^ 2 + (C'.t * ↑C''.u ^ 3 + C'.r * C''.s * ↑C''.u ^ 2 + C''.t) [PROOFSTEP] ring1 [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R C : VariableChange R ⊢ variableChange W VariableChange.id = W [PROOFSTEP] rw [VariableChange.id, variableChange, inv_one, Units.val_one] [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R C : VariableChange R ⊢ { a₁ := 1 * (W.a₁ + 2 * { u := 1, r := 0, s := 0, t := 0 }.s), a₂ := 1 ^ 2 * (W.a₂ - { u := 1, r := 0, s := 0, t := 0 }.s * W.a₁ + 3 * { u := 1, r := 0, s := 0, t := 0 }.r - { u := 1, r := 0, s := 0, t := 0 }.s ^ 2), a₃ := 1 ^ 3 * (W.a₃ + { u := 1, r := 0, s := 0, t := 0 }.r * W.a₁ + 2 * { u := 1, r := 0, s := 0, t := 0 }.t), a₄ := 1 ^ 4 * (W.a₄ - { u := 1, r := 0, s := 0, t := 0 }.s * W.a₃ + 2 * { u := 1, r := 0, s := 0, t := 0 }.r * W.a₂ - ({ u := 1, r := 0, s := 0, t := 0 }.t + { u := 1, r := 0, s := 0, t := 0 }.r * { u := 1, r := 0, s := 0, t := 0 }.s) * W.a₁ + 3 * { u := 1, r := 0, s := 0, t := 0 }.r ^ 2 - 2 * { u := 1, r := 0, s := 0, t := 0 }.s * { u := 1, r := 0, s := 0, t := 0 }.t), a₆ := 1 ^ 6 * (W.a₆ + { u := 1, r := 0, s := 0, t := 0 }.r * W.a₄ + { u := 1, r := 0, s := 0, t := 0 }.r ^ 2 * W.a₂ + { u := 1, r := 0, s := 0, t := 0 }.r ^ 3 - { u := 1, r := 0, s := 0, t := 0 }.t * W.a₃ - { u := 1, r := 0, s := 0, t := 0 }.t ^ 2 - { u := 1, r := 0, s := 0, t := 0 }.r * { u := 1, r := 0, s := 0, t := 0 }.t * W.a₁) } = W [PROOFSTEP] ext [GOAL] case a₁ R : Type u inst✝ : CommRing R W : WeierstrassCurve R C : VariableChange R ⊢ { a₁ := 1 * (W.a₁ + 2 * { u := 1, r := 0, s := 0, t := 0 }.s), a₂ := 1 ^ 2 * (W.a₂ - { u := 1, r := 0, s := 0, t := 0 }.s * W.a₁ + 3 * { u := 1, r := 0, s := 0, t := 0 }.r - { u := 1, r := 0, s := 0, t := 0 }.s ^ 2), a₃ := 1 ^ 3 * (W.a₃ + { u := 1, r := 0, s := 0, t := 0 }.r * W.a₁ + 2 * { u := 1, r := 0, s := 0, t := 0 }.t), a₄ := 1 ^ 4 * (W.a₄ - { u := 1, r := 0, s := 0, t := 0 }.s * W.a₃ + 2 * { u := 1, r := 0, s := 0, t := 0 }.r * W.a₂ - ({ u := 1, r := 0, s := 0, t := 0 }.t + { u := 1, r := 0, s := 0, t := 0 }.r * { u := 1, r := 0, s := 0, t := 0 }.s) * W.a₁ + 3 * { u := 1, r := 0, s := 0, t := 0 }.r ^ 2 - 2 * { u := 1, r := 0, s := 0, t := 0 }.s * { u := 1, r := 0, s := 0, t := 0 }.t), a₆ := 1 ^ 6 * (W.a₆ + { u := 1, r := 0, s := 0, t := 0 }.r * W.a₄ + { u := 1, r := 0, s := 0, t := 0 }.r ^ 2 * W.a₂ + { u := 1, r := 0, s := 0, t := 0 }.r ^ 3 - { u := 1, r := 0, s := 0, t := 0 }.t * W.a₃ - { u := 1, r := 0, s := 0, t := 0 }.t ^ 2 - { u := 1, r := 0, s := 0, t := 0 }.r * { u := 1, r := 0, s := 0, t := 0 }.t * W.a₁) }.a₁ = W.a₁ [PROOFSTEP] dsimp only [GOAL] case a₁ R : Type u inst✝ : CommRing R W : WeierstrassCurve R C : VariableChange R ⊢ 1 * (W.a₁ + 2 * 0) = W.a₁ [PROOFSTEP] ring1 [GOAL] case a₂ R : Type u inst✝ : CommRing R W : WeierstrassCurve R C : VariableChange R ⊢ { a₁ := 1 * (W.a₁ + 2 * { u := 1, r := 0, s := 0, t := 0 }.s), a₂ := 1 ^ 2 * (W.a₂ - { u := 1, r := 0, s := 0, t := 0 }.s * W.a₁ + 3 * { u := 1, r := 0, s := 0, t := 0 }.r - { u := 1, r := 0, s := 0, t := 0 }.s ^ 2), a₃ := 1 ^ 3 * (W.a₃ + { u := 1, r := 0, s := 0, t := 0 }.r * W.a₁ + 2 * { u := 1, r := 0, s := 0, t := 0 }.t), a₄ := 1 ^ 4 * (W.a₄ - { u := 1, r := 0, s := 0, t := 0 }.s * W.a₃ + 2 * { u := 1, r := 0, s := 0, t := 0 }.r * W.a₂ - ({ u := 1, r := 0, s := 0, t := 0 }.t + { u := 1, r := 0, s := 0, t := 0 }.r * { u := 1, r := 0, s := 0, t := 0 }.s) * W.a₁ + 3 * { u := 1, r := 0, s := 0, t := 0 }.r ^ 2 - 2 * { u := 1, r := 0, s := 0, t := 0 }.s * { u := 1, r := 0, s := 0, t := 0 }.t), a₆ := 1 ^ 6 * (W.a₆ + { u := 1, r := 0, s := 0, t := 0 }.r * W.a₄ + { u := 1, r := 0, s := 0, t := 0 }.r ^ 2 * W.a₂ + { u := 1, r := 0, s := 0, t := 0 }.r ^ 3 - { u := 1, r := 0, s := 0, t := 0 }.t * W.a₃ - { u := 1, r := 0, s := 0, t := 0 }.t ^ 2 - { u := 1, r := 0, s := 0, t := 0 }.r * { u := 1, r := 0, s := 0, t := 0 }.t * W.a₁) }.a₂ = W.a₂ [PROOFSTEP] dsimp only [GOAL] case a₂ R : Type u inst✝ : CommRing R W : WeierstrassCurve R C : VariableChange R ⊢ 1 ^ 2 * (W.a₂ - 0 * W.a₁ + 3 * 0 - 0 ^ 2) = W.a₂ [PROOFSTEP] ring1 [GOAL] case a₃ R : Type u inst✝ : CommRing R W : WeierstrassCurve R C : VariableChange R ⊢ { a₁ := 1 * (W.a₁ + 2 * { u := 1, r := 0, s := 0, t := 0 }.s), a₂ := 1 ^ 2 * (W.a₂ - { u := 1, r := 0, s := 0, t := 0 }.s * W.a₁ + 3 * { u := 1, r := 0, s := 0, t := 0 }.r - { u := 1, r := 0, s := 0, t := 0 }.s ^ 2), a₃ := 1 ^ 3 * (W.a₃ + { u := 1, r := 0, s := 0, t := 0 }.r * W.a₁ + 2 * { u := 1, r := 0, s := 0, t := 0 }.t), a₄ := 1 ^ 4 * (W.a₄ - { u := 1, r := 0, s := 0, t := 0 }.s * W.a₃ + 2 * { u := 1, r := 0, s := 0, t := 0 }.r * W.a₂ - ({ u := 1, r := 0, s := 0, t := 0 }.t + { u := 1, r := 0, s := 0, t := 0 }.r * { u := 1, r := 0, s := 0, t := 0 }.s) * W.a₁ + 3 * { u := 1, r := 0, s := 0, t := 0 }.r ^ 2 - 2 * { u := 1, r := 0, s := 0, t := 0 }.s * { u := 1, r := 0, s := 0, t := 0 }.t), a₆ := 1 ^ 6 * (W.a₆ + { u := 1, r := 0, s := 0, t := 0 }.r * W.a₄ + { u := 1, r := 0, s := 0, t := 0 }.r ^ 2 * W.a₂ + { u := 1, r := 0, s := 0, t := 0 }.r ^ 3 - { u := 1, r := 0, s := 0, t := 0 }.t * W.a₃ - { u := 1, r := 0, s := 0, t := 0 }.t ^ 2 - { u := 1, r := 0, s := 0, t := 0 }.r * { u := 1, r := 0, s := 0, t := 0 }.t * W.a₁) }.a₃ = W.a₃ [PROOFSTEP] dsimp only [GOAL] case a₃ R : Type u inst✝ : CommRing R W : WeierstrassCurve R C : VariableChange R ⊢ 1 ^ 3 * (W.a₃ + 0 * W.a₁ + 2 * 0) = W.a₃ [PROOFSTEP] ring1 [GOAL] case a₄ R : Type u inst✝ : CommRing R W : WeierstrassCurve R C : VariableChange R ⊢ { a₁ := 1 * (W.a₁ + 2 * { u := 1, r := 0, s := 0, t := 0 }.s), a₂ := 1 ^ 2 * (W.a₂ - { u := 1, r := 0, s := 0, t := 0 }.s * W.a₁ + 3 * { u := 1, r := 0, s := 0, t := 0 }.r - { u := 1, r := 0, s := 0, t := 0 }.s ^ 2), a₃ := 1 ^ 3 * (W.a₃ + { u := 1, r := 0, s := 0, t := 0 }.r * W.a₁ + 2 * { u := 1, r := 0, s := 0, t := 0 }.t), a₄ := 1 ^ 4 * (W.a₄ - { u := 1, r := 0, s := 0, t := 0 }.s * W.a₃ + 2 * { u := 1, r := 0, s := 0, t := 0 }.r * W.a₂ - ({ u := 1, r := 0, s := 0, t := 0 }.t + { u := 1, r := 0, s := 0, t := 0 }.r * { u := 1, r := 0, s := 0, t := 0 }.s) * W.a₁ + 3 * { u := 1, r := 0, s := 0, t := 0 }.r ^ 2 - 2 * { u := 1, r := 0, s := 0, t := 0 }.s * { u := 1, r := 0, s := 0, t := 0 }.t), a₆ := 1 ^ 6 * (W.a₆ + { u := 1, r := 0, s := 0, t := 0 }.r * W.a₄ + { u := 1, r := 0, s := 0, t := 0 }.r ^ 2 * W.a₂ + { u := 1, r := 0, s := 0, t := 0 }.r ^ 3 - { u := 1, r := 0, s := 0, t := 0 }.t * W.a₃ - { u := 1, r := 0, s := 0, t := 0 }.t ^ 2 - { u := 1, r := 0, s := 0, t := 0 }.r * { u := 1, r := 0, s := 0, t := 0 }.t * W.a₁) }.a₄ = W.a₄ [PROOFSTEP] dsimp only [GOAL] case a₄ R : Type u inst✝ : CommRing R W : WeierstrassCurve R C : VariableChange R ⊢ 1 ^ 4 * (W.a₄ - 0 * W.a₃ + 2 * 0 * W.a₂ - (0 + 0 * 0) * W.a₁ + 3 * 0 ^ 2 - 2 * 0 * 0) = W.a₄ [PROOFSTEP] ring1 [GOAL] case a₆ R : Type u inst✝ : CommRing R W : WeierstrassCurve R C : VariableChange R ⊢ { a₁ := 1 * (W.a₁ + 2 * { u := 1, r := 0, s := 0, t := 0 }.s), a₂ := 1 ^ 2 * (W.a₂ - { u := 1, r := 0, s := 0, t := 0 }.s * W.a₁ + 3 * { u := 1, r := 0, s := 0, t := 0 }.r - { u := 1, r := 0, s := 0, t := 0 }.s ^ 2), a₃ := 1 ^ 3 * (W.a₃ + { u := 1, r := 0, s := 0, t := 0 }.r * W.a₁ + 2 * { u := 1, r := 0, s := 0, t := 0 }.t), a₄ := 1 ^ 4 * (W.a₄ - { u := 1, r := 0, s := 0, t := 0 }.s * W.a₃ + 2 * { u := 1, r := 0, s := 0, t := 0 }.r * W.a₂ - ({ u := 1, r := 0, s := 0, t := 0 }.t + { u := 1, r := 0, s := 0, t := 0 }.r * { u := 1, r := 0, s := 0, t := 0 }.s) * W.a₁ + 3 * { u := 1, r := 0, s := 0, t := 0 }.r ^ 2 - 2 * { u := 1, r := 0, s := 0, t := 0 }.s * { u := 1, r := 0, s := 0, t := 0 }.t), a₆ := 1 ^ 6 * (W.a₆ + { u := 1, r := 0, s := 0, t := 0 }.r * W.a₄ + { u := 1, r := 0, s := 0, t := 0 }.r ^ 2 * W.a₂ + { u := 1, r := 0, s := 0, t := 0 }.r ^ 3 - { u := 1, r := 0, s := 0, t := 0 }.t * W.a₃ - { u := 1, r := 0, s := 0, t := 0 }.t ^ 2 - { u := 1, r := 0, s := 0, t := 0 }.r * { u := 1, r := 0, s := 0, t := 0 }.t * W.a₁) }.a₆ = W.a₆ [PROOFSTEP] dsimp only [GOAL] case a₆ R : Type u inst✝ : CommRing R W : WeierstrassCurve R C : VariableChange R ⊢ 1 ^ 6 * (W.a₆ + 0 * W.a₄ + 0 ^ 2 * W.a₂ + 0 ^ 3 - 0 * W.a₃ - 0 ^ 2 - 0 * 0 * W.a₁) = W.a₆ [PROOFSTEP] ring1 [GOAL] R : Type u inst✝ : CommRing R W✝ : WeierstrassCurve R C✝ C C' : VariableChange R W : WeierstrassCurve R ⊢ variableChange W (VariableChange.comp C C') = variableChange (variableChange W C') C [PROOFSTEP] simp only [VariableChange.comp, variableChange] [GOAL] R : Type u inst✝ : CommRing R W✝ : WeierstrassCurve R C✝ C C' : VariableChange R W : WeierstrassCurve R ⊢ { a₁ := ↑(C.u * C'.u)⁻¹ * (W.a₁ + 2 * (↑C'.u * C.s + C'.s)), a₂ := ↑(C.u * C'.u)⁻¹ ^ 2 * (W.a₂ - (↑C'.u * C.s + C'.s) * W.a₁ + 3 * (C.r * ↑C'.u ^ 2 + C'.r) - (↑C'.u * C.s + C'.s) ^ 2), a₃ := ↑(C.u * C'.u)⁻¹ ^ 3 * (W.a₃ + (C.r * ↑C'.u ^ 2 + C'.r) * W.a₁ + 2 * (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t)), a₄ := ↑(C.u * C'.u)⁻¹ ^ 4 * (W.a₄ - (↑C'.u * C.s + C'.s) * W.a₃ + 2 * (C.r * ↑C'.u ^ 2 + C'.r) * W.a₂ - (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t + (C.r * ↑C'.u ^ 2 + C'.r) * (↑C'.u * C.s + C'.s)) * W.a₁ + 3 * (C.r * ↑C'.u ^ 2 + C'.r) ^ 2 - 2 * (↑C'.u * C.s + C'.s) * (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t)), a₆ := ↑(C.u * C'.u)⁻¹ ^ 6 * (W.a₆ + (C.r * ↑C'.u ^ 2 + C'.r) * W.a₄ + (C.r * ↑C'.u ^ 2 + C'.r) ^ 2 * W.a₂ + (C.r * ↑C'.u ^ 2 + C'.r) ^ 3 - (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) * W.a₃ - (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) ^ 2 - (C.r * ↑C'.u ^ 2 + C'.r) * (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) * W.a₁) } = { a₁ := ↑C.u⁻¹ * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s) + 2 * C.s), a₂ := ↑C.u⁻¹ ^ 2 * (↑C'.u⁻¹ ^ 2 * (W.a₂ - C'.s * W.a₁ + 3 * C'.r - C'.s ^ 2) - C.s * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s)) + 3 * C.r - C.s ^ 2), a₃ := ↑C.u⁻¹ ^ 3 * (↑C'.u⁻¹ ^ 3 * (W.a₃ + C'.r * W.a₁ + 2 * C'.t) + C.r * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s)) + 2 * C.t), a₄ := ↑C.u⁻¹ ^ 4 * (↑C'.u⁻¹ ^ 4 * (W.a₄ - C'.s * W.a₃ + 2 * C'.r * W.a₂ - (C'.t + C'.r * C'.s) * W.a₁ + 3 * C'.r ^ 2 - 2 * C'.s * C'.t) - C.s * (↑C'.u⁻¹ ^ 3 * (W.a₃ + C'.r * W.a₁ + 2 * C'.t)) + 2 * C.r * (↑C'.u⁻¹ ^ 2 * (W.a₂ - C'.s * W.a₁ + 3 * C'.r - C'.s ^ 2)) - (C.t + C.r * C.s) * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s)) + 3 * C.r ^ 2 - 2 * C.s * C.t), a₆ := ↑C.u⁻¹ ^ 6 * (↑C'.u⁻¹ ^ 6 * (W.a₆ + C'.r * W.a₄ + C'.r ^ 2 * W.a₂ + C'.r ^ 3 - C'.t * W.a₃ - C'.t ^ 2 - C'.r * C'.t * W.a₁) + C.r * (↑C'.u⁻¹ ^ 4 * (W.a₄ - C'.s * W.a₃ + 2 * C'.r * W.a₂ - (C'.t + C'.r * C'.s) * W.a₁ + 3 * C'.r ^ 2 - 2 * C'.s * C'.t)) + C.r ^ 2 * (↑C'.u⁻¹ ^ 2 * (W.a₂ - C'.s * W.a₁ + 3 * C'.r - C'.s ^ 2)) + C.r ^ 3 - C.t * (↑C'.u⁻¹ ^ 3 * (W.a₃ + C'.r * W.a₁ + 2 * C'.t)) - C.t ^ 2 - C.r * C.t * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s))) } [PROOFSTEP] ext [GOAL] case a₁ R : Type u inst✝ : CommRing R W✝ : WeierstrassCurve R C✝ C C' : VariableChange R W : WeierstrassCurve R ⊢ { a₁ := ↑(C.u * C'.u)⁻¹ * (W.a₁ + 2 * (↑C'.u * C.s + C'.s)), a₂ := ↑(C.u * C'.u)⁻¹ ^ 2 * (W.a₂ - (↑C'.u * C.s + C'.s) * W.a₁ + 3 * (C.r * ↑C'.u ^ 2 + C'.r) - (↑C'.u * C.s + C'.s) ^ 2), a₃ := ↑(C.u * C'.u)⁻¹ ^ 3 * (W.a₃ + (C.r * ↑C'.u ^ 2 + C'.r) * W.a₁ + 2 * (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t)), a₄ := ↑(C.u * C'.u)⁻¹ ^ 4 * (W.a₄ - (↑C'.u * C.s + C'.s) * W.a₃ + 2 * (C.r * ↑C'.u ^ 2 + C'.r) * W.a₂ - (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t + (C.r * ↑C'.u ^ 2 + C'.r) * (↑C'.u * C.s + C'.s)) * W.a₁ + 3 * (C.r * ↑C'.u ^ 2 + C'.r) ^ 2 - 2 * (↑C'.u * C.s + C'.s) * (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t)), a₆ := ↑(C.u * C'.u)⁻¹ ^ 6 * (W.a₆ + (C.r * ↑C'.u ^ 2 + C'.r) * W.a₄ + (C.r * ↑C'.u ^ 2 + C'.r) ^ 2 * W.a₂ + (C.r * ↑C'.u ^ 2 + C'.r) ^ 3 - (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) * W.a₃ - (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) ^ 2 - (C.r * ↑C'.u ^ 2 + C'.r) * (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) * W.a₁) }.a₁ = { a₁ := ↑C.u⁻¹ * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s) + 2 * C.s), a₂ := ↑C.u⁻¹ ^ 2 * (↑C'.u⁻¹ ^ 2 * (W.a₂ - C'.s * W.a₁ + 3 * C'.r - C'.s ^ 2) - C.s * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s)) + 3 * C.r - C.s ^ 2), a₃ := ↑C.u⁻¹ ^ 3 * (↑C'.u⁻¹ ^ 3 * (W.a₃ + C'.r * W.a₁ + 2 * C'.t) + C.r * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s)) + 2 * C.t), a₄ := ↑C.u⁻¹ ^ 4 * (↑C'.u⁻¹ ^ 4 * (W.a₄ - C'.s * W.a₃ + 2 * C'.r * W.a₂ - (C'.t + C'.r * C'.s) * W.a₁ + 3 * C'.r ^ 2 - 2 * C'.s * C'.t) - C.s * (↑C'.u⁻¹ ^ 3 * (W.a₃ + C'.r * W.a₁ + 2 * C'.t)) + 2 * C.r * (↑C'.u⁻¹ ^ 2 * (W.a₂ - C'.s * W.a₁ + 3 * C'.r - C'.s ^ 2)) - (C.t + C.r * C.s) * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s)) + 3 * C.r ^ 2 - 2 * C.s * C.t), a₆ := ↑C.u⁻¹ ^ 6 * (↑C'.u⁻¹ ^ 6 * (W.a₆ + C'.r * W.a₄ + C'.r ^ 2 * W.a₂ + C'.r ^ 3 - C'.t * W.a₃ - C'.t ^ 2 - C'.r * C'.t * W.a₁) + C.r * (↑C'.u⁻¹ ^ 4 * (W.a₄ - C'.s * W.a₃ + 2 * C'.r * W.a₂ - (C'.t + C'.r * C'.s) * W.a₁ + 3 * C'.r ^ 2 - 2 * C'.s * C'.t)) + C.r ^ 2 * (↑C'.u⁻¹ ^ 2 * (W.a₂ - C'.s * W.a₁ + 3 * C'.r - C'.s ^ 2)) + C.r ^ 3 - C.t * (↑C'.u⁻¹ ^ 3 * (W.a₃ + C'.r * W.a₁ + 2 * C'.t)) - C.t ^ 2 - C.r * C.t * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s))) }.a₁ [PROOFSTEP] simp only [mul_inv, Units.val_mul] [GOAL] case a₂ R : Type u inst✝ : CommRing R W✝ : WeierstrassCurve R C✝ C C' : VariableChange R W : WeierstrassCurve R ⊢ { a₁ := ↑(C.u * C'.u)⁻¹ * (W.a₁ + 2 * (↑C'.u * C.s + C'.s)), a₂ := ↑(C.u * C'.u)⁻¹ ^ 2 * (W.a₂ - (↑C'.u * C.s + C'.s) * W.a₁ + 3 * (C.r * ↑C'.u ^ 2 + C'.r) - (↑C'.u * C.s + C'.s) ^ 2), a₃ := ↑(C.u * C'.u)⁻¹ ^ 3 * (W.a₃ + (C.r * ↑C'.u ^ 2 + C'.r) * W.a₁ + 2 * (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t)), a₄ := ↑(C.u * C'.u)⁻¹ ^ 4 * (W.a₄ - (↑C'.u * C.s + C'.s) * W.a₃ + 2 * (C.r * ↑C'.u ^ 2 + C'.r) * W.a₂ - (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t + (C.r * ↑C'.u ^ 2 + C'.r) * (↑C'.u * C.s + C'.s)) * W.a₁ + 3 * (C.r * ↑C'.u ^ 2 + C'.r) ^ 2 - 2 * (↑C'.u * C.s + C'.s) * (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t)), a₆ := ↑(C.u * C'.u)⁻¹ ^ 6 * (W.a₆ + (C.r * ↑C'.u ^ 2 + C'.r) * W.a₄ + (C.r * ↑C'.u ^ 2 + C'.r) ^ 2 * W.a₂ + (C.r * ↑C'.u ^ 2 + C'.r) ^ 3 - (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) * W.a₃ - (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) ^ 2 - (C.r * ↑C'.u ^ 2 + C'.r) * (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) * W.a₁) }.a₂ = { a₁ := ↑C.u⁻¹ * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s) + 2 * C.s), a₂ := ↑C.u⁻¹ ^ 2 * (↑C'.u⁻¹ ^ 2 * (W.a₂ - C'.s * W.a₁ + 3 * C'.r - C'.s ^ 2) - C.s * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s)) + 3 * C.r - C.s ^ 2), a₃ := ↑C.u⁻¹ ^ 3 * (↑C'.u⁻¹ ^ 3 * (W.a₃ + C'.r * W.a₁ + 2 * C'.t) + C.r * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s)) + 2 * C.t), a₄ := ↑C.u⁻¹ ^ 4 * (↑C'.u⁻¹ ^ 4 * (W.a₄ - C'.s * W.a₃ + 2 * C'.r * W.a₂ - (C'.t + C'.r * C'.s) * W.a₁ + 3 * C'.r ^ 2 - 2 * C'.s * C'.t) - C.s * (↑C'.u⁻¹ ^ 3 * (W.a₃ + C'.r * W.a₁ + 2 * C'.t)) + 2 * C.r * (↑C'.u⁻¹ ^ 2 * (W.a₂ - C'.s * W.a₁ + 3 * C'.r - C'.s ^ 2)) - (C.t + C.r * C.s) * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s)) + 3 * C.r ^ 2 - 2 * C.s * C.t), a₆ := ↑C.u⁻¹ ^ 6 * (↑C'.u⁻¹ ^ 6 * (W.a₆ + C'.r * W.a₄ + C'.r ^ 2 * W.a₂ + C'.r ^ 3 - C'.t * W.a₃ - C'.t ^ 2 - C'.r * C'.t * W.a₁) + C.r * (↑C'.u⁻¹ ^ 4 * (W.a₄ - C'.s * W.a₃ + 2 * C'.r * W.a₂ - (C'.t + C'.r * C'.s) * W.a₁ + 3 * C'.r ^ 2 - 2 * C'.s * C'.t)) + C.r ^ 2 * (↑C'.u⁻¹ ^ 2 * (W.a₂ - C'.s * W.a₁ + 3 * C'.r - C'.s ^ 2)) + C.r ^ 3 - C.t * (↑C'.u⁻¹ ^ 3 * (W.a₃ + C'.r * W.a₁ + 2 * C'.t)) - C.t ^ 2 - C.r * C.t * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s))) }.a₂ [PROOFSTEP] simp only [mul_inv, Units.val_mul] [GOAL] case a₃ R : Type u inst✝ : CommRing R W✝ : WeierstrassCurve R C✝ C C' : VariableChange R W : WeierstrassCurve R ⊢ { a₁ := ↑(C.u * C'.u)⁻¹ * (W.a₁ + 2 * (↑C'.u * C.s + C'.s)), a₂ := ↑(C.u * C'.u)⁻¹ ^ 2 * (W.a₂ - (↑C'.u * C.s + C'.s) * W.a₁ + 3 * (C.r * ↑C'.u ^ 2 + C'.r) - (↑C'.u * C.s + C'.s) ^ 2), a₃ := ↑(C.u * C'.u)⁻¹ ^ 3 * (W.a₃ + (C.r * ↑C'.u ^ 2 + C'.r) * W.a₁ + 2 * (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t)), a₄ := ↑(C.u * C'.u)⁻¹ ^ 4 * (W.a₄ - (↑C'.u * C.s + C'.s) * W.a₃ + 2 * (C.r * ↑C'.u ^ 2 + C'.r) * W.a₂ - (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t + (C.r * ↑C'.u ^ 2 + C'.r) * (↑C'.u * C.s + C'.s)) * W.a₁ + 3 * (C.r * ↑C'.u ^ 2 + C'.r) ^ 2 - 2 * (↑C'.u * C.s + C'.s) * (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t)), a₆ := ↑(C.u * C'.u)⁻¹ ^ 6 * (W.a₆ + (C.r * ↑C'.u ^ 2 + C'.r) * W.a₄ + (C.r * ↑C'.u ^ 2 + C'.r) ^ 2 * W.a₂ + (C.r * ↑C'.u ^ 2 + C'.r) ^ 3 - (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) * W.a₃ - (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) ^ 2 - (C.r * ↑C'.u ^ 2 + C'.r) * (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) * W.a₁) }.a₃ = { a₁ := ↑C.u⁻¹ * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s) + 2 * C.s), a₂ := ↑C.u⁻¹ ^ 2 * (↑C'.u⁻¹ ^ 2 * (W.a₂ - C'.s * W.a₁ + 3 * C'.r - C'.s ^ 2) - C.s * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s)) + 3 * C.r - C.s ^ 2), a₃ := ↑C.u⁻¹ ^ 3 * (↑C'.u⁻¹ ^ 3 * (W.a₃ + C'.r * W.a₁ + 2 * C'.t) + C.r * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s)) + 2 * C.t), a₄ := ↑C.u⁻¹ ^ 4 * (↑C'.u⁻¹ ^ 4 * (W.a₄ - C'.s * W.a₃ + 2 * C'.r * W.a₂ - (C'.t + C'.r * C'.s) * W.a₁ + 3 * C'.r ^ 2 - 2 * C'.s * C'.t) - C.s * (↑C'.u⁻¹ ^ 3 * (W.a₃ + C'.r * W.a₁ + 2 * C'.t)) + 2 * C.r * (↑C'.u⁻¹ ^ 2 * (W.a₂ - C'.s * W.a₁ + 3 * C'.r - C'.s ^ 2)) - (C.t + C.r * C.s) * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s)) + 3 * C.r ^ 2 - 2 * C.s * C.t), a₆ := ↑C.u⁻¹ ^ 6 * (↑C'.u⁻¹ ^ 6 * (W.a₆ + C'.r * W.a₄ + C'.r ^ 2 * W.a₂ + C'.r ^ 3 - C'.t * W.a₃ - C'.t ^ 2 - C'.r * C'.t * W.a₁) + C.r * (↑C'.u⁻¹ ^ 4 * (W.a₄ - C'.s * W.a₃ + 2 * C'.r * W.a₂ - (C'.t + C'.r * C'.s) * W.a₁ + 3 * C'.r ^ 2 - 2 * C'.s * C'.t)) + C.r ^ 2 * (↑C'.u⁻¹ ^ 2 * (W.a₂ - C'.s * W.a₁ + 3 * C'.r - C'.s ^ 2)) + C.r ^ 3 - C.t * (↑C'.u⁻¹ ^ 3 * (W.a₃ + C'.r * W.a₁ + 2 * C'.t)) - C.t ^ 2 - C.r * C.t * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s))) }.a₃ [PROOFSTEP] simp only [mul_inv, Units.val_mul] [GOAL] case a₄ R : Type u inst✝ : CommRing R W✝ : WeierstrassCurve R C✝ C C' : VariableChange R W : WeierstrassCurve R ⊢ { a₁ := ↑(C.u * C'.u)⁻¹ * (W.a₁ + 2 * (↑C'.u * C.s + C'.s)), a₂ := ↑(C.u * C'.u)⁻¹ ^ 2 * (W.a₂ - (↑C'.u * C.s + C'.s) * W.a₁ + 3 * (C.r * ↑C'.u ^ 2 + C'.r) - (↑C'.u * C.s + C'.s) ^ 2), a₃ := ↑(C.u * C'.u)⁻¹ ^ 3 * (W.a₃ + (C.r * ↑C'.u ^ 2 + C'.r) * W.a₁ + 2 * (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t)), a₄ := ↑(C.u * C'.u)⁻¹ ^ 4 * (W.a₄ - (↑C'.u * C.s + C'.s) * W.a₃ + 2 * (C.r * ↑C'.u ^ 2 + C'.r) * W.a₂ - (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t + (C.r * ↑C'.u ^ 2 + C'.r) * (↑C'.u * C.s + C'.s)) * W.a₁ + 3 * (C.r * ↑C'.u ^ 2 + C'.r) ^ 2 - 2 * (↑C'.u * C.s + C'.s) * (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t)), a₆ := ↑(C.u * C'.u)⁻¹ ^ 6 * (W.a₆ + (C.r * ↑C'.u ^ 2 + C'.r) * W.a₄ + (C.r * ↑C'.u ^ 2 + C'.r) ^ 2 * W.a₂ + (C.r * ↑C'.u ^ 2 + C'.r) ^ 3 - (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) * W.a₃ - (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) ^ 2 - (C.r * ↑C'.u ^ 2 + C'.r) * (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) * W.a₁) }.a₄ = { a₁ := ↑C.u⁻¹ * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s) + 2 * C.s), a₂ := ↑C.u⁻¹ ^ 2 * (↑C'.u⁻¹ ^ 2 * (W.a₂ - C'.s * W.a₁ + 3 * C'.r - C'.s ^ 2) - C.s * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s)) + 3 * C.r - C.s ^ 2), a₃ := ↑C.u⁻¹ ^ 3 * (↑C'.u⁻¹ ^ 3 * (W.a₃ + C'.r * W.a₁ + 2 * C'.t) + C.r * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s)) + 2 * C.t), a₄ := ↑C.u⁻¹ ^ 4 * (↑C'.u⁻¹ ^ 4 * (W.a₄ - C'.s * W.a₃ + 2 * C'.r * W.a₂ - (C'.t + C'.r * C'.s) * W.a₁ + 3 * C'.r ^ 2 - 2 * C'.s * C'.t) - C.s * (↑C'.u⁻¹ ^ 3 * (W.a₃ + C'.r * W.a₁ + 2 * C'.t)) + 2 * C.r * (↑C'.u⁻¹ ^ 2 * (W.a₂ - C'.s * W.a₁ + 3 * C'.r - C'.s ^ 2)) - (C.t + C.r * C.s) * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s)) + 3 * C.r ^ 2 - 2 * C.s * C.t), a₆ := ↑C.u⁻¹ ^ 6 * (↑C'.u⁻¹ ^ 6 * (W.a₆ + C'.r * W.a₄ + C'.r ^ 2 * W.a₂ + C'.r ^ 3 - C'.t * W.a₃ - C'.t ^ 2 - C'.r * C'.t * W.a₁) + C.r * (↑C'.u⁻¹ ^ 4 * (W.a₄ - C'.s * W.a₃ + 2 * C'.r * W.a₂ - (C'.t + C'.r * C'.s) * W.a₁ + 3 * C'.r ^ 2 - 2 * C'.s * C'.t)) + C.r ^ 2 * (↑C'.u⁻¹ ^ 2 * (W.a₂ - C'.s * W.a₁ + 3 * C'.r - C'.s ^ 2)) + C.r ^ 3 - C.t * (↑C'.u⁻¹ ^ 3 * (W.a₃ + C'.r * W.a₁ + 2 * C'.t)) - C.t ^ 2 - C.r * C.t * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s))) }.a₄ [PROOFSTEP] simp only [mul_inv, Units.val_mul] [GOAL] case a₆ R : Type u inst✝ : CommRing R W✝ : WeierstrassCurve R C✝ C C' : VariableChange R W : WeierstrassCurve R ⊢ { a₁ := ↑(C.u * C'.u)⁻¹ * (W.a₁ + 2 * (↑C'.u * C.s + C'.s)), a₂ := ↑(C.u * C'.u)⁻¹ ^ 2 * (W.a₂ - (↑C'.u * C.s + C'.s) * W.a₁ + 3 * (C.r * ↑C'.u ^ 2 + C'.r) - (↑C'.u * C.s + C'.s) ^ 2), a₃ := ↑(C.u * C'.u)⁻¹ ^ 3 * (W.a₃ + (C.r * ↑C'.u ^ 2 + C'.r) * W.a₁ + 2 * (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t)), a₄ := ↑(C.u * C'.u)⁻¹ ^ 4 * (W.a₄ - (↑C'.u * C.s + C'.s) * W.a₃ + 2 * (C.r * ↑C'.u ^ 2 + C'.r) * W.a₂ - (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t + (C.r * ↑C'.u ^ 2 + C'.r) * (↑C'.u * C.s + C'.s)) * W.a₁ + 3 * (C.r * ↑C'.u ^ 2 + C'.r) ^ 2 - 2 * (↑C'.u * C.s + C'.s) * (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t)), a₆ := ↑(C.u * C'.u)⁻¹ ^ 6 * (W.a₆ + (C.r * ↑C'.u ^ 2 + C'.r) * W.a₄ + (C.r * ↑C'.u ^ 2 + C'.r) ^ 2 * W.a₂ + (C.r * ↑C'.u ^ 2 + C'.r) ^ 3 - (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) * W.a₃ - (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) ^ 2 - (C.r * ↑C'.u ^ 2 + C'.r) * (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) * W.a₁) }.a₆ = { a₁ := ↑C.u⁻¹ * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s) + 2 * C.s), a₂ := ↑C.u⁻¹ ^ 2 * (↑C'.u⁻¹ ^ 2 * (W.a₂ - C'.s * W.a₁ + 3 * C'.r - C'.s ^ 2) - C.s * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s)) + 3 * C.r - C.s ^ 2), a₃ := ↑C.u⁻¹ ^ 3 * (↑C'.u⁻¹ ^ 3 * (W.a₃ + C'.r * W.a₁ + 2 * C'.t) + C.r * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s)) + 2 * C.t), a₄ := ↑C.u⁻¹ ^ 4 * (↑C'.u⁻¹ ^ 4 * (W.a₄ - C'.s * W.a₃ + 2 * C'.r * W.a₂ - (C'.t + C'.r * C'.s) * W.a₁ + 3 * C'.r ^ 2 - 2 * C'.s * C'.t) - C.s * (↑C'.u⁻¹ ^ 3 * (W.a₃ + C'.r * W.a₁ + 2 * C'.t)) + 2 * C.r * (↑C'.u⁻¹ ^ 2 * (W.a₂ - C'.s * W.a₁ + 3 * C'.r - C'.s ^ 2)) - (C.t + C.r * C.s) * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s)) + 3 * C.r ^ 2 - 2 * C.s * C.t), a₆ := ↑C.u⁻¹ ^ 6 * (↑C'.u⁻¹ ^ 6 * (W.a₆ + C'.r * W.a₄ + C'.r ^ 2 * W.a₂ + C'.r ^ 3 - C'.t * W.a₃ - C'.t ^ 2 - C'.r * C'.t * W.a₁) + C.r * (↑C'.u⁻¹ ^ 4 * (W.a₄ - C'.s * W.a₃ + 2 * C'.r * W.a₂ - (C'.t + C'.r * C'.s) * W.a₁ + 3 * C'.r ^ 2 - 2 * C'.s * C'.t)) + C.r ^ 2 * (↑C'.u⁻¹ ^ 2 * (W.a₂ - C'.s * W.a₁ + 3 * C'.r - C'.s ^ 2)) + C.r ^ 3 - C.t * (↑C'.u⁻¹ ^ 3 * (W.a₃ + C'.r * W.a₁ + 2 * C'.t)) - C.t ^ 2 - C.r * C.t * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s))) }.a₆ [PROOFSTEP] simp only [mul_inv, Units.val_mul] [GOAL] case a₁ R : Type u inst✝ : CommRing R W✝ : WeierstrassCurve R C✝ C C' : VariableChange R W : WeierstrassCurve R ⊢ ↑C.u⁻¹ * ↑C'.u⁻¹ * (W.a₁ + 2 * (↑C'.u * C.s + C'.s)) = ↑C.u⁻¹ * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s) + 2 * C.s) [PROOFSTEP] linear_combination (norm := ring1) ↑C.u⁻¹ * C.s * 2 * C'.u.inv_mul [GOAL] case a R : Type u inst✝ : CommRing R W✝ : WeierstrassCurve R C✝ C C' : VariableChange R W : WeierstrassCurve R ⊢ ↑C.u⁻¹ * ↑C'.u⁻¹ * (W.a₁ + 2 * (↑C'.u * C.s + C'.s)) - ↑C.u⁻¹ * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s) + 2 * C.s) - (↑C.u⁻¹ * C.s * 2 * (↑C'.u⁻¹ * ↑C'.u) - ↑C.u⁻¹ * C.s * 2 * 1) = 0 [PROOFSTEP] ring1 [GOAL] case a₂ R : Type u inst✝ : CommRing R W✝ : WeierstrassCurve R C✝ C C' : VariableChange R W : WeierstrassCurve R ⊢ (↑C.u⁻¹ * ↑C'.u⁻¹) ^ 2 * (W.a₂ - (↑C'.u * C.s + C'.s) * W.a₁ + 3 * (C.r * ↑C'.u ^ 2 + C'.r) - (↑C'.u * C.s + C'.s) ^ 2) = ↑C.u⁻¹ ^ 2 * (↑C'.u⁻¹ ^ 2 * (W.a₂ - C'.s * W.a₁ + 3 * C'.r - C'.s ^ 2) - C.s * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s)) + 3 * C.r - C.s ^ 2) [PROOFSTEP] linear_combination (norm := ring1) C.s * (-C'.s * 2 - W.a₁) * (↑C.u⁻¹ : R) ^ 2 * ↑C'.u⁻¹ * C'.u.inv_mul + (C.r * 3 - C.s ^ 2) * (↑C.u⁻¹ : R) ^ 2 * pow_mul_pow_eq_one 2 C'.u.inv_mul [GOAL] case a R : Type u inst✝ : CommRing R W✝ : WeierstrassCurve R C✝ C C' : VariableChange R W : WeierstrassCurve R ⊢ (↑C.u⁻¹ * ↑C'.u⁻¹) ^ 2 * (W.a₂ - (↑C'.u * C.s + C'.s) * W.a₁ + 3 * (C.r * ↑C'.u ^ 2 + C'.r) - (↑C'.u * C.s + C'.s) ^ 2) - ↑C.u⁻¹ ^ 2 * (↑C'.u⁻¹ ^ 2 * (W.a₂ - C'.s * W.a₁ + 3 * C'.r - C'.s ^ 2) - C.s * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s)) + 3 * C.r - C.s ^ 2) - (C.s * (-C'.s * 2 - W.a₁) * ↑C.u⁻¹ ^ 2 * ↑C'.u⁻¹ * (↑C'.u⁻¹ * ↑C'.u) + (C.r * 3 - C.s ^ 2) * ↑C.u⁻¹ ^ 2 * (↑C'.u⁻¹ ^ 2 * ↑C'.u ^ 2) - (C.s * (-C'.s * 2 - W.a₁) * ↑C.u⁻¹ ^ 2 * ↑C'.u⁻¹ * 1 + (C.r * 3 - C.s ^ 2) * ↑C.u⁻¹ ^ 2 * 1)) = 0 [PROOFSTEP] ring1 [GOAL] case a₃ R : Type u inst✝ : CommRing R W✝ : WeierstrassCurve R C✝ C C' : VariableChange R W : WeierstrassCurve R ⊢ (↑C.u⁻¹ * ↑C'.u⁻¹) ^ 3 * (W.a₃ + (C.r * ↑C'.u ^ 2 + C'.r) * W.a₁ + 2 * (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t)) = ↑C.u⁻¹ ^ 3 * (↑C'.u⁻¹ ^ 3 * (W.a₃ + C'.r * W.a₁ + 2 * C'.t) + C.r * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s)) + 2 * C.t) [PROOFSTEP] linear_combination (norm := ring1) C.r * (C'.s * 2 + W.a₁) * (↑C.u⁻¹ : R) ^ 3 * ↑C'.u⁻¹ * pow_mul_pow_eq_one 2 C'.u.inv_mul + C.t * 2 * (↑C.u⁻¹ : R) ^ 3 * pow_mul_pow_eq_one 3 C'.u.inv_mul [GOAL] case a R : Type u inst✝ : CommRing R W✝ : WeierstrassCurve R C✝ C C' : VariableChange R W : WeierstrassCurve R ⊢ (↑C.u⁻¹ * ↑C'.u⁻¹) ^ 3 * (W.a₃ + (C.r * ↑C'.u ^ 2 + C'.r) * W.a₁ + 2 * (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t)) - ↑C.u⁻¹ ^ 3 * (↑C'.u⁻¹ ^ 3 * (W.a₃ + C'.r * W.a₁ + 2 * C'.t) + C.r * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s)) + 2 * C.t) - (C.r * (C'.s * 2 + W.a₁) * ↑C.u⁻¹ ^ 3 * ↑C'.u⁻¹ * (↑C'.u⁻¹ ^ 2 * ↑C'.u ^ 2) + C.t * 2 * ↑C.u⁻¹ ^ 3 * (↑C'.u⁻¹ ^ 3 * ↑C'.u ^ 3) - (C.r * (C'.s * 2 + W.a₁) * ↑C.u⁻¹ ^ 3 * ↑C'.u⁻¹ * 1 + C.t * 2 * ↑C.u⁻¹ ^ 3 * 1)) = 0 [PROOFSTEP] ring1 [GOAL] case a₄ R : Type u inst✝ : CommRing R W✝ : WeierstrassCurve R C✝ C C' : VariableChange R W : WeierstrassCurve R ⊢ (↑C.u⁻¹ * ↑C'.u⁻¹) ^ 4 * (W.a₄ - (↑C'.u * C.s + C'.s) * W.a₃ + 2 * (C.r * ↑C'.u ^ 2 + C'.r) * W.a₂ - (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t + (C.r * ↑C'.u ^ 2 + C'.r) * (↑C'.u * C.s + C'.s)) * W.a₁ + 3 * (C.r * ↑C'.u ^ 2 + C'.r) ^ 2 - 2 * (↑C'.u * C.s + C'.s) * (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t)) = ↑C.u⁻¹ ^ 4 * (↑C'.u⁻¹ ^ 4 * (W.a₄ - C'.s * W.a₃ + 2 * C'.r * W.a₂ - (C'.t + C'.r * C'.s) * W.a₁ + 3 * C'.r ^ 2 - 2 * C'.s * C'.t) - C.s * (↑C'.u⁻¹ ^ 3 * (W.a₃ + C'.r * W.a₁ + 2 * C'.t)) + 2 * C.r * (↑C'.u⁻¹ ^ 2 * (W.a₂ - C'.s * W.a₁ + 3 * C'.r - C'.s ^ 2)) - (C.t + C.r * C.s) * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s)) + 3 * C.r ^ 2 - 2 * C.s * C.t) [PROOFSTEP] linear_combination (norm := ring1) C.s * (-W.a₃ - C'.r * W.a₁ - C'.t * 2) * (↑C.u⁻¹ : R) ^ 4 * (↑C'.u⁻¹ : R) ^ 3 * C'.u.inv_mul + (↑C.u⁻¹ : R) ^ 4 * (↑C'.u⁻¹ : R) ^ 2 * (C.r * C'.r * 6 + C.r * W.a₂ * 2 - C'.s * C.r * W.a₁ * 2 - C'.s ^ 2 * C.r * 2) * pow_mul_pow_eq_one 2 C'.u.inv_mul + -(↑C.u⁻¹ : R) ^ 4 * ↑C'.u⁻¹ * (C.s * C'.s * C.r * 2 + C.s * C.r * W.a₁ + C'.s * C.t * 2 + C.t * W.a₁) * pow_mul_pow_eq_one 3 C'.u.inv_mul + (↑C.u⁻¹ : R) ^ 4 * (C.r ^ 2 * 3 - C.s * C.t * 2) * pow_mul_pow_eq_one 4 C'.u.inv_mul [GOAL] case a R : Type u inst✝ : CommRing R W✝ : WeierstrassCurve R C✝ C C' : VariableChange R W : WeierstrassCurve R ⊢ (↑C.u⁻¹ * ↑C'.u⁻¹) ^ 4 * (W.a₄ - (↑C'.u * C.s + C'.s) * W.a₃ + 2 * (C.r * ↑C'.u ^ 2 + C'.r) * W.a₂ - (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t + (C.r * ↑C'.u ^ 2 + C'.r) * (↑C'.u * C.s + C'.s)) * W.a₁ + 3 * (C.r * ↑C'.u ^ 2 + C'.r) ^ 2 - 2 * (↑C'.u * C.s + C'.s) * (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t)) - ↑C.u⁻¹ ^ 4 * (↑C'.u⁻¹ ^ 4 * (W.a₄ - C'.s * W.a₃ + 2 * C'.r * W.a₂ - (C'.t + C'.r * C'.s) * W.a₁ + 3 * C'.r ^ 2 - 2 * C'.s * C'.t) - C.s * (↑C'.u⁻¹ ^ 3 * (W.a₃ + C'.r * W.a₁ + 2 * C'.t)) + 2 * C.r * (↑C'.u⁻¹ ^ 2 * (W.a₂ - C'.s * W.a₁ + 3 * C'.r - C'.s ^ 2)) - (C.t + C.r * C.s) * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s)) + 3 * C.r ^ 2 - 2 * C.s * C.t) - (C.s * (-W.a₃ - C'.r * W.a₁ - C'.t * 2) * ↑C.u⁻¹ ^ 4 * ↑C'.u⁻¹ ^ 3 * (↑C'.u⁻¹ * ↑C'.u) + ↑C.u⁻¹ ^ 4 * ↑C'.u⁻¹ ^ 2 * (C.r * C'.r * 6 + C.r * W.a₂ * 2 - C'.s * C.r * W.a₁ * 2 - C'.s ^ 2 * C.r * 2) * (↑C'.u⁻¹ ^ 2 * ↑C'.u ^ 2) + -↑C.u⁻¹ ^ 4 * ↑C'.u⁻¹ * (C.s * C'.s * C.r * 2 + C.s * C.r * W.a₁ + C'.s * C.t * 2 + C.t * W.a₁) * (↑C'.u⁻¹ ^ 3 * ↑C'.u ^ 3) + ↑C.u⁻¹ ^ 4 * (C.r ^ 2 * 3 - C.s * C.t * 2) * (↑C'.u⁻¹ ^ 4 * ↑C'.u ^ 4) - (C.s * (-W.a₃ - C'.r * W.a₁ - C'.t * 2) * ↑C.u⁻¹ ^ 4 * ↑C'.u⁻¹ ^ 3 * 1 + ↑C.u⁻¹ ^ 4 * ↑C'.u⁻¹ ^ 2 * (C.r * C'.r * 6 + C.r * W.a₂ * 2 - C'.s * C.r * W.a₁ * 2 - C'.s ^ 2 * C.r * 2) * 1 + -↑C.u⁻¹ ^ 4 * ↑C'.u⁻¹ * (C.s * C'.s * C.r * 2 + C.s * C.r * W.a₁ + C'.s * C.t * 2 + C.t * W.a₁) * 1 + ↑C.u⁻¹ ^ 4 * (C.r ^ 2 * 3 - C.s * C.t * 2) * 1)) = 0 [PROOFSTEP] ring1 [GOAL] case a₆ R : Type u inst✝ : CommRing R W✝ : WeierstrassCurve R C✝ C C' : VariableChange R W : WeierstrassCurve R ⊢ (↑C.u⁻¹ * ↑C'.u⁻¹) ^ 6 * (W.a₆ + (C.r * ↑C'.u ^ 2 + C'.r) * W.a₄ + (C.r * ↑C'.u ^ 2 + C'.r) ^ 2 * W.a₂ + (C.r * ↑C'.u ^ 2 + C'.r) ^ 3 - (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) * W.a₃ - (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) ^ 2 - (C.r * ↑C'.u ^ 2 + C'.r) * (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) * W.a₁) = ↑C.u⁻¹ ^ 6 * (↑C'.u⁻¹ ^ 6 * (W.a₆ + C'.r * W.a₄ + C'.r ^ 2 * W.a₂ + C'.r ^ 3 - C'.t * W.a₃ - C'.t ^ 2 - C'.r * C'.t * W.a₁) + C.r * (↑C'.u⁻¹ ^ 4 * (W.a₄ - C'.s * W.a₃ + 2 * C'.r * W.a₂ - (C'.t + C'.r * C'.s) * W.a₁ + 3 * C'.r ^ 2 - 2 * C'.s * C'.t)) + C.r ^ 2 * (↑C'.u⁻¹ ^ 2 * (W.a₂ - C'.s * W.a₁ + 3 * C'.r - C'.s ^ 2)) + C.r ^ 3 - C.t * (↑C'.u⁻¹ ^ 3 * (W.a₃ + C'.r * W.a₁ + 2 * C'.t)) - C.t ^ 2 - C.r * C.t * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s))) [PROOFSTEP] linear_combination (norm := ring1) C.r * (↑C.u⁻¹ : R) ^ 6 * (↑C'.u⁻¹ : R) ^ 4 * (C'.r * W.a₂ * 2 - C'.r * C'.s * W.a₁ + C'.r ^ 2 * 3 + W.a₄ - C'.s * C'.t * 2 - C'.s * W.a₃ - C'.t * W.a₁) * pow_mul_pow_eq_one 2 C'.u.inv_mul + -(↑C.u⁻¹ : R) ^ 6 * (↑C'.u⁻¹ : R) ^ 3 * C.t * (C'.r * W.a₁ + C'.t * 2 + W.a₃) * pow_mul_pow_eq_one 3 C'.u.inv_mul + C.r ^ 2 * (↑C.u⁻¹ : R) ^ 6 * (↑C'.u⁻¹ : R) ^ 2 * (C'.r * 3 + W.a₂ - C'.s * W.a₁ - C'.s ^ 2) * pow_mul_pow_eq_one 4 C'.u.inv_mul + -C.r * C.t * (↑C.u⁻¹ : R) ^ 6 * ↑C'.u⁻¹ * (C'.s * 2 + W.a₁) * pow_mul_pow_eq_one 5 C'.u.inv_mul + (↑C.u⁻¹ : R) ^ 6 * (C.r ^ 3 - C.t ^ 2) * pow_mul_pow_eq_one 6 C'.u.inv_mul [GOAL] case a R : Type u inst✝ : CommRing R W✝ : WeierstrassCurve R C✝ C C' : VariableChange R W : WeierstrassCurve R ⊢ (↑C.u⁻¹ * ↑C'.u⁻¹) ^ 6 * (W.a₆ + (C.r * ↑C'.u ^ 2 + C'.r) * W.a₄ + (C.r * ↑C'.u ^ 2 + C'.r) ^ 2 * W.a₂ + (C.r * ↑C'.u ^ 2 + C'.r) ^ 3 - (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) * W.a₃ - (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) ^ 2 - (C.r * ↑C'.u ^ 2 + C'.r) * (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) * W.a₁) - ↑C.u⁻¹ ^ 6 * (↑C'.u⁻¹ ^ 6 * (W.a₆ + C'.r * W.a₄ + C'.r ^ 2 * W.a₂ + C'.r ^ 3 - C'.t * W.a₃ - C'.t ^ 2 - C'.r * C'.t * W.a₁) + C.r * (↑C'.u⁻¹ ^ 4 * (W.a₄ - C'.s * W.a₃ + 2 * C'.r * W.a₂ - (C'.t + C'.r * C'.s) * W.a₁ + 3 * C'.r ^ 2 - 2 * C'.s * C'.t)) + C.r ^ 2 * (↑C'.u⁻¹ ^ 2 * (W.a₂ - C'.s * W.a₁ + 3 * C'.r - C'.s ^ 2)) + C.r ^ 3 - C.t * (↑C'.u⁻¹ ^ 3 * (W.a₃ + C'.r * W.a₁ + 2 * C'.t)) - C.t ^ 2 - C.r * C.t * (↑C'.u⁻¹ * (W.a₁ + 2 * C'.s))) - (C.r * ↑C.u⁻¹ ^ 6 * ↑C'.u⁻¹ ^ 4 * (C'.r * W.a₂ * 2 - C'.r * C'.s * W.a₁ + C'.r ^ 2 * 3 + W.a₄ - C'.s * C'.t * 2 - C'.s * W.a₃ - C'.t * W.a₁) * (↑C'.u⁻¹ ^ 2 * ↑C'.u ^ 2) + -↑C.u⁻¹ ^ 6 * ↑C'.u⁻¹ ^ 3 * C.t * (C'.r * W.a₁ + C'.t * 2 + W.a₃) * (↑C'.u⁻¹ ^ 3 * ↑C'.u ^ 3) + C.r ^ 2 * ↑C.u⁻¹ ^ 6 * ↑C'.u⁻¹ ^ 2 * (C'.r * 3 + W.a₂ - C'.s * W.a₁ - C'.s ^ 2) * (↑C'.u⁻¹ ^ 4 * ↑C'.u ^ 4) + -C.r * C.t * ↑C.u⁻¹ ^ 6 * ↑C'.u⁻¹ * (C'.s * 2 + W.a₁) * (↑C'.u⁻¹ ^ 5 * ↑C'.u ^ 5) + ↑C.u⁻¹ ^ 6 * (C.r ^ 3 - C.t ^ 2) * (↑C'.u⁻¹ ^ 6 * ↑C'.u ^ 6) - (C.r * ↑C.u⁻¹ ^ 6 * ↑C'.u⁻¹ ^ 4 * (C'.r * W.a₂ * 2 - C'.r * C'.s * W.a₁ + C'.r ^ 2 * 3 + W.a₄ - C'.s * C'.t * 2 - C'.s * W.a₃ - C'.t * W.a₁) * 1 + -↑C.u⁻¹ ^ 6 * ↑C'.u⁻¹ ^ 3 * C.t * (C'.r * W.a₁ + C'.t * 2 + W.a₃) * 1 + C.r ^ 2 * ↑C.u⁻¹ ^ 6 * ↑C'.u⁻¹ ^ 2 * (C'.r * 3 + W.a₂ - C'.s * W.a₁ - C'.s ^ 2) * 1 + -C.r * C.t * ↑C.u⁻¹ ^ 6 * ↑C'.u⁻¹ * (C'.s * 2 + W.a₁) * 1 + ↑C.u⁻¹ ^ 6 * (C.r ^ 3 - C.t ^ 2) * 1)) = 0 [PROOFSTEP] ring1 [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R C : VariableChange R ⊢ b₂ (variableChange W C) = ↑C.u⁻¹ ^ 2 * (b₂ W + 12 * C.r) [PROOFSTEP] simp only [b₂, variableChange_a₁, variableChange_a₂] [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R C : VariableChange R ⊢ (↑C.u⁻¹ * (W.a₁ + 2 * C.s)) ^ 2 + 4 * (↑C.u⁻¹ ^ 2 * (W.a₂ - C.s * W.a₁ + 3 * C.r - C.s ^ 2)) = ↑C.u⁻¹ ^ 2 * (W.a₁ ^ 2 + 4 * W.a₂ + 12 * C.r) [PROOFSTEP] ring1 [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R C : VariableChange R ⊢ b₄ (variableChange W C) = ↑C.u⁻¹ ^ 4 * (b₄ W + C.r * b₂ W + 6 * C.r ^ 2) [PROOFSTEP] simp only [b₂, b₄, variableChange_a₁, variableChange_a₃, variableChange_a₄] [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R C : VariableChange R ⊢ 2 * (↑C.u⁻¹ ^ 4 * (W.a₄ - C.s * W.a₃ + 2 * C.r * W.a₂ - (C.t + C.r * C.s) * W.a₁ + 3 * C.r ^ 2 - 2 * C.s * C.t)) + ↑C.u⁻¹ * (W.a₁ + 2 * C.s) * (↑C.u⁻¹ ^ 3 * (W.a₃ + C.r * W.a₁ + 2 * C.t)) = ↑C.u⁻¹ ^ 4 * (2 * W.a₄ + W.a₁ * W.a₃ + C.r * (W.a₁ ^ 2 + 4 * W.a₂) + 6 * C.r ^ 2) [PROOFSTEP] ring1 [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R C : VariableChange R ⊢ b₆ (variableChange W C) = ↑C.u⁻¹ ^ 6 * (b₆ W + 2 * C.r * b₄ W + C.r ^ 2 * b₂ W + 4 * C.r ^ 3) [PROOFSTEP] simp only [b₂, b₄, b₆, variableChange_a₃, variableChange_a₆] [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R C : VariableChange R ⊢ (↑C.u⁻¹ ^ 3 * (W.a₃ + C.r * W.a₁ + 2 * C.t)) ^ 2 + 4 * (↑C.u⁻¹ ^ 6 * (W.a₆ + C.r * W.a₄ + C.r ^ 2 * W.a₂ + C.r ^ 3 - C.t * W.a₃ - C.t ^ 2 - C.r * C.t * W.a₁)) = ↑C.u⁻¹ ^ 6 * (W.a₃ ^ 2 + 4 * W.a₆ + 2 * C.r * (2 * W.a₄ + W.a₁ * W.a₃) + C.r ^ 2 * (W.a₁ ^ 2 + 4 * W.a₂) + 4 * C.r ^ 3) [PROOFSTEP] ring1 [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R C : VariableChange R ⊢ b₈ (variableChange W C) = ↑C.u⁻¹ ^ 8 * (b₈ W + 3 * C.r * b₆ W + 3 * C.r ^ 2 * b₄ W + C.r ^ 3 * b₂ W + 3 * C.r ^ 4) [PROOFSTEP] simp only [b₂, b₄, b₆, b₈, variableChange_a₁, variableChange_a₂, variableChange_a₃, variableChange_a₄, variableChange_a₆] [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R C : VariableChange R ⊢ (↑C.u⁻¹ * (W.a₁ + 2 * C.s)) ^ 2 * (↑C.u⁻¹ ^ 6 * (W.a₆ + C.r * W.a₄ + C.r ^ 2 * W.a₂ + C.r ^ 3 - C.t * W.a₃ - C.t ^ 2 - C.r * C.t * W.a₁)) + 4 * (↑C.u⁻¹ ^ 2 * (W.a₂ - C.s * W.a₁ + 3 * C.r - C.s ^ 2)) * (↑C.u⁻¹ ^ 6 * (W.a₆ + C.r * W.a₄ + C.r ^ 2 * W.a₂ + C.r ^ 3 - C.t * W.a₃ - C.t ^ 2 - C.r * C.t * W.a₁)) - ↑C.u⁻¹ * (W.a₁ + 2 * C.s) * (↑C.u⁻¹ ^ 3 * (W.a₃ + C.r * W.a₁ + 2 * C.t)) * (↑C.u⁻¹ ^ 4 * (W.a₄ - C.s * W.a₃ + 2 * C.r * W.a₂ - (C.t + C.r * C.s) * W.a₁ + 3 * C.r ^ 2 - 2 * C.s * C.t)) + ↑C.u⁻¹ ^ 2 * (W.a₂ - C.s * W.a₁ + 3 * C.r - C.s ^ 2) * (↑C.u⁻¹ ^ 3 * (W.a₃ + C.r * W.a₁ + 2 * C.t)) ^ 2 - (↑C.u⁻¹ ^ 4 * (W.a₄ - C.s * W.a₃ + 2 * C.r * W.a₂ - (C.t + C.r * C.s) * W.a₁ + 3 * C.r ^ 2 - 2 * C.s * C.t)) ^ 2 = ↑C.u⁻¹ ^ 8 * (W.a₁ ^ 2 * W.a₆ + 4 * W.a₂ * W.a₆ - W.a₁ * W.a₃ * W.a₄ + W.a₂ * W.a₃ ^ 2 - W.a₄ ^ 2 + 3 * C.r * (W.a₃ ^ 2 + 4 * W.a₆) + 3 * C.r ^ 2 * (2 * W.a₄ + W.a₁ * W.a₃) + C.r ^ 3 * (W.a₁ ^ 2 + 4 * W.a₂) + 3 * C.r ^ 4) [PROOFSTEP] ring1 [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R C : VariableChange R ⊢ c₄ (variableChange W C) = ↑C.u⁻¹ ^ 4 * c₄ W [PROOFSTEP] simp only [c₄, variableChange_b₂, variableChange_b₄] [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R C : VariableChange R ⊢ (↑C.u⁻¹ ^ 2 * (b₂ W + 12 * C.r)) ^ 2 - 24 * (↑C.u⁻¹ ^ 4 * (b₄ W + C.r * b₂ W + 6 * C.r ^ 2)) = ↑C.u⁻¹ ^ 4 * (b₂ W ^ 2 - 24 * b₄ W) [PROOFSTEP] ring1 [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R C : VariableChange R ⊢ c₆ (variableChange W C) = ↑C.u⁻¹ ^ 6 * c₆ W [PROOFSTEP] simp only [c₆, variableChange_b₂, variableChange_b₄, variableChange_b₆] [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R C : VariableChange R ⊢ -(↑C.u⁻¹ ^ 2 * (b₂ W + 12 * C.r)) ^ 3 + 36 * (↑C.u⁻¹ ^ 2 * (b₂ W + 12 * C.r)) * (↑C.u⁻¹ ^ 4 * (b₄ W + C.r * b₂ W + 6 * C.r ^ 2)) - 216 * (↑C.u⁻¹ ^ 6 * (b₆ W + 2 * C.r * b₄ W + C.r ^ 2 * b₂ W + 4 * C.r ^ 3)) = ↑C.u⁻¹ ^ 6 * (-b₂ W ^ 3 + 36 * b₂ W * b₄ W - 216 * b₆ W) [PROOFSTEP] ring1 [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R C : VariableChange R ⊢ Δ (variableChange W C) = ↑C.u⁻¹ ^ 12 * Δ W [PROOFSTEP] simp only [b₂, b₄, b₆, b₈, Δ, variableChange_a₁, variableChange_a₂, variableChange_a₃, variableChange_a₄, variableChange_a₆] [GOAL] R : Type u inst✝ : CommRing R W : WeierstrassCurve R C : VariableChange R ⊢ -((↑C.u⁻¹ * (W.a₁ + 2 * C.s)) ^ 2 + 4 * (↑C.u⁻¹ ^ 2 * (W.a₂ - C.s * W.a₁ + 3 * C.r - C.s ^ 2))) ^ 2 * ((↑C.u⁻¹ * (W.a₁ + 2 * C.s)) ^ 2 * (↑C.u⁻¹ ^ 6 * (W.a₆ + C.r * W.a₄ + C.r ^ 2 * W.a₂ + C.r ^ 3 - C.t * W.a₃ - C.t ^ 2 - C.r * C.t * W.a₁)) + 4 * (↑C.u⁻¹ ^ 2 * (W.a₂ - C.s * W.a₁ + 3 * C.r - C.s ^ 2)) * (↑C.u⁻¹ ^ 6 * (W.a₆ + C.r * W.a₄ + C.r ^ 2 * W.a₂ + C.r ^ 3 - C.t * W.a₃ - C.t ^ 2 - C.r * C.t * W.a₁)) - ↑C.u⁻¹ * (W.a₁ + 2 * C.s) * (↑C.u⁻¹ ^ 3 * (W.a₃ + C.r * W.a₁ + 2 * C.t)) * (↑C.u⁻¹ ^ 4 * (W.a₄ - C.s * W.a₃ + 2 * C.r * W.a₂ - (C.t + C.r * C.s) * W.a₁ + 3 * C.r ^ 2 - 2 * C.s * C.t)) + ↑C.u⁻¹ ^ 2 * (W.a₂ - C.s * W.a₁ + 3 * C.r - C.s ^ 2) * (↑C.u⁻¹ ^ 3 * (W.a₃ + C.r * W.a₁ + 2 * C.t)) ^ 2 - (↑C.u⁻¹ ^ 4 * (W.a₄ - C.s * W.a₃ + 2 * C.r * W.a₂ - (C.t + C.r * C.s) * W.a₁ + 3 * C.r ^ 2 - 2 * C.s * C.t)) ^ 2) - 8 * (2 * (↑C.u⁻¹ ^ 4 * (W.a₄ - C.s * W.a₃ + 2 * C.r * W.a₂ - (C.t + C.r * C.s) * W.a₁ + 3 * C.r ^ 2 - 2 * C.s * C.t)) + ↑C.u⁻¹ * (W.a₁ + 2 * C.s) * (↑C.u⁻¹ ^ 3 * (W.a₃ + C.r * W.a₁ + 2 * C.t))) ^ 3 - 27 * ((↑C.u⁻¹ ^ 3 * (W.a₃ + C.r * W.a₁ + 2 * C.t)) ^ 2 + 4 * (↑C.u⁻¹ ^ 6 * (W.a₆ + C.r * W.a₄ + C.r ^ 2 * W.a₂ + C.r ^ 3 - C.t * W.a₃ - C.t ^ 2 - C.r * C.t * W.a₁))) ^ 2 + 9 * ((↑C.u⁻¹ * (W.a₁ + 2 * C.s)) ^ 2 + 4 * (↑C.u⁻¹ ^ 2 * (W.a₂ - C.s * W.a₁ + 3 * C.r - C.s ^ 2))) * (2 * (↑C.u⁻¹ ^ 4 * (W.a₄ - C.s * W.a₃ + 2 * C.r * W.a₂ - (C.t + C.r * C.s) * W.a₁ + 3 * C.r ^ 2 - 2 * C.s * C.t)) + ↑C.u⁻¹ * (W.a₁ + 2 * C.s) * (↑C.u⁻¹ ^ 3 * (W.a₃ + C.r * W.a₁ + 2 * C.t))) * ((↑C.u⁻¹ ^ 3 * (W.a₃ + C.r * W.a₁ + 2 * C.t)) ^ 2 + 4 * (↑C.u⁻¹ ^ 6 * (W.a₆ + C.r * W.a₄ + C.r ^ 2 * W.a₂ + C.r ^ 3 - C.t * W.a₃ - C.t ^ 2 - C.r * C.t * W.a₁))) = ↑C.u⁻¹ ^ 12 * (-(W.a₁ ^ 2 + 4 * W.a₂) ^ 2 * (W.a₁ ^ 2 * W.a₆ + 4 * W.a₂ * W.a₆ - W.a₁ * W.a₃ * W.a₄ + W.a₂ * W.a₃ ^ 2 - W.a₄ ^ 2) - 8 * (2 * W.a₄ + W.a₁ * W.a₃) ^ 3 - 27 * (W.a₃ ^ 2 + 4 * W.a₆) ^ 2 + 9 * (W.a₁ ^ 2 + 4 * W.a₂) * (2 * W.a₄ + W.a₁ * W.a₃) * (W.a₃ ^ 2 + 4 * W.a₆)) [PROOFSTEP] ring1 [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ b₂ (baseChange W A) = ↑(algebraMap R A) (b₂ W) [PROOFSTEP] simp only [b₂, baseChange_a₁, baseChange_a₂] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ ↑(algebraMap R A) W.a₁ ^ 2 + 4 * ↑(algebraMap R A) W.a₂ = ↑(algebraMap R A) (W.a₁ ^ 2 + 4 * W.a₂) [PROOFSTEP] map_simp [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ b₄ (baseChange W A) = ↑(algebraMap R A) (b₄ W) [PROOFSTEP] simp only [b₄, baseChange_a₁, baseChange_a₃, baseChange_a₄] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ 2 * ↑(algebraMap R A) W.a₄ + ↑(algebraMap R A) W.a₁ * ↑(algebraMap R A) W.a₃ = ↑(algebraMap R A) (2 * W.a₄ + W.a₁ * W.a₃) [PROOFSTEP] map_simp [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ b₆ (baseChange W A) = ↑(algebraMap R A) (b₆ W) [PROOFSTEP] simp only [b₆, baseChange_a₃, baseChange_a₆] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ ↑(algebraMap R A) W.a₃ ^ 2 + 4 * ↑(algebraMap R A) W.a₆ = ↑(algebraMap R A) (W.a₃ ^ 2 + 4 * W.a₆) [PROOFSTEP] map_simp [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ b₈ (baseChange W A) = ↑(algebraMap R A) (b₈ W) [PROOFSTEP] simp only [b₈, baseChange_a₁, baseChange_a₂, baseChange_a₃, baseChange_a₄, baseChange_a₆] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ ↑(algebraMap R A) W.a₁ ^ 2 * ↑(algebraMap R A) W.a₆ + 4 * ↑(algebraMap R A) W.a₂ * ↑(algebraMap R A) W.a₆ - ↑(algebraMap R A) W.a₁ * ↑(algebraMap R A) W.a₃ * ↑(algebraMap R A) W.a₄ + ↑(algebraMap R A) W.a₂ * ↑(algebraMap R A) W.a₃ ^ 2 - ↑(algebraMap R A) W.a₄ ^ 2 = ↑(algebraMap R A) (W.a₁ ^ 2 * W.a₆ + 4 * W.a₂ * W.a₆ - W.a₁ * W.a₃ * W.a₄ + W.a₂ * W.a₃ ^ 2 - W.a₄ ^ 2) [PROOFSTEP] map_simp [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ c₄ (baseChange W A) = ↑(algebraMap R A) (c₄ W) [PROOFSTEP] simp only [c₄, baseChange_b₂, baseChange_b₄] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ ↑(algebraMap R A) (b₂ W) ^ 2 - 24 * ↑(algebraMap R A) (b₄ W) = ↑(algebraMap R A) (b₂ W ^ 2 - 24 * b₄ W) [PROOFSTEP] map_simp [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ c₆ (baseChange W A) = ↑(algebraMap R A) (c₆ W) [PROOFSTEP] simp only [c₆, baseChange_b₂, baseChange_b₄, baseChange_b₆] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ -↑(algebraMap R A) (b₂ W) ^ 3 + 36 * ↑(algebraMap R A) (b₂ W) * ↑(algebraMap R A) (b₄ W) - 216 * ↑(algebraMap R A) (b₆ W) = ↑(algebraMap R A) (-b₂ W ^ 3 + 36 * b₂ W * b₄ W - 216 * b₆ W) [PROOFSTEP] map_simp [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ Δ (baseChange W A) = ↑(algebraMap R A) (Δ W) [PROOFSTEP] simp only [Δ, baseChange_b₂, baseChange_b₄, baseChange_b₆, baseChange_b₈] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ -↑(algebraMap R A) (b₂ W) ^ 2 * ↑(algebraMap R A) (b₈ W) - 8 * ↑(algebraMap R A) (b₄ W) ^ 3 - 27 * ↑(algebraMap R A) (b₆ W) ^ 2 + 9 * ↑(algebraMap R A) (b₂ W) * ↑(algebraMap R A) (b₄ W) * ↑(algebraMap R A) (b₆ W) = ↑(algebraMap R A) (-b₂ W ^ 2 * b₈ W - 8 * b₄ W ^ 3 - 27 * b₆ W ^ 2 + 9 * b₂ W * b₄ W * b₆ W) [PROOFSTEP] map_simp [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ baseChange W R = W [PROOFSTEP] ext [GOAL] case a₁ R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ (baseChange W R).a₁ = W.a₁ [PROOFSTEP] rfl [GOAL] case a₂ R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ (baseChange W R).a₂ = W.a₂ [PROOFSTEP] rfl [GOAL] case a₃ R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ (baseChange W R).a₃ = W.a₃ [PROOFSTEP] rfl [GOAL] case a₄ R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ (baseChange W R).a₄ = W.a₄ [PROOFSTEP] rfl [GOAL] case a₆ R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ (baseChange W R).a₆ = W.a₆ [PROOFSTEP] rfl [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ baseChange (baseChange W A) B = baseChange W B [PROOFSTEP] ext [GOAL] case a₁ R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ (baseChange (baseChange W A) B).a₁ = (baseChange W B).a₁ [PROOFSTEP] exact (IsScalarTower.algebraMap_apply R A B _).symm [GOAL] case a₂ R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ (baseChange (baseChange W A) B).a₂ = (baseChange W B).a₂ [PROOFSTEP] exact (IsScalarTower.algebraMap_apply R A B _).symm [GOAL] case a₃ R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ (baseChange (baseChange W A) B).a₃ = (baseChange W B).a₃ [PROOFSTEP] exact (IsScalarTower.algebraMap_apply R A B _).symm [GOAL] case a₄ R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ (baseChange (baseChange W A) B).a₄ = (baseChange W B).a₄ [PROOFSTEP] exact (IsScalarTower.algebraMap_apply R A B _).symm [GOAL] case a₆ R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ (baseChange (baseChange W A) B).a₆ = (baseChange W B).a₆ [PROOFSTEP] exact (IsScalarTower.algebraMap_apply R A B _).symm [GOAL] R : Type u inst✝⁶ : CommRing R W✝ : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B h : Function.Injective ↑(algebraMap R A) W W' : WeierstrassCurve R h1 : (fun W => baseChange W A) W = (fun W => baseChange W A) W' ⊢ W = W' [PROOFSTEP] rcases mk.inj h1 with ⟨_, _, _, _, _⟩ [GOAL] case intro.intro.intro.intro R : Type u inst✝⁶ : CommRing R W✝ : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B h : Function.Injective ↑(algebraMap R A) W W' : WeierstrassCurve R h1 : (fun W => baseChange W A) W = (fun W => baseChange W A) W' left✝³ : ↑(algebraMap R A) W.a₁ = ↑(algebraMap R A) W'.a₁ left✝² : ↑(algebraMap R A) W.a₂ = ↑(algebraMap R A) W'.a₂ left✝¹ : ↑(algebraMap R A) W.a₃ = ↑(algebraMap R A) W'.a₃ left✝ : ↑(algebraMap R A) W.a₄ = ↑(algebraMap R A) W'.a₄ right✝ : ↑(algebraMap R A) W.a₆ = ↑(algebraMap R A) W'.a₆ ⊢ W = W' [PROOFSTEP] ext [GOAL] case intro.intro.intro.intro.a₁ R : Type u inst✝⁶ : CommRing R W✝ : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B h : Function.Injective ↑(algebraMap R A) W W' : WeierstrassCurve R h1 : (fun W => baseChange W A) W = (fun W => baseChange W A) W' left✝³ : ↑(algebraMap R A) W.a₁ = ↑(algebraMap R A) W'.a₁ left✝² : ↑(algebraMap R A) W.a₂ = ↑(algebraMap R A) W'.a₂ left✝¹ : ↑(algebraMap R A) W.a₃ = ↑(algebraMap R A) W'.a₃ left✝ : ↑(algebraMap R A) W.a₄ = ↑(algebraMap R A) W'.a₄ right✝ : ↑(algebraMap R A) W.a₆ = ↑(algebraMap R A) W'.a₆ ⊢ W.a₁ = W'.a₁ [PROOFSTEP] apply_fun _ using h [GOAL] case intro.intro.intro.intro.a₂ R : Type u inst✝⁶ : CommRing R W✝ : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B h : Function.Injective ↑(algebraMap R A) W W' : WeierstrassCurve R h1 : (fun W => baseChange W A) W = (fun W => baseChange W A) W' left✝³ : ↑(algebraMap R A) W.a₁ = ↑(algebraMap R A) W'.a₁ left✝² : ↑(algebraMap R A) W.a₂ = ↑(algebraMap R A) W'.a₂ left✝¹ : ↑(algebraMap R A) W.a₃ = ↑(algebraMap R A) W'.a₃ left✝ : ↑(algebraMap R A) W.a₄ = ↑(algebraMap R A) W'.a₄ right✝ : ↑(algebraMap R A) W.a₆ = ↑(algebraMap R A) W'.a₆ ⊢ W.a₂ = W'.a₂ [PROOFSTEP] apply_fun _ using h [GOAL] case intro.intro.intro.intro.a₃ R : Type u inst✝⁶ : CommRing R W✝ : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B h : Function.Injective ↑(algebraMap R A) W W' : WeierstrassCurve R h1 : (fun W => baseChange W A) W = (fun W => baseChange W A) W' left✝³ : ↑(algebraMap R A) W.a₁ = ↑(algebraMap R A) W'.a₁ left✝² : ↑(algebraMap R A) W.a₂ = ↑(algebraMap R A) W'.a₂ left✝¹ : ↑(algebraMap R A) W.a₃ = ↑(algebraMap R A) W'.a₃ left✝ : ↑(algebraMap R A) W.a₄ = ↑(algebraMap R A) W'.a₄ right✝ : ↑(algebraMap R A) W.a₆ = ↑(algebraMap R A) W'.a₆ ⊢ W.a₃ = W'.a₃ [PROOFSTEP] apply_fun _ using h [GOAL] case intro.intro.intro.intro.a₄ R : Type u inst✝⁶ : CommRing R W✝ : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B h : Function.Injective ↑(algebraMap R A) W W' : WeierstrassCurve R h1 : (fun W => baseChange W A) W = (fun W => baseChange W A) W' left✝³ : ↑(algebraMap R A) W.a₁ = ↑(algebraMap R A) W'.a₁ left✝² : ↑(algebraMap R A) W.a₂ = ↑(algebraMap R A) W'.a₂ left✝¹ : ↑(algebraMap R A) W.a₃ = ↑(algebraMap R A) W'.a₃ left✝ : ↑(algebraMap R A) W.a₄ = ↑(algebraMap R A) W'.a₄ right✝ : ↑(algebraMap R A) W.a₆ = ↑(algebraMap R A) W'.a₆ ⊢ W.a₄ = W'.a₄ [PROOFSTEP] apply_fun _ using h [GOAL] case intro.intro.intro.intro.a₆ R : Type u inst✝⁶ : CommRing R W✝ : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B h : Function.Injective ↑(algebraMap R A) W W' : WeierstrassCurve R h1 : (fun W => baseChange W A) W = (fun W => baseChange W A) W' left✝³ : ↑(algebraMap R A) W.a₁ = ↑(algebraMap R A) W'.a₁ left✝² : ↑(algebraMap R A) W.a₂ = ↑(algebraMap R A) W'.a₂ left✝¹ : ↑(algebraMap R A) W.a₃ = ↑(algebraMap R A) W'.a₃ left✝ : ↑(algebraMap R A) W.a₄ = ↑(algebraMap R A) W'.a₄ right✝ : ↑(algebraMap R A) W.a₆ = ↑(algebraMap R A) W'.a₆ ⊢ W.a₆ = W'.a₆ [PROOFSTEP] apply_fun _ using h [GOAL] case intro.intro.intro.intro.a₁ R : Type u inst✝⁶ : CommRing R W✝ : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B h : Function.Injective ↑(algebraMap R A) W W' : WeierstrassCurve R h1 : (fun W => baseChange W A) W = (fun W => baseChange W A) W' left✝³ : ↑(algebraMap R A) W.a₁ = ↑(algebraMap R A) W'.a₁ left✝² : ↑(algebraMap R A) W.a₂ = ↑(algebraMap R A) W'.a₂ left✝¹ : ↑(algebraMap R A) W.a₃ = ↑(algebraMap R A) W'.a₃ left✝ : ↑(algebraMap R A) W.a₄ = ↑(algebraMap R A) W'.a₄ right✝ : ↑(algebraMap R A) W.a₆ = ↑(algebraMap R A) W'.a₆ ⊢ ↑(algebraMap R A) W.a₁ = ↑(algebraMap R A) W'.a₁ [PROOFSTEP] assumption [GOAL] case intro.intro.intro.intro.a₂ R : Type u inst✝⁶ : CommRing R W✝ : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B h : Function.Injective ↑(algebraMap R A) W W' : WeierstrassCurve R h1 : (fun W => baseChange W A) W = (fun W => baseChange W A) W' left✝³ : ↑(algebraMap R A) W.a₁ = ↑(algebraMap R A) W'.a₁ left✝² : ↑(algebraMap R A) W.a₂ = ↑(algebraMap R A) W'.a₂ left✝¹ : ↑(algebraMap R A) W.a₃ = ↑(algebraMap R A) W'.a₃ left✝ : ↑(algebraMap R A) W.a₄ = ↑(algebraMap R A) W'.a₄ right✝ : ↑(algebraMap R A) W.a₆ = ↑(algebraMap R A) W'.a₆ ⊢ ↑(algebraMap R A) W.a₂ = ↑(algebraMap R A) W'.a₂ [PROOFSTEP] assumption [GOAL] case intro.intro.intro.intro.a₃ R : Type u inst✝⁶ : CommRing R W✝ : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B h : Function.Injective ↑(algebraMap R A) W W' : WeierstrassCurve R h1 : (fun W => baseChange W A) W = (fun W => baseChange W A) W' left✝³ : ↑(algebraMap R A) W.a₁ = ↑(algebraMap R A) W'.a₁ left✝² : ↑(algebraMap R A) W.a₂ = ↑(algebraMap R A) W'.a₂ left✝¹ : ↑(algebraMap R A) W.a₃ = ↑(algebraMap R A) W'.a₃ left✝ : ↑(algebraMap R A) W.a₄ = ↑(algebraMap R A) W'.a₄ right✝ : ↑(algebraMap R A) W.a₆ = ↑(algebraMap R A) W'.a₆ ⊢ ↑(algebraMap R A) W.a₃ = ↑(algebraMap R A) W'.a₃ [PROOFSTEP] assumption [GOAL] case intro.intro.intro.intro.a₄ R : Type u inst✝⁶ : CommRing R W✝ : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B h : Function.Injective ↑(algebraMap R A) W W' : WeierstrassCurve R h1 : (fun W => baseChange W A) W = (fun W => baseChange W A) W' left✝³ : ↑(algebraMap R A) W.a₁ = ↑(algebraMap R A) W'.a₁ left✝² : ↑(algebraMap R A) W.a₂ = ↑(algebraMap R A) W'.a₂ left✝¹ : ↑(algebraMap R A) W.a₃ = ↑(algebraMap R A) W'.a₃ left✝ : ↑(algebraMap R A) W.a₄ = ↑(algebraMap R A) W'.a₄ right✝ : ↑(algebraMap R A) W.a₆ = ↑(algebraMap R A) W'.a₆ ⊢ ↑(algebraMap R A) W.a₄ = ↑(algebraMap R A) W'.a₄ [PROOFSTEP] assumption [GOAL] case intro.intro.intro.intro.a₆ R : Type u inst✝⁶ : CommRing R W✝ : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B h : Function.Injective ↑(algebraMap R A) W W' : WeierstrassCurve R h1 : (fun W => baseChange W A) W = (fun W => baseChange W A) W' left✝³ : ↑(algebraMap R A) W.a₁ = ↑(algebraMap R A) W'.a₁ left✝² : ↑(algebraMap R A) W.a₂ = ↑(algebraMap R A) W'.a₂ left✝¹ : ↑(algebraMap R A) W.a₃ = ↑(algebraMap R A) W'.a₃ left✝ : ↑(algebraMap R A) W.a₄ = ↑(algebraMap R A) W'.a₄ right✝ : ↑(algebraMap R A) W.a₆ = ↑(algebraMap R A) W'.a₆ ⊢ ↑(algebraMap R A) W.a₆ = ↑(algebraMap R A) W'.a₆ [PROOFSTEP] assumption [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C : VariableChange R ⊢ baseChange A id = id [PROOFSTEP] simp only [id, baseChange] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C : VariableChange R ⊢ { u := ↑(Units.map ↑(algebraMap R A)) 1, r := ↑(algebraMap R A) 0, s := ↑(algebraMap R A) 0, t := ↑(algebraMap R A) 0 } = { u := 1, r := 0, s := 0, t := 0 } [PROOFSTEP] ext [GOAL] case u.a R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C : VariableChange R ⊢ ↑{ u := ↑(Units.map ↑(algebraMap R A)) 1, r := ↑(algebraMap R A) 0, s := ↑(algebraMap R A) 0, t := ↑(algebraMap R A) 0 }.u = ↑{ u := 1, r := 0, s := 0, t := 0 }.u [PROOFSTEP] simp only [map_one, Units.val_one, map_zero] [GOAL] case r R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C : VariableChange R ⊢ { u := ↑(Units.map ↑(algebraMap R A)) 1, r := ↑(algebraMap R A) 0, s := ↑(algebraMap R A) 0, t := ↑(algebraMap R A) 0 }.r = { u := 1, r := 0, s := 0, t := 0 }.r [PROOFSTEP] simp only [map_one, Units.val_one, map_zero] [GOAL] case s R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C : VariableChange R ⊢ { u := ↑(Units.map ↑(algebraMap R A)) 1, r := ↑(algebraMap R A) 0, s := ↑(algebraMap R A) 0, t := ↑(algebraMap R A) 0 }.s = { u := 1, r := 0, s := 0, t := 0 }.s [PROOFSTEP] simp only [map_one, Units.val_one, map_zero] [GOAL] case t R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C : VariableChange R ⊢ { u := ↑(Units.map ↑(algebraMap R A)) 1, r := ↑(algebraMap R A) 0, s := ↑(algebraMap R A) 0, t := ↑(algebraMap R A) 0 }.t = { u := 1, r := 0, s := 0, t := 0 }.t [PROOFSTEP] simp only [map_one, Units.val_one, map_zero] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C C' : VariableChange R ⊢ baseChange A (comp C C') = comp (baseChange A C) (baseChange A C') [PROOFSTEP] simp only [comp, baseChange] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C C' : VariableChange R ⊢ { u := ↑(Units.map ↑(algebraMap R A)) (C.u * C'.u), r := ↑(algebraMap R A) (C.r * ↑C'.u ^ 2 + C'.r), s := ↑(algebraMap R A) (↑C'.u * C.s + C'.s), t := ↑(algebraMap R A) (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) } = { u := ↑(Units.map ↑(algebraMap R A)) C.u * ↑(Units.map ↑(algebraMap R A)) C'.u, r := ↑(algebraMap R A) C.r * ↑(↑(Units.map ↑(algebraMap R A)) C'.u) ^ 2 + ↑(algebraMap R A) C'.r, s := ↑(↑(Units.map ↑(algebraMap R A)) C'.u) * ↑(algebraMap R A) C.s + ↑(algebraMap R A) C'.s, t := ↑(algebraMap R A) C.t * ↑(↑(Units.map ↑(algebraMap R A)) C'.u) ^ 3 + ↑(algebraMap R A) C.r * ↑(algebraMap R A) C'.s * ↑(↑(Units.map ↑(algebraMap R A)) C'.u) ^ 2 + ↑(algebraMap R A) C'.t } [PROOFSTEP] ext [GOAL] case u.a R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C C' : VariableChange R ⊢ ↑{ u := ↑(Units.map ↑(algebraMap R A)) (C.u * C'.u), r := ↑(algebraMap R A) (C.r * ↑C'.u ^ 2 + C'.r), s := ↑(algebraMap R A) (↑C'.u * C.s + C'.s), t := ↑(algebraMap R A) (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) }.u = ↑{ u := ↑(Units.map ↑(algebraMap R A)) C.u * ↑(Units.map ↑(algebraMap R A)) C'.u, r := ↑(algebraMap R A) C.r * ↑(↑(Units.map ↑(algebraMap R A)) C'.u) ^ 2 + ↑(algebraMap R A) C'.r, s := ↑(↑(Units.map ↑(algebraMap R A)) C'.u) * ↑(algebraMap R A) C.s + ↑(algebraMap R A) C'.s, t := ↑(algebraMap R A) C.t * ↑(↑(Units.map ↑(algebraMap R A)) C'.u) ^ 3 + ↑(algebraMap R A) C.r * ↑(algebraMap R A) C'.s * ↑(↑(Units.map ↑(algebraMap R A)) C'.u) ^ 2 + ↑(algebraMap R A) C'.t }.u [PROOFSTEP] simp only [Units.coe_map, Units.coe_map_inv, MonoidHom.coe_coe, map_ofNat, map_neg, map_add, map_sub, map_mul, map_pow] [GOAL] case r R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C C' : VariableChange R ⊢ { u := ↑(Units.map ↑(algebraMap R A)) (C.u * C'.u), r := ↑(algebraMap R A) (C.r * ↑C'.u ^ 2 + C'.r), s := ↑(algebraMap R A) (↑C'.u * C.s + C'.s), t := ↑(algebraMap R A) (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) }.r = { u := ↑(Units.map ↑(algebraMap R A)) C.u * ↑(Units.map ↑(algebraMap R A)) C'.u, r := ↑(algebraMap R A) C.r * ↑(↑(Units.map ↑(algebraMap R A)) C'.u) ^ 2 + ↑(algebraMap R A) C'.r, s := ↑(↑(Units.map ↑(algebraMap R A)) C'.u) * ↑(algebraMap R A) C.s + ↑(algebraMap R A) C'.s, t := ↑(algebraMap R A) C.t * ↑(↑(Units.map ↑(algebraMap R A)) C'.u) ^ 3 + ↑(algebraMap R A) C.r * ↑(algebraMap R A) C'.s * ↑(↑(Units.map ↑(algebraMap R A)) C'.u) ^ 2 + ↑(algebraMap R A) C'.t }.r [PROOFSTEP] simp only [Units.coe_map, Units.coe_map_inv, MonoidHom.coe_coe, map_ofNat, map_neg, map_add, map_sub, map_mul, map_pow] [GOAL] case s R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C C' : VariableChange R ⊢ { u := ↑(Units.map ↑(algebraMap R A)) (C.u * C'.u), r := ↑(algebraMap R A) (C.r * ↑C'.u ^ 2 + C'.r), s := ↑(algebraMap R A) (↑C'.u * C.s + C'.s), t := ↑(algebraMap R A) (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) }.s = { u := ↑(Units.map ↑(algebraMap R A)) C.u * ↑(Units.map ↑(algebraMap R A)) C'.u, r := ↑(algebraMap R A) C.r * ↑(↑(Units.map ↑(algebraMap R A)) C'.u) ^ 2 + ↑(algebraMap R A) C'.r, s := ↑(↑(Units.map ↑(algebraMap R A)) C'.u) * ↑(algebraMap R A) C.s + ↑(algebraMap R A) C'.s, t := ↑(algebraMap R A) C.t * ↑(↑(Units.map ↑(algebraMap R A)) C'.u) ^ 3 + ↑(algebraMap R A) C.r * ↑(algebraMap R A) C'.s * ↑(↑(Units.map ↑(algebraMap R A)) C'.u) ^ 2 + ↑(algebraMap R A) C'.t }.s [PROOFSTEP] simp only [Units.coe_map, Units.coe_map_inv, MonoidHom.coe_coe, map_ofNat, map_neg, map_add, map_sub, map_mul, map_pow] [GOAL] case t R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C C' : VariableChange R ⊢ { u := ↑(Units.map ↑(algebraMap R A)) (C.u * C'.u), r := ↑(algebraMap R A) (C.r * ↑C'.u ^ 2 + C'.r), s := ↑(algebraMap R A) (↑C'.u * C.s + C'.s), t := ↑(algebraMap R A) (C.t * ↑C'.u ^ 3 + C.r * C'.s * ↑C'.u ^ 2 + C'.t) }.t = { u := ↑(Units.map ↑(algebraMap R A)) C.u * ↑(Units.map ↑(algebraMap R A)) C'.u, r := ↑(algebraMap R A) C.r * ↑(↑(Units.map ↑(algebraMap R A)) C'.u) ^ 2 + ↑(algebraMap R A) C'.r, s := ↑(↑(Units.map ↑(algebraMap R A)) C'.u) * ↑(algebraMap R A) C.s + ↑(algebraMap R A) C'.s, t := ↑(algebraMap R A) C.t * ↑(↑(Units.map ↑(algebraMap R A)) C'.u) ^ 3 + ↑(algebraMap R A) C.r * ↑(algebraMap R A) C'.s * ↑(↑(Units.map ↑(algebraMap R A)) C'.u) ^ 2 + ↑(algebraMap R A) C'.t }.t [PROOFSTEP] simp only [Units.coe_map, Units.coe_map_inv, MonoidHom.coe_coe, map_ofNat, map_neg, map_add, map_sub, map_mul, map_pow] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C : VariableChange R ⊢ baseChange B (baseChange A C) = baseChange B C [PROOFSTEP] ext [GOAL] case u.a R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C : VariableChange R ⊢ ↑(baseChange B (baseChange A C)).u = ↑(baseChange B C).u [PROOFSTEP] exact (IsScalarTower.algebraMap_apply R A B _).symm [GOAL] case r R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C : VariableChange R ⊢ (baseChange B (baseChange A C)).r = (baseChange B C).r [PROOFSTEP] exact (IsScalarTower.algebraMap_apply R A B _).symm [GOAL] case s R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C : VariableChange R ⊢ (baseChange B (baseChange A C)).s = (baseChange B C).s [PROOFSTEP] exact (IsScalarTower.algebraMap_apply R A B _).symm [GOAL] case t R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C : VariableChange R ⊢ (baseChange B (baseChange A C)).t = (baseChange B C).t [PROOFSTEP] exact (IsScalarTower.algebraMap_apply R A B _).symm [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C✝ : VariableChange R h : Function.Injective ↑(algebraMap R A) C C' : VariableChange R h1 : baseChange A C = baseChange A C' ⊢ C = C' [PROOFSTEP] rcases mk.inj h1 with ⟨h1, _, _, _⟩ [GOAL] case intro.intro.intro R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C✝ : VariableChange R h : Function.Injective ↑(algebraMap R A) C C' : VariableChange R h1✝ : baseChange A C = baseChange A C' h1 : ↑(Units.map ↑(algebraMap R A)) C.u = ↑(Units.map ↑(algebraMap R A)) C'.u left✝¹ : ↑(algebraMap R A) C.r = ↑(algebraMap R A) C'.r left✝ : ↑(algebraMap R A) C.s = ↑(algebraMap R A) C'.s right✝ : ↑(algebraMap R A) C.t = ↑(algebraMap R A) C'.t ⊢ C = C' [PROOFSTEP] replace h1 := (Units.mk.inj h1).left [GOAL] case intro.intro.intro R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C✝ : VariableChange R h : Function.Injective ↑(algebraMap R A) C C' : VariableChange R h1✝ : baseChange A C = baseChange A C' left✝¹ : ↑(algebraMap R A) C.r = ↑(algebraMap R A) C'.r left✝ : ↑(algebraMap R A) C.s = ↑(algebraMap R A) C'.s right✝ : ↑(algebraMap R A) C.t = ↑(algebraMap R A) C'.t h1 : ↑↑(algebraMap R A) ↑C.u = ↑↑(algebraMap R A) ↑C'.u ⊢ C = C' [PROOFSTEP] ext [GOAL] case intro.intro.intro.u.a R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C✝ : VariableChange R h : Function.Injective ↑(algebraMap R A) C C' : VariableChange R h1✝ : baseChange A C = baseChange A C' left✝¹ : ↑(algebraMap R A) C.r = ↑(algebraMap R A) C'.r left✝ : ↑(algebraMap R A) C.s = ↑(algebraMap R A) C'.s right✝ : ↑(algebraMap R A) C.t = ↑(algebraMap R A) C'.t h1 : ↑↑(algebraMap R A) ↑C.u = ↑↑(algebraMap R A) ↑C'.u ⊢ ↑C.u = ↑C'.u [PROOFSTEP] apply_fun _ using h [GOAL] case intro.intro.intro.r R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C✝ : VariableChange R h : Function.Injective ↑(algebraMap R A) C C' : VariableChange R h1✝ : baseChange A C = baseChange A C' left✝¹ : ↑(algebraMap R A) C.r = ↑(algebraMap R A) C'.r left✝ : ↑(algebraMap R A) C.s = ↑(algebraMap R A) C'.s right✝ : ↑(algebraMap R A) C.t = ↑(algebraMap R A) C'.t h1 : ↑↑(algebraMap R A) ↑C.u = ↑↑(algebraMap R A) ↑C'.u ⊢ C.r = C'.r [PROOFSTEP] apply_fun _ using h [GOAL] case intro.intro.intro.s R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C✝ : VariableChange R h : Function.Injective ↑(algebraMap R A) C C' : VariableChange R h1✝ : baseChange A C = baseChange A C' left✝¹ : ↑(algebraMap R A) C.r = ↑(algebraMap R A) C'.r left✝ : ↑(algebraMap R A) C.s = ↑(algebraMap R A) C'.s right✝ : ↑(algebraMap R A) C.t = ↑(algebraMap R A) C'.t h1 : ↑↑(algebraMap R A) ↑C.u = ↑↑(algebraMap R A) ↑C'.u ⊢ C.s = C'.s [PROOFSTEP] apply_fun _ using h [GOAL] case intro.intro.intro.t R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C✝ : VariableChange R h : Function.Injective ↑(algebraMap R A) C C' : VariableChange R h1✝ : baseChange A C = baseChange A C' left✝¹ : ↑(algebraMap R A) C.r = ↑(algebraMap R A) C'.r left✝ : ↑(algebraMap R A) C.s = ↑(algebraMap R A) C'.s right✝ : ↑(algebraMap R A) C.t = ↑(algebraMap R A) C'.t h1 : ↑↑(algebraMap R A) ↑C.u = ↑↑(algebraMap R A) ↑C'.u ⊢ C.t = C'.t [PROOFSTEP] apply_fun _ using h [GOAL] case intro.intro.intro.u.a R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C✝ : VariableChange R h : Function.Injective ↑(algebraMap R A) C C' : VariableChange R h1✝ : baseChange A C = baseChange A C' left✝¹ : ↑(algebraMap R A) C.r = ↑(algebraMap R A) C'.r left✝ : ↑(algebraMap R A) C.s = ↑(algebraMap R A) C'.s right✝ : ↑(algebraMap R A) C.t = ↑(algebraMap R A) C'.t h1 : ↑↑(algebraMap R A) ↑C.u = ↑↑(algebraMap R A) ↑C'.u ⊢ ↑(algebraMap R A) ↑C.u = ↑(algebraMap R A) ↑C'.u [PROOFSTEP] assumption [GOAL] case intro.intro.intro.r R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C✝ : VariableChange R h : Function.Injective ↑(algebraMap R A) C C' : VariableChange R h1✝ : baseChange A C = baseChange A C' left✝¹ : ↑(algebraMap R A) C.r = ↑(algebraMap R A) C'.r left✝ : ↑(algebraMap R A) C.s = ↑(algebraMap R A) C'.s right✝ : ↑(algebraMap R A) C.t = ↑(algebraMap R A) C'.t h1 : ↑↑(algebraMap R A) ↑C.u = ↑↑(algebraMap R A) ↑C'.u ⊢ ↑(algebraMap R A) C.r = ↑(algebraMap R A) C'.r [PROOFSTEP] assumption [GOAL] case intro.intro.intro.s R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C✝ : VariableChange R h : Function.Injective ↑(algebraMap R A) C C' : VariableChange R h1✝ : baseChange A C = baseChange A C' left✝¹ : ↑(algebraMap R A) C.r = ↑(algebraMap R A) C'.r left✝ : ↑(algebraMap R A) C.s = ↑(algebraMap R A) C'.s right✝ : ↑(algebraMap R A) C.t = ↑(algebraMap R A) C'.t h1 : ↑↑(algebraMap R A) ↑C.u = ↑↑(algebraMap R A) ↑C'.u ⊢ ↑(algebraMap R A) C.s = ↑(algebraMap R A) C'.s [PROOFSTEP] assumption [GOAL] case intro.intro.intro.t R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C✝ : VariableChange R h : Function.Injective ↑(algebraMap R A) C C' : VariableChange R h1✝ : baseChange A C = baseChange A C' left✝¹ : ↑(algebraMap R A) C.r = ↑(algebraMap R A) C'.r left✝ : ↑(algebraMap R A) C.s = ↑(algebraMap R A) C'.s right✝ : ↑(algebraMap R A) C.t = ↑(algebraMap R A) C'.t h1 : ↑↑(algebraMap R A) ↑C.u = ↑↑(algebraMap R A) ↑C'.u ⊢ ↑(algebraMap R A) C.t = ↑(algebraMap R A) C'.t [PROOFSTEP] assumption [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C : VariableChange R ⊢ variableChange (baseChange W A) (VariableChange.baseChange A C) = baseChange (variableChange W C) A [PROOFSTEP] simp only [baseChange, variableChange, VariableChange.baseChange] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C : VariableChange R ⊢ { a₁ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ * (↑(algebraMap R A) W.a₁ + 2 * ↑(algebraMap R A) C.s), a₂ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ ^ 2 * (↑(algebraMap R A) W.a₂ - ↑(algebraMap R A) C.s * ↑(algebraMap R A) W.a₁ + 3 * ↑(algebraMap R A) C.r - ↑(algebraMap R A) C.s ^ 2), a₃ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ ^ 3 * (↑(algebraMap R A) W.a₃ + ↑(algebraMap R A) C.r * ↑(algebraMap R A) W.a₁ + 2 * ↑(algebraMap R A) C.t), a₄ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ ^ 4 * (↑(algebraMap R A) W.a₄ - ↑(algebraMap R A) C.s * ↑(algebraMap R A) W.a₃ + 2 * ↑(algebraMap R A) C.r * ↑(algebraMap R A) W.a₂ - (↑(algebraMap R A) C.t + ↑(algebraMap R A) C.r * ↑(algebraMap R A) C.s) * ↑(algebraMap R A) W.a₁ + 3 * ↑(algebraMap R A) C.r ^ 2 - 2 * ↑(algebraMap R A) C.s * ↑(algebraMap R A) C.t), a₆ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ ^ 6 * (↑(algebraMap R A) W.a₆ + ↑(algebraMap R A) C.r * ↑(algebraMap R A) W.a₄ + ↑(algebraMap R A) C.r ^ 2 * ↑(algebraMap R A) W.a₂ + ↑(algebraMap R A) C.r ^ 3 - ↑(algebraMap R A) C.t * ↑(algebraMap R A) W.a₃ - ↑(algebraMap R A) C.t ^ 2 - ↑(algebraMap R A) C.r * ↑(algebraMap R A) C.t * ↑(algebraMap R A) W.a₁) } = { a₁ := ↑(algebraMap R A) (↑C.u⁻¹ * (W.a₁ + 2 * C.s)), a₂ := ↑(algebraMap R A) (↑C.u⁻¹ ^ 2 * (W.a₂ - C.s * W.a₁ + 3 * C.r - C.s ^ 2)), a₃ := ↑(algebraMap R A) (↑C.u⁻¹ ^ 3 * (W.a₃ + C.r * W.a₁ + 2 * C.t)), a₄ := ↑(algebraMap R A) (↑C.u⁻¹ ^ 4 * (W.a₄ - C.s * W.a₃ + 2 * C.r * W.a₂ - (C.t + C.r * C.s) * W.a₁ + 3 * C.r ^ 2 - 2 * C.s * C.t)), a₆ := ↑(algebraMap R A) (↑C.u⁻¹ ^ 6 * (W.a₆ + C.r * W.a₄ + C.r ^ 2 * W.a₂ + C.r ^ 3 - C.t * W.a₃ - C.t ^ 2 - C.r * C.t * W.a₁)) } [PROOFSTEP] ext [GOAL] case a₁ R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C : VariableChange R ⊢ { a₁ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ * (↑(algebraMap R A) W.a₁ + 2 * ↑(algebraMap R A) C.s), a₂ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ ^ 2 * (↑(algebraMap R A) W.a₂ - ↑(algebraMap R A) C.s * ↑(algebraMap R A) W.a₁ + 3 * ↑(algebraMap R A) C.r - ↑(algebraMap R A) C.s ^ 2), a₃ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ ^ 3 * (↑(algebraMap R A) W.a₃ + ↑(algebraMap R A) C.r * ↑(algebraMap R A) W.a₁ + 2 * ↑(algebraMap R A) C.t), a₄ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ ^ 4 * (↑(algebraMap R A) W.a₄ - ↑(algebraMap R A) C.s * ↑(algebraMap R A) W.a₃ + 2 * ↑(algebraMap R A) C.r * ↑(algebraMap R A) W.a₂ - (↑(algebraMap R A) C.t + ↑(algebraMap R A) C.r * ↑(algebraMap R A) C.s) * ↑(algebraMap R A) W.a₁ + 3 * ↑(algebraMap R A) C.r ^ 2 - 2 * ↑(algebraMap R A) C.s * ↑(algebraMap R A) C.t), a₆ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ ^ 6 * (↑(algebraMap R A) W.a₆ + ↑(algebraMap R A) C.r * ↑(algebraMap R A) W.a₄ + ↑(algebraMap R A) C.r ^ 2 * ↑(algebraMap R A) W.a₂ + ↑(algebraMap R A) C.r ^ 3 - ↑(algebraMap R A) C.t * ↑(algebraMap R A) W.a₃ - ↑(algebraMap R A) C.t ^ 2 - ↑(algebraMap R A) C.r * ↑(algebraMap R A) C.t * ↑(algebraMap R A) W.a₁) }.a₁ = { a₁ := ↑(algebraMap R A) (↑C.u⁻¹ * (W.a₁ + 2 * C.s)), a₂ := ↑(algebraMap R A) (↑C.u⁻¹ ^ 2 * (W.a₂ - C.s * W.a₁ + 3 * C.r - C.s ^ 2)), a₃ := ↑(algebraMap R A) (↑C.u⁻¹ ^ 3 * (W.a₃ + C.r * W.a₁ + 2 * C.t)), a₄ := ↑(algebraMap R A) (↑C.u⁻¹ ^ 4 * (W.a₄ - C.s * W.a₃ + 2 * C.r * W.a₂ - (C.t + C.r * C.s) * W.a₁ + 3 * C.r ^ 2 - 2 * C.s * C.t)), a₆ := ↑(algebraMap R A) (↑C.u⁻¹ ^ 6 * (W.a₆ + C.r * W.a₄ + C.r ^ 2 * W.a₂ + C.r ^ 3 - C.t * W.a₃ - C.t ^ 2 - C.r * C.t * W.a₁)) }.a₁ [PROOFSTEP] simp only [Units.coe_map, Units.coe_map_inv, MonoidHom.coe_coe, map_ofNat, map_neg, map_add, map_sub, map_mul, map_pow] [GOAL] case a₂ R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C : VariableChange R ⊢ { a₁ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ * (↑(algebraMap R A) W.a₁ + 2 * ↑(algebraMap R A) C.s), a₂ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ ^ 2 * (↑(algebraMap R A) W.a₂ - ↑(algebraMap R A) C.s * ↑(algebraMap R A) W.a₁ + 3 * ↑(algebraMap R A) C.r - ↑(algebraMap R A) C.s ^ 2), a₃ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ ^ 3 * (↑(algebraMap R A) W.a₃ + ↑(algebraMap R A) C.r * ↑(algebraMap R A) W.a₁ + 2 * ↑(algebraMap R A) C.t), a₄ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ ^ 4 * (↑(algebraMap R A) W.a₄ - ↑(algebraMap R A) C.s * ↑(algebraMap R A) W.a₃ + 2 * ↑(algebraMap R A) C.r * ↑(algebraMap R A) W.a₂ - (↑(algebraMap R A) C.t + ↑(algebraMap R A) C.r * ↑(algebraMap R A) C.s) * ↑(algebraMap R A) W.a₁ + 3 * ↑(algebraMap R A) C.r ^ 2 - 2 * ↑(algebraMap R A) C.s * ↑(algebraMap R A) C.t), a₆ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ ^ 6 * (↑(algebraMap R A) W.a₆ + ↑(algebraMap R A) C.r * ↑(algebraMap R A) W.a₄ + ↑(algebraMap R A) C.r ^ 2 * ↑(algebraMap R A) W.a₂ + ↑(algebraMap R A) C.r ^ 3 - ↑(algebraMap R A) C.t * ↑(algebraMap R A) W.a₃ - ↑(algebraMap R A) C.t ^ 2 - ↑(algebraMap R A) C.r * ↑(algebraMap R A) C.t * ↑(algebraMap R A) W.a₁) }.a₂ = { a₁ := ↑(algebraMap R A) (↑C.u⁻¹ * (W.a₁ + 2 * C.s)), a₂ := ↑(algebraMap R A) (↑C.u⁻¹ ^ 2 * (W.a₂ - C.s * W.a₁ + 3 * C.r - C.s ^ 2)), a₃ := ↑(algebraMap R A) (↑C.u⁻¹ ^ 3 * (W.a₃ + C.r * W.a₁ + 2 * C.t)), a₄ := ↑(algebraMap R A) (↑C.u⁻¹ ^ 4 * (W.a₄ - C.s * W.a₃ + 2 * C.r * W.a₂ - (C.t + C.r * C.s) * W.a₁ + 3 * C.r ^ 2 - 2 * C.s * C.t)), a₆ := ↑(algebraMap R A) (↑C.u⁻¹ ^ 6 * (W.a₆ + C.r * W.a₄ + C.r ^ 2 * W.a₂ + C.r ^ 3 - C.t * W.a₃ - C.t ^ 2 - C.r * C.t * W.a₁)) }.a₂ [PROOFSTEP] simp only [Units.coe_map, Units.coe_map_inv, MonoidHom.coe_coe, map_ofNat, map_neg, map_add, map_sub, map_mul, map_pow] [GOAL] case a₃ R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C : VariableChange R ⊢ { a₁ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ * (↑(algebraMap R A) W.a₁ + 2 * ↑(algebraMap R A) C.s), a₂ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ ^ 2 * (↑(algebraMap R A) W.a₂ - ↑(algebraMap R A) C.s * ↑(algebraMap R A) W.a₁ + 3 * ↑(algebraMap R A) C.r - ↑(algebraMap R A) C.s ^ 2), a₃ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ ^ 3 * (↑(algebraMap R A) W.a₃ + ↑(algebraMap R A) C.r * ↑(algebraMap R A) W.a₁ + 2 * ↑(algebraMap R A) C.t), a₄ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ ^ 4 * (↑(algebraMap R A) W.a₄ - ↑(algebraMap R A) C.s * ↑(algebraMap R A) W.a₃ + 2 * ↑(algebraMap R A) C.r * ↑(algebraMap R A) W.a₂ - (↑(algebraMap R A) C.t + ↑(algebraMap R A) C.r * ↑(algebraMap R A) C.s) * ↑(algebraMap R A) W.a₁ + 3 * ↑(algebraMap R A) C.r ^ 2 - 2 * ↑(algebraMap R A) C.s * ↑(algebraMap R A) C.t), a₆ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ ^ 6 * (↑(algebraMap R A) W.a₆ + ↑(algebraMap R A) C.r * ↑(algebraMap R A) W.a₄ + ↑(algebraMap R A) C.r ^ 2 * ↑(algebraMap R A) W.a₂ + ↑(algebraMap R A) C.r ^ 3 - ↑(algebraMap R A) C.t * ↑(algebraMap R A) W.a₃ - ↑(algebraMap R A) C.t ^ 2 - ↑(algebraMap R A) C.r * ↑(algebraMap R A) C.t * ↑(algebraMap R A) W.a₁) }.a₃ = { a₁ := ↑(algebraMap R A) (↑C.u⁻¹ * (W.a₁ + 2 * C.s)), a₂ := ↑(algebraMap R A) (↑C.u⁻¹ ^ 2 * (W.a₂ - C.s * W.a₁ + 3 * C.r - C.s ^ 2)), a₃ := ↑(algebraMap R A) (↑C.u⁻¹ ^ 3 * (W.a₃ + C.r * W.a₁ + 2 * C.t)), a₄ := ↑(algebraMap R A) (↑C.u⁻¹ ^ 4 * (W.a₄ - C.s * W.a₃ + 2 * C.r * W.a₂ - (C.t + C.r * C.s) * W.a₁ + 3 * C.r ^ 2 - 2 * C.s * C.t)), a₆ := ↑(algebraMap R A) (↑C.u⁻¹ ^ 6 * (W.a₆ + C.r * W.a₄ + C.r ^ 2 * W.a₂ + C.r ^ 3 - C.t * W.a₃ - C.t ^ 2 - C.r * C.t * W.a₁)) }.a₃ [PROOFSTEP] simp only [Units.coe_map, Units.coe_map_inv, MonoidHom.coe_coe, map_ofNat, map_neg, map_add, map_sub, map_mul, map_pow] [GOAL] case a₄ R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C : VariableChange R ⊢ { a₁ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ * (↑(algebraMap R A) W.a₁ + 2 * ↑(algebraMap R A) C.s), a₂ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ ^ 2 * (↑(algebraMap R A) W.a₂ - ↑(algebraMap R A) C.s * ↑(algebraMap R A) W.a₁ + 3 * ↑(algebraMap R A) C.r - ↑(algebraMap R A) C.s ^ 2), a₃ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ ^ 3 * (↑(algebraMap R A) W.a₃ + ↑(algebraMap R A) C.r * ↑(algebraMap R A) W.a₁ + 2 * ↑(algebraMap R A) C.t), a₄ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ ^ 4 * (↑(algebraMap R A) W.a₄ - ↑(algebraMap R A) C.s * ↑(algebraMap R A) W.a₃ + 2 * ↑(algebraMap R A) C.r * ↑(algebraMap R A) W.a₂ - (↑(algebraMap R A) C.t + ↑(algebraMap R A) C.r * ↑(algebraMap R A) C.s) * ↑(algebraMap R A) W.a₁ + 3 * ↑(algebraMap R A) C.r ^ 2 - 2 * ↑(algebraMap R A) C.s * ↑(algebraMap R A) C.t), a₆ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ ^ 6 * (↑(algebraMap R A) W.a₆ + ↑(algebraMap R A) C.r * ↑(algebraMap R A) W.a₄ + ↑(algebraMap R A) C.r ^ 2 * ↑(algebraMap R A) W.a₂ + ↑(algebraMap R A) C.r ^ 3 - ↑(algebraMap R A) C.t * ↑(algebraMap R A) W.a₃ - ↑(algebraMap R A) C.t ^ 2 - ↑(algebraMap R A) C.r * ↑(algebraMap R A) C.t * ↑(algebraMap R A) W.a₁) }.a₄ = { a₁ := ↑(algebraMap R A) (↑C.u⁻¹ * (W.a₁ + 2 * C.s)), a₂ := ↑(algebraMap R A) (↑C.u⁻¹ ^ 2 * (W.a₂ - C.s * W.a₁ + 3 * C.r - C.s ^ 2)), a₃ := ↑(algebraMap R A) (↑C.u⁻¹ ^ 3 * (W.a₃ + C.r * W.a₁ + 2 * C.t)), a₄ := ↑(algebraMap R A) (↑C.u⁻¹ ^ 4 * (W.a₄ - C.s * W.a₃ + 2 * C.r * W.a₂ - (C.t + C.r * C.s) * W.a₁ + 3 * C.r ^ 2 - 2 * C.s * C.t)), a₆ := ↑(algebraMap R A) (↑C.u⁻¹ ^ 6 * (W.a₆ + C.r * W.a₄ + C.r ^ 2 * W.a₂ + C.r ^ 3 - C.t * W.a₃ - C.t ^ 2 - C.r * C.t * W.a₁)) }.a₄ [PROOFSTEP] simp only [Units.coe_map, Units.coe_map_inv, MonoidHom.coe_coe, map_ofNat, map_neg, map_add, map_sub, map_mul, map_pow] [GOAL] case a₆ R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B C : VariableChange R ⊢ { a₁ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ * (↑(algebraMap R A) W.a₁ + 2 * ↑(algebraMap R A) C.s), a₂ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ ^ 2 * (↑(algebraMap R A) W.a₂ - ↑(algebraMap R A) C.s * ↑(algebraMap R A) W.a₁ + 3 * ↑(algebraMap R A) C.r - ↑(algebraMap R A) C.s ^ 2), a₃ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ ^ 3 * (↑(algebraMap R A) W.a₃ + ↑(algebraMap R A) C.r * ↑(algebraMap R A) W.a₁ + 2 * ↑(algebraMap R A) C.t), a₄ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ ^ 4 * (↑(algebraMap R A) W.a₄ - ↑(algebraMap R A) C.s * ↑(algebraMap R A) W.a₃ + 2 * ↑(algebraMap R A) C.r * ↑(algebraMap R A) W.a₂ - (↑(algebraMap R A) C.t + ↑(algebraMap R A) C.r * ↑(algebraMap R A) C.s) * ↑(algebraMap R A) W.a₁ + 3 * ↑(algebraMap R A) C.r ^ 2 - 2 * ↑(algebraMap R A) C.s * ↑(algebraMap R A) C.t), a₆ := ↑(↑(Units.map ↑(algebraMap R A)) C.u)⁻¹ ^ 6 * (↑(algebraMap R A) W.a₆ + ↑(algebraMap R A) C.r * ↑(algebraMap R A) W.a₄ + ↑(algebraMap R A) C.r ^ 2 * ↑(algebraMap R A) W.a₂ + ↑(algebraMap R A) C.r ^ 3 - ↑(algebraMap R A) C.t * ↑(algebraMap R A) W.a₃ - ↑(algebraMap R A) C.t ^ 2 - ↑(algebraMap R A) C.r * ↑(algebraMap R A) C.t * ↑(algebraMap R A) W.a₁) }.a₆ = { a₁ := ↑(algebraMap R A) (↑C.u⁻¹ * (W.a₁ + 2 * C.s)), a₂ := ↑(algebraMap R A) (↑C.u⁻¹ ^ 2 * (W.a₂ - C.s * W.a₁ + 3 * C.r - C.s ^ 2)), a₃ := ↑(algebraMap R A) (↑C.u⁻¹ ^ 3 * (W.a₃ + C.r * W.a₁ + 2 * C.t)), a₄ := ↑(algebraMap R A) (↑C.u⁻¹ ^ 4 * (W.a₄ - C.s * W.a₃ + 2 * C.r * W.a₂ - (C.t + C.r * C.s) * W.a₁ + 3 * C.r ^ 2 - 2 * C.s * C.t)), a₆ := ↑(algebraMap R A) (↑C.u⁻¹ ^ 6 * (W.a₆ + C.r * W.a₄ + C.r ^ 2 * W.a₂ + C.r ^ 3 - C.t * W.a₃ - C.t ^ 2 - C.r * C.t * W.a₁)) }.a₆ [PROOFSTEP] simp only [Units.coe_map, Units.coe_map_inv, MonoidHom.coe_coe, map_ofNat, map_neg, map_add, map_sub, map_mul, map_pow] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ Cubic.disc (twoTorsionPolynomial W) = 16 * Δ W [PROOFSTEP] simp only [b₂, b₄, b₆, b₈, Δ, twoTorsionPolynomial, Cubic.disc] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ (W.a₁ ^ 2 + 4 * W.a₂) ^ 2 * (2 * (2 * W.a₄ + W.a₁ * W.a₃)) ^ 2 - 4 * 4 * (2 * (2 * W.a₄ + W.a₁ * W.a₃)) ^ 3 - 4 * (W.a₁ ^ 2 + 4 * W.a₂) ^ 3 * (W.a₃ ^ 2 + 4 * W.a₆) - 27 * 4 ^ 2 * (W.a₃ ^ 2 + 4 * W.a₆) ^ 2 + 18 * 4 * (W.a₁ ^ 2 + 4 * W.a₂) * (2 * (2 * W.a₄ + W.a₁ * W.a₃)) * (W.a₃ ^ 2 + 4 * W.a₆) = 16 * (-(W.a₁ ^ 2 + 4 * W.a₂) ^ 2 * (W.a₁ ^ 2 * W.a₆ + 4 * W.a₂ * W.a₆ - W.a₁ * W.a₃ * W.a₄ + W.a₂ * W.a₃ ^ 2 - W.a₄ ^ 2) - 8 * (2 * W.a₄ + W.a₁ * W.a₃) ^ 3 - 27 * (W.a₃ ^ 2 + 4 * W.a₆) ^ 2 + 9 * (W.a₁ ^ 2 + 4 * W.a₂) * (2 * W.a₄ + W.a₁ * W.a₃) * (W.a₃ ^ 2 + 4 * W.a₆)) [PROOFSTEP] ring1 [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : Invertible 2 ⊢ IsUnit (Cubic.disc (twoTorsionPolynomial W)) ↔ IsUnit (Δ W) [PROOFSTEP] rw [twoTorsionPolynomial_disc, IsUnit.mul_iff, show (16 : R) = 2 ^ 4 by norm_num1] [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : Invertible 2 ⊢ 16 = 2 ^ 4 [PROOFSTEP] norm_num1 [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : Invertible 2 ⊢ IsUnit (2 ^ 4) ∧ IsUnit (Δ W) ↔ IsUnit (Δ W) [PROOFSTEP] exact and_iff_right <| isUnit_of_invertible <| 2 ^ 4 [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ WeierstrassCurve.polynomial W = Cubic.toPoly { a := 0, b := 1, c := Cubic.toPoly { a := 0, b := 0, c := W.a₁, d := W.a₃ }, d := Cubic.toPoly { a := -1, b := -W.a₂, c := -W.a₄, d := -W.a₆ } } [PROOFSTEP] simp only [WeierstrassCurve.polynomial, Cubic.toPoly] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ Y ^ 2 + ↑C (↑C W.a₁ * Y + ↑C W.a₃) * Y - ↑C (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆) = ↑C 0 * Y ^ 3 + ↑C 1 * Y ^ 2 + ↑C (↑C 0 * Y ^ 3 + ↑C 0 * Y ^ 2 + ↑C W.a₁ * Y + ↑C W.a₃) * Y + ↑C (↑C (-1) * Y ^ 3 + ↑C (-W.a₂) * Y ^ 2 + ↑C (-W.a₄) * Y + ↑C (-W.a₆)) [PROOFSTEP] C_simp [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ Y ^ 2 + (↑C (↑C W.a₁) * ↑C Y + ↑C (↑C W.a₃)) * Y - (↑C Y ^ 3 + ↑C (↑C W.a₂) * ↑C Y ^ 2 + ↑C (↑C W.a₄) * ↑C Y + ↑C (↑C W.a₆)) = 0 * Y ^ 3 + 1 * Y ^ 2 + (0 * ↑C Y ^ 3 + 0 * ↑C Y ^ 2 + ↑C (↑C W.a₁) * ↑C Y + ↑C (↑C W.a₃)) * Y + (-1 * ↑C Y ^ 3 + -↑C (↑C W.a₂) * ↑C Y ^ 2 + -↑C (↑C W.a₄) * ↑C Y + -↑C (↑C W.a₆)) [PROOFSTEP] ring1 [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : Nontrivial R ⊢ WeierstrassCurve.polynomial W ≠ 0 [PROOFSTEP] rw [polynomial_eq] [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : Nontrivial R ⊢ Cubic.toPoly { a := 0, b := 1, c := Cubic.toPoly { a := 0, b := 0, c := W.a₁, d := W.a₃ }, d := Cubic.toPoly { a := -1, b := -W.a₂, c := -W.a₄, d := -W.a₆ } } ≠ 0 [PROOFSTEP] exact Cubic.ne_zero_of_b_ne_zero one_ne_zero [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : Nontrivial R ⊢ degree (WeierstrassCurve.polynomial W) = 2 [PROOFSTEP] rw [polynomial_eq] [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : Nontrivial R ⊢ degree (Cubic.toPoly { a := 0, b := 1, c := Cubic.toPoly { a := 0, b := 0, c := W.a₁, d := W.a₃ }, d := Cubic.toPoly { a := -1, b := -W.a₂, c := -W.a₄, d := -W.a₆ } }) = 2 [PROOFSTEP] exact Cubic.degree_of_b_ne_zero' one_ne_zero [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : Nontrivial R ⊢ natDegree (WeierstrassCurve.polynomial W) = 2 [PROOFSTEP] rw [polynomial_eq] [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : Nontrivial R ⊢ natDegree (Cubic.toPoly { a := 0, b := 1, c := Cubic.toPoly { a := 0, b := 0, c := W.a₁, d := W.a₃ }, d := Cubic.toPoly { a := -1, b := -W.a₂, c := -W.a₄, d := -W.a₆ } }) = 2 [PROOFSTEP] exact Cubic.natDegree_of_b_ne_zero' one_ne_zero [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ Monic (WeierstrassCurve.polynomial W) [PROOFSTEP] nontriviality R [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ✝ : Nontrivial R ⊢ Monic (WeierstrassCurve.polynomial W) [PROOFSTEP] simpa only [polynomial_eq] using Cubic.monic_of_b_eq_one' [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : IsDomain R ⊢ Irreducible (WeierstrassCurve.polynomial W) [PROOFSTEP] by_contra h [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : IsDomain R h : ¬Irreducible (WeierstrassCurve.polynomial W) ⊢ False [PROOFSTEP] rcases(W.monic_polynomial.not_irreducible_iff_exists_add_mul_eq_coeff W.natDegree_polynomial).mp h with ⟨f, g, h0, h1⟩ [GOAL] case intro.intro.intro R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : IsDomain R h : ¬Irreducible (WeierstrassCurve.polynomial W) f g : R[X] h0 : coeff (WeierstrassCurve.polynomial W) 0 = f * g h1 : coeff (WeierstrassCurve.polynomial W) 1 = f + g ⊢ False [PROOFSTEP] simp only [polynomial_eq, Cubic.coeff_eq_c, Cubic.coeff_eq_d] at h0 h1 [GOAL] case intro.intro.intro R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : IsDomain R h : ¬Irreducible (WeierstrassCurve.polynomial W) f g : R[X] h0 : Cubic.toPoly { a := -1, b := -W.a₂, c := -W.a₄, d := -W.a₆ } = f * g h1 : Cubic.toPoly { a := 0, b := 0, c := W.a₁, d := W.a₃ } = f + g ⊢ False [PROOFSTEP] apply_fun degree at h0 h1 [GOAL] case intro.intro.intro R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : IsDomain R h : ¬Irreducible (WeierstrassCurve.polynomial W) f g : R[X] h0 : degree (Cubic.toPoly { a := -1, b := -W.a₂, c := -W.a₄, d := -W.a₆ }) = degree (f * g) h1 : degree (Cubic.toPoly { a := 0, b := 0, c := W.a₁, d := W.a₃ }) = degree (f + g) ⊢ False [PROOFSTEP] rw [Cubic.degree_of_a_ne_zero' <| neg_ne_zero.mpr <| one_ne_zero' R, degree_mul] at h0 [GOAL] case intro.intro.intro R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : IsDomain R h : ¬Irreducible (WeierstrassCurve.polynomial W) f g : R[X] h0 : 3 = degree f + degree g h1 : degree (Cubic.toPoly { a := 0, b := 0, c := W.a₁, d := W.a₃ }) = degree (f + g) ⊢ False [PROOFSTEP] apply (h1.symm.le.trans Cubic.degree_of_b_eq_zero').not_lt [GOAL] case intro.intro.intro R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : IsDomain R h : ¬Irreducible (WeierstrassCurve.polynomial W) f g : R[X] h0 : 3 = degree f + degree g h1 : degree (Cubic.toPoly { a := 0, b := 0, c := W.a₁, d := W.a₃ }) = degree (f + g) ⊢ 1 < degree (f + g) [PROOFSTEP] rcases Nat.WithBot.add_eq_three_iff.mp h0.symm with h | h | h | h [GOAL] case intro.intro.intro.inl R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : IsDomain R h✝ : ¬Irreducible (WeierstrassCurve.polynomial W) f g : R[X] h0 : 3 = degree f + degree g h1 : degree (Cubic.toPoly { a := 0, b := 0, c := W.a₁, d := W.a₃ }) = degree (f + g) h : degree f = 0 ∧ degree g = 3 ⊢ 1 < degree (f + g) case intro.intro.intro.inr.inl R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : IsDomain R h✝ : ¬Irreducible (WeierstrassCurve.polynomial W) f g : R[X] h0 : 3 = degree f + degree g h1 : degree (Cubic.toPoly { a := 0, b := 0, c := W.a₁, d := W.a₃ }) = degree (f + g) h : degree f = 1 ∧ degree g = 2 ⊢ 1 < degree (f + g) case intro.intro.intro.inr.inr.inl R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : IsDomain R h✝ : ¬Irreducible (WeierstrassCurve.polynomial W) f g : R[X] h0 : 3 = degree f + degree g h1 : degree (Cubic.toPoly { a := 0, b := 0, c := W.a₁, d := W.a₃ }) = degree (f + g) h : degree f = 2 ∧ degree g = 1 ⊢ 1 < degree (f + g) case intro.intro.intro.inr.inr.inr R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : IsDomain R h✝ : ¬Irreducible (WeierstrassCurve.polynomial W) f g : R[X] h0 : 3 = degree f + degree g h1 : degree (Cubic.toPoly { a := 0, b := 0, c := W.a₁, d := W.a₃ }) = degree (f + g) h : degree f = 3 ∧ degree g = 0 ⊢ 1 < degree (f + g) [PROOFSTEP] iterate 2 rw [degree_add_eq_right_of_degree_lt] <;> simp only [h] [GOAL] case intro.intro.intro.inl R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : IsDomain R h✝ : ¬Irreducible (WeierstrassCurve.polynomial W) f g : R[X] h0 : 3 = degree f + degree g h1 : degree (Cubic.toPoly { a := 0, b := 0, c := W.a₁, d := W.a₃ }) = degree (f + g) h : degree f = 0 ∧ degree g = 3 ⊢ 1 < degree (f + g) [PROOFSTEP] rw [degree_add_eq_right_of_degree_lt] [GOAL] case intro.intro.intro.inl R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : IsDomain R h✝ : ¬Irreducible (WeierstrassCurve.polynomial W) f g : R[X] h0 : 3 = degree f + degree g h1 : degree (Cubic.toPoly { a := 0, b := 0, c := W.a₁, d := W.a₃ }) = degree (f + g) h : degree f = 0 ∧ degree g = 3 ⊢ 1 < degree g [PROOFSTEP] simp only [h] [GOAL] case intro.intro.intro.inl R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : IsDomain R h✝ : ¬Irreducible (WeierstrassCurve.polynomial W) f g : R[X] h0 : 3 = degree f + degree g h1 : degree (Cubic.toPoly { a := 0, b := 0, c := W.a₁, d := W.a₃ }) = degree (f + g) h : degree f = 0 ∧ degree g = 3 ⊢ degree f < degree g [PROOFSTEP] simp only [h] [GOAL] case intro.intro.intro.inr.inl R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : IsDomain R h✝ : ¬Irreducible (WeierstrassCurve.polynomial W) f g : R[X] h0 : 3 = degree f + degree g h1 : degree (Cubic.toPoly { a := 0, b := 0, c := W.a₁, d := W.a₃ }) = degree (f + g) h : degree f = 1 ∧ degree g = 2 ⊢ 1 < degree (f + g) [PROOFSTEP] rw [degree_add_eq_right_of_degree_lt] [GOAL] case intro.intro.intro.inr.inl R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : IsDomain R h✝ : ¬Irreducible (WeierstrassCurve.polynomial W) f g : R[X] h0 : 3 = degree f + degree g h1 : degree (Cubic.toPoly { a := 0, b := 0, c := W.a₁, d := W.a₃ }) = degree (f + g) h : degree f = 1 ∧ degree g = 2 ⊢ 1 < degree g [PROOFSTEP] simp only [h] [GOAL] case intro.intro.intro.inr.inl R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : IsDomain R h✝ : ¬Irreducible (WeierstrassCurve.polynomial W) f g : R[X] h0 : 3 = degree f + degree g h1 : degree (Cubic.toPoly { a := 0, b := 0, c := W.a₁, d := W.a₃ }) = degree (f + g) h : degree f = 1 ∧ degree g = 2 ⊢ degree f < degree g [PROOFSTEP] simp only [h] [GOAL] case intro.intro.intro.inr.inr.inl R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : IsDomain R h✝ : ¬Irreducible (WeierstrassCurve.polynomial W) f g : R[X] h0 : 3 = degree f + degree g h1 : degree (Cubic.toPoly { a := 0, b := 0, c := W.a₁, d := W.a₃ }) = degree (f + g) h : degree f = 2 ∧ degree g = 1 ⊢ 1 < degree (f + g) case intro.intro.intro.inr.inr.inr R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : IsDomain R h✝ : ¬Irreducible (WeierstrassCurve.polynomial W) f g : R[X] h0 : 3 = degree f + degree g h1 : degree (Cubic.toPoly { a := 0, b := 0, c := W.a₁, d := W.a₃ }) = degree (f + g) h : degree f = 3 ∧ degree g = 0 ⊢ 1 < degree (f + g) [PROOFSTEP] iterate 2 rw [degree_add_eq_left_of_degree_lt] <;> simp only [h] [GOAL] case intro.intro.intro.inr.inr.inl R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : IsDomain R h✝ : ¬Irreducible (WeierstrassCurve.polynomial W) f g : R[X] h0 : 3 = degree f + degree g h1 : degree (Cubic.toPoly { a := 0, b := 0, c := W.a₁, d := W.a₃ }) = degree (f + g) h : degree f = 2 ∧ degree g = 1 ⊢ 1 < degree (f + g) [PROOFSTEP] rw [degree_add_eq_left_of_degree_lt] [GOAL] case intro.intro.intro.inr.inr.inl R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : IsDomain R h✝ : ¬Irreducible (WeierstrassCurve.polynomial W) f g : R[X] h0 : 3 = degree f + degree g h1 : degree (Cubic.toPoly { a := 0, b := 0, c := W.a₁, d := W.a₃ }) = degree (f + g) h : degree f = 2 ∧ degree g = 1 ⊢ 1 < degree f [PROOFSTEP] simp only [h] [GOAL] case intro.intro.intro.inr.inr.inl R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : IsDomain R h✝ : ¬Irreducible (WeierstrassCurve.polynomial W) f g : R[X] h0 : 3 = degree f + degree g h1 : degree (Cubic.toPoly { a := 0, b := 0, c := W.a₁, d := W.a₃ }) = degree (f + g) h : degree f = 2 ∧ degree g = 1 ⊢ degree g < degree f [PROOFSTEP] simp only [h] [GOAL] case intro.intro.intro.inr.inr.inr R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : IsDomain R h✝ : ¬Irreducible (WeierstrassCurve.polynomial W) f g : R[X] h0 : 3 = degree f + degree g h1 : degree (Cubic.toPoly { a := 0, b := 0, c := W.a₁, d := W.a₃ }) = degree (f + g) h : degree f = 3 ∧ degree g = 0 ⊢ 1 < degree (f + g) [PROOFSTEP] rw [degree_add_eq_left_of_degree_lt] [GOAL] case intro.intro.intro.inr.inr.inr R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : IsDomain R h✝ : ¬Irreducible (WeierstrassCurve.polynomial W) f g : R[X] h0 : 3 = degree f + degree g h1 : degree (Cubic.toPoly { a := 0, b := 0, c := W.a₁, d := W.a₃ }) = degree (f + g) h : degree f = 3 ∧ degree g = 0 ⊢ 1 < degree f [PROOFSTEP] simp only [h] [GOAL] case intro.intro.intro.inr.inr.inr R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B inst✝ : IsDomain R h✝ : ¬Irreducible (WeierstrassCurve.polynomial W) f g : R[X] h0 : 3 = degree f + degree g h1 : degree (Cubic.toPoly { a := 0, b := 0, c := W.a₁, d := W.a₃ }) = degree (f + g) h : degree f = 3 ∧ degree g = 0 ⊢ degree g < degree f [PROOFSTEP] simp only [h] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x y : R ⊢ eval x (eval (↑C y) (WeierstrassCurve.polynomial W)) = y ^ 2 + W.a₁ * x * y + W.a₃ * y - (x ^ 3 + W.a₂ * x ^ 2 + W.a₄ * x + W.a₆) [PROOFSTEP] simp only [WeierstrassCurve.polynomial] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x y : R ⊢ eval x (eval (↑C y) (Y ^ 2 + ↑C (↑C W.a₁ * Y + ↑C W.a₃) * Y - ↑C (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆))) = y ^ 2 + W.a₁ * x * y + W.a₃ * y - (x ^ 3 + W.a₂ * x ^ 2 + W.a₄ * x + W.a₆) [PROOFSTEP] eval_simp [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x y : R ⊢ y ^ 2 + (W.a₁ * x + W.a₃) * y - (x ^ 3 + W.a₂ * x ^ 2 + W.a₄ * x + W.a₆) = y ^ 2 + W.a₁ * x * y + W.a₃ * y - (x ^ 3 + W.a₂ * x ^ 2 + W.a₄ * x + W.a₆) [PROOFSTEP] rw [add_mul, ← add_assoc] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ eval 0 (eval 0 (WeierstrassCurve.polynomial W)) = -W.a₆ [PROOFSTEP] simp only [← C_0, eval_polynomial, zero_add, zero_sub, mul_zero, zero_pow <| Nat.zero_lt_succ _] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x y : R ⊢ WeierstrassCurve.equation W x y ↔ y ^ 2 + W.a₁ * x * y + W.a₃ * y - (x ^ 3 + W.a₂ * x ^ 2 + W.a₄ * x + W.a₆) = 0 [PROOFSTEP] rw [WeierstrassCurve.equation, eval_polynomial] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x y : R ⊢ WeierstrassCurve.equation W x y ↔ y ^ 2 + W.a₁ * x * y + W.a₃ * y = x ^ 3 + W.a₂ * x ^ 2 + W.a₄ * x + W.a₆ [PROOFSTEP] rw [equation_iff', sub_eq_zero] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ WeierstrassCurve.equation W 0 0 ↔ W.a₆ = 0 [PROOFSTEP] rw [WeierstrassCurve.equation, C_0, eval_polynomial_zero, neg_eq_zero] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x y : R ⊢ WeierstrassCurve.equation W x y ↔ WeierstrassCurve.equation (variableChange W { u := 1, r := x, s := 0, t := y }) 0 0 [PROOFSTEP] rw [equation_iff', ← neg_eq_zero, equation_zero, variableChange_a₆, inv_one, Units.val_one] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x y : R ⊢ -(y ^ 2 + W.a₁ * x * y + W.a₃ * y - (x ^ 3 + W.a₂ * x ^ 2 + W.a₄ * x + W.a₆)) = 0 ↔ 1 ^ 6 * (W.a₆ + { u := 1, r := x, s := 0, t := y }.r * W.a₄ + { u := 1, r := x, s := 0, t := y }.r ^ 2 * W.a₂ + { u := 1, r := x, s := 0, t := y }.r ^ 3 - { u := 1, r := x, s := 0, t := y }.t * W.a₃ - { u := 1, r := x, s := 0, t := y }.t ^ 2 - { u := 1, r := x, s := 0, t := y }.r * { u := 1, r := x, s := 0, t := y }.t * W.a₁) = 0 [PROOFSTEP] congr! 1 [GOAL] case a.h.e'_2 R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x y : R ⊢ -(y ^ 2 + W.a₁ * x * y + W.a₃ * y - (x ^ 3 + W.a₂ * x ^ 2 + W.a₄ * x + W.a₆)) = 1 ^ 6 * (W.a₆ + { u := 1, r := x, s := 0, t := y }.r * W.a₄ + { u := 1, r := x, s := 0, t := y }.r ^ 2 * W.a₂ + { u := 1, r := x, s := 0, t := y }.r ^ 3 - { u := 1, r := x, s := 0, t := y }.t * W.a₃ - { u := 1, r := x, s := 0, t := y }.t ^ 2 - { u := 1, r := x, s := 0, t := y }.r * { u := 1, r := x, s := 0, t := y }.t * W.a₁) [PROOFSTEP] ring1 [GOAL] R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R ⊢ WeierstrassCurve.equation W x y ↔ WeierstrassCurve.equation (baseChange W A) (↑(algebraMap R A) x) (↑(algebraMap R A) y) [PROOFSTEP] simp only [equation_iff] [GOAL] R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R ⊢ y ^ 2 + W.a₁ * x * y + W.a₃ * y = x ^ 3 + W.a₂ * x ^ 2 + W.a₄ * x + W.a₆ ↔ ↑(algebraMap R A) y ^ 2 + (baseChange W A).a₁ * ↑(algebraMap R A) x * ↑(algebraMap R A) y + (baseChange W A).a₃ * ↑(algebraMap R A) y = ↑(algebraMap R A) x ^ 3 + (baseChange W A).a₂ * ↑(algebraMap R A) x ^ 2 + (baseChange W A).a₄ * ↑(algebraMap R A) x + (baseChange W A).a₆ [PROOFSTEP] exact ⟨fun h => by convert congr_arg (algebraMap R A) h <;> map_simp <;> rfl, fun h => by apply NoZeroSMulDivisors.algebraMap_injective R A; map_simp; exact h⟩ [GOAL] R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : y ^ 2 + W.a₁ * x * y + W.a₃ * y = x ^ 3 + W.a₂ * x ^ 2 + W.a₄ * x + W.a₆ ⊢ ↑(algebraMap R A) y ^ 2 + (baseChange W A).a₁ * ↑(algebraMap R A) x * ↑(algebraMap R A) y + (baseChange W A).a₃ * ↑(algebraMap R A) y = ↑(algebraMap R A) x ^ 3 + (baseChange W A).a₂ * ↑(algebraMap R A) x ^ 2 + (baseChange W A).a₄ * ↑(algebraMap R A) x + (baseChange W A).a₆ [PROOFSTEP] convert congr_arg (algebraMap R A) h [GOAL] case h.e'_2 R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : y ^ 2 + W.a₁ * x * y + W.a₃ * y = x ^ 3 + W.a₂ * x ^ 2 + W.a₄ * x + W.a₆ ⊢ ↑(algebraMap R A) y ^ 2 + (baseChange W A).a₁ * ↑(algebraMap R A) x * ↑(algebraMap R A) y + (baseChange W A).a₃ * ↑(algebraMap R A) y = ↑(algebraMap R A) (y ^ 2 + W.a₁ * x * y + W.a₃ * y) [PROOFSTEP] map_simp [GOAL] case h.e'_3 R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : y ^ 2 + W.a₁ * x * y + W.a₃ * y = x ^ 3 + W.a₂ * x ^ 2 + W.a₄ * x + W.a₆ ⊢ ↑(algebraMap R A) x ^ 3 + (baseChange W A).a₂ * ↑(algebraMap R A) x ^ 2 + (baseChange W A).a₄ * ↑(algebraMap R A) x + (baseChange W A).a₆ = ↑(algebraMap R A) (x ^ 3 + W.a₂ * x ^ 2 + W.a₄ * x + W.a₆) [PROOFSTEP] map_simp [GOAL] case h.e'_2 R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : y ^ 2 + W.a₁ * x * y + W.a₃ * y = x ^ 3 + W.a₂ * x ^ 2 + W.a₄ * x + W.a₆ ⊢ ↑(algebraMap R A) y ^ 2 + (baseChange W A).a₁ * ↑(algebraMap R A) x * ↑(algebraMap R A) y + (baseChange W A).a₃ * ↑(algebraMap R A) y = ↑(algebraMap R A) y ^ 2 + ↑(algebraMap R A) W.a₁ * ↑(algebraMap R A) x * ↑(algebraMap R A) y + ↑(algebraMap R A) W.a₃ * ↑(algebraMap R A) y [PROOFSTEP] rfl [GOAL] case h.e'_3 R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : y ^ 2 + W.a₁ * x * y + W.a₃ * y = x ^ 3 + W.a₂ * x ^ 2 + W.a₄ * x + W.a₆ ⊢ ↑(algebraMap R A) x ^ 3 + (baseChange W A).a₂ * ↑(algebraMap R A) x ^ 2 + (baseChange W A).a₄ * ↑(algebraMap R A) x + (baseChange W A).a₆ = ↑(algebraMap R A) x ^ 3 + ↑(algebraMap R A) W.a₂ * ↑(algebraMap R A) x ^ 2 + ↑(algebraMap R A) W.a₄ * ↑(algebraMap R A) x + ↑(algebraMap R A) W.a₆ [PROOFSTEP] rfl [GOAL] R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : ↑(algebraMap R A) y ^ 2 + (baseChange W A).a₁ * ↑(algebraMap R A) x * ↑(algebraMap R A) y + (baseChange W A).a₃ * ↑(algebraMap R A) y = ↑(algebraMap R A) x ^ 3 + (baseChange W A).a₂ * ↑(algebraMap R A) x ^ 2 + (baseChange W A).a₄ * ↑(algebraMap R A) x + (baseChange W A).a₆ ⊢ y ^ 2 + W.a₁ * x * y + W.a₃ * y = x ^ 3 + W.a₂ * x ^ 2 + W.a₄ * x + W.a₆ [PROOFSTEP] apply NoZeroSMulDivisors.algebraMap_injective R A [GOAL] case a R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : ↑(algebraMap R A) y ^ 2 + (baseChange W A).a₁ * ↑(algebraMap R A) x * ↑(algebraMap R A) y + (baseChange W A).a₃ * ↑(algebraMap R A) y = ↑(algebraMap R A) x ^ 3 + (baseChange W A).a₂ * ↑(algebraMap R A) x ^ 2 + (baseChange W A).a₄ * ↑(algebraMap R A) x + (baseChange W A).a₆ ⊢ ↑(algebraMap R A) (y ^ 2 + W.a₁ * x * y + W.a₃ * y) = ↑(algebraMap R A) (x ^ 3 + W.a₂ * x ^ 2 + W.a₄ * x + W.a₆) [PROOFSTEP] map_simp [GOAL] case a R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : ↑(algebraMap R A) y ^ 2 + (baseChange W A).a₁ * ↑(algebraMap R A) x * ↑(algebraMap R A) y + (baseChange W A).a₃ * ↑(algebraMap R A) y = ↑(algebraMap R A) x ^ 3 + (baseChange W A).a₂ * ↑(algebraMap R A) x ^ 2 + (baseChange W A).a₄ * ↑(algebraMap R A) x + (baseChange W A).a₆ ⊢ ↑(algebraMap R A) y ^ 2 + ↑(algebraMap R A) W.a₁ * ↑(algebraMap R A) x * ↑(algebraMap R A) y + ↑(algebraMap R A) W.a₃ * ↑(algebraMap R A) y = ↑(algebraMap R A) x ^ 3 + ↑(algebraMap R A) W.a₂ * ↑(algebraMap R A) x ^ 2 + ↑(algebraMap R A) W.a₄ * ↑(algebraMap R A) x + ↑(algebraMap R A) W.a₆ [PROOFSTEP] exact h [GOAL] R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial B inst✝ : NoZeroSMulDivisors A B x y : A ⊢ WeierstrassCurve.equation (baseChange W A) x y ↔ WeierstrassCurve.equation (baseChange W B) (↑(algebraMap A B) x) (↑(algebraMap A B) y) [PROOFSTEP] rw [equation_iff_baseChange (W.baseChange A) B, baseChange_baseChange] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x y : R ⊢ eval x (eval (↑C y) (WeierstrassCurve.polynomialX W)) = W.a₁ * y - (3 * x ^ 2 + 2 * W.a₂ * x + W.a₄) [PROOFSTEP] simp only [WeierstrassCurve.polynomialX] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x y : R ⊢ eval x (eval (↑C y) (↑C (↑C W.a₁) * Y - ↑C (↑C 3 * Y ^ 2 + ↑C (2 * W.a₂) * Y + ↑C W.a₄))) = W.a₁ * y - (3 * x ^ 2 + 2 * W.a₂ * x + W.a₄) [PROOFSTEP] eval_simp [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ eval 0 (eval 0 (WeierstrassCurve.polynomialX W)) = -W.a₄ [PROOFSTEP] simp only [← C_0, eval_polynomialX, zero_add, zero_sub, mul_zero, zero_pow zero_lt_two] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x y : R ⊢ eval x (eval (↑C y) (WeierstrassCurve.polynomialY W)) = 2 * y + W.a₁ * x + W.a₃ [PROOFSTEP] simp only [WeierstrassCurve.polynomialY] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x y : R ⊢ eval x (eval (↑C y) (↑C (↑C 2) * Y + ↑C (↑C W.a₁ * Y + ↑C W.a₃))) = 2 * y + W.a₁ * x + W.a₃ [PROOFSTEP] eval_simp [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x y : R ⊢ 2 * y + (W.a₁ * x + W.a₃) = 2 * y + W.a₁ * x + W.a₃ [PROOFSTEP] rw [← add_assoc] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ eval 0 (eval 0 (WeierstrassCurve.polynomialY W)) = W.a₃ [PROOFSTEP] simp only [← C_0, eval_polynomialY, zero_add, mul_zero] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x y : R ⊢ WeierstrassCurve.nonsingular W x y ↔ WeierstrassCurve.equation W x y ∧ (W.a₁ * y - (3 * x ^ 2 + 2 * W.a₂ * x + W.a₄) ≠ 0 ∨ 2 * y + W.a₁ * x + W.a₃ ≠ 0) [PROOFSTEP] rw [WeierstrassCurve.nonsingular, equation_iff', eval_polynomialX, eval_polynomialY] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x y : R ⊢ WeierstrassCurve.nonsingular W x y ↔ WeierstrassCurve.equation W x y ∧ (W.a₁ * y ≠ 3 * x ^ 2 + 2 * W.a₂ * x + W.a₄ ∨ y ≠ -y - W.a₁ * x - W.a₃) [PROOFSTEP] rw [nonsingular_iff', sub_ne_zero, ← @sub_ne_zero _ _ y] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x y : R ⊢ WeierstrassCurve.equation W x y ∧ (W.a₁ * y ≠ 3 * x ^ 2 + 2 * W.a₂ * x + W.a₄ ∨ 2 * y + W.a₁ * x + W.a₃ ≠ 0) ↔ WeierstrassCurve.equation W x y ∧ (W.a₁ * y ≠ 3 * x ^ 2 + 2 * W.a₂ * x + W.a₄ ∨ y - (-y - W.a₁ * x - W.a₃) ≠ 0) [PROOFSTEP] congr! 3 [GOAL] case a.h.e'_2.h.e'_2.h.e'_2 R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x y : R ⊢ 2 * y + W.a₁ * x + W.a₃ = y - (-y - W.a₁ * x - W.a₃) [PROOFSTEP] ring1 [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B ⊢ WeierstrassCurve.nonsingular W 0 0 ↔ W.a₆ = 0 ∧ (W.a₃ ≠ 0 ∨ W.a₄ ≠ 0) [PROOFSTEP] rw [WeierstrassCurve.nonsingular, equation_zero, C_0, eval_polynomialX_zero, neg_ne_zero, eval_polynomialY_zero, or_comm] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x y : R ⊢ WeierstrassCurve.nonsingular W x y ↔ WeierstrassCurve.nonsingular (variableChange W { u := 1, r := x, s := 0, t := y }) 0 0 [PROOFSTEP] rw [nonsingular_iff', equation_iff_variableChange, equation_zero, ← neg_ne_zero, or_comm, nonsingular_zero, variableChange_a₃, variableChange_a₄, inv_one, Units.val_one] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x y : R ⊢ (variableChange W { u := 1, r := x, s := 0, t := y }).a₆ = 0 ∧ (2 * y + W.a₁ * x + W.a₃ ≠ 0 ∨ -(W.a₁ * y - (3 * x ^ 2 + 2 * W.a₂ * x + W.a₄)) ≠ 0) ↔ (variableChange W { u := 1, r := x, s := 0, t := y }).a₆ = 0 ∧ (1 ^ 3 * (W.a₃ + { u := 1, r := x, s := 0, t := y }.r * W.a₁ + 2 * { u := 1, r := x, s := 0, t := y }.t) ≠ 0 ∨ 1 ^ 4 * (W.a₄ - { u := 1, r := x, s := 0, t := y }.s * W.a₃ + 2 * { u := 1, r := x, s := 0, t := y }.r * W.a₂ - ({ u := 1, r := x, s := 0, t := y }.t + { u := 1, r := x, s := 0, t := y }.r * { u := 1, r := x, s := 0, t := y }.s) * W.a₁ + 3 * { u := 1, r := x, s := 0, t := y }.r ^ 2 - 2 * { u := 1, r := x, s := 0, t := y }.s * { u := 1, r := x, s := 0, t := y }.t) ≠ 0) [PROOFSTEP] simp only [variableChange] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x y : R ⊢ ↑1⁻¹ ^ 6 * (W.a₆ + x * W.a₄ + x ^ 2 * W.a₂ + x ^ 3 - y * W.a₃ - y ^ 2 - x * y * W.a₁) = 0 ∧ (2 * y + W.a₁ * x + W.a₃ ≠ 0 ∨ -(W.a₁ * y - (3 * x ^ 2 + 2 * W.a₂ * x + W.a₄)) ≠ 0) ↔ ↑1⁻¹ ^ 6 * (W.a₆ + x * W.a₄ + x ^ 2 * W.a₂ + x ^ 3 - y * W.a₃ - y ^ 2 - x * y * W.a₁) = 0 ∧ (1 ^ 3 * (W.a₃ + x * W.a₁ + 2 * y) ≠ 0 ∨ 1 ^ 4 * (W.a₄ - 0 * W.a₃ + 2 * x * W.a₂ - (y + x * 0) * W.a₁ + 3 * x ^ 2 - 2 * 0 * y) ≠ 0) [PROOFSTEP] congr! 3 [GOAL] case a.h.e'_2.h.e'_1.h.e'_2 R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x y : R ⊢ 2 * y + W.a₁ * x + W.a₃ = 1 ^ 3 * (W.a₃ + x * W.a₁ + 2 * y) [PROOFSTEP] ring1 [GOAL] case a.h.e'_2.h.e'_2.h.e'_2 R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x y : R ⊢ -(W.a₁ * y - (3 * x ^ 2 + 2 * W.a₂ * x + W.a₄)) = 1 ^ 4 * (W.a₄ - 0 * W.a₃ + 2 * x * W.a₂ - (y + x * 0) * W.a₁ + 3 * x ^ 2 - 2 * 0 * y) [PROOFSTEP] ring1 [GOAL] R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R ⊢ WeierstrassCurve.nonsingular W x y ↔ WeierstrassCurve.nonsingular (baseChange W A) (↑(algebraMap R A) x) (↑(algebraMap R A) y) [PROOFSTEP] rw [nonsingular_iff, nonsingular_iff, and_congr <| W.equation_iff_baseChange A x y] [GOAL] R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R ⊢ W.a₁ * y ≠ 3 * x ^ 2 + 2 * W.a₂ * x + W.a₄ ∨ y ≠ -y - W.a₁ * x - W.a₃ ↔ (baseChange W A).a₁ * ↑(algebraMap R A) y ≠ 3 * ↑(algebraMap R A) x ^ 2 + 2 * (baseChange W A).a₂ * ↑(algebraMap R A) x + (baseChange W A).a₄ ∨ ↑(algebraMap R A) y ≠ -↑(algebraMap R A) y - (baseChange W A).a₁ * ↑(algebraMap R A) x - (baseChange W A).a₃ [PROOFSTEP] refine ⟨Or.imp (not_imp_not.mpr fun h => ?_) (not_imp_not.mpr fun h => ?_), Or.imp (not_imp_not.mpr fun h => ?_) (not_imp_not.mpr fun h => ?_)⟩ [GOAL] case refine_1 R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : (baseChange W A).a₁ * ↑(algebraMap R A) y = 3 * ↑(algebraMap R A) x ^ 2 + 2 * (baseChange W A).a₂ * ↑(algebraMap R A) x + (baseChange W A).a₄ ⊢ W.a₁ * y = 3 * x ^ 2 + 2 * W.a₂ * x + W.a₄ case refine_2 R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : ↑(algebraMap R A) y = -↑(algebraMap R A) y - (baseChange W A).a₁ * ↑(algebraMap R A) x - (baseChange W A).a₃ ⊢ y = -y - W.a₁ * x - W.a₃ case refine_3 R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : W.a₁ * y = 3 * x ^ 2 + 2 * W.a₂ * x + W.a₄ ⊢ (baseChange W A).a₁ * ↑(algebraMap R A) y = 3 * ↑(algebraMap R A) x ^ 2 + 2 * (baseChange W A).a₂ * ↑(algebraMap R A) x + (baseChange W A).a₄ case refine_4 R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : y = -y - W.a₁ * x - W.a₃ ⊢ ↑(algebraMap R A) y = -↑(algebraMap R A) y - (baseChange W A).a₁ * ↑(algebraMap R A) x - (baseChange W A).a₃ [PROOFSTEP] any_goals apply NoZeroSMulDivisors.algebraMap_injective R A; map_simp; exact h [GOAL] case refine_1 R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : (baseChange W A).a₁ * ↑(algebraMap R A) y = 3 * ↑(algebraMap R A) x ^ 2 + 2 * (baseChange W A).a₂ * ↑(algebraMap R A) x + (baseChange W A).a₄ ⊢ W.a₁ * y = 3 * x ^ 2 + 2 * W.a₂ * x + W.a₄ [PROOFSTEP] apply NoZeroSMulDivisors.algebraMap_injective R A [GOAL] case refine_1.a R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : (baseChange W A).a₁ * ↑(algebraMap R A) y = 3 * ↑(algebraMap R A) x ^ 2 + 2 * (baseChange W A).a₂ * ↑(algebraMap R A) x + (baseChange W A).a₄ ⊢ ↑(algebraMap R A) (W.a₁ * y) = ↑(algebraMap R A) (3 * x ^ 2 + 2 * W.a₂ * x + W.a₄) [PROOFSTEP] map_simp [GOAL] case refine_1.a R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : (baseChange W A).a₁ * ↑(algebraMap R A) y = 3 * ↑(algebraMap R A) x ^ 2 + 2 * (baseChange W A).a₂ * ↑(algebraMap R A) x + (baseChange W A).a₄ ⊢ ↑(algebraMap R A) W.a₁ * ↑(algebraMap R A) y = 3 * ↑(algebraMap R A) x ^ 2 + 2 * ↑(algebraMap R A) W.a₂ * ↑(algebraMap R A) x + ↑(algebraMap R A) W.a₄ [PROOFSTEP] exact h [GOAL] case refine_2 R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : ↑(algebraMap R A) y = -↑(algebraMap R A) y - (baseChange W A).a₁ * ↑(algebraMap R A) x - (baseChange W A).a₃ ⊢ y = -y - W.a₁ * x - W.a₃ [PROOFSTEP] apply NoZeroSMulDivisors.algebraMap_injective R A [GOAL] case refine_2.a R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : ↑(algebraMap R A) y = -↑(algebraMap R A) y - (baseChange W A).a₁ * ↑(algebraMap R A) x - (baseChange W A).a₃ ⊢ ↑(algebraMap R A) y = ↑(algebraMap R A) (-y - W.a₁ * x - W.a₃) [PROOFSTEP] map_simp [GOAL] case refine_2.a R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : ↑(algebraMap R A) y = -↑(algebraMap R A) y - (baseChange W A).a₁ * ↑(algebraMap R A) x - (baseChange W A).a₃ ⊢ ↑(algebraMap R A) y = -↑(algebraMap R A) y - ↑(algebraMap R A) W.a₁ * ↑(algebraMap R A) x - ↑(algebraMap R A) W.a₃ [PROOFSTEP] exact h [GOAL] case refine_3 R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : W.a₁ * y = 3 * x ^ 2 + 2 * W.a₂ * x + W.a₄ ⊢ (baseChange W A).a₁ * ↑(algebraMap R A) y = 3 * ↑(algebraMap R A) x ^ 2 + 2 * (baseChange W A).a₂ * ↑(algebraMap R A) x + (baseChange W A).a₄ [PROOFSTEP] apply NoZeroSMulDivisors.algebraMap_injective R A [GOAL] case refine_4 R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : y = -y - W.a₁ * x - W.a₃ ⊢ ↑(algebraMap R A) y = -↑(algebraMap R A) y - (baseChange W A).a₁ * ↑(algebraMap R A) x - (baseChange W A).a₃ [PROOFSTEP] apply NoZeroSMulDivisors.algebraMap_injective R A [GOAL] case refine_3 R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : W.a₁ * y = 3 * x ^ 2 + 2 * W.a₂ * x + W.a₄ ⊢ (baseChange W A).a₁ * ↑(algebraMap R A) y = 3 * ↑(algebraMap R A) x ^ 2 + 2 * (baseChange W A).a₂ * ↑(algebraMap R A) x + (baseChange W A).a₄ case refine_4 R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : y = -y - W.a₁ * x - W.a₃ ⊢ ↑(algebraMap R A) y = -↑(algebraMap R A) y - (baseChange W A).a₁ * ↑(algebraMap R A) x - (baseChange W A).a₃ [PROOFSTEP] any_goals convert congr_arg (algebraMap R A) h <;> map_simp <;> rfl [GOAL] case refine_3 R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : W.a₁ * y = 3 * x ^ 2 + 2 * W.a₂ * x + W.a₄ ⊢ (baseChange W A).a₁ * ↑(algebraMap R A) y = 3 * ↑(algebraMap R A) x ^ 2 + 2 * (baseChange W A).a₂ * ↑(algebraMap R A) x + (baseChange W A).a₄ [PROOFSTEP] convert congr_arg (algebraMap R A) h [GOAL] case h.e'_2 R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : W.a₁ * y = 3 * x ^ 2 + 2 * W.a₂ * x + W.a₄ ⊢ (baseChange W A).a₁ * ↑(algebraMap R A) y = ↑(algebraMap R A) (W.a₁ * y) [PROOFSTEP] map_simp [GOAL] case h.e'_3 R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : W.a₁ * y = 3 * x ^ 2 + 2 * W.a₂ * x + W.a₄ ⊢ 3 * ↑(algebraMap R A) x ^ 2 + 2 * (baseChange W A).a₂ * ↑(algebraMap R A) x + (baseChange W A).a₄ = ↑(algebraMap R A) (3 * x ^ 2 + 2 * W.a₂ * x + W.a₄) [PROOFSTEP] map_simp [GOAL] case h.e'_2 R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : W.a₁ * y = 3 * x ^ 2 + 2 * W.a₂ * x + W.a₄ ⊢ (baseChange W A).a₁ * ↑(algebraMap R A) y = ↑(algebraMap R A) W.a₁ * ↑(algebraMap R A) y [PROOFSTEP] rfl [GOAL] case h.e'_3 R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : W.a₁ * y = 3 * x ^ 2 + 2 * W.a₂ * x + W.a₄ ⊢ 3 * ↑(algebraMap R A) x ^ 2 + 2 * (baseChange W A).a₂ * ↑(algebraMap R A) x + (baseChange W A).a₄ = 3 * ↑(algebraMap R A) x ^ 2 + 2 * ↑(algebraMap R A) W.a₂ * ↑(algebraMap R A) x + ↑(algebraMap R A) W.a₄ [PROOFSTEP] rfl [GOAL] case refine_4 R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : y = -y - W.a₁ * x - W.a₃ ⊢ ↑(algebraMap R A) y = -↑(algebraMap R A) y - (baseChange W A).a₁ * ↑(algebraMap R A) x - (baseChange W A).a₃ [PROOFSTEP] convert congr_arg (algebraMap R A) h [GOAL] case h.e'_3 R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : y = -y - W.a₁ * x - W.a₃ ⊢ -↑(algebraMap R A) y - (baseChange W A).a₁ * ↑(algebraMap R A) x - (baseChange W A).a₃ = ↑(algebraMap R A) (-y - W.a₁ * x - W.a₃) [PROOFSTEP] map_simp [GOAL] case h.e'_3 R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial A inst✝ : NoZeroSMulDivisors R A x y : R h : y = -y - W.a₁ * x - W.a₃ ⊢ -↑(algebraMap R A) y - (baseChange W A).a₁ * ↑(algebraMap R A) x - (baseChange W A).a₃ = -↑(algebraMap R A) y - ↑(algebraMap R A) W.a₁ * ↑(algebraMap R A) x - ↑(algebraMap R A) W.a₃ [PROOFSTEP] rfl [GOAL] R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : Nontrivial B inst✝ : NoZeroSMulDivisors A B x y : A ⊢ WeierstrassCurve.nonsingular (baseChange W A) x y ↔ WeierstrassCurve.nonsingular (baseChange W B) (↑(algebraMap A B) x) (↑(algebraMap A B) y) [PROOFSTEP] rw [nonsingular_iff_baseChange (W.baseChange A) B, baseChange_baseChange] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B h : WeierstrassCurve.equation W 0 0 hΔ : Δ W ≠ 0 ⊢ WeierstrassCurve.nonsingular W 0 0 [PROOFSTEP] simp only [equation_zero, nonsingular_zero] at * [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B hΔ : Δ W ≠ 0 h : W.a₆ = 0 ⊢ W.a₆ = 0 ∧ (W.a₃ ≠ 0 ∨ W.a₄ ≠ 0) [PROOFSTEP] contrapose! hΔ [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B h : W.a₆ = 0 hΔ : W.a₆ = 0 → W.a₃ = 0 ∧ W.a₄ = 0 ⊢ Δ W = 0 [PROOFSTEP] simp only [b₂, b₄, b₆, b₈, Δ, h, hΔ] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B h : W.a₆ = 0 hΔ : W.a₆ = 0 → W.a₃ = 0 ∧ W.a₄ = 0 ⊢ -(W.a₁ ^ 2 + 4 * W.a₂) ^ 2 * (W.a₁ ^ 2 * 0 + 4 * W.a₂ * 0 - W.a₁ * 0 * 0 + W.a₂ * 0 ^ 2 - 0 ^ 2) - 8 * (2 * 0 + W.a₁ * 0) ^ 3 - 27 * (0 ^ 2 + 4 * 0) ^ 2 + 9 * (W.a₁ ^ 2 + 4 * W.a₂) * (2 * 0 + W.a₁ * 0) * (0 ^ 2 + 4 * 0) = 0 [PROOFSTEP] ring1 [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x y : R h : WeierstrassCurve.equation W x y hΔ : Δ W ≠ 0 ⊢ Δ (variableChange W { u := 1, r := x, s := 0, t := y }) ≠ 0 [PROOFSTEP] rwa [variableChange_Δ, inv_one, Units.val_one, one_pow, one_mul] [GOAL] R : Type u inst✝⁸ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁷ : CommRing A inst✝⁶ : Algebra R A B : Type w inst✝⁵ : CommRing B inst✝⁴ : Algebra R B inst✝³ : Algebra A B inst✝² : IsScalarTower R A B inst✝¹ : IsDomain R inst✝ : NormalizedGCDMonoid R ⊢ IsPrime (span {WeierstrassCurve.polynomial W}) [PROOFSTEP] simpa only [span_singleton_prime W.polynomial_ne_zero, ← GCDMonoid.irreducible_iff_prime] using W.irreducible_polynomial [GOAL] R : Type u inst✝⁷ : CommRing R W✝ : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B F : Type u inst✝ : Field F W : WeierstrassCurve F ⊢ IsDomain (CoordinateRing W) [PROOFSTEP] classical exact instIsDomainCoordinateRing W [GOAL] R : Type u inst✝⁷ : CommRing R W✝ : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B F : Type u inst✝ : Field F W : WeierstrassCurve F ⊢ IsDomain (CoordinateRing W) [PROOFSTEP] exact instIsDomainCoordinateRing W [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : Nontrivial R ⊢ natDegree (↑C (Y - ↑C x)) < natDegree (WeierstrassCurve.polynomial W) [PROOFSTEP] rw [natDegree_polynomial, natDegree_C] [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : Nontrivial R ⊢ 0 < 2 [PROOFSTEP] norm_num1 [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : Nontrivial R ⊢ natDegree (Y - ↑C y) < natDegree (WeierstrassCurve.polynomial W) [PROOFSTEP] rw [natDegree_polynomial, natDegree_X_sub_C] [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : Nontrivial R ⊢ 1 < 2 [PROOFSTEP] norm_num1 [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x✝ : R y✝ : R[X] x : R y : R[X] h : eval x (eval y (WeierstrassCurve.polynomial W)) = 0 ⊢ XYIdeal W x y = Ideal.map (Quotient.mkₐ R (span {WeierstrassCurve.polynomial W})) (span {↑C (Y - ↑C x), Y - ↑C y}) [PROOFSTEP] simp only [XYIdeal, XClass, YClass, ← Set.image_pair, ← map_span] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x✝ : R y✝ : R[X] x : R y : R[X] h : eval x (eval y (WeierstrassCurve.polynomial W)) = 0 ⊢ Ideal.map (mk W) (span {↑C (Y - ↑C x), Y - ↑C y}) = Ideal.map (Quotient.mkₐ R (span {WeierstrassCurve.polynomial W})) (span {↑C (Y - ↑C x), Y - ↑C y}) [PROOFSTEP] rfl [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x : R y : R[X] ⊢ Basis (Fin 2) R[X] (CoordinateRing W) [PROOFSTEP] classical exact (subsingleton_or_nontrivial R).by_cases (fun _ => default) fun _ => (AdjoinRoot.powerBasis' W.monic_polynomial).basis.reindex <| finCongr W.natDegree_polynomial [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x : R y : R[X] ⊢ Basis (Fin 2) R[X] (CoordinateRing W) [PROOFSTEP] exact (subsingleton_or_nontrivial R).by_cases (fun _ => default) fun _ => (AdjoinRoot.powerBasis' W.monic_polynomial).basis.reindex <| finCongr W.natDegree_polynomial [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x : R y : R[X] n : Fin 2 ⊢ ↑(CoordinateRing.basis W) n = (AdjoinRoot.powerBasis' (_ : Monic (WeierstrassCurve.polynomial W))).gen ^ ↑n [PROOFSTEP] classical nontriviality R rw [CoordinateRing.basis, Or.by_cases, dif_neg <| not_subsingleton R, Basis.reindex_apply, PowerBasis.basis_eq_pow] rfl [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x : R y : R[X] n : Fin 2 ⊢ ↑(CoordinateRing.basis W) n = (AdjoinRoot.powerBasis' (_ : Monic (WeierstrassCurve.polynomial W))).gen ^ ↑n [PROOFSTEP] nontriviality R [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x : R y : R[X] n : Fin 2 ✝ : Nontrivial R ⊢ ↑(CoordinateRing.basis W) n = (AdjoinRoot.powerBasis' (_ : Monic (WeierstrassCurve.polynomial W))).gen ^ ↑n [PROOFSTEP] rw [CoordinateRing.basis, Or.by_cases, dif_neg <| not_subsingleton R, Basis.reindex_apply, PowerBasis.basis_eq_pow] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x : R y : R[X] n : Fin 2 ✝ : Nontrivial R ⊢ (AdjoinRoot.powerBasis' (_ : Monic (WeierstrassCurve.polynomial W))).gen ^ ↑(↑(finCongr (_ : natDegree (WeierstrassCurve.polynomial W) = 2)).symm n) = (AdjoinRoot.powerBasis' (_ : Monic (WeierstrassCurve.polynomial W))).gen ^ ↑n [PROOFSTEP] rfl [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x : R y : R[X] ⊢ ↑(CoordinateRing.basis W) 0 = 1 [PROOFSTEP] simpa only [basis_apply] using pow_zero _ [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x : R y : R[X] ⊢ ↑(CoordinateRing.basis W) 1 = ↑(mk W) Y [PROOFSTEP] simpa only [basis_apply] using pow_one _ [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x : R y : R[X] ⊢ ↑(CoordinateRing.basis W) = ![1, ↑(mk W) Y] [PROOFSTEP] ext n [GOAL] case h R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x : R y : R[X] n : Fin 2 ⊢ ↑(CoordinateRing.basis W) n = Matrix.vecCons 1 ![↑(mk W) Y] n [PROOFSTEP] fin_cases n [GOAL] case h.head R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x : R y : R[X] ⊢ ↑(CoordinateRing.basis W) { val := 0, isLt := (_ : 0 < 2) } = Matrix.vecCons 1 ![↑(mk W) Y] { val := 0, isLt := (_ : 0 < 2) } case h.tail.head R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x : R y : R[X] ⊢ ↑(CoordinateRing.basis W) { val := 1, isLt := (_ : (fun a => a < 2) 1) } = Matrix.vecCons 1 ![↑(mk W) Y] { val := 1, isLt := (_ : (fun a => a < 2) 1) } [PROOFSTEP] exacts [basis_zero W, basis_one W] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x : R y p q : R[X] hpq : p • 1 + q • ↑(mk W) Y = 0 ⊢ p = 0 ∧ q = 0 [PROOFSTEP] have h := Fintype.linearIndependent_iff.mp (CoordinateRing.basis W).linearIndependent ![p, q] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x : R y p q : R[X] hpq : p • 1 + q • ↑(mk W) Y = 0 h : (Finset.sum Finset.univ fun i => Matrix.vecCons p ![q] i • ↑(CoordinateRing.basis W) i) = 0 → ∀ (i : Fin 2), Matrix.vecCons p ![q] i = 0 ⊢ p = 0 ∧ q = 0 [PROOFSTEP] erw [Fin.sum_univ_succ, basis_zero, Fin.sum_univ_one, basis_one] at h [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x : R y p q : R[X] hpq : p • 1 + q • ↑(mk W) Y = 0 h : Matrix.vecCons p ![q] 0 • 1 + Matrix.vecCons p ![q] (Fin.succ 0) • ↑(mk W) Y = 0 → ∀ (i : Fin 2), Matrix.vecCons p ![q] i = 0 ⊢ p = 0 ∧ q = 0 [PROOFSTEP] exact ⟨h hpq 0, h hpq 1⟩ [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x✝ : R y : R[X] x : CoordinateRing W ⊢ ∃ p q, p • 1 + q • ↑(mk W) Y = x [PROOFSTEP] have h := (CoordinateRing.basis W).sum_equivFun x [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x✝ : R y : R[X] x : CoordinateRing W h : (Finset.sum Finset.univ fun i => ↑(Basis.equivFun (CoordinateRing.basis W)) x i • ↑(CoordinateRing.basis W) i) = x ⊢ ∃ p q, p • 1 + q • ↑(mk W) Y = x [PROOFSTEP] erw [Fin.sum_univ_succ, Fin.sum_univ_one, basis_zero, basis_one] at h [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x✝ : R y : R[X] x : CoordinateRing W h : ↑(Basis.equivFun (CoordinateRing.basis W)) x 0 • 1 + ↑(Basis.equivFun (CoordinateRing.basis W)) x (Fin.succ 0) • ↑(mk W) Y = x ⊢ ∃ p q, p • 1 + q • ↑(mk W) Y = x [PROOFSTEP] exact ⟨_, _, h⟩ [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x : R y p q : R[X] ⊢ (p • 1 + q • ↑(mk W) Y) * ↑(mk W) (↑C y) = (p * y) • 1 + (q * y) • ↑(mk W) Y [PROOFSTEP] simp only [smul, _root_.map_mul] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x : R y p q : R[X] ⊢ (↑(mk W) (↑C p) * 1 + ↑(mk W) (↑C q) * ↑(mk W) Y) * ↑(mk W) (↑C y) = ↑(mk W) (↑C p) * ↑(mk W) (↑C y) * 1 + ↑(mk W) (↑C q) * ↑(mk W) (↑C y) * ↑(mk W) Y [PROOFSTEP] ring1 [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x : R y p q : R[X] ⊢ (p • 1 + q • ↑(mk W) Y) * ↑(mk W) Y = (q * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) • 1 + (p - q * (↑C W.a₁ * Y + ↑C W.a₃)) • ↑(mk W) Y [PROOFSTEP] have Y_sq : mk W Y ^ 2 = mk W (C (X ^ 3 + C W.a₂ * X ^ 2 + C W.a₄ * X + C W.a₆) - C (C W.a₁ * X + C W.a₃) * Y) := by exact AdjoinRoot.mk_eq_mk.mpr ⟨1, by rw [WeierstrassCurve.polynomial]; ring1⟩ [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x : R y p q : R[X] ⊢ ↑(mk W) Y ^ 2 = ↑(mk W) (↑C (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆) - ↑C (↑C W.a₁ * Y + ↑C W.a₃) * Y) [PROOFSTEP] exact AdjoinRoot.mk_eq_mk.mpr ⟨1, by rw [WeierstrassCurve.polynomial]; ring1⟩ [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x : R y p q : R[X] ⊢ (fun x => x ^ 2) Y - (↑C (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆) - ↑C (↑C W.a₁ * Y + ↑C W.a₃) * Y) = WeierstrassCurve.polynomial W * 1 [PROOFSTEP] rw [WeierstrassCurve.polynomial] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x : R y p q : R[X] ⊢ (fun x => x ^ 2) Y - (↑C (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆) - ↑C (↑C W.a₁ * Y + ↑C W.a₃) * Y) = (Y ^ 2 + ↑C (↑C W.a₁ * Y + ↑C W.a₃) * Y - ↑C (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) * 1 [PROOFSTEP] ring1 [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x : R y p q : R[X] Y_sq : ↑(mk W) Y ^ 2 = ↑(mk W) (↑C (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆) - ↑C (↑C W.a₁ * Y + ↑C W.a₃) * Y) ⊢ (p • 1 + q • ↑(mk W) Y) * ↑(mk W) Y = (q * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) • 1 + (p - q * (↑C W.a₁ * Y + ↑C W.a₃)) • ↑(mk W) Y [PROOFSTEP] simp_rw [smul, add_mul, mul_assoc, ← sq, Y_sq, C_sub, map_sub, C_mul, _root_.map_mul] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x : R y p q : R[X] Y_sq : ↑(mk W) Y ^ 2 = ↑(mk W) (↑C (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆) - ↑C (↑C W.a₁ * Y + ↑C W.a₃) * Y) ⊢ ↑(mk W) (↑C p) * (1 * ↑(mk W) Y) + ↑(mk W) (↑C q) * (↑(mk W) (↑C (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) - ↑(mk W) (↑C (↑C W.a₁ * Y + ↑C W.a₃)) * ↑(mk W) Y) = ↑(mk W) (↑C q) * ↑(mk W) (↑C (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) * 1 + (↑(mk W) (↑C p) - ↑(mk W) (↑C q) * ↑(mk W) (↑C (↑C W.a₁ * Y + ↑C W.a₃))) * ↑(mk W) Y [PROOFSTEP] ring1 [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x : R y p q : R[X] ⊢ ↑(Algebra.norm R[X]) (p • 1 + q • ↑(mk W) Y) = p ^ 2 - p * q * (↑C W.a₁ * Y + ↑C W.a₃) - q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆) [PROOFSTEP] simp_rw [Algebra.norm_eq_matrix_det <| CoordinateRing.basis W, Matrix.det_fin_two, Algebra.leftMulMatrix_eq_repr_mul, basis_zero, mul_one, basis_one, smul_basis_mul_Y, map_add, Finsupp.add_apply, map_smul, Finsupp.smul_apply, ← basis_zero, ← basis_one, Basis.repr_self_apply, if_pos, if_neg, smul_eq_mul] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x : R y p q : R[X] ⊢ (p * 1 + q * 0) * (q * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆) * 0 + (p - q * (↑C W.a₁ * Y + ↑C W.a₃)) * 1) - (q * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆) * 1 + (p - q * (↑C W.a₁ * Y + ↑C W.a₃)) * 0) * (p * 0 + q * 1) = p ^ 2 - p * q * (↑C W.a₁ * Y + ↑C W.a₃) - q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆) [PROOFSTEP] ring1 [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x : R y p q : R[X] ⊢ ↑C (↑(Algebra.norm R[X]) (p • 1 + q • ↑(mk W) Y)) - (↑C p + ↑C q * Y) * (↑C p + ↑C q * (-Y - ↑C (↑C W.a₁ * Y + ↑C W.a₃))) = WeierstrassCurve.polynomial W * ↑C q ^ 2 [PROOFSTEP] simp only [norm_smul_basis, WeierstrassCurve.polynomial] [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x : R y p q : R[X] ⊢ ↑C (p ^ 2 - p * q * (↑C W.a₁ * Y + ↑C W.a₃) - q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) - (↑C p + ↑C q * Y) * (↑C p + ↑C q * (-Y - ↑C (↑C W.a₁ * Y + ↑C W.a₃))) = (Y ^ 2 + ↑C (↑C W.a₁ * Y + ↑C W.a₃) * Y - ↑C (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) * ↑C q ^ 2 [PROOFSTEP] C_simp [GOAL] R : Type u inst✝⁶ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁵ : CommRing A inst✝⁴ : Algebra R A B : Type w inst✝³ : CommRing B inst✝² : Algebra R B inst✝¹ : Algebra A B inst✝ : IsScalarTower R A B x : R y p q : R[X] ⊢ ↑C p ^ 2 - ↑C p * ↑C q * (↑C (↑C W.a₁) * ↑C Y + ↑C (↑C W.a₃)) - ↑C q ^ 2 * (↑C Y ^ 3 + ↑C (↑C W.a₂) * ↑C Y ^ 2 + ↑C (↑C W.a₄) * ↑C Y + ↑C (↑C W.a₆)) - (↑C p + ↑C q * Y) * (↑C p + ↑C q * (-Y - (↑C (↑C W.a₁) * ↑C Y + ↑C (↑C W.a₃)))) = (Y ^ 2 + (↑C (↑C W.a₁) * ↑C Y + ↑C (↑C W.a₃)) * Y - (↑C Y ^ 3 + ↑C (↑C W.a₂) * ↑C Y ^ 2 + ↑C (↑C W.a₄) * ↑C Y + ↑C (↑C W.a₆))) * ↑C q ^ 2 [PROOFSTEP] ring1 [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] ⊢ degree (↑(Algebra.norm R[X]) (p • 1 + q • ↑(mk W) Y)) = max (2 • degree p) (2 • degree q + 3) [PROOFSTEP] have hdp : (p ^ 2).degree = 2 • p.degree := degree_pow p 2 [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hdp : degree (p ^ 2) = 2 • degree p ⊢ degree (↑(Algebra.norm R[X]) (p • 1 + q • ↑(mk W) Y)) = max (2 • degree p) (2 • degree q + 3) [PROOFSTEP] have hdpq : (p * q * (C W.a₁ * X + C W.a₃)).degree ≤ p.degree + q.degree + 1 := by simpa only [degree_mul] using add_le_add_left degree_linear_le (p.degree + q.degree) [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hdp : degree (p ^ 2) = 2 • degree p ⊢ degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ degree p + degree q + 1 [PROOFSTEP] simpa only [degree_mul] using add_le_add_left degree_linear_le (p.degree + q.degree) [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hdp : degree (p ^ 2) = 2 • degree p hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ degree p + degree q + 1 ⊢ degree (↑(Algebra.norm R[X]) (p • 1 + q • ↑(mk W) Y)) = max (2 • degree p) (2 • degree q + 3) [PROOFSTEP] have hdq : (q ^ 2 * (X ^ 3 + C W.a₂ * X ^ 2 + C W.a₄ * X + C W.a₆)).degree = 2 • q.degree + 3 := by rw [degree_mul, degree_pow, ← one_mul <| X ^ 3, ← C_1, degree_cubic <| one_ne_zero' R] [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hdp : degree (p ^ 2) = 2 • degree p hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ degree p + degree q + 1 ⊢ degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • degree q + 3 [PROOFSTEP] rw [degree_mul, degree_pow, ← one_mul <| X ^ 3, ← C_1, degree_cubic <| one_ne_zero' R] [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hdp : degree (p ^ 2) = 2 • degree p hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ degree p + degree q + 1 hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • degree q + 3 ⊢ degree (↑(Algebra.norm R[X]) (p • 1 + q • ↑(mk W) Y)) = max (2 • degree p) (2 • degree q + 3) [PROOFSTEP] rw [norm_smul_basis] [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hdp : degree (p ^ 2) = 2 • degree p hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ degree p + degree q + 1 hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • degree q + 3 ⊢ degree (p ^ 2 - p * q * (↑C W.a₁ * Y + ↑C W.a₃) - q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = max (2 • degree p) (2 • degree q + 3) [PROOFSTEP] by_cases hp : p = 0 [GOAL] case pos R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hdp : degree (p ^ 2) = 2 • degree p hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ degree p + degree q + 1 hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • degree q + 3 hp : p = 0 ⊢ degree (p ^ 2 - p * q * (↑C W.a₁ * Y + ↑C W.a₃) - q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = max (2 • degree p) (2 • degree q + 3) [PROOFSTEP] simpa only [hp, hdq, neg_zero, zero_sub, zero_mul, zero_pow zero_lt_two, degree_neg] using (max_bot_left _).symm [GOAL] case neg R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hdp : degree (p ^ 2) = 2 • degree p hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ degree p + degree q + 1 hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • degree q + 3 hp : ¬p = 0 ⊢ degree (p ^ 2 - p * q * (↑C W.a₁ * Y + ↑C W.a₃) - q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = max (2 • degree p) (2 • degree q + 3) [PROOFSTEP] by_cases hq : q = 0 [GOAL] case pos R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hdp : degree (p ^ 2) = 2 • degree p hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ degree p + degree q + 1 hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • degree q + 3 hp : ¬p = 0 hq : q = 0 ⊢ degree (p ^ 2 - p * q * (↑C W.a₁ * Y + ↑C W.a₃) - q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = max (2 • degree p) (2 • degree q + 3) [PROOFSTEP] simpa only [hq, hdp, sub_zero, zero_mul, mul_zero, zero_pow zero_lt_two] using (max_bot_right _).symm [GOAL] case neg R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hdp : degree (p ^ 2) = 2 • degree p hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ degree p + degree q + 1 hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • degree q + 3 hp : ¬p = 0 hq : ¬q = 0 ⊢ degree (p ^ 2 - p * q * (↑C W.a₁ * Y + ↑C W.a₃) - q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = max (2 • degree p) (2 • degree q + 3) [PROOFSTEP] rw [← not_congr degree_eq_bot] at hp hq [GOAL] case neg R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hdp : degree (p ^ 2) = 2 • degree p hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ degree p + degree q + 1 hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • degree q + 3 hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ ⊢ degree (p ^ 2 - p * q * (↑C W.a₁ * Y + ↑C W.a₃) - q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = max (2 • degree p) (2 • degree q + 3) [PROOFSTEP] rcases hp' : p.degree with _ | dp [GOAL] case neg.none R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hdp : degree (p ^ 2) = 2 • degree p hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ degree p + degree q + 1 hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • degree q + 3 hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ hp' : degree p = none ⊢ degree (p ^ 2 - p * q * (↑C W.a₁ * Y + ↑C W.a₃) - q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = max (2 • none) (2 • degree q + 3) [PROOFSTEP] exact (hp hp').elim [GOAL] case neg.some R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hdp : degree (p ^ 2) = 2 • degree p hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ degree p + degree q + 1 hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • degree q + 3 hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ dp : ℕ hp' : degree p = some dp ⊢ degree (p ^ 2 - p * q * (↑C W.a₁ * Y + ↑C W.a₃) - q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = max (2 • some dp) (2 • degree q + 3) [PROOFSTEP] rw [hp'] at hdp hdpq [GOAL] case neg.some R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • degree q + 3 hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ dp : ℕ hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ some dp + degree q + 1 hdp : degree (p ^ 2) = 2 • some dp hp' : degree p = some dp ⊢ degree (p ^ 2 - p * q * (↑C W.a₁ * Y + ↑C W.a₃) - q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = max (2 • some dp) (2 • degree q + 3) [PROOFSTEP] rcases hq' : q.degree with _ | dq [GOAL] case neg.some.none R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • degree q + 3 hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ dp : ℕ hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ some dp + degree q + 1 hdp : degree (p ^ 2) = 2 • some dp hp' : degree p = some dp hq' : degree q = none ⊢ degree (p ^ 2 - p * q * (↑C W.a₁ * Y + ↑C W.a₃) - q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = max (2 • some dp) (2 • none + 3) [PROOFSTEP] exact (hq hq').elim [GOAL] case neg.some.some R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • degree q + 3 hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ dp : ℕ hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ some dp + degree q + 1 hdp : degree (p ^ 2) = 2 • some dp hp' : degree p = some dp dq : ℕ hq' : degree q = some dq ⊢ degree (p ^ 2 - p * q * (↑C W.a₁ * Y + ↑C W.a₃) - q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = max (2 • some dp) (2 • some dq + 3) [PROOFSTEP] rw [hq'] at hdpq hdq [GOAL] case neg.some.some R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ dp : ℕ hdp : degree (p ^ 2) = 2 • some dp hp' : degree p = some dp dq : ℕ hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • some dq + 3 hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ some dp + some dq + 1 hq' : degree q = some dq ⊢ degree (p ^ 2 - p * q * (↑C W.a₁ * Y + ↑C W.a₃) - q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = max (2 • some dp) (2 • some dq + 3) [PROOFSTEP] rcases le_or_lt dp (dq + 1) with hpq | hpq [GOAL] case neg.some.some.inl R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ dp : ℕ hdp : degree (p ^ 2) = 2 • some dp hp' : degree p = some dp dq : ℕ hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • some dq + 3 hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ some dp + some dq + 1 hq' : degree q = some dq hpq : dp ≤ dq + 1 ⊢ degree (p ^ 2 - p * q * (↑C W.a₁ * Y + ↑C W.a₃) - q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = max (2 • some dp) (2 • some dq + 3) [PROOFSTEP] convert (degree_sub_eq_right_of_degree_lt <| (degree_sub_le _ _).trans_lt <| max_lt_iff.mpr ⟨hdp.trans_lt _, hdpq.trans_lt _⟩).trans (max_eq_right_of_lt _).symm [GOAL] case h.e'_3.h.e'_4 R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ dp : ℕ hdp : degree (p ^ 2) = 2 • some dp hp' : degree p = some dp dq : ℕ hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • some dq + 3 hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ some dp + some dq + 1 hq' : degree q = some dq hpq : dp ≤ dq + 1 ⊢ 2 • some dq + 3 = degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) [PROOFSTEP] rw [hdq] [GOAL] case neg.some.some.inl.convert_2 R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ dp : ℕ hdp : degree (p ^ 2) = 2 • some dp hp' : degree p = some dp dq : ℕ hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • some dq + 3 hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ some dp + some dq + 1 hq' : degree q = some dq hpq : dp ≤ dq + 1 ⊢ 2 • some dp < degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) [PROOFSTEP] rw [hdq] [GOAL] case neg.some.some.inl.convert_3 R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ dp : ℕ hdp : degree (p ^ 2) = 2 • some dp hp' : degree p = some dp dq : ℕ hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • some dq + 3 hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ some dp + some dq + 1 hq' : degree q = some dq hpq : dp ≤ dq + 1 ⊢ some dp + some dq + 1 < degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) [PROOFSTEP] rw [hdq] [GOAL] case neg.some.some.inl.convert_5 R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ dp : ℕ hdp : degree (p ^ 2) = 2 • some dp hp' : degree p = some dp dq : ℕ hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • some dq + 3 hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ some dp + some dq + 1 hq' : degree q = some dq hpq : dp ≤ dq + 1 ⊢ 2 • some dp < degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) [PROOFSTEP] rw [hdq] [GOAL] case neg.some.some.inl.convert_2 R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ dp : ℕ hdp : degree (p ^ 2) = 2 • some dp hp' : degree p = some dp dq : ℕ hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • some dq + 3 hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ some dp + some dq + 1 hq' : degree q = some dq hpq : dp ≤ dq + 1 ⊢ 2 • some dp < 2 • some dq + 3 [PROOFSTEP] exact WithBot.coe_lt_coe.mpr <| by linarith only [hpq] [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ dp : ℕ hdp : degree (p ^ 2) = 2 • some dp hp' : degree p = some dp dq : ℕ hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • some dq + 3 hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ some dp + some dq + 1 hq' : degree q = some dq hpq : dp ≤ dq + 1 ⊢ (fun x x_1 => x + x_1) dp ((fun x x_1 => x + x_1) dp 0) < (fun x x_1 => x + x_1) ((fun x x_1 => x + x_1) dq ((fun x x_1 => x + x_1) dq 0)) ↑3 [PROOFSTEP] linarith only [hpq] [GOAL] case neg.some.some.inl.convert_3 R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ dp : ℕ hdp : degree (p ^ 2) = 2 • some dp hp' : degree p = some dp dq : ℕ hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • some dq + 3 hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ some dp + some dq + 1 hq' : degree q = some dq hpq : dp ≤ dq + 1 ⊢ some dp + some dq + 1 < 2 • some dq + 3 [PROOFSTEP] exact WithBot.coe_lt_coe.mpr <| by linarith only [hpq] [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ dp : ℕ hdp : degree (p ^ 2) = 2 • some dp hp' : degree p = some dp dq : ℕ hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • some dq + 3 hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ some dp + some dq + 1 hq' : degree q = some dq hpq : dp ≤ dq + 1 ⊢ (fun x x_1 => x + x_1) ((fun x x_1 => x + x_1) dp dq) 1 < (fun x x_1 => x + x_1) ((fun x x_1 => x + x_1) dq ((fun x x_1 => x + x_1) dq 0)) ↑3 [PROOFSTEP] linarith only [hpq] [GOAL] case neg.some.some.inl.convert_5 R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ dp : ℕ hdp : degree (p ^ 2) = 2 • some dp hp' : degree p = some dp dq : ℕ hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • some dq + 3 hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ some dp + some dq + 1 hq' : degree q = some dq hpq : dp ≤ dq + 1 ⊢ 2 • some dp < 2 • some dq + 3 [PROOFSTEP] exact WithBot.coe_lt_coe.mpr <| by linarith only [hpq] [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ dp : ℕ hdp : degree (p ^ 2) = 2 • some dp hp' : degree p = some dp dq : ℕ hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • some dq + 3 hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ some dp + some dq + 1 hq' : degree q = some dq hpq : dp ≤ dq + 1 ⊢ (fun x x_1 => x + x_1) dp ((fun x x_1 => x + x_1) dp 0) < (fun x x_1 => x + x_1) ((fun x x_1 => x + x_1) dq ((fun x x_1 => x + x_1) dq 0)) ↑3 [PROOFSTEP] linarith only [hpq] [GOAL] case neg.some.some.inr R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ dp : ℕ hdp : degree (p ^ 2) = 2 • some dp hp' : degree p = some dp dq : ℕ hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • some dq + 3 hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ some dp + some dq + 1 hq' : degree q = some dq hpq : dq + 1 < dp ⊢ degree (p ^ 2 - p * q * (↑C W.a₁ * Y + ↑C W.a₃) - q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = max (2 • some dp) (2 • some dq + 3) [PROOFSTEP] rw [sub_sub] [GOAL] case neg.some.some.inr R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ dp : ℕ hdp : degree (p ^ 2) = 2 • some dp hp' : degree p = some dp dq : ℕ hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • some dq + 3 hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ some dp + some dq + 1 hq' : degree q = some dq hpq : dq + 1 < dp ⊢ degree (p ^ 2 - (p * q * (↑C W.a₁ * Y + ↑C W.a₃) + q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆))) = max (2 • some dp) (2 • some dq + 3) [PROOFSTEP] convert (degree_sub_eq_left_of_degree_lt <| (degree_add_le _ _).trans_lt <| max_lt_iff.mpr ⟨hdpq.trans_lt _, hdq.trans_lt _⟩).trans (max_eq_left_of_lt _).symm [GOAL] case h.e'_3.h.e'_3 R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ dp : ℕ hdp : degree (p ^ 2) = 2 • some dp hp' : degree p = some dp dq : ℕ hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • some dq + 3 hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ some dp + some dq + 1 hq' : degree q = some dq hpq : dq + 1 < dp ⊢ 2 • some dp = degree (p ^ 2) [PROOFSTEP] rw [hdp] [GOAL] case neg.some.some.inr.convert_2 R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ dp : ℕ hdp : degree (p ^ 2) = 2 • some dp hp' : degree p = some dp dq : ℕ hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • some dq + 3 hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ some dp + some dq + 1 hq' : degree q = some dq hpq : dq + 1 < dp ⊢ some dp + some dq + 1 < degree (p ^ 2) [PROOFSTEP] rw [hdp] [GOAL] case neg.some.some.inr.convert_3 R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ dp : ℕ hdp : degree (p ^ 2) = 2 • some dp hp' : degree p = some dp dq : ℕ hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • some dq + 3 hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ some dp + some dq + 1 hq' : degree q = some dq hpq : dq + 1 < dp ⊢ 2 • some dq + 3 < degree (p ^ 2) [PROOFSTEP] rw [hdp] [GOAL] case neg.some.some.inr.convert_5 R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ dp : ℕ hdp : degree (p ^ 2) = 2 • some dp hp' : degree p = some dp dq : ℕ hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • some dq + 3 hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ some dp + some dq + 1 hq' : degree q = some dq hpq : dq + 1 < dp ⊢ 2 • some dq + 3 < degree (p ^ 2) [PROOFSTEP] rw [hdp] [GOAL] case neg.some.some.inr.convert_2 R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ dp : ℕ hdp : degree (p ^ 2) = 2 • some dp hp' : degree p = some dp dq : ℕ hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • some dq + 3 hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ some dp + some dq + 1 hq' : degree q = some dq hpq : dq + 1 < dp ⊢ some dp + some dq + 1 < 2 • some dp [PROOFSTEP] exact WithBot.coe_lt_coe.mpr <| by linarith only [hpq] [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ dp : ℕ hdp : degree (p ^ 2) = 2 • some dp hp' : degree p = some dp dq : ℕ hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • some dq + 3 hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ some dp + some dq + 1 hq' : degree q = some dq hpq : dq + 1 < dp ⊢ (fun x x_1 => x + x_1) ((fun x x_1 => x + x_1) dp dq) 1 < (fun x x_1 => x + x_1) dp ((fun x x_1 => x + x_1) dp 0) [PROOFSTEP] linarith only [hpq] [GOAL] case neg.some.some.inr.convert_3 R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ dp : ℕ hdp : degree (p ^ 2) = 2 • some dp hp' : degree p = some dp dq : ℕ hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • some dq + 3 hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ some dp + some dq + 1 hq' : degree q = some dq hpq : dq + 1 < dp ⊢ 2 • some dq + 3 < 2 • some dp [PROOFSTEP] exact WithBot.coe_lt_coe.mpr <| by linarith only [hpq] [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ dp : ℕ hdp : degree (p ^ 2) = 2 • some dp hp' : degree p = some dp dq : ℕ hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • some dq + 3 hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ some dp + some dq + 1 hq' : degree q = some dq hpq : dq + 1 < dp ⊢ (fun x x_1 => x + x_1) ((fun x x_1 => x + x_1) dq ((fun x x_1 => x + x_1) dq 0)) ↑3 < (fun x x_1 => x + x_1) dp ((fun x x_1 => x + x_1) dp 0) [PROOFSTEP] linarith only [hpq] [GOAL] case neg.some.some.inr.convert_5 R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ dp : ℕ hdp : degree (p ^ 2) = 2 • some dp hp' : degree p = some dp dq : ℕ hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • some dq + 3 hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ some dp + some dq + 1 hq' : degree q = some dq hpq : dq + 1 < dp ⊢ 2 • some dq + 3 < 2 • some dp [PROOFSTEP] exact WithBot.coe_lt_coe.mpr <| by linarith only [hpq] [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] hp : ¬degree p = ⊥ hq : ¬degree q = ⊥ dp : ℕ hdp : degree (p ^ 2) = 2 • some dp hp' : degree p = some dp dq : ℕ hdq : degree (q ^ 2 * (Y ^ 3 + ↑C W.a₂ * Y ^ 2 + ↑C W.a₄ * Y + ↑C W.a₆)) = 2 • some dq + 3 hdpq : degree (p * q * (↑C W.a₁ * Y + ↑C W.a₃)) ≤ some dp + some dq + 1 hq' : degree q = some dq hpq : dq + 1 < dp ⊢ (fun x x_1 => x + x_1) ((fun x x_1 => x + x_1) dq ((fun x x_1 => x + x_1) dq 0)) ↑3 < (fun x x_1 => x + x_1) dp ((fun x x_1 => x + x_1) dp 0) [PROOFSTEP] linarith only [hpq] [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x✝ : R y : R[X] inst✝ : IsDomain R x : CoordinateRing W ⊢ degree (↑(Algebra.norm R[X]) x) ≠ 1 [PROOFSTEP] rcases exists_smul_basis_eq x with ⟨p, q, rfl⟩ [GOAL] case intro.intro R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] ⊢ degree (↑(Algebra.norm R[X]) (p • 1 + q • ↑(mk W) Y)) ≠ 1 [PROOFSTEP] rw [degree_norm_smul_basis] [GOAL] case intro.intro R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] ⊢ max (2 • degree p) (2 • degree q + 3) ≠ 1 [PROOFSTEP] rcases p.degree with (_ | _ | _ | _) [GOAL] case intro.intro.none R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] ⊢ max (2 • none) (2 • degree q + 3) ≠ 1 [PROOFSTEP] cases q.degree [GOAL] case intro.intro.some.zero R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] ⊢ max (2 • some Nat.zero) (2 • degree q + 3) ≠ 1 [PROOFSTEP] cases q.degree [GOAL] case intro.intro.some.succ.zero R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] ⊢ max (2 • some (Nat.succ Nat.zero)) (2 • degree q + 3) ≠ 1 [PROOFSTEP] cases q.degree [GOAL] case intro.intro.some.succ.succ R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] n✝ : ℕ ⊢ max (2 • some (Nat.succ (Nat.succ n✝))) (2 • degree q + 3) ≠ 1 [PROOFSTEP] cases q.degree [GOAL] case intro.intro.none.none R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] ⊢ max (2 • none) (2 • none + 3) ≠ 1 case intro.intro.none.some R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] val✝ : ℕ ⊢ max (2 • none) (2 • some val✝ + 3) ≠ 1 case intro.intro.some.zero.none R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] ⊢ max (2 • some Nat.zero) (2 • none + 3) ≠ 1 case intro.intro.some.zero.some R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] val✝ : ℕ ⊢ max (2 • some Nat.zero) (2 • some val✝ + 3) ≠ 1 case intro.intro.some.succ.zero.none R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] ⊢ max (2 • some (Nat.succ Nat.zero)) (2 • none + 3) ≠ 1 case intro.intro.some.succ.zero.some R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] val✝ : ℕ ⊢ max (2 • some (Nat.succ Nat.zero)) (2 • some val✝ + 3) ≠ 1 case intro.intro.some.succ.succ.none R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] n✝ : ℕ ⊢ max (2 • some (Nat.succ (Nat.succ n✝))) (2 • none + 3) ≠ 1 case intro.intro.some.succ.succ.some R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] n✝ val✝ : ℕ ⊢ max (2 • some (Nat.succ (Nat.succ n✝))) (2 • some val✝ + 3) ≠ 1 [PROOFSTEP] any_goals rintro (_ | _) -- porting note: replaced `dec_trivial` with `(cmp_eq_lt_iff _ _).mp rfl` but cannot be inlined [GOAL] case intro.intro.none.none R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] ⊢ max (2 • none) (2 • none + 3) ≠ 1 [PROOFSTEP] rintro (_ | _) -- porting note: replaced `dec_trivial` with `(cmp_eq_lt_iff _ _).mp rfl` but cannot be inlined [GOAL] case intro.intro.none.some R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] val✝ : ℕ ⊢ max (2 • none) (2 • some val✝ + 3) ≠ 1 [PROOFSTEP] rintro (_ | _) -- porting note: replaced `dec_trivial` with `(cmp_eq_lt_iff _ _).mp rfl` but cannot be inlined [GOAL] case intro.intro.some.zero.none R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] ⊢ max (2 • some Nat.zero) (2 • none + 3) ≠ 1 [PROOFSTEP] rintro (_ | _) -- porting note: replaced `dec_trivial` with `(cmp_eq_lt_iff _ _).mp rfl` but cannot be inlined [GOAL] case intro.intro.some.zero.some R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] val✝ : ℕ ⊢ max (2 • some Nat.zero) (2 • some val✝ + 3) ≠ 1 [PROOFSTEP] rintro (_ | _) -- porting note: replaced `dec_trivial` with `(cmp_eq_lt_iff _ _).mp rfl` but cannot be inlined [GOAL] case intro.intro.some.succ.zero.none R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] ⊢ max (2 • some (Nat.succ Nat.zero)) (2 • none + 3) ≠ 1 [PROOFSTEP] rintro (_ | _) -- porting note: replaced `dec_trivial` with `(cmp_eq_lt_iff _ _).mp rfl` but cannot be inlined [GOAL] case intro.intro.some.succ.zero.some R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] val✝ : ℕ ⊢ max (2 • some (Nat.succ Nat.zero)) (2 • some val✝ + 3) ≠ 1 [PROOFSTEP] rintro (_ | _) -- porting note: replaced `dec_trivial` with `(cmp_eq_lt_iff _ _).mp rfl` but cannot be inlined [GOAL] case intro.intro.some.succ.succ.none R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] n✝ : ℕ ⊢ max (2 • some (Nat.succ (Nat.succ n✝))) (2 • none + 3) ≠ 1 [PROOFSTEP] rintro (_ | _) -- porting note: replaced `dec_trivial` with `(cmp_eq_lt_iff _ _).mp rfl` but cannot be inlined [GOAL] case intro.intro.some.succ.succ.some R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] n✝ val✝ : ℕ ⊢ max (2 • some (Nat.succ (Nat.succ n✝))) (2 • some val✝ + 3) ≠ 1 [PROOFSTEP] rintro (_ | _) -- porting note: replaced `dec_trivial` with `(cmp_eq_lt_iff _ _).mp rfl` but cannot be inlined [GOAL] case intro.intro.some.succ.succ.some R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] n✝ val✝ : ℕ ⊢ max (2 • some (Nat.succ (Nat.succ n✝))) (2 • some val✝ + 3) ≠ 1 [PROOFSTEP] apply (lt_max_of_lt_right _).ne' [GOAL] R : Type u inst✝⁷ : CommRing R W : WeierstrassCurve R A : Type v inst✝⁶ : CommRing A inst✝⁵ : Algebra R A B : Type w inst✝⁴ : CommRing B inst✝³ : Algebra R B inst✝² : Algebra A B inst✝¹ : IsScalarTower R A B x : R y : R[X] inst✝ : IsDomain R p q : R[X] n✝ val✝ : ℕ ⊢ 1 < 2 • some val✝ + 3 [PROOFSTEP] exact (cmp_eq_lt_iff _ _).mp rfl [GOAL] R : Type u inst✝¹ : CommRing R E : EllipticCurve R inst✝ : Invertible 3 this : Invertible (-3 ^ 3) ⊢ ↑(unitOfInvertible (-3 ^ 3)) = WeierstrassCurve.Δ (WeierstrassCurve.ofJ0 R) [PROOFSTEP] rw [unitOfInvertible_val, WeierstrassCurve.ofJ0_Δ R] [GOAL] R : Type u inst✝¹ : CommRing R E : EllipticCurve R inst✝ : Invertible 3 this : Invertible (-3 ^ 3) ⊢ -3 ^ 3 = -27 [PROOFSTEP] norm_num1 [GOAL] R : Type u inst✝¹ : CommRing R E : EllipticCurve R inst✝ : Invertible 3 ⊢ j (ofJ0 R) = 0 [PROOFSTEP] simp only [j, ofJ0, WeierstrassCurve.ofJ0_c₄] [GOAL] R : Type u inst✝¹ : CommRing R E : EllipticCurve R inst✝ : Invertible 3 ⊢ ↑(unitOfInvertible (-3 ^ 3))⁻¹ * 0 ^ 3 = 0 [PROOFSTEP] ring1 [GOAL] R : Type u inst✝¹ : CommRing R E : EllipticCurve R inst✝ : Invertible 2 this : Invertible (-2 ^ 6) ⊢ ↑(unitOfInvertible (-2 ^ 6)) = WeierstrassCurve.Δ (WeierstrassCurve.ofJ1728 R) [PROOFSTEP] rw [unitOfInvertible_val, WeierstrassCurve.ofJ1728_Δ R] [GOAL] R : Type u inst✝¹ : CommRing R E : EllipticCurve R inst✝ : Invertible 2 this : Invertible (-2 ^ 6) ⊢ -2 ^ 6 = -64 [PROOFSTEP] norm_num1 [GOAL] R : Type u inst✝¹ : CommRing R E : EllipticCurve R inst✝ : Invertible 2 ⊢ j (ofJ1728 R) = 1728 [PROOFSTEP] field_simp [j, ofJ1728, @unitOfInvertible_val _ _ _ <| invertibleNeg _, WeierstrassCurve.ofJ1728_c₄] [GOAL] R : Type u inst✝¹ : CommRing R E : EllipticCurve R inst✝ : Invertible 2 ⊢ -(1728 * 2 ^ 6) = (-48) ^ 3 [PROOFSTEP] norm_num1 [GOAL] R : Type u inst✝² : CommRing R E : EllipticCurve R j : R inst✝¹ : Invertible j inst✝ : Invertible (j - 1728) ⊢ EllipticCurve.j (ofJ' j) = j [PROOFSTEP] field_simp [EllipticCurve.j, ofJ', @unitOfInvertible_val _ _ _ <| invertibleMul _ _, WeierstrassCurve.ofJ_c₄] [GOAL] R : Type u inst✝² : CommRing R E : EllipticCurve R j : R inst✝¹ : Invertible j inst✝ : Invertible (j - 1728) ⊢ j * (j ^ 2 * (j - 1728) ^ 9) = (j * (j - 1728) ^ 3) ^ 3 [PROOFSTEP] ring1 [GOAL] R : Type u inst✝¹ : CommRing R E : EllipticCurve R F : Type u inst✝ : Field F j : F ⊢ Nat.coprime 2 3 [PROOFSTEP] norm_num1 [GOAL] R : Type u inst✝² : CommRing R E : EllipticCurve R F : Type u inst✝¹ : Field F j : F inst✝ : DecidableEq F h0 : ¬j = 0 h1728 : j = 1728 h : 2 = 0 ⊢ j = 0 [PROOFSTEP] rw [h1728, show (1728 : F) = 2 * 864 by norm_num1, h, zero_mul] [GOAL] R : Type u inst✝² : CommRing R E : EllipticCurve R F : Type u inst✝¹ : Field F j : F inst✝ : DecidableEq F h0 : ¬j = 0 h1728 : j = 1728 h : 2 = 0 ⊢ 1728 = 2 * 864 [PROOFSTEP] norm_num1 [GOAL] R : Type u inst✝² : CommRing R E : EllipticCurve R F : Type u inst✝¹ : Field F j : F inst✝ : DecidableEq F h3 : NeZero 3 ⊢ ofJ 0 = ofJ0 F [PROOFSTEP] rw [ofJ, dif_pos rfl, dif_neg h3.out] [GOAL] R : Type u inst✝² : CommRing R E : EllipticCurve R F : Type u inst✝¹ : Field F j : F inst✝ : DecidableEq F h3 : 3 = 0 ⊢ ofJ 0 = ofJ1728 F [PROOFSTEP] rw [ofJ, dif_pos rfl, dif_pos h3] [GOAL] R : Type u inst✝² : CommRing R E : EllipticCurve R F : Type u inst✝¹ : Field F j : F inst✝ : DecidableEq F h3 : 3 = 0 ⊢ ofJ 1728 = ofJ1728 F [PROOFSTEP] rw [ofJ, dif_pos <| by rw [show (1728 : F) = 3 * 576 by norm_num1, h3, zero_mul], dif_pos h3] [GOAL] R : Type u inst✝² : CommRing R E : EllipticCurve R F : Type u inst✝¹ : Field F j : F inst✝ : DecidableEq F h3 : 3 = 0 ⊢ 1728 = 0 [PROOFSTEP] rw [show (1728 : F) = 3 * 576 by norm_num1, h3, zero_mul] [GOAL] R : Type u inst✝² : CommRing R E : EllipticCurve R F : Type u inst✝¹ : Field F j : F inst✝ : DecidableEq F h3 : 3 = 0 ⊢ 1728 = 3 * 576 [PROOFSTEP] norm_num1 [GOAL] R : Type u inst✝² : CommRing R E : EllipticCurve R F : Type u inst✝¹ : Field F j : F inst✝ : DecidableEq F h2 : NeZero 2 ⊢ ofJ 1728 = ofJ1728 F [PROOFSTEP] by_cases h3 : (3 : F) = 0 [GOAL] case pos R : Type u inst✝² : CommRing R E : EllipticCurve R F : Type u inst✝¹ : Field F j : F inst✝ : DecidableEq F h2 : NeZero 2 h3 : 3 = 0 ⊢ ofJ 1728 = ofJ1728 F [PROOFSTEP] exact ofJ_1728_of_three_eq_zero h3 [GOAL] case neg R : Type u inst✝² : CommRing R E : EllipticCurve R F : Type u inst✝¹ : Field F j : F inst✝ : DecidableEq F h2 : NeZero 2 h3 : ¬3 = 0 ⊢ ofJ 1728 = ofJ1728 F [PROOFSTEP] have h : (1728 : F) ≠ 0 := fun h => or_iff_not_and_not.mp (mul_eq_zero.mp <| by rwa [show 2 ^ 6 * 3 ^ 3 = (1728 : F) by norm_num1]) ⟨pow_ne_zero 6 h2.out, pow_ne_zero 3 h3⟩ [GOAL] R : Type u inst✝² : CommRing R E : EllipticCurve R F : Type u inst✝¹ : Field F j : F inst✝ : DecidableEq F h2 : NeZero 2 h3 : ¬3 = 0 h : 1728 = 0 ⊢ 2 ^ 6 * 3 ^ 3 = 0 [PROOFSTEP] rwa [show 2 ^ 6 * 3 ^ 3 = (1728 : F) by norm_num1] [GOAL] R : Type u inst✝² : CommRing R E : EllipticCurve R F : Type u inst✝¹ : Field F j : F inst✝ : DecidableEq F h2 : NeZero 2 h3 : ¬3 = 0 h : 1728 = 0 ⊢ 2 ^ 6 * 3 ^ 3 = 1728 [PROOFSTEP] norm_num1 [GOAL] case neg R : Type u inst✝² : CommRing R E : EllipticCurve R F : Type u inst✝¹ : Field F j : F inst✝ : DecidableEq F h2 : NeZero 2 h3 : ¬3 = 0 h : 1728 ≠ 0 ⊢ ofJ 1728 = ofJ1728 F [PROOFSTEP] rw [ofJ, dif_neg h, dif_pos rfl] [GOAL] R : Type u inst✝² : CommRing R E : EllipticCurve R F : Type u inst✝¹ : Field F j : F inst✝ : DecidableEq F h2 : 2 = 0 ⊢ ofJ 1728 = ofJ0 F [PROOFSTEP] rw [ofJ, dif_pos <| by rw [show (1728 : F) = 2 * 864 by norm_num1, h2, zero_mul], dif_neg] [GOAL] R : Type u inst✝² : CommRing R E : EllipticCurve R F : Type u inst✝¹ : Field F j : F inst✝ : DecidableEq F h2 : 2 = 0 ⊢ 1728 = 0 [PROOFSTEP] rw [show (1728 : F) = 2 * 864 by norm_num1, h2, zero_mul] [GOAL] R : Type u inst✝² : CommRing R E : EllipticCurve R F : Type u inst✝¹ : Field F j : F inst✝ : DecidableEq F h2 : 2 = 0 ⊢ 1728 = 2 * 864 [PROOFSTEP] norm_num1 [GOAL] R : Type u inst✝² : CommRing R E : EllipticCurve R F : Type u inst✝¹ : Field F j : F inst✝ : DecidableEq F h0 : j ≠ 0 h1728 : j ≠ 1728 ⊢ ofJ j = ofJ' j [PROOFSTEP] rw [ofJ, dif_neg h0, dif_neg h1728] [GOAL] R : Type u inst✝² : CommRing R E : EllipticCurve R F : Type u inst✝¹ : Field F j : F inst✝ : DecidableEq F ⊢ EllipticCurve.j (ofJ j) = j [PROOFSTEP] by_cases h0 : j = 0 [GOAL] case pos R : Type u inst✝² : CommRing R E : EllipticCurve R F : Type u inst✝¹ : Field F j : F inst✝ : DecidableEq F h0 : j = 0 ⊢ EllipticCurve.j (ofJ j) = j [PROOFSTEP] by_cases h3 : (3 : F) = 0 [GOAL] case pos R : Type u inst✝² : CommRing R E : EllipticCurve R F : Type u inst✝¹ : Field F j : F inst✝ : DecidableEq F h0 : j = 0 h3 : 3 = 0 ⊢ EllipticCurve.j (ofJ j) = j [PROOFSTEP] rw [h0, ofJ_0_of_three_eq_zero h3, @ofJ1728_j _ _ <| invertibleOfNonzero <| two_or_three_ne_zero.neg_resolve_right h3, show (1728 : F) = 3 * 576 by norm_num1, h3, zero_mul] [GOAL] R : Type u inst✝² : CommRing R E : EllipticCurve R F : Type u inst✝¹ : Field F j : F inst✝ : DecidableEq F h0 : j = 0 h3 : 3 = 0 ⊢ 1728 = 3 * 576 [PROOFSTEP] norm_num1 [GOAL] case neg R : Type u inst✝² : CommRing R E : EllipticCurve R F : Type u inst✝¹ : Field F j : F inst✝ : DecidableEq F h0 : j = 0 h3 : ¬3 = 0 ⊢ EllipticCurve.j (ofJ j) = j [PROOFSTEP] rw [h0, ofJ_0_of_three_ne_zero (h3 := neZero_iff.2 h3), @ofJ0_j _ _ <| invertibleOfNonzero h3] [GOAL] case neg R : Type u inst✝² : CommRing R E : EllipticCurve R F : Type u inst✝¹ : Field F j : F inst✝ : DecidableEq F h0 : ¬j = 0 ⊢ EllipticCurve.j (ofJ j) = j [PROOFSTEP] by_cases h1728 : j = 1728 [GOAL] case pos R : Type u inst✝² : CommRing R E : EllipticCurve R F : Type u inst✝¹ : Field F j : F inst✝ : DecidableEq F h0 : ¬j = 0 h1728 : j = 1728 ⊢ EllipticCurve.j (ofJ j) = j [PROOFSTEP] have h2 : (2 : F) ≠ 0 := fun h => h0 <| by rw [h1728, show (1728 : F) = 2 * 864 by norm_num1, h, zero_mul] [GOAL] R : Type u inst✝² : CommRing R E : EllipticCurve R F : Type u inst✝¹ : Field F j : F inst✝ : DecidableEq F h0 : ¬j = 0 h1728 : j = 1728 h : 2 = 0 ⊢ j = 0 [PROOFSTEP] rw [h1728, show (1728 : F) = 2 * 864 by norm_num1, h, zero_mul] [GOAL] R : Type u inst✝² : CommRing R E : EllipticCurve R F : Type u inst✝¹ : Field F j : F inst✝ : DecidableEq F h0 : ¬j = 0 h1728 : j = 1728 h : 2 = 0 ⊢ 1728 = 2 * 864 [PROOFSTEP] norm_num1 [GOAL] case pos R : Type u inst✝² : CommRing R E : EllipticCurve R F : Type u inst✝¹ : Field F j : F inst✝ : DecidableEq F h0 : ¬j = 0 h1728 : j = 1728 h2 : 2 ≠ 0 ⊢ EllipticCurve.j (ofJ j) = j [PROOFSTEP] rw [h1728, ofJ_1728_of_two_ne_zero (h2 := neZero_iff.2 h2), @ofJ1728_j _ _ <| invertibleOfNonzero h2] [GOAL] case neg R : Type u inst✝² : CommRing R E : EllipticCurve R F : Type u inst✝¹ : Field F j : F inst✝ : DecidableEq F h0 : ¬j = 0 h1728 : ¬j = 1728 ⊢ EllipticCurve.j (ofJ j) = j [PROOFSTEP] rw [ofJ_ne_0_ne_1728 j h0 h1728, @ofJ'_j _ _ _ (invertibleOfNonzero h0) (invertibleOfNonzero <| sub_ne_zero_of_ne h1728)] [GOAL] R : Type u inst✝ : CommRing R E : EllipticCurve R C : WeierstrassCurve.VariableChange R ⊢ ↑(C.u⁻¹ ^ 12 * E.Δ') = WeierstrassCurve.Δ (WeierstrassCurve.variableChange E.toWeierstrassCurve C) [PROOFSTEP] rw [Units.val_mul, Units.val_pow_eq_pow_val, coe_Δ', E.variableChange_Δ] [GOAL] R : Type u inst✝ : CommRing R E : EllipticCurve R C : WeierstrassCurve.VariableChange R ⊢ variableChange E WeierstrassCurve.VariableChange.id = E [PROOFSTEP] simp only [variableChange, WeierstrassCurve.variableChange_id] [GOAL] R : Type u inst✝ : CommRing R E : EllipticCurve R C : WeierstrassCurve.VariableChange R ⊢ { toWeierstrassCurve := E.toWeierstrassCurve, Δ' := WeierstrassCurve.VariableChange.id.u⁻¹ ^ 12 * E.Δ', coe_Δ' := (_ : ↑(WeierstrassCurve.VariableChange.id.u⁻¹ ^ 12 * E.Δ') = WeierstrassCurve.Δ E.toWeierstrassCurve) } = E [PROOFSTEP] simp only [WeierstrassCurve.VariableChange.id, inv_one, one_pow, one_mul] [GOAL] R : Type u inst✝ : CommRing R E✝ : EllipticCurve R C✝ C C' : WeierstrassCurve.VariableChange R E : EllipticCurve R ⊢ variableChange E (WeierstrassCurve.VariableChange.comp C C') = variableChange (variableChange E C') C [PROOFSTEP] simp only [variableChange, WeierstrassCurve.variableChange_comp] [GOAL] R : Type u inst✝ : CommRing R E✝ : EllipticCurve R C✝ C C' : WeierstrassCurve.VariableChange R E : EllipticCurve R ⊢ { toWeierstrassCurve := WeierstrassCurve.variableChange (WeierstrassCurve.variableChange E.toWeierstrassCurve C') C, Δ' := (WeierstrassCurve.VariableChange.comp C C').u⁻¹ ^ 12 * E.Δ', coe_Δ' := (_ : ↑((WeierstrassCurve.VariableChange.comp C C').u⁻¹ ^ 12 * E.Δ') = WeierstrassCurve.Δ (WeierstrassCurve.variableChange (WeierstrassCurve.variableChange E.toWeierstrassCurve C') C)) } = { toWeierstrassCurve := WeierstrassCurve.variableChange (WeierstrassCurve.variableChange E.toWeierstrassCurve C') C, Δ' := C.u⁻¹ ^ 12 * (C'.u⁻¹ ^ 12 * E.Δ'), coe_Δ' := (_ : ↑(C.u⁻¹ ^ 12 * (C'.u⁻¹ ^ 12 * E.Δ')) = WeierstrassCurve.Δ (WeierstrassCurve.variableChange (WeierstrassCurve.variableChange E.toWeierstrassCurve C') C)) } [PROOFSTEP] simp only [WeierstrassCurve.VariableChange.comp, mul_inv, mul_pow, ← mul_assoc] [GOAL] R : Type u inst✝ : CommRing R E : EllipticCurve R C : WeierstrassCurve.VariableChange R ⊢ ↑(variableChange E C).Δ' = ↑C.u⁻¹ ^ 12 * ↑E.Δ' [PROOFSTEP] rw [variableChange_Δ', Units.val_mul, Units.val_pow_eq_pow_val] [GOAL] R : Type u inst✝ : CommRing R E : EllipticCurve R C : WeierstrassCurve.VariableChange R ⊢ ↑(variableChange E C).Δ'⁻¹ = ↑C.u ^ 12 * ↑E.Δ'⁻¹ [PROOFSTEP] rw [variableChange_Δ', mul_inv, inv_pow, inv_inv, Units.val_mul, Units.val_pow_eq_pow_val] [GOAL] R : Type u inst✝ : CommRing R E : EllipticCurve R C : WeierstrassCurve.VariableChange R ⊢ j (variableChange E C) = j E [PROOFSTEP] rw [j, coe_inv_variableChange_Δ'] [GOAL] R : Type u inst✝ : CommRing R E : EllipticCurve R C : WeierstrassCurve.VariableChange R ⊢ ↑C.u ^ 12 * ↑E.Δ'⁻¹ * WeierstrassCurve.c₄ (variableChange E C).toWeierstrassCurve ^ 3 = j E [PROOFSTEP] have hu : (C.u * ↑C.u⁻¹ : R) ^ 12 = 1 := by rw [C.u.mul_inv, one_pow] [GOAL] R : Type u inst✝ : CommRing R E : EllipticCurve R C : WeierstrassCurve.VariableChange R ⊢ (↑C.u * ↑C.u⁻¹) ^ 12 = 1 [PROOFSTEP] rw [C.u.mul_inv, one_pow] [GOAL] R : Type u inst✝ : CommRing R E : EllipticCurve R C : WeierstrassCurve.VariableChange R hu : (↑C.u * ↑C.u⁻¹) ^ 12 = 1 ⊢ ↑C.u ^ 12 * ↑E.Δ'⁻¹ * WeierstrassCurve.c₄ (variableChange E C).toWeierstrassCurve ^ 3 = j E [PROOFSTEP] linear_combination (norm := (rw [variableChange_toWeierstrassCurve, WeierstrassCurve.variableChange_c₄, j]; ring1)) E.j * hu [GOAL] case a R : Type u inst✝ : CommRing R E : EllipticCurve R C : WeierstrassCurve.VariableChange R hu : (↑C.u * ↑C.u⁻¹) ^ 12 = 1 ⊢ ↑C.u ^ 12 * ↑E.Δ'⁻¹ * WeierstrassCurve.c₄ (variableChange E C).toWeierstrassCurve ^ 3 - j E - (j E * (↑C.u * ↑C.u⁻¹) ^ 12 - j E * 1) = 0 [PROOFSTEP] rw [variableChange_toWeierstrassCurve, WeierstrassCurve.variableChange_c₄, j] [GOAL] case a R : Type u inst✝ : CommRing R E : EllipticCurve R C : WeierstrassCurve.VariableChange R hu : (↑C.u * ↑C.u⁻¹) ^ 12 = 1 ⊢ ↑C.u ^ 12 * ↑E.Δ'⁻¹ * (↑C.u⁻¹ ^ 4 * WeierstrassCurve.c₄ E.toWeierstrassCurve) ^ 3 - ↑E.Δ'⁻¹ * WeierstrassCurve.c₄ E.toWeierstrassCurve ^ 3 - (↑E.Δ'⁻¹ * WeierstrassCurve.c₄ E.toWeierstrassCurve ^ 3 * (↑C.u * ↑C.u⁻¹) ^ 12 - ↑E.Δ'⁻¹ * WeierstrassCurve.c₄ E.toWeierstrassCurve ^ 3 * 1) = 0 [PROOFSTEP] ring1 [GOAL] R : Type u inst✝² : CommRing R E : EllipticCurve R A : Type v inst✝¹ : CommRing A inst✝ : Algebra R A ⊢ ↑(↑(Units.map ↑(algebraMap R A)) E.Δ') = WeierstrassCurve.Δ (WeierstrassCurve.baseChange E.toWeierstrassCurve A) [PROOFSTEP] simp only [Units.coe_map, coe_Δ', E.baseChange_Δ] [GOAL] R : Type u inst✝² : CommRing R E : EllipticCurve R A : Type v inst✝¹ : CommRing A inst✝ : Algebra R A ⊢ ↑↑(algebraMap R A) (WeierstrassCurve.Δ E.toWeierstrassCurve) = ↑(algebraMap R A) (WeierstrassCurve.Δ E.toWeierstrassCurve) [PROOFSTEP] rfl [GOAL] R : Type u inst✝² : CommRing R E : EllipticCurve R A : Type v inst✝¹ : CommRing A inst✝ : Algebra R A ⊢ j (baseChange E A) = ↑(algebraMap R A) (j E) [PROOFSTEP] simp only [j, baseChange, E.baseChange_c₄] [GOAL] R : Type u inst✝² : CommRing R E : EllipticCurve R A : Type v inst✝¹ : CommRing A inst✝ : Algebra R A ⊢ ↑(↑(Units.map ↑(algebraMap R A)) E.Δ')⁻¹ * ↑(algebraMap R A) (WeierstrassCurve.c₄ E.toWeierstrassCurve) ^ 3 = ↑(algebraMap R A) (↑E.Δ'⁻¹ * WeierstrassCurve.c₄ E.toWeierstrassCurve ^ 3) [PROOFSTEP] map_simp [GOAL] R : Type u inst✝² : CommRing R E : EllipticCurve R A : Type v inst✝¹ : CommRing A inst✝ : Algebra R A ⊢ ↑(↑(Units.map ↑(algebraMap R A)) E.Δ')⁻¹ * ↑(algebraMap R A) (WeierstrassCurve.c₄ E.toWeierstrassCurve) ^ 3 = ↑(algebraMap R A) ↑E.Δ'⁻¹ * ↑(algebraMap R A) (WeierstrassCurve.c₄ E.toWeierstrassCurve) ^ 3 [PROOFSTEP] rfl [GOAL] R : Type u inst✝² : CommRing R E✝ : EllipticCurve R A : Type v inst✝¹ : CommRing A inst✝ : Algebra R A h : Function.Injective ↑(algebraMap R A) E E' : EllipticCurve R h1 : (fun E => baseChange E A) E = (fun E => baseChange E A) E' ⊢ E = E' [PROOFSTEP] rcases mk.inj h1 with ⟨h1, h2⟩ [GOAL] case intro R : Type u inst✝² : CommRing R E✝ : EllipticCurve R A : Type v inst✝¹ : CommRing A inst✝ : Algebra R A h : Function.Injective ↑(algebraMap R A) E E' : EllipticCurve R h1✝ : (fun E => baseChange E A) E = (fun E => baseChange E A) E' h1 : WeierstrassCurve.baseChange E.toWeierstrassCurve A = WeierstrassCurve.baseChange E'.toWeierstrassCurve A h2 : ↑(Units.map ↑(algebraMap R A)) E.Δ' = ↑(Units.map ↑(algebraMap R A)) E'.Δ' ⊢ E = E' [PROOFSTEP] replace h2 := (Units.mk.inj h2).left [GOAL] case intro R : Type u inst✝² : CommRing R E✝ : EllipticCurve R A : Type v inst✝¹ : CommRing A inst✝ : Algebra R A h : Function.Injective ↑(algebraMap R A) E E' : EllipticCurve R h1✝ : (fun E => baseChange E A) E = (fun E => baseChange E A) E' h1 : WeierstrassCurve.baseChange E.toWeierstrassCurve A = WeierstrassCurve.baseChange E'.toWeierstrassCurve A h2 : ↑↑(algebraMap R A) ↑E.Δ' = ↑↑(algebraMap R A) ↑E'.Δ' ⊢ E = E' [PROOFSTEP] rcases WeierstrassCurve.mk.inj h1 with ⟨_, _, _, _, _⟩ [GOAL] case intro.intro.intro.intro.intro R : Type u inst✝² : CommRing R E✝ : EllipticCurve R A : Type v inst✝¹ : CommRing A inst✝ : Algebra R A h : Function.Injective ↑(algebraMap R A) E E' : EllipticCurve R h1✝ : (fun E => baseChange E A) E = (fun E => baseChange E A) E' h1 : WeierstrassCurve.baseChange E.toWeierstrassCurve A = WeierstrassCurve.baseChange E'.toWeierstrassCurve A h2 : ↑↑(algebraMap R A) ↑E.Δ' = ↑↑(algebraMap R A) ↑E'.Δ' left✝³ : ↑(algebraMap R A) E.a₁ = ↑(algebraMap R A) E'.a₁ left✝² : ↑(algebraMap R A) E.a₂ = ↑(algebraMap R A) E'.a₂ left✝¹ : ↑(algebraMap R A) E.a₃ = ↑(algebraMap R A) E'.a₃ left✝ : ↑(algebraMap R A) E.a₄ = ↑(algebraMap R A) E'.a₄ right✝ : ↑(algebraMap R A) E.a₆ = ↑(algebraMap R A) E'.a₆ ⊢ E = E' [PROOFSTEP] ext [GOAL] case intro.intro.intro.intro.intro.a₁ R : Type u inst✝² : CommRing R E✝ : EllipticCurve R A : Type v inst✝¹ : CommRing A inst✝ : Algebra R A h : Function.Injective ↑(algebraMap R A) E E' : EllipticCurve R h1✝ : (fun E => baseChange E A) E = (fun E => baseChange E A) E' h1 : WeierstrassCurve.baseChange E.toWeierstrassCurve A = WeierstrassCurve.baseChange E'.toWeierstrassCurve A h2 : ↑↑(algebraMap R A) ↑E.Δ' = ↑↑(algebraMap R A) ↑E'.Δ' left✝³ : ↑(algebraMap R A) E.a₁ = ↑(algebraMap R A) E'.a₁ left✝² : ↑(algebraMap R A) E.a₂ = ↑(algebraMap R A) E'.a₂ left✝¹ : ↑(algebraMap R A) E.a₃ = ↑(algebraMap R A) E'.a₃ left✝ : ↑(algebraMap R A) E.a₄ = ↑(algebraMap R A) E'.a₄ right✝ : ↑(algebraMap R A) E.a₆ = ↑(algebraMap R A) E'.a₆ ⊢ E.a₁ = E'.a₁ [PROOFSTEP] apply_fun _ using h [GOAL] case intro.intro.intro.intro.intro.a₂ R : Type u inst✝² : CommRing R E✝ : EllipticCurve R A : Type v inst✝¹ : CommRing A inst✝ : Algebra R A h : Function.Injective ↑(algebraMap R A) E E' : EllipticCurve R h1✝ : (fun E => baseChange E A) E = (fun E => baseChange E A) E' h1 : WeierstrassCurve.baseChange E.toWeierstrassCurve A = WeierstrassCurve.baseChange E'.toWeierstrassCurve A h2 : ↑↑(algebraMap R A) ↑E.Δ' = ↑↑(algebraMap R A) ↑E'.Δ' left✝³ : ↑(algebraMap R A) E.a₁ = ↑(algebraMap R A) E'.a₁ left✝² : ↑(algebraMap R A) E.a₂ = ↑(algebraMap R A) E'.a₂ left✝¹ : ↑(algebraMap R A) E.a₃ = ↑(algebraMap R A) E'.a₃ left✝ : ↑(algebraMap R A) E.a₄ = ↑(algebraMap R A) E'.a₄ right✝ : ↑(algebraMap R A) E.a₆ = ↑(algebraMap R A) E'.a₆ ⊢ E.a₂ = E'.a₂ [PROOFSTEP] apply_fun _ using h [GOAL] case intro.intro.intro.intro.intro.a₃ R : Type u inst✝² : CommRing R E✝ : EllipticCurve R A : Type v inst✝¹ : CommRing A inst✝ : Algebra R A h : Function.Injective ↑(algebraMap R A) E E' : EllipticCurve R h1✝ : (fun E => baseChange E A) E = (fun E => baseChange E A) E' h1 : WeierstrassCurve.baseChange E.toWeierstrassCurve A = WeierstrassCurve.baseChange E'.toWeierstrassCurve A h2 : ↑↑(algebraMap R A) ↑E.Δ' = ↑↑(algebraMap R A) ↑E'.Δ' left✝³ : ↑(algebraMap R A) E.a₁ = ↑(algebraMap R A) E'.a₁ left✝² : ↑(algebraMap R A) E.a₂ = ↑(algebraMap R A) E'.a₂ left✝¹ : ↑(algebraMap R A) E.a₃ = ↑(algebraMap R A) E'.a₃ left✝ : ↑(algebraMap R A) E.a₄ = ↑(algebraMap R A) E'.a₄ right✝ : ↑(algebraMap R A) E.a₆ = ↑(algebraMap R A) E'.a₆ ⊢ E.a₃ = E'.a₃ [PROOFSTEP] apply_fun _ using h [GOAL] case intro.intro.intro.intro.intro.a₄ R : Type u inst✝² : CommRing R E✝ : EllipticCurve R A : Type v inst✝¹ : CommRing A inst✝ : Algebra R A h : Function.Injective ↑(algebraMap R A) E E' : EllipticCurve R h1✝ : (fun E => baseChange E A) E = (fun E => baseChange E A) E' h1 : WeierstrassCurve.baseChange E.toWeierstrassCurve A = WeierstrassCurve.baseChange E'.toWeierstrassCurve A h2 : ↑↑(algebraMap R A) ↑E.Δ' = ↑↑(algebraMap R A) ↑E'.Δ' left✝³ : ↑(algebraMap R A) E.a₁ = ↑(algebraMap R A) E'.a₁ left✝² : ↑(algebraMap R A) E.a₂ = ↑(algebraMap R A) E'.a₂ left✝¹ : ↑(algebraMap R A) E.a₃ = ↑(algebraMap R A) E'.a₃ left✝ : ↑(algebraMap R A) E.a₄ = ↑(algebraMap R A) E'.a₄ right✝ : ↑(algebraMap R A) E.a₆ = ↑(algebraMap R A) E'.a₆ ⊢ E.a₄ = E'.a₄ [PROOFSTEP] apply_fun _ using h [GOAL] case intro.intro.intro.intro.intro.a₆ R : Type u inst✝² : CommRing R E✝ : EllipticCurve R A : Type v inst✝¹ : CommRing A inst✝ : Algebra R A h : Function.Injective ↑(algebraMap R A) E E' : EllipticCurve R h1✝ : (fun E => baseChange E A) E = (fun E => baseChange E A) E' h1 : WeierstrassCurve.baseChange E.toWeierstrassCurve A = WeierstrassCurve.baseChange E'.toWeierstrassCurve A h2 : ↑↑(algebraMap R A) ↑E.Δ' = ↑↑(algebraMap R A) ↑E'.Δ' left✝³ : ↑(algebraMap R A) E.a₁ = ↑(algebraMap R A) E'.a₁ left✝² : ↑(algebraMap R A) E.a₂ = ↑(algebraMap R A) E'.a₂ left✝¹ : ↑(algebraMap R A) E.a₃ = ↑(algebraMap R A) E'.a₃ left✝ : ↑(algebraMap R A) E.a₄ = ↑(algebraMap R A) E'.a₄ right✝ : ↑(algebraMap R A) E.a₆ = ↑(algebraMap R A) E'.a₆ ⊢ E.a₆ = E'.a₆ [PROOFSTEP] apply_fun _ using h [GOAL] case intro.intro.intro.intro.intro.Δ'.a R : Type u inst✝² : CommRing R E✝ : EllipticCurve R A : Type v inst✝¹ : CommRing A inst✝ : Algebra R A h : Function.Injective ↑(algebraMap R A) E E' : EllipticCurve R h1✝ : (fun E => baseChange E A) E = (fun E => baseChange E A) E' h1 : WeierstrassCurve.baseChange E.toWeierstrassCurve A = WeierstrassCurve.baseChange E'.toWeierstrassCurve A h2 : ↑↑(algebraMap R A) ↑E.Δ' = ↑↑(algebraMap R A) ↑E'.Δ' left✝³ : ↑(algebraMap R A) E.a₁ = ↑(algebraMap R A) E'.a₁ left✝² : ↑(algebraMap R A) E.a₂ = ↑(algebraMap R A) E'.a₂ left✝¹ : ↑(algebraMap R A) E.a₃ = ↑(algebraMap R A) E'.a₃ left✝ : ↑(algebraMap R A) E.a₄ = ↑(algebraMap R A) E'.a₄ right✝ : ↑(algebraMap R A) E.a₆ = ↑(algebraMap R A) E'.a₆ ⊢ ↑E.Δ' = ↑E'.Δ' [PROOFSTEP] apply_fun _ using h [GOAL] case intro.intro.intro.intro.intro.a₁ R : Type u inst✝² : CommRing R E✝ : EllipticCurve R A : Type v inst✝¹ : CommRing A inst✝ : Algebra R A h : Function.Injective ↑(algebraMap R A) E E' : EllipticCurve R h1✝ : (fun E => baseChange E A) E = (fun E => baseChange E A) E' h1 : WeierstrassCurve.baseChange E.toWeierstrassCurve A = WeierstrassCurve.baseChange E'.toWeierstrassCurve A h2 : ↑↑(algebraMap R A) ↑E.Δ' = ↑↑(algebraMap R A) ↑E'.Δ' left✝³ : ↑(algebraMap R A) E.a₁ = ↑(algebraMap R A) E'.a₁ left✝² : ↑(algebraMap R A) E.a₂ = ↑(algebraMap R A) E'.a₂ left✝¹ : ↑(algebraMap R A) E.a₃ = ↑(algebraMap R A) E'.a₃ left✝ : ↑(algebraMap R A) E.a₄ = ↑(algebraMap R A) E'.a₄ right✝ : ↑(algebraMap R A) E.a₆ = ↑(algebraMap R A) E'.a₆ ⊢ ↑(algebraMap R A) E.a₁ = ↑(algebraMap R A) E'.a₁ [PROOFSTEP] assumption [GOAL] case intro.intro.intro.intro.intro.a₂ R : Type u inst✝² : CommRing R E✝ : EllipticCurve R A : Type v inst✝¹ : CommRing A inst✝ : Algebra R A h : Function.Injective ↑(algebraMap R A) E E' : EllipticCurve R h1✝ : (fun E => baseChange E A) E = (fun E => baseChange E A) E' h1 : WeierstrassCurve.baseChange E.toWeierstrassCurve A = WeierstrassCurve.baseChange E'.toWeierstrassCurve A h2 : ↑↑(algebraMap R A) ↑E.Δ' = ↑↑(algebraMap R A) ↑E'.Δ' left✝³ : ↑(algebraMap R A) E.a₁ = ↑(algebraMap R A) E'.a₁ left✝² : ↑(algebraMap R A) E.a₂ = ↑(algebraMap R A) E'.a₂ left✝¹ : ↑(algebraMap R A) E.a₃ = ↑(algebraMap R A) E'.a₃ left✝ : ↑(algebraMap R A) E.a₄ = ↑(algebraMap R A) E'.a₄ right✝ : ↑(algebraMap R A) E.a₆ = ↑(algebraMap R A) E'.a₆ ⊢ ↑(algebraMap R A) E.a₂ = ↑(algebraMap R A) E'.a₂ [PROOFSTEP] assumption [GOAL] case intro.intro.intro.intro.intro.a₃ R : Type u inst✝² : CommRing R E✝ : EllipticCurve R A : Type v inst✝¹ : CommRing A inst✝ : Algebra R A h : Function.Injective ↑(algebraMap R A) E E' : EllipticCurve R h1✝ : (fun E => baseChange E A) E = (fun E => baseChange E A) E' h1 : WeierstrassCurve.baseChange E.toWeierstrassCurve A = WeierstrassCurve.baseChange E'.toWeierstrassCurve A h2 : ↑↑(algebraMap R A) ↑E.Δ' = ↑↑(algebraMap R A) ↑E'.Δ' left✝³ : ↑(algebraMap R A) E.a₁ = ↑(algebraMap R A) E'.a₁ left✝² : ↑(algebraMap R A) E.a₂ = ↑(algebraMap R A) E'.a₂ left✝¹ : ↑(algebraMap R A) E.a₃ = ↑(algebraMap R A) E'.a₃ left✝ : ↑(algebraMap R A) E.a₄ = ↑(algebraMap R A) E'.a₄ right✝ : ↑(algebraMap R A) E.a₆ = ↑(algebraMap R A) E'.a₆ ⊢ ↑(algebraMap R A) E.a₃ = ↑(algebraMap R A) E'.a₃ [PROOFSTEP] assumption [GOAL] case intro.intro.intro.intro.intro.a₄ R : Type u inst✝² : CommRing R E✝ : EllipticCurve R A : Type v inst✝¹ : CommRing A inst✝ : Algebra R A h : Function.Injective ↑(algebraMap R A) E E' : EllipticCurve R h1✝ : (fun E => baseChange E A) E = (fun E => baseChange E A) E' h1 : WeierstrassCurve.baseChange E.toWeierstrassCurve A = WeierstrassCurve.baseChange E'.toWeierstrassCurve A h2 : ↑↑(algebraMap R A) ↑E.Δ' = ↑↑(algebraMap R A) ↑E'.Δ' left✝³ : ↑(algebraMap R A) E.a₁ = ↑(algebraMap R A) E'.a₁ left✝² : ↑(algebraMap R A) E.a₂ = ↑(algebraMap R A) E'.a₂ left✝¹ : ↑(algebraMap R A) E.a₃ = ↑(algebraMap R A) E'.a₃ left✝ : ↑(algebraMap R A) E.a₄ = ↑(algebraMap R A) E'.a₄ right✝ : ↑(algebraMap R A) E.a₆ = ↑(algebraMap R A) E'.a₆ ⊢ ↑(algebraMap R A) E.a₄ = ↑(algebraMap R A) E'.a₄ [PROOFSTEP] assumption [GOAL] case intro.intro.intro.intro.intro.a₆ R : Type u inst✝² : CommRing R E✝ : EllipticCurve R A : Type v inst✝¹ : CommRing A inst✝ : Algebra R A h : Function.Injective ↑(algebraMap R A) E E' : EllipticCurve R h1✝ : (fun E => baseChange E A) E = (fun E => baseChange E A) E' h1 : WeierstrassCurve.baseChange E.toWeierstrassCurve A = WeierstrassCurve.baseChange E'.toWeierstrassCurve A h2 : ↑↑(algebraMap R A) ↑E.Δ' = ↑↑(algebraMap R A) ↑E'.Δ' left✝³ : ↑(algebraMap R A) E.a₁ = ↑(algebraMap R A) E'.a₁ left✝² : ↑(algebraMap R A) E.a₂ = ↑(algebraMap R A) E'.a₂ left✝¹ : ↑(algebraMap R A) E.a₃ = ↑(algebraMap R A) E'.a₃ left✝ : ↑(algebraMap R A) E.a₄ = ↑(algebraMap R A) E'.a₄ right✝ : ↑(algebraMap R A) E.a₆ = ↑(algebraMap R A) E'.a₆ ⊢ ↑(algebraMap R A) E.a₆ = ↑(algebraMap R A) E'.a₆ [PROOFSTEP] assumption [GOAL] case intro.intro.intro.intro.intro.Δ'.a R : Type u inst✝² : CommRing R E✝ : EllipticCurve R A : Type v inst✝¹ : CommRing A inst✝ : Algebra R A h : Function.Injective ↑(algebraMap R A) E E' : EllipticCurve R h1✝ : (fun E => baseChange E A) E = (fun E => baseChange E A) E' h1 : WeierstrassCurve.baseChange E.toWeierstrassCurve A = WeierstrassCurve.baseChange E'.toWeierstrassCurve A h2 : ↑↑(algebraMap R A) ↑E.Δ' = ↑↑(algebraMap R A) ↑E'.Δ' left✝³ : ↑(algebraMap R A) E.a₁ = ↑(algebraMap R A) E'.a₁ left✝² : ↑(algebraMap R A) E.a₂ = ↑(algebraMap R A) E'.a₂ left✝¹ : ↑(algebraMap R A) E.a₃ = ↑(algebraMap R A) E'.a₃ left✝ : ↑(algebraMap R A) E.a₄ = ↑(algebraMap R A) E'.a₄ right✝ : ↑(algebraMap R A) E.a₆ = ↑(algebraMap R A) E'.a₆ ⊢ ↑(algebraMap R A) ↑E.Δ' = ↑(algebraMap R A) ↑E'.Δ' [PROOFSTEP] assumption
#define BOOST_TEST_MODULE "Cuttle FileUI Tests" #define BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp>
! { dg-do run } ! { dg-shouldfail "negative NCOPIES argument to REPEAT intrinsic" } character(len=80) :: str integer :: i i = -1 write(str,"(a)") repeat ("a", f()) if (trim(str) /= "aaaa") call abort write(str,"(a)") repeat ("a", i) contains integer function f() integer :: x = 5 save x x = x - 1 f = x end function f end ! { dg-output "Fortran runtime error: Argument NCOPIES of REPEAT intrinsic is negative .* line 6)"
theory bin_plus_comm imports Main "$HIPSTER_HOME/IsaHipster" begin datatype Bin = One | ZeroAnd "Bin" | OneAnd "Bin" fun s :: "Bin => Bin" where "s (One) = ZeroAnd One" | "s (ZeroAnd xs) = OneAnd xs" | "s (OneAnd ys) = ZeroAnd (s ys)" fun plus :: "Bin => Bin => Bin" where "plus (One) y = s y" | "plus (ZeroAnd z) (One) = s (ZeroAnd z)" | "plus (ZeroAnd z) (ZeroAnd ys) = ZeroAnd (plus z ys)" | "plus (ZeroAnd z) (OneAnd xs) = OneAnd (plus z xs)" | "plus (OneAnd x2) (One) = s (OneAnd x2)" | "plus (OneAnd x2) (ZeroAnd zs) = OneAnd (plus x2 zs)" | "plus (OneAnd x2) (OneAnd ys2) = ZeroAnd (s (plus x2 ys2))" (*hipster s plus *) theorem x0 : "!! (x :: Bin) (y :: Bin) . (plus x y) = (plus y x)" by (tactic \<open>Subgoal.FOCUS_PARAMS (K (Tactic_Data.hard_tac @{context})) @{context} 1\<close>) end
(* Author: Lukas Bulwahn <lukas.bulwahn-at-gmail.com> *) section \<open>Surjections from A to B up to a Permutation on B\<close> theory Twelvefold_Way_Entry9 imports Twelvefold_Way_Entry7 begin subsection \<open>Properties for Bijections\<close> lemma surjective_on_implies_card_eq: assumes "f ` A = B" shows "card ((\<lambda>b. {x \<in> A. f x = b}) ` B - {{}}) = card B" proof - from \<open>f ` A = B\<close> have "{} \<notin> (\<lambda>b. {x \<in> A. f x = b}) ` B" by auto from \<open>f ` A = B\<close> have "inj_on (\<lambda>b. {x \<in> A. f x = b}) B" by (fastforce intro: inj_onI) have "card ((\<lambda>b. {x \<in> A. f x = b}) ` B - {{}}) = card ((\<lambda>b. {x \<in> A. f x = b}) ` B)" using \<open>{} \<notin> (\<lambda>b. {x \<in> A. f x = b}) ` B\<close> by simp also have "\<dots> = card B" using \<open>inj_on (\<lambda>b. {x \<in> A. f x = b}) B\<close> by (rule card_image) finally show ?thesis . qed lemma card_eq_implies_surjective_on: assumes "finite B" "f \<in> A \<rightarrow>\<^sub>E B" assumes card_eq: "card ((\<lambda>b. {x \<in> A. f x = b}) ` B - {{}}) = card B" shows "f ` A = B" proof from \<open>f \<in> A \<rightarrow>\<^sub>E B\<close> show "f ` A \<subseteq> B" by auto next show "B \<subseteq> f ` A" proof fix x assume "x \<in> B" have "{} \<notin> (\<lambda>b. {x \<in> A. f x = b}) ` B" proof (cases "card B \<ge> 1") assume "\<not> card B \<ge> 1" from this have "card B = 0" by simp from this \<open>finite B\<close> have "B = {}" by simp from this show ?thesis by simp next assume "card B \<ge> 1" show ?thesis proof (rule ccontr) assume "\<not> {} \<notin> (\<lambda>b. {x \<in> A. f x = b}) ` B" from this have "{} \<in> (\<lambda>b. {x \<in> A. f x = b}) ` B" by simp moreover have "card ((\<lambda>b. {x \<in> A. f x = b}) ` B) \<le> card B" using \<open>finite B\<close> card_image_le by blast moreover have "finite ((\<lambda>b. {x \<in> A. f x = b}) ` B)" using \<open>finite B\<close> by auto ultimately have "card ((\<lambda>b. {x \<in> A. f x = b}) ` B - {{}}) \<le> card B - 1" by (auto simp add: card_Diff_singleton) from this card_eq \<open>card B \<ge> 1\<close> show False by auto qed qed from this \<open>x \<in> B\<close> show "x \<in> f ` A" by force qed qed lemma functions_of_is_surj_on: assumes "finite A" "finite B" assumes "partition_on A P" "card P = card B" shows "univ (\<lambda>f. f ` A = B) (functions_of P A B)" proof - have "functions_of P A B \<in> (A \<rightarrow>\<^sub>E B) // range_permutation A B" using functions_of \<open>finite A\<close> \<open>finite B\<close> \<open>partition_on A P\<close> \<open>card P = card B\<close> by fastforce from this obtain f where eq_f: "functions_of P A B = range_permutation A B `` {f}" and "f \<in> A \<rightarrow>\<^sub>E B" using quotientE by blast from eq_f have "f \<in> functions_of P A B" using \<open>f \<in> A \<rightarrow>\<^sub>E B\<close> equiv_range_permutation equiv_class_self by fastforce from \<open>f \<in> functions_of P A B\<close> have eq: "(\<lambda>b. {x \<in> A. f x = b}) ` B - {{}} = P" unfolding functions_of_def by auto from this have "card ((\<lambda>b. {x \<in> A. f x = b}) ` B - {{}}) = card B" using \<open>card P = card B\<close> by simp from \<open>finite B\<close> \<open>f \<in> A \<rightarrow>\<^sub>E B\<close> this have "f ` A = B" using card_eq_implies_surjective_on by blast from this show ?thesis unfolding eq_f using equiv_range_permutation surj_on_respects_range_permutation \<open>f \<in> A \<rightarrow>\<^sub>E B\<close> by (subst univ_commute') assumption+ qed subsection \<open>Bijections\<close> lemma bij_betw_partitions_of: assumes "finite A" "finite B" shows "bij_betw (partitions_of A B) ({f \<in> A \<rightarrow>\<^sub>E B. f ` A = B} // range_permutation A B) {P. partition_on A P \<and> card P = card B}" proof (rule bij_betw_byWitness[where f'="\<lambda>P. functions_of P A B"]) have quotient_eq: "{f \<in> A \<rightarrow>\<^sub>E B. f ` A = B} // range_permutation A B = {F \<in> ((A \<rightarrow>\<^sub>E B) // range_permutation A B). univ (\<lambda>f. f ` A = B) F}" using equiv_range_permutation[of A B] surj_on_respects_range_permutation[of A B] by (simp only: univ_preserves_predicate) show "\<forall>F\<in>{f \<in> A \<rightarrow>\<^sub>E B. f ` A = B} // range_permutation A B. functions_of (partitions_of A B F) A B = F" using \<open>finite B\<close> by (simp add: functions_of_partitions_of quotient_eq) show "\<forall>P\<in>{P. partition_on A P \<and> card P = card B}. partitions_of A B (functions_of P A B) = P" using \<open>finite A\<close> \<open>finite B\<close> by (auto simp add: partitions_of_functions_of) show "partitions_of A B ` ({f \<in> A \<rightarrow>\<^sub>E B. f ` A = B} // range_permutation A B) \<subseteq> {P. partition_on A P \<and> card P = card B}" using \<open>finite B\<close> quotient_eq card_partitions_of partitions_of by fastforce show "(\<lambda>P. functions_of P A B) ` {P. partition_on A P \<and> card P = card B} \<subseteq> {f \<in> A \<rightarrow>\<^sub>E B. f ` A = B} // range_permutation A B" using \<open>finite A\<close> \<open>finite B\<close> by (auto simp add: quotient_eq intro: functions_of functions_of_is_surj_on) qed subsection \<open>Cardinality\<close> lemma card_surjective_functions_range_permutation: assumes "finite A" "finite B" shows "card ({f \<in> A \<rightarrow>\<^sub>E B. f ` A = B} // range_permutation A B) = Stirling (card A) (card B)" proof - have "bij_betw (partitions_of A B) ({f \<in> A \<rightarrow>\<^sub>E B. f ` A = B} // range_permutation A B) {P. partition_on A P \<and> card P = card B}" using \<open>finite A\<close> \<open>finite B\<close> by (rule bij_betw_partitions_of) from this have "card ({f \<in> A \<rightarrow>\<^sub>E B. f ` A = B} // range_permutation A B) = card {P. partition_on A P \<and> card P = card B}" by (rule bij_betw_same_card) also have "card {P. partition_on A P \<and> card P = card B} = Stirling (card A) (card B)" using \<open>finite A\<close> by (rule card_partition_on) finally show ?thesis . qed end
rebol [ title: "UDP-server test" ] udp-server-port: open/direct/no-wait udp://:1111 set-modes udp-server-port [receive-buffer-size: 2000000] udp-server-port-handler: func[port /local bytes ud ][ bytes: copy port print ["UDP read" length? bytes "bytes"] ] networking/add-port udp-server-port :udp-server-port-handler
lemma lebesgue_measurable_scaling[measurable]: "(*\<^sub>R) x \<in> lebesgue \<rightarrow>\<^sub>M lebesgue"
```python # check convergence rate of Fourier series and # global polynomials on either an exponential # function or a Gaussian bell. # Plot log-log and do regression / least square . # Discuss the problems with using regression / least square import sympy as sym from approx1D import least_squares_non_verbose import scipy import scipy.integrate import time def Lagrange_series(N): psi = [] h = 1.0/N points = [i*h for i in range(N+1)] for i in range(len(points)): p = 1 for k in range(len(points)): if k != i: p *= (x - points[k])/(points[i] - points[k]) psi.append(p) return psi def Bernstein_series(N): psi = [] for k in range(0,N+1): psi_k = sym.binomial(N, k)*x**k*(1-x)**(N-k) psi.append(psi_k) return psi def Sinusoidal_series(N): psi = [] for k in range(1,N): psi_k = sym.sin(sym.pi*k*x) psi.append(psi_k) return psi def Taylor_series(N): psi = [] for k in range(1,N): psi_k = x**k psi.append(psi_k) return psi def series(series_type, N): if series_type== "Taylor" : return Taylor_series(N) elif series_type== "Sinusoidal" : return Sinusoidal_series(N) elif series_type== "Bernstein" : return Bernstein_series(N) elif series_type== "Lagrange" : return Lagrange_series(N) else: print("series type unknown ") # sys.exit(0) def convergence_rate_analysis(series_type, func): Ns =[2, 4, 8, 16] norms = [] cpu_times = [] for N in Ns: psi = series(series_type, N) t0 = time.time() u, c = least_squares_non_verbose(gauss_bell, psi, Omega, False) t1 = time.time() error2 = sym.lambdify([x], (func - u)**2) L2_norm = scipy.integrate.quad(error2, Omega[0], Omega[1]) L2_norm = scipy.sqrt(L2_norm) norms.append(L2_norm[0]) cpu_times.append(t1-t0) return Ns, norms, cpu_times Omega = [0, 1] x = sym.Symbol("x") gauss_bell = sym.exp(-(x-0.5)**2) - sym.exp(-0.5**2) step = sym.Piecewise( (1, 0.25 < x), (0, True) )- sym.Piecewise( (1, 0.75 < x), (0, True) ) func = gauss_bell import matplotlib.pyplot as plt series_types = ["Taylor", "Sinusoidal", "Bernstein", "Lagrange"] for series_type in series_types: Ns, norms, cpu_times = convergence_rate_analysis(series_type, func) plt.loglog(Ns, norms) print((series_type, "Ns ", Ns)) print((" norms ", norms)) print((" cpu_time ", cpu_times)) print("") plt.legend(series_types, loc="lower left") plt.savefig("Bell_convergence_loglog.png") plt.savefig("Bell_convergence_loglog.pdf") plt.hold(False) for series_type in series_types: # plt.loglog(Ns, cpu_times) Ns, norms, cpu_times = convergence_rate_analysis(series_type, func) plt.loglog(Ns, cpu_times) plt.hold(True) plt.legend(series_types, loc="lower right") #plt.show() plt.savefig("Bell_computations_loglog.png") plt.savefig("Bell_computations_loglog.pdf") plt.hold(False) for series_type in series_types: Ns, norms, cpu_times = convergence_rate_analysis(series_type, func) plt.semilogy(Ns, norms) plt.hold(True) print((series_type, "Ns ", Ns)) print((" norms ", norms)) print((" cpu_time ", cpu_times)) print("") plt.legend(series_types, loc="lower left") #plt.show() plt.savefig("Bell_convergence_semilog.png") plt.savefig("Bell_convergence_semilog.pdf") plt.hold(False) ```
lemma diameter_singleton [simp]: "diameter{x} = 0"
(* standard, recommended (basic_induction) Prove the following using induction. You might need previously proven results. *) From LF Require Export basics. Theorem mult_0_r : forall n:nat, n * 0 = 0. Proof. intros. induction n. reflexivity. rewrite <- mult_n_O. reflexivity. Qed. Theorem plus_n_Sm : forall n m : nat, S (n + m) = n + (S m). Proof. intros. induction n. reflexivity. simpl. rewrite <- IHn. reflexivity. Qed. Theorem plus_comm : forall n m : nat, n + m = m + n. Proof. intros. induction n. - simpl. rewrite <- plus_n_O. reflexivity. - simpl. rewrite <- plus_n_Sm. rewrite <- IHn. reflexivity. Qed. Theorem plus_assoc : forall n m p : nat, n + (m + p) = (n + m) + p. Proof. intros. induction n. reflexivity. simpl. rewrite <- IHn. reflexivity. Qed. (******************************) (* standard (double_plus) Consider the following function, which doubles its argument: Fixpoint double (n:nat) := match n with | O ⇒ O | S n' ⇒ S (S (double n')) end. Use induction to prove this simple fact about double: *) Fixpoint double (n:nat) := match n with | O => O | S n' => S (S (double n')) end. Lemma double_plus : forall n, double n = n + n . Proof. intros. induction n. reflexivity. simpl. rewrite -> IHn. rewrite -> plus_n_Sm. reflexivity. Qed. (******************************) (* standard, optional (evenb_S) One inconvenient aspect of our definition of evenb n is the recursive call on- n - 2. This makes proofs about evenb n harder when done by induction on n, since we may need an induction hypothesis about n - 2. The following lemma gives an alternative characterization of evenb (S n) that- works better with induction: *) Theorem negb_involutive : forall b:bool, negb (negb b) = b. Proof. destruct b. reflexivity. reflexivity. Qed. Theorem evenb_S : forall n : nat, evenb (S n) = negb (evenb n). Proof. intros. induction n. reflexivity. rewrite -> IHn. rewrite -> negb_involutive. reflexivity. Qed. (******************************) (* standard, recommended (mult_comm) Use assert to help prove this theorem.- You shouldn't need to use induction on plus_swap. *) Theorem plus_swap : forall n m p : nat, n + (m + p) = m + (n + p). Proof. intros. rewrite -> plus_assoc. rewrite -> plus_assoc. assert (H: n + m = m + n). rewrite plus_comm. reflexivity. rewrite -> H. reflexivity. Qed. (* Now prove commutativity of multiplication. You will probably want to define and prove a "helper" theorem to be used in- the proof of this one. Hint: what is n × (1 + k)? *) Theorem mult_1_plus_n : forall m n : nat, n * ( S m ) = n + ( n * m ) . Proof. intros. induction n. reflexivity. simpl. rewrite -> plus_swap. f_equal. f_equal. assumption. Qed. Theorem mult_comm : forall m n : nat, m * n = n * m. Proof. intros. induction n. rewrite <- mult_n_O. reflexivity. simpl. rewrite -> mult_1_plus_n. rewrite -> IHn. reflexivity. Qed. (******************************) (* standard, optional (more_exercises) Take a piece of paper. For each of the following theorems, first _think_ about whether (a) it can be proved using only simplification and rewriting, (b) it also requires case analysis ([destruct]), or (c) it also requires induction. Write down your prediction. Then fill in the proof. (There is no need to turn in your piece of paper; this is just to encourage you to reflect before you hack!) *) Check leb. Theorem leb_refl : forall n:nat, true = (n <=? n). Proof. intros. induction n. reflexivity. simpl. assumption. Qed. Theorem zero_nbeq_S : forall n:nat, 0 =? (S n) = false. Proof. intros. reflexivity. Qed. Theorem andb_false_r : forall b : bool, andb b false = false. Proof. destruct b;reflexivity. Qed. Theorem plus_ble_compat_l : forall n m p : nat, n <=? m = true -> (p + n) <=? (p + m) = true. Proof. intros. induction p. assumption. assumption. Qed. Theorem S_nbeq_0 : forall n:nat, (S n) =? 0 = false. Proof. intros. reflexivity. Qed. Theorem mult_1_l : forall n:nat, 1 * n = n. Proof. intros. simpl. rewrite <- plus_n_O. reflexivity. Qed. Lemma excluded_middle: forall b : bool, orb b (negb b) = true. Proof. intros. destruct b; reflexivity. Qed. Theorem all3_spec : forall b c : bool, orb (andb b c) (orb (negb b) (negb c)) = true. Proof. intros. destruct b. simpl. rewrite excluded_middle; reflexivity. reflexivity. Qed. Theorem mult_plus_distr_r : forall n m p : nat, (n + m) * p = (n * p) + (m * p). Proof. intros. induction n. reflexivity. simpl. rewrite -> IHn. rewrite -> plus_assoc. reflexivity. Qed. Theorem mult_assoc : forall n m p : nat, n * (m * p) = (n * m) * p. Proof. intros. induction n. reflexivity. simpl. rewrite -> IHn. rewrite mult_plus_distr_r. reflexivity. Qed. (******************************) (* standard, recommended (binary_commute) Recall the [incr] and [bin_to_nat] functions that you wrote for the [binary] exercise in the [Basics] chapter. Prove that the following diagram commutes: incr bin ----------------------> bin | | bin_to_nat | | bin_to_nat | | v v nat ----------------------> nat S That is, incrementing a binary number and then converting it to a (unary) natural number yields the same result as first converting it to a natural number and then incrementing. Name your theorem [bin_to_nat_pres_incr] ("pres" for "preserves"). *) Lemma S_m_n : forall n m : nat, S ( m + n ) = S m + n. Proof. intros. induction n;reflexivity. Qed. Lemma incr_m_S_nat_m : forall m : bin, bin_to_nat m + 1 = S (bin_to_nat m). Proof. intros. induction m. reflexivity. simpl. rewrite <- plus_n_O. rewrite <- plus_assoc. rewrite -> IHm. rewrite S_m_n. rewrite <- plus_comm. reflexivity. simpl. rewrite <- plus_n_O. rewrite -> S_m_n. rewrite <- plus_comm. reflexivity. Qed. Lemma bin_to_nat_pres_incr : forall m : bin, bin_to_nat (incr m) = S (bin_to_nat m). Proof. intros m. induction m. reflexivity. simpl. rewrite <- plus_n_O. rewrite <- plus_assoc. rewrite plus_n_Sm. rewrite <- incr_m_S_nat_m. reflexivity. simpl. rewrite <- plus_n_O. rewrite <- plus_n_O. rewrite -> IHm. simpl. rewrite <- incr_m_S_nat_m. simpl. rewrite -> S_m_n. rewrite -> S_m_n. rewrite -> S_m_n. rewrite <- plus_assoc. reflexivity. Qed. (* advanced (binary_inverse) This is a further continuation of the previous exercises about binary numbers. You may find you need to go back and change your earlier definitions to get things to work here. (a) First, write a function to convert natural numbers to binary numbers. *) Fixpoint nat_to_bin (n:nat) : bin := match n with | O => Z | S n' => incr (nat_to_bin n') end. (** Prove that, if we start with any [nat], convert it to binary, and convert it back, we get the same [nat] we started with. (Hint: If your definition of [nat_to_bin] involved any extra functions, you may need to prove a subsidiary lemma showing how such functions relate to [nat_to_bin].) *) Theorem nat_bin_nat : forall n, bin_to_nat (nat_to_bin n) = n. Proof. intros. induction n. reflexivity. simpl. rewrite bin_to_nat_pres_incr. rewrite IHn. reflexivity. Qed. (** (b) One might naturally expect that we should also prove the opposite direction -- that starting with a binary number, converting to a natural, and then back to binary should yield the same number we started with. However, this is not the case! Explain (in a comment) what the problem is. *) (**** The defined Binary Representation for each nat is not unique. For example 0 can be represnted as Z, B Z, B B B Z, ... ****) (** (c) Define a normalization function -- i.e., a function [normalize] going directly from [bin] to [bin] (i.e., _not_ by converting to [nat] and back) such that, for any binary number [b], converting [b] to a natural and then back to binary yields [(normalize b)]. Prove it. (Warning: This part is a bit tricky -- you may end up defining several auxiliary lemmas. One good way to find out what you need is to start by trying to prove the main statement, see where you get stuck, and see if you can find a lemma -- perhaps requiring its own inductive proof -- that will allow the main proof to make progress.) Don't define this using [nat_to_bin] and [bin_to_nat]! *) (* Double of Z is Z and double of anything else is just itself with another- zero in front of it *) Fixpoint double_bin (b:bin) : bin := match b with | Z => Z | _ => A b end. (* Normal of Z is Z, Normal of anything in form of "n'0" is normal of n' with 0 in front of it- (see double_bin definition) Normal of anything in form of "n'1" is normal of n' whit 1 in front of it This Definition can be rewrite without double, just using B as zero-concatinator *) Fixpoint normalize (b:bin) : bin := match b with | Z => Z | A b' => double_bin( normalize b') | B b' => B (normalize b') end. Lemma double_inc : forall m : bin, double_bin ( incr m ) = incr (incr ( double_bin m )). Proof. intros. induction m; reflexivity. Qed. Lemma double_to_plus : forall n : nat, nat_to_bin (n + n) = double_bin (nat_to_bin n). Proof. intros. induction n. simpl. reflexivity. simpl. rewrite <- plus_n_Sm. simpl. rewrite -> IHn. simpl. rewrite double_inc. reflexivity. Qed. Lemma plus_1_to_inct : forall n : nat, nat_to_bin (n + 1) = incr (nat_to_bin n). Proof. intros. induction n. reflexivity. simpl. rewrite IHn. reflexivity. Qed. Lemma incr_double : forall m : bin, incr (double_bin m) = B m. Proof. intros. induction m;reflexivity. Qed. Theorem bin_nat_bin: forall m : bin, nat_to_bin (bin_to_nat m) = normalize m. Proof. intros. induction m. reflexivity. simpl. rewrite <- plus_n_O. rewrite double_to_plus. rewrite IHm; reflexivity. simpl. rewrite <- plus_n_O. rewrite plus_1_to_inct. rewrite double_to_plus. rewrite IHm. rewrite incr_double. reflexivity. Qed.
import Math.Combinat.Partitions (_partitions) import Numeric.LinearAlgebra import System.IO (putStrLn) import Text.Printf (printf) getX :: Matrix Double -> Matrix Double getX = takeColumns 2 getY :: Matrix Double -> Vector Double getY = head . toColumns . dropColumns 2 nonLinear :: Matrix Double -> Matrix Double nonLinear = fromRows . map (fromList . nonLinearRow . toList) . toRows where nonLinearRow [x1, x2] = [1, x1, x2, x1^2, x2^2, x1 * x2, abs (x1 - x2), abs (x1 + x2)] classificationError :: Vector Double -> Vector Double -> Double classificationError v y = let sv = mapVector signum v diffs = zipVectorWith (((fromIntegral . fromEnum).) . (/=)) sv y in foldVector (+) 0 diffs / fromIntegral (dim y) regularizedRegression :: Matrix Double -> Vector Double -> Double -> Vector Double regularizedRegression x y lambda = let xt = trans x xtx = multiply xt x n = cols x lambdaI = diag (constant lambda n) z = multiply (pinv (xtx + lambdaI)) xt in z `mXv` y experiment :: Matrix Double -> Vector Double -> Matrix Double -> Vector Double -> Double -> (Double, Double) experiment x y x' y' lambda = let z = regularizedRegression x y lambda xz = x `mXv` z ein = classificationError xz y x'z = x' `mXv` z eout = classificationError x'z y' in (ein, eout) main = do inputMatrix <- fromFile "in.dta" (35, 3) testMatrix <- fromFile "out.dta" (250, 3) let x = nonLinear (getX inputMatrix) y = getY inputMatrix x' = nonLinear (getX testMatrix) y' = getY testMatrix let run = experiment x y x' y' let (ein, eout) = run 0 putStrLn $ printf "2)\tE_{in} = %.5f\n\tE_{out} = %.5f" ein eout let (ein, eout) = run (10**(-3)) putStrLn $ printf "3)\tE_{in} = %.5f\n\tE_{out} = %.5f" ein eout let (ein, eout) = run (10**3) putStrLn $ printf "4)\tE_{in} = %.5f\n\tE_{out} = %.5f" ein eout let lambdas = [2, 1, 0, -1, -2] :: [Double] eouts = map (snd . run . (10**)) lambdas best = minimum (zip eouts lambdas) putStrLn $ printf "5)\t%d" (floor $ snd best :: Int) putStrLn $ printf "6)\t%f" (fst best) let layerings = filter (all (>= 2)) $ _partitions 36 cost p = cost' $ 10:p where cost' [x] = x cost' (x:y:xs) = x * (y - 1) + cost' (y:xs) costs = map cost layerings putStrLn $ printf "9)\t%d" (minimum costs) putStrLn $ printf "10)\t%d" (maximum costs)
func $foo ( var %i i32, var %j i32, var %k i32) i32 { return ( intrinsicop i32 JSOP_STRICTEQ ( dread i32 %i, intrinsicop i32 JS_NUMBER (dread i32 %k))) }
module n2o.Network.Core where open import proto.Base open import proto.IO open import n2o.Network.Internal {-# FOREIGN GHC import Network.N2O.Core #-} postulate protoRun : ∀ {F : Set → Set} {A : Set} → F A → List (Proto F A) → N2O F A (Result (F A)) {-# COMPILE GHC protoRun = Network.N2O.Core.protoRun #-}
% This script performs our evaluation on simulated datasets obtained from % our ground truth data. %% Update MATLAB path. addpath(genpath('../utility')); addpath(genpath('../algorithms/OpticalFlow')); addpath(genpath('../algorithms/SRAlgorithms')); %% Evaluation settings. % Path to input data and result directory. inputDir = '../../data'; datasetConfig = 'baselineDatasets'; resultDir = '../../results/simulatedDatasets'; % Parameters for this evaluation. initEvaluationParametersForSimulatedDatasets; %% Start evaluation. processDatasets(inputDir, datasetConfig, resultDir, binningFactors, numberOfFrames, startReferenceFrame, numberOfFrames_val, sliding_val, sr_method, binning_val, scenes_val, compressions(compress_val), 1, true);
# Programming Exercise 4: Neural Networks Learning ## Introduction In this exercise, you will implement the backpropagation algorithm for neural networks and apply it to the task of hand-written digit recognition. Before starting on the programming exercise, we strongly recommend watching the video lectures and completing the review questions for the associated topics. All the information you need for solving this assignment is in this notebook, and all the code you will be implementing will take place within this notebook. The assignment can be promptly submitted to the coursera grader directly from this notebook (code and instructions are included below). Before we begin with the exercises, we need to import all libraries required for this programming exercise. Throughout the course, we will be using [`numpy`](http://www.numpy.org/) for all arrays and matrix operations, [`matplotlib`](https://matplotlib.org/) for plotting, and [`scipy`](https://docs.scipy.org/doc/scipy/reference/) for scientific and numerical computation functions and tools. You can find instructions on how to install required libraries in the README file in the [github repository](https://github.com/dibgerge/ml-coursera-python-assignments). ```python # used for manipulating directory paths import os # Scientific and vector computation for python import numpy as np # Plotting library from matplotlib import pyplot # Optimization module in scipy from scipy import optimize # will be used to load MATLAB mat datafile format from scipy.io import loadmat # library written for this exercise providing additional functions for assignment submission, and others import utils # define the submission/grader object for this exercise grader = utils.Grader() # tells matplotlib to embed plots within the notebook %matplotlib inline ``` ## Submission and Grading After completing each part of the assignment, be sure to submit your solutions to the grader. The following is a breakdown of how each part of this exercise is scored. | Section | Part | Submission function | Points | :- |:- | :- | :-: | 1 | [Feedforward and Cost Function](#section1) | [`nnCostFunction`](#nnCostFunction) | 30 | 2 | [Regularized Cost Function](#section2) | [`nnCostFunction`](#nnCostFunction) | 15 | 3 | [Sigmoid Gradient](#section3) | [`sigmoidGradient`](#sigmoidGradient) | 5 | 4 | [Neural Net Gradient Function (Backpropagation)](#section4) | [`nnCostFunction`](#nnCostFunction) | 40 | 5 | [Regularized Gradient](#section5) | [`nnCostFunction`](#nnCostFunction) |10 | | Total Points | | 100 You are allowed to submit your solutions multiple times, and we will take only the highest score into consideration. <div class="alert alert-block alert-warning"> At the end of each section in this notebook, we have a cell which contains code for submitting the solutions thus far to the grader. Execute the cell to see your score up to the current section. For all your work to be submitted properly, you must execute those cells at least once. </div> ## Neural Networks In the previous exercise, you implemented feedforward propagation for neural networks and used it to predict handwritten digits with the weights we provided. In this exercise, you will implement the backpropagation algorithm to learn the parameters for the neural network. We start the exercise by first loading the dataset. ```python # training data stored in arrays X, y data = loadmat(os.path.join('Data', 'ex4data1.mat')) X, y = data['X'], data['y'].ravel() # set the zero digit to 0, rather than its mapped 10 in this dataset # This is an artifact due to the fact that this dataset was used in # MATLAB where there is no index 0 y[y == 10] = 0 # Number of training examples m = y.size ``` ### 1.1 Visualizing the data You will begin by visualizing a subset of the training set, using the function `displayData`, which is the same function we used in Exercise 3. It is provided in the `utils.py` file for this assignment as well. The dataset is also the same one you used in the previous exercise. There are 5000 training examples in `ex4data1.mat`, where each training example is a 20 pixel by 20 pixel grayscale image of the digit. Each pixel is represented by a floating point number indicating the grayscale intensity at that location. The 20 by 20 grid of pixels is “unrolled” into a 400-dimensional vector. Each of these training examples becomes a single row in our data matrix $X$. This gives us a 5000 by 400 matrix $X$ where every row is a training example for a handwritten digit image. $$ X = \begin{bmatrix} - \left(x^{(1)} \right)^T - \\ - \left(x^{(2)} \right)^T - \\ \vdots \\ - \left(x^{(m)} \right)^T - \\ \end{bmatrix} $$ The second part of the training set is a 5000-dimensional vector `y` that contains labels for the training set. The following cell randomly selects 100 images from the dataset and plots them. ```python # Randomly select 100 data points to display rand_indices = np.random.choice(m, 100, replace=False) sel = X[rand_indices, :] utils.displayData(sel) ``` ### 1.2 Model representation Our neural network is shown in the following figure. It has 3 layers - an input layer, a hidden layer and an output layer. Recall that our inputs are pixel values of digit images. Since the images are of size $20 \times 20$, this gives us 400 input layer units (not counting the extra bias unit which always outputs +1). The training data was loaded into the variables `X` and `y` above. You have been provided with a set of network parameters ($\Theta^{(1)}, \Theta^{(2)}$) already trained by us. These are stored in `ex4weights.mat` and will be loaded in the next cell of this notebook into `Theta1` and `Theta2`. The parameters have dimensions that are sized for a neural network with 25 units in the second layer and 10 output units (corresponding to the 10 digit classes). ```python # Setup the parameters you will use for this exercise input_layer_size = 400 # 20x20 Input Images of Digits hidden_layer_size = 25 # 25 hidden units num_labels = 10 # 10 labels, from 0 to 9 # Load the weights into variables Theta1 and Theta2 weights = loadmat(os.path.join('Data', 'ex4weights.mat')) # Theta1 has size 25 x 401 # Theta2 has size 10 x 26 Theta1, Theta2 = weights['Theta1'], weights['Theta2'] # swap first and last columns of Theta2, due to legacy from MATLAB indexing, # since the weight file ex3weights.mat was saved based on MATLAB indexing Theta2 = np.roll(Theta2, 1, axis=0) # Unroll parameters nn_params = np.concatenate([Theta1.ravel(), Theta2.ravel()]) ``` <a id="section1"></a> ### 1.3 Feedforward and cost function Now you will implement the cost function and gradient for the neural network. First, complete the code for the function `nnCostFunction` in the next cell to return the cost. Recall that the cost function for the neural network (without regularization) is: $$ J(\theta) = \frac{1}{m} \sum_{i=1}^{m}\sum_{k=1}^{K} \left[ - y_k^{(i)} \log \left( \left( h_\theta \left( x^{(i)} \right) \right)_k \right) - \left( 1 - y_k^{(i)} \right) \log \left( 1 - \left( h_\theta \left( x^{(i)} \right) \right)_k \right) \right]$$ where $h_\theta \left( x^{(i)} \right)$ is computed as shown in the neural network figure above, and K = 10 is the total number of possible labels. Note that $h_\theta(x^{(i)})_k = a_k^{(3)}$ is the activation (output value) of the $k^{th}$ output unit. Also, recall that whereas the original labels (in the variable y) were 0, 1, ..., 9, for the purpose of training a neural network, we need to encode the labels as vectors containing only values 0 or 1, so that $$ y = \begin{bmatrix} 1 \\ 0 \\ 0 \\\vdots \\ 0 \end{bmatrix}, \quad \begin{bmatrix} 0 \\ 1 \\ 0 \\ \vdots \\ 0 \end{bmatrix}, \quad \cdots \quad \text{or} \qquad \begin{bmatrix} 0 \\ 0 \\ 0 \\ \vdots \\ 1 \end{bmatrix}. $$ For example, if $x^{(i)}$ is an image of the digit 5, then the corresponding $y^{(i)}$ (that you should use with the cost function) should be a 10-dimensional vector with $y_5 = 1$, and the other elements equal to 0. You should implement the feedforward computation that computes $h_\theta(x^{(i)})$ for every example $i$ and sum the cost over all examples. **Your code should also work for a dataset of any size, with any number of labels** (you can assume that there are always at least $K \ge 3$ labels). <div class="alert alert-box alert-warning"> **Implementation Note:** The matrix $X$ contains the examples in rows (i.e., X[i,:] is the i-th training example $x^{(i)}$, expressed as a $n \times 1$ vector.) When you complete the code in `nnCostFunction`, you will need to add the column of 1’s to the X matrix. The parameters for each unit in the neural network is represented in Theta1 and Theta2 as one row. Specifically, the first row of Theta1 corresponds to the first hidden unit in the second layer. You can use a for-loop over the examples to compute the cost. </div> <a id="nnCostFunction"></a> ```python def nnCostFunction(nn_params, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_=0.0): """ Implements the neural network cost function and gradient for a two layer neural network which performs classification. Parameters ---------- nn_params : array_like The parameters for the neural network which are "unrolled" into a vector. This needs to be converted back into the weight matrices Theta1 and Theta2. input_layer_size : int Number of features for the input layer. hidden_layer_size : int Number of hidden units in the second layer. num_labels : int Total number of labels, or equivalently number of units in output layer. X : array_like Input dataset. A matrix of shape (m x input_layer_size). y : array_like Dataset labels. A vector of shape (m,). lambda_ : float, optional Regularization parameter. Returns ------- J : float The computed value for the cost function at the current weight values. grad : array_like An "unrolled" vector of the partial derivatives of the concatenatation of neural network weights Theta1 and Theta2. Instructions ------------ You should complete the code by working through the following parts. - Part 1: Feedforward the neural network and return the cost in the variable J. After implementing Part 1, you can verify that your cost function computation is correct by verifying the cost computed in the following cell. - Part 2: Implement the backpropagation algorithm to compute the gradients Theta1_grad and Theta2_grad. You should return the partial derivatives of the cost function with respect to Theta1 and Theta2 in Theta1_grad and Theta2_grad, respectively. After implementing Part 2, you can check that your implementation is correct by running checkNNGradients provided in the utils.py module. Note: The vector y passed into the function is a vector of labels containing values from 0..K-1. You need to map this vector into a binary vector of 1's and 0's to be used with the neural network cost function. Hint: We recommend implementing backpropagation using a for-loop over the training examples if you are implementing it for the first time. - Part 3: Implement regularization with the cost function and gradients. Hint: You can implement this around the code for backpropagation. That is, you can compute the gradients for the regularization separately and then add them to Theta1_grad and Theta2_grad from Part 2. Note ---- We have provided an implementation for the sigmoid function in the file `utils.py` accompanying this assignment. """ # Reshape nn_params back into the parameters Theta1 and Theta2, the weight matrices # for our 2 layer neural network Theta1 = np.reshape(nn_params[:hidden_layer_size * (input_layer_size + 1)], (hidden_layer_size, (input_layer_size + 1))) Theta2 = np.reshape(nn_params[(hidden_layer_size * (input_layer_size + 1)):], (num_labels, (hidden_layer_size + 1))) # Setup some useful variables m = y.size # You need to return the following variables correctly J = 0 Theta1_grad = np.zeros(Theta1.shape) Theta2_grad = np.zeros(Theta2.shape) # ====================== YOUR CODE HERE ====================== ### refer assigment3, for these 4 lines ### X = np.concatenate([np.ones((m, 1)), X], axis=1) a2 = utils.sigmoid(np.dot(Theta1, X.T)) a2 = np.concatenate([np.ones((1,m)), a2], axis = 0) a3 = utils.sigmoid(np.dot(Theta2, a2)) #shape = (10,m) #print(a3.shape) ########################################## h = a3 for k in range(0, num_labels): q = np.copy(y) q = (q == k) # q is now a vector where q(i) = 1 if yi == k else q(i) = 0 if q.dtype == bool: q = q.astype(int) #print(q) temp_1 = np.dot(np.log(h[k, :]), q) # h[k, :] take the row corresponding to that classifier temp_2 = np.dot(np.log(1-h[k, :]), 1 - q) J += temp_1 + temp_2 J = -J / m J = np.sum(J) # unregularized #regulaize J using lambda_ #square the theta(wieghts) matrices, ignoring theta0 terms J += lambda_ / (2*m) * (np.sum(np.square(Theta1[:, 1:])) + np.sum(np.square(Theta2[:, 1:]))) #finding gradients out = np.zeros((num_labels, m)) for k in range(0, num_labels): q = np.copy(y) q = (q == k) if q.dtype == bool: q = q.astype(int) out[k, :] = q.T delta3 = a3 - out #print(delta3.shape) #print(Theta2.T.shape) #print(delta3.shape) delta2 = np.dot(Theta2.T, delta3) * (a2 * (1-a2)) #g'(z) = g(z)*(1-g(z)) = a*(1-a) delta2 = delta2[1:, :] #remove gradient for bias unit #print("X: ", X.shape) #print("delta2 ", delta2.shape) #print("delta3 ", delta3.shape) #Delta(l)_ij = a(l)_j.delta(l+1)_i Delta2 = np.dot(delta3, a2.T) Delta1 = np.dot(delta2, X) D1, D2 = (Delta1 / m, Delta2 / m) #regularize gradeint #print(Delta1.shape) #print(Delta2.shape) D1[:, 1:] += (lambda_ / m)*Theta1[:, 1:] D2[:, 1:] += (lambda_ / m) *Theta2[:, 1:] Theta1_grad, Theta2_grad = D1, D2 # ================================================================ # Unroll gradients # grad = np.concatenate([Theta1_grad.ravel(order=order), Theta2_grad.ravel(order=order)]) grad = np.concatenate([Theta1_grad.ravel(), Theta2_grad.ravel()]) return J, grad ``` <div class="alert alert-box alert-warning"> Use the following links to go back to the different parts of this exercise that require to modify the function `nnCostFunction`.<br> Back to: - [Feedforward and cost function](#section1) - [Regularized cost](#section2) - [Neural Network Gradient (Backpropagation)](#section4) - [Regularized Gradient](#section5) </div> Once you are done, call your `nnCostFunction` using the loaded set of parameters for `Theta1` and `Theta2`. You should see that the cost is about 0.287629. ```python lambda_ = 0 J, _ = nnCostFunction(nn_params, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_) print('Cost at parameters (loaded from ex4weights): %.6f ' % J) print('The cost should be about : 0.287629.') ``` Cost at parameters (loaded from ex4weights): 0.287629 The cost should be about : 0.287629. *You should now submit your solutions.* ```python grader = utils.Grader() grader[1] = nnCostFunction grader.grade() ``` Submitting Solutions | Programming Exercise neural-network-learning Login (email address): [email protected] Token: jG20HwMr00ho3JSi Part Name | Score | Feedback --------- | ----- | -------- Feedforward and Cost Function | 30 / 30 | Nice work! Regularized Cost Function | 0 / 15 | Sigmoid Gradient | 0 / 5 | Neural Network Gradient (Backpropagation) | 0 / 40 | Regularized Gradient | 0 / 10 | -------------------------------- | 30 / 100 | <a id="section2"></a> ### 1.4 Regularized cost function The cost function for neural networks with regularization is given by: $$ J(\theta) = \frac{1}{m} \sum_{i=1}^{m}\sum_{k=1}^{K} \left[ - y_k^{(i)} \log \left( \left( h_\theta \left( x^{(i)} \right) \right)_k \right) - \left( 1 - y_k^{(i)} \right) \log \left( 1 - \left( h_\theta \left( x^{(i)} \right) \right)_k \right) \right] + \frac{\lambda}{2 m} \left[ \sum_{j=1}^{25} \sum_{k=1}^{400} \left( \Theta_{j,k}^{(1)} \right)^2 + \sum_{j=1}^{10} \sum_{k=1}^{25} \left( \Theta_{j,k}^{(2)} \right)^2 \right] $$ You can assume that the neural network will only have 3 layers - an input layer, a hidden layer and an output layer. However, your code should work for any number of input units, hidden units and outputs units. While we have explicitly listed the indices above for $\Theta^{(1)}$ and $\Theta^{(2)}$ for clarity, do note that your code should in general work with $\Theta^{(1)}$ and $\Theta^{(2)}$ of any size. Note that you should not be regularizing the terms that correspond to the bias. For the matrices `Theta1` and `Theta2`, this corresponds to the first column of each matrix. You should now add regularization to your cost function. Notice that you can first compute the unregularized cost function $J$ using your existing `nnCostFunction` and then later add the cost for the regularization terms. [Click here to go back to `nnCostFunction` for editing.](#nnCostFunction) Once you are done, the next cell will call your `nnCostFunction` using the loaded set of parameters for `Theta1` and `Theta2`, and $\lambda = 1$. You should see that the cost is about 0.383770. ```python # Weight regularization parameter (we set this to 1 here). lambda_ = 1 J, _ = nnCostFunction(nn_params, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_) print('Cost at parameters (loaded from ex4weights): %.6f' % J) print('This value should be about : 0.383770.') ``` Cost at parameters (loaded from ex4weights): 0.383770 This value should be about : 0.383770. *You should now submit your solutions.* ```python grader[2] = nnCostFunction grader.grade() ``` Submitting Solutions | Programming Exercise neural-network-learning Use token from last successful submission ([email protected])? (Y/n): y Part Name | Score | Feedback --------- | ----- | -------- Feedforward and Cost Function | 30 / 30 | Nice work! Regularized Cost Function | 15 / 15 | Nice work! Sigmoid Gradient | 0 / 5 | Neural Network Gradient (Backpropagation) | 0 / 40 | Regularized Gradient | 0 / 10 | -------------------------------- | 45 / 100 | ## 2 Backpropagation In this part of the exercise, you will implement the backpropagation algorithm to compute the gradient for the neural network cost function. You will need to update the function `nnCostFunction` so that it returns an appropriate value for `grad`. Once you have computed the gradient, you will be able to train the neural network by minimizing the cost function $J(\theta)$ using an advanced optimizer such as `scipy`'s `optimize.minimize`. You will first implement the backpropagation algorithm to compute the gradients for the parameters for the (unregularized) neural network. After you have verified that your gradient computation for the unregularized case is correct, you will implement the gradient for the regularized neural network. <a id="section3"></a> ### 2.1 Sigmoid Gradient To help you get started with this part of the exercise, you will first implement the sigmoid gradient function. The gradient for the sigmoid function can be computed as $$ g'(z) = \frac{d}{dz} g(z) = g(z)\left(1-g(z)\right) $$ where $$ \text{sigmoid}(z) = g(z) = \frac{1}{1 + e^{-z}} $$ Now complete the implementation of `sigmoidGradient` in the next cell. <a id="sigmoidGradient"></a> ```python def sigmoidGradient(z): """ Computes the gradient of the sigmoid function evaluated at z. This should work regardless if z is a matrix or a vector. In particular, if z is a vector or matrix, you should return the gradient for each element. Parameters ---------- z : array_like A vector or matrix as input to the sigmoid function. Returns -------- g : array_like Gradient of the sigmoid function. Has the same shape as z. Instructions ------------ Compute the gradient of the sigmoid function evaluated at each value of z (z can be a matrix, vector or scalar). Note ---- We have provided an implementation of the sigmoid function in `utils.py` file accompanying this assignment. """ g = np.zeros(z.shape) # ====================== YOUR CODE HERE ====================== d = utils.sigmoid(z) g = d * (1- d) # ============================================================= return g ``` When you are done, the following cell call `sigmoidGradient` on a given vector `z`. Try testing a few values by calling `sigmoidGradient(z)`. For large values (both positive and negative) of z, the gradient should be close to 0. When $z = 0$, the gradient should be exactly 0.25. Your code should also work with vectors and matrices. For a matrix, your function should perform the sigmoid gradient function on every element. ```python z = np.array([-1, -0.5, 0, 0.5, 1]) g = sigmoidGradient(z) print('Sigmoid gradient evaluated at [-1 -0.5 0 0.5 1]:\n ') print(g) ``` Sigmoid gradient evaluated at [-1 -0.5 0 0.5 1]: [0.19661193 0.23500371 0.25 0.23500371 0.19661193] *You should now submit your solutions.* ```python grader[3] = sigmoidGradient grader.grade() ``` Submitting Solutions | Programming Exercise neural-network-learning Use token from last successful submission ([email protected])? (Y/n): y Part Name | Score | Feedback --------- | ----- | -------- Feedforward and Cost Function | 30 / 30 | Nice work! Regularized Cost Function | 15 / 15 | Nice work! Sigmoid Gradient | 5 / 5 | Nice work! Neural Network Gradient (Backpropagation) | 0 / 40 | Regularized Gradient | 0 / 10 | -------------------------------- | 50 / 100 | ## 2.2 Random Initialization When training neural networks, it is important to randomly initialize the parameters for symmetry breaking. One effective strategy for random initialization is to randomly select values for $\Theta^{(l)}$ uniformly in the range $[-\epsilon_{init}, \epsilon_{init}]$. You should use $\epsilon_{init} = 0.12$. This range of values ensures that the parameters are kept small and makes the learning more efficient. <div class="alert alert-box alert-warning"> One effective strategy for choosing $\epsilon_{init}$ is to base it on the number of units in the network. A good choice of $\epsilon_{init}$ is $\epsilon_{init} = \frac{\sqrt{6}}{\sqrt{L_{in} + L_{out}}}$ where $L_{in} = s_l$ and $L_{out} = s_{l+1}$ are the number of units in the layers adjacent to $\Theta^{l}$. </div> Your job is to complete the function `randInitializeWeights` to initialize the weights for $\Theta$. Modify the function by filling in the following code: ```python # Randomly initialize the weights to small values W = np.random.rand(L_out, 1 + L_in) * 2 * epsilon_init - epsilon_init ``` Note that we give the function an argument for $\epsilon$ with default value `epsilon_init = 0.12`. ```python def randInitializeWeights(L_in, L_out, epsilon_init=0.12): """ Randomly initialize the weights of a layer in a neural network. Parameters ---------- L_in : int Number of incomming connections. L_out : int Number of outgoing connections. epsilon_init : float, optional Range of values which the weight can take from a uniform distribution. Returns ------- W : array_like The weight initialiatized to random values. Note that W should be set to a matrix of size(L_out, 1 + L_in) as the first column of W handles the "bias" terms. Instructions ------------ Initialize W randomly so that we break the symmetry while training the neural network. Note that the first column of W corresponds to the parameters for the bias unit. """ # You need to return the following variables correctly W = np.zeros((L_out, 1 + L_in)) # ====================== YOUR CODE HERE ====================== epsilon_init = np.sqrt(6) / (np.sqrt(L_out) + np.sqrt(L_in)) W = np.random.rand(L_out, 1 + L_in) * (2*epsilon_init - epsilon_init) # -eps <= W <= eps # ============================================================ return W ``` *You do not need to submit any code for this part of the exercise.* Execute the following cell to initialize the weights for the 2 layers in the neural network using the `randInitializeWeights` function. ```python print('Initializing Neural Network Parameters ...') initial_Theta1 = randInitializeWeights(input_layer_size, hidden_layer_size) initial_Theta2 = randInitializeWeights(hidden_layer_size, num_labels) # Unroll parameters initial_nn_params = np.concatenate([initial_Theta1.ravel(), initial_Theta2.ravel()], axis=0) ``` Initializing Neural Network Parameters ... <a id="section4"></a> ### 2.4 Backpropagation Now, you will implement the backpropagation algorithm. Recall that the intuition behind the backpropagation algorithm is as follows. Given a training example $(x^{(t)}, y^{(t)})$, we will first run a “forward pass” to compute all the activations throughout the network, including the output value of the hypothesis $h_\theta(x)$. Then, for each node $j$ in layer $l$, we would like to compute an “error term” $\delta_j^{(l)}$ that measures how much that node was “responsible” for any errors in our output. For an output node, we can directly measure the difference between the network’s activation and the true target value, and use that to define $\delta_j^{(3)}$ (since layer 3 is the output layer). For the hidden units, you will compute $\delta_j^{(l)}$ based on a weighted average of the error terms of the nodes in layer $(l+1)$. In detail, here is the backpropagation algorithm (also depicted in the figure above). You should implement steps 1 to 4 in a loop that processes one example at a time. Concretely, you should implement a for-loop `for t in range(m)` and place steps 1-4 below inside the for-loop, with the $t^{th}$ iteration performing the calculation on the $t^{th}$ training example $(x^{(t)}, y^{(t)})$. Step 5 will divide the accumulated gradients by $m$ to obtain the gradients for the neural network cost function. 1. Set the input layer’s values $(a^{(1)})$ to the $t^{th }$training example $x^{(t)}$. Perform a feedforward pass, computing the activations $(z^{(2)}, a^{(2)}, z^{(3)}, a^{(3)})$ for layers 2 and 3. Note that you need to add a `+1` term to ensure that the vectors of activations for layers $a^{(1)}$ and $a^{(2)}$ also include the bias unit. In `numpy`, if a 1 is a column matrix, adding one corresponds to `a_1 = np.concatenate([np.ones((m, 1)), a_1], axis=1)`. 1. For each output unit $k$ in layer 3 (the output layer), set $$\delta_k^{(3)} = \left(a_k^{(3)} - y_k \right)$$ where $y_k \in \{0, 1\}$ indicates whether the current training example belongs to class $k$ $(y_k = 1)$, or if it belongs to a different class $(y_k = 0)$. You may find logical arrays helpful for this task (explained in the previous programming exercise). 1. For the hidden layer $l = 2$, set $$ \delta^{(2)} = \left( \Theta^{(2)} \right)^T \delta^{(3)} * g'\left(z^{(2)} \right)$$ Note that the symbol $*$ performs element wise multiplication in `numpy`. 1. Accumulate the gradient from this example using the following formula. Note that you should skip or remove $\delta_0^{(2)}$. In `numpy`, removing $\delta_0^{(2)}$ corresponds to `delta_2 = delta_2[1:]`. 1. Obtain the (unregularized) gradient for the neural network cost function by dividing the accumulated gradients by $\frac{1}{m}$: $$ \frac{\partial}{\partial \Theta_{ij}^{(l)}} J(\Theta) = D_{ij}^{(l)} = \frac{1}{m} \Delta_{ij}^{(l)}$$ <div class="alert alert-box alert-warning"> **Python/Numpy tip**: You should implement the backpropagation algorithm only after you have successfully completed the feedforward and cost functions. While implementing the backpropagation alogrithm, it is often useful to use the `shape` function to print out the shapes of the variables you are working with if you run into dimension mismatch errors. </div> [Click here to go back and update the function `nnCostFunction` with the backpropagation algorithm](#nnCostFunction). After you have implemented the backpropagation algorithm, we will proceed to run gradient checking on your implementation. The gradient check will allow you to increase your confidence that your code is computing the gradients correctly. ### 2.4 Gradient checking In your neural network, you are minimizing the cost function $J(\Theta)$. To perform gradient checking on your parameters, you can imagine “unrolling” the parameters $\Theta^{(1)}$, $\Theta^{(2)}$ into a long vector $\theta$. By doing so, you can think of the cost function being $J(\Theta)$ instead and use the following gradient checking procedure. Suppose you have a function $f_i(\theta)$ that purportedly computes $\frac{\partial}{\partial \theta_i} J(\theta)$; you’d like to check if $f_i$ is outputting correct derivative values. $$ \text{Let } \theta^{(i+)} = \theta + \begin{bmatrix} 0 \\ 0 \\ \vdots \\ \epsilon \\ \vdots \\ 0 \end{bmatrix} \quad \text{and} \quad \theta^{(i-)} = \theta - \begin{bmatrix} 0 \\ 0 \\ \vdots \\ \epsilon \\ \vdots \\ 0 \end{bmatrix} $$ So, $\theta^{(i+)}$ is the same as $\theta$, except its $i^{th}$ element has been incremented by $\epsilon$. Similarly, $\theta^{(i−)}$ is the corresponding vector with the $i^{th}$ element decreased by $\epsilon$. You can now numerically verify $f_i(\theta)$’s correctness by checking, for each $i$, that: $$ f_i\left( \theta \right) \approx \frac{J\left( \theta^{(i+)}\right) - J\left( \theta^{(i-)} \right)}{2\epsilon} $$ The degree to which these two values should approximate each other will depend on the details of $J$. But assuming $\epsilon = 10^{-4}$, you’ll usually find that the left- and right-hand sides of the above will agree to at least 4 significant digits (and often many more). We have implemented the function to compute the numerical gradient for you in `computeNumericalGradient` (within the file `utils.py`). While you are not required to modify the file, we highly encourage you to take a look at the code to understand how it works. In the next cell we will run the provided function `checkNNGradients` which will create a small neural network and dataset that will be used for checking your gradients. If your backpropagation implementation is correct, you should see a relative difference that is less than 1e-9. <div class="alert alert-box alert-success"> **Practical Tip**: When performing gradient checking, it is much more efficient to use a small neural network with a relatively small number of input units and hidden units, thus having a relatively small number of parameters. Each dimension of $\theta$ requires two evaluations of the cost function and this can be expensive. In the function `checkNNGradients`, our code creates a small random model and dataset which is used with `computeNumericalGradient` for gradient checking. Furthermore, after you are confident that your gradient computations are correct, you should turn off gradient checking before running your learning algorithm. </div> <div class="alert alert-box alert-success"> **Practical Tip:** Gradient checking works for any function where you are computing the cost and the gradient. Concretely, you can use the same `computeNumericalGradient` function to check if your gradient implementations for the other exercises are correct too (e.g., logistic regression’s cost function). </div> ```python utils.checkNNGradients(nnCostFunction) ``` [[-9.27825235e-03 -9.27825236e-03] [-3.04978709e-06 -3.04978914e-06] [-1.75060082e-04 -1.75060082e-04] [-9.62660640e-05 -9.62660620e-05] [ 8.89911959e-03 8.89911960e-03] [ 1.42869427e-05 1.42869443e-05] [ 2.33146356e-04 2.33146357e-04] [ 1.17982666e-04 1.17982666e-04] [-8.36010761e-03 -8.36010762e-03] [-2.59383115e-05 -2.59383100e-05] [-2.87468729e-04 -2.87468729e-04] [-1.37149707e-04 -1.37149706e-04] [ 7.62813551e-03 7.62813551e-03] [ 3.69883235e-05 3.69883234e-05] [ 3.35320347e-04 3.35320347e-04] [ 1.53247079e-04 1.53247082e-04] [-6.74798370e-03 -6.74798370e-03] [-4.68759764e-05 -4.68759769e-05] [-3.76215585e-04 -3.76215587e-04] [-1.66560297e-04 -1.66560294e-04] [ 3.14544970e-01 3.14544970e-01] [ 1.64090819e-01 1.64090819e-01] [ 1.64567932e-01 1.64567932e-01] [ 1.58339334e-01 1.58339334e-01] [ 1.51127527e-01 1.51127527e-01] [ 1.49568335e-01 1.49568335e-01] [ 1.11056588e-01 1.11056588e-01] [ 5.75736493e-02 5.75736493e-02] [ 5.77867378e-02 5.77867378e-02] [ 5.59235296e-02 5.59235296e-02] [ 5.36967009e-02 5.36967009e-02] [ 5.31542052e-02 5.31542052e-02] [ 9.74006970e-02 9.74006970e-02] [ 5.04575855e-02 5.04575855e-02] [ 5.07530173e-02 5.07530173e-02] [ 4.91620841e-02 4.91620841e-02] [ 4.71456249e-02 4.71456249e-02] [ 4.65597186e-02 4.65597186e-02]] The above two columns you get should be very similar. (Left-Your Numerical Gradient, Right-Analytical Gradient) If your backpropagation implementation is correct, then the relative difference will be small (less than 1e-9). Relative Difference: 2.17458e-11 *Once your cost function passes the gradient check for the (unregularized) neural network cost function, you should submit the neural network gradient function (backpropagation).* ```python grader[4] = nnCostFunction grader.grade() ``` Submitting Solutions | Programming Exercise neural-network-learning Use token from last successful submission ([email protected])? (Y/n): y Part Name | Score | Feedback --------- | ----- | -------- Feedforward and Cost Function | 30 / 30 | Nice work! Regularized Cost Function | 15 / 15 | Nice work! Sigmoid Gradient | 5 / 5 | Nice work! Neural Network Gradient (Backpropagation) | 40 / 40 | Nice work! Regularized Gradient | 0 / 10 | -------------------------------- | 90 / 100 | <a id="section5"></a> ### 2.5 Regularized Neural Network After you have successfully implemented the backpropagation algorithm, you will add regularization to the gradient. To account for regularization, it turns out that you can add this as an additional term *after* computing the gradients using backpropagation. Specifically, after you have computed $\Delta_{ij}^{(l)}$ using backpropagation, you should add regularization using $$ \begin{align} & \frac{\partial}{\partial \Theta_{ij}^{(l)}} J(\Theta) = D_{ij}^{(l)} = \frac{1}{m} \Delta_{ij}^{(l)} & \qquad \text{for } j = 0 \\ & \frac{\partial}{\partial \Theta_{ij}^{(l)}} J(\Theta) = D_{ij}^{(l)} = \frac{1}{m} \Delta_{ij}^{(l)} + \frac{\lambda}{m} \Theta_{ij}^{(l)} & \qquad \text{for } j \ge 1 \end{align} $$ Note that you should *not* be regularizing the first column of $\Theta^{(l)}$ which is used for the bias term. Furthermore, in the parameters $\Theta_{ij}^{(l)}$, $i$ is indexed starting from 1, and $j$ is indexed starting from 0. Thus, $$ \Theta^{(l)} = \begin{bmatrix} \Theta_{1,0}^{(i)} & \Theta_{1,1}^{(l)} & \cdots \\ \Theta_{2,0}^{(i)} & \Theta_{2,1}^{(l)} & \cdots \\ \vdots & ~ & \ddots \end{bmatrix} $$ [Now modify your code that computes grad in `nnCostFunction` to account for regularization.](#nnCostFunction) After you are done, the following cell runs gradient checking on your implementation. If your code is correct, you should expect to see a relative difference that is less than 1e-9. ```python # Check gradients by running checkNNGradients lambda_ = 3 utils.checkNNGradients(nnCostFunction, lambda_) # Also output the costFunction debugging values debug_J, _ = nnCostFunction(nn_params, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_) print('\n\nCost at (fixed) debugging parameters (w/ lambda = %f): %f ' % (lambda_, debug_J)) print('(for lambda = 3, this value should be about 0.576051)') ``` [[-9.27825235e-03 -9.27825236e-03] [-1.67679797e-02 -1.67679797e-02] [-6.01744725e-02 -6.01744725e-02] [-1.73704651e-02 -1.73704651e-02] [ 8.89911959e-03 8.89911960e-03] [ 3.94334829e-02 3.94334829e-02] [-3.19612287e-02 -3.19612287e-02] [-5.75658668e-02 -5.75658668e-02] [-8.36010761e-03 -8.36010762e-03] [ 5.93355565e-02 5.93355565e-02] [ 2.49225535e-02 2.49225535e-02] [-4.51963845e-02 -4.51963845e-02] [ 7.62813551e-03 7.62813551e-03] [ 2.47640974e-02 2.47640974e-02] [ 5.97717617e-02 5.97717617e-02] [ 9.14587966e-03 9.14587966e-03] [-6.74798370e-03 -6.74798370e-03] [-3.26881426e-02 -3.26881426e-02] [ 3.86410548e-02 3.86410548e-02] [ 5.46101547e-02 5.46101547e-02] [ 3.14544970e-01 3.14544970e-01] [ 1.18682669e-01 1.18682669e-01] [ 2.03987128e-01 2.03987128e-01] [ 1.25698067e-01 1.25698067e-01] [ 1.76337550e-01 1.76337550e-01] [ 1.32294136e-01 1.32294136e-01] [ 1.11056588e-01 1.11056588e-01] [ 3.81928666e-05 3.81928696e-05] [ 1.17148233e-01 1.17148233e-01] [-4.07588279e-03 -4.07588279e-03] [ 1.13133142e-01 1.13133142e-01] [-4.52964427e-03 -4.52964427e-03] [ 9.74006970e-02 9.74006970e-02] [ 3.36926556e-02 3.36926556e-02] [ 7.54801264e-02 7.54801264e-02] [ 1.69677090e-02 1.69677090e-02] [ 8.61628953e-02 8.61628953e-02] [ 1.50048382e-03 1.50048382e-03]] The above two columns you get should be very similar. (Left-Your Numerical Gradient, Right-Analytical Gradient) If your backpropagation implementation is correct, then the relative difference will be small (less than 1e-9). Relative Difference: 2.09791e-11 Cost at (fixed) debugging parameters (w/ lambda = 3.000000): 0.576051 (for lambda = 3, this value should be about 0.576051) ```python grader[5] = nnCostFunction grader.grade() ``` Submitting Solutions | Programming Exercise neural-network-learning Use token from last successful submission ([email protected])? (Y/n): y Part Name | Score | Feedback --------- | ----- | -------- Feedforward and Cost Function | 30 / 30 | Nice work! Regularized Cost Function | 15 / 15 | Nice work! Sigmoid Gradient | 5 / 5 | Nice work! Neural Network Gradient (Backpropagation) | 40 / 40 | Nice work! Regularized Gradient | 10 / 10 | Nice work! -------------------------------- | 100 / 100 | ### 2.6 Learning parameters using `scipy.optimize.minimize` After you have successfully implemented the neural network cost function and gradient computation, the next step we will use `scipy`'s minimization to learn a good set parameters. ```python # After you have completed the assignment, change the maxiter to a larger # value to see how more training helps. options= {'maxiter': 300} # You should also try different values of lambda lambda_ = 1.36 # Create "short hand" for the cost function to be minimized costFunction = lambda p: nnCostFunction(p, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_) # Now, costFunction is a function that takes in only one argument # (the neural network parameters) res = optimize.minimize(costFunction, initial_nn_params, jac=True, method='TNC', options=options) # get the solution of the optimization nn_params = res.x # Obtain Theta1 and Theta2 back from nn_params Theta1 = np.reshape(nn_params[:hidden_layer_size * (input_layer_size + 1)], (hidden_layer_size, (input_layer_size + 1))) Theta2 = np.reshape(nn_params[(hidden_layer_size * (input_layer_size + 1)):], (num_labels, (hidden_layer_size + 1))) ``` After the training completes, we will proceed to report the training accuracy of your classifier by computing the percentage of examples it got correct. If your implementation is correct, you should see a reported training accuracy of about 95.3% (this may vary by about 1% due to the random initialization). It is possible to get higher training accuracies by training the neural network for more iterations. We encourage you to try training the neural network for more iterations (e.g., set `maxiter` to 400) and also vary the regularization parameter $\lambda$. With the right learning settings, it is possible to get the neural network to perfectly fit the training set. ```python pred = utils.predict(Theta1, Theta2, X) print('Training Set Accuracy: %f' % (np.mean(pred == y) * 100)) ``` Training Set Accuracy: 98.580000 ## 3 Visualizing the Hidden Layer One way to understand what your neural network is learning is to visualize what the representations captured by the hidden units. Informally, given a particular hidden unit, one way to visualize what it computes is to find an input $x$ that will cause it to activate (that is, to have an activation value ($a_i^{(l)}$) close to 1). For the neural network you trained, notice that the $i^{th}$ row of $\Theta^{(1)}$ is a 401-dimensional vector that represents the parameter for the $i^{th}$ hidden unit. If we discard the bias term, we get a 400 dimensional vector that represents the weights from each input pixel to the hidden unit. Thus, one way to visualize the “representation” captured by the hidden unit is to reshape this 400 dimensional vector into a 20 × 20 image and display it (It turns out that this is equivalent to finding the input that gives the highest activation for the hidden unit, given a “norm” constraint on the input (i.e., $||x||_2 \le 1$)). The next cell does this by using the `displayData` function and it will show you an image with 25 units, each corresponding to one hidden unit in the network. In your trained network, you should find that the hidden units corresponds roughly to detectors that look for strokes and other patterns in the input. ```python utils.displayData(Theta1[:, 1:]) ``` ### 3.1 Optional (ungraded) exercise In this part of the exercise, you will get to try out different learning settings for the neural network to see how the performance of the neural network varies with the regularization parameter $\lambda$ and number of training steps (the `maxiter` option when using `scipy.optimize.minimize`). Neural networks are very powerful models that can form highly complex decision boundaries. Without regularization, it is possible for a neural network to “overfit” a training set so that it obtains close to 100% accuracy on the training set but does not as well on new examples that it has not seen before. You can set the regularization $\lambda$ to a smaller value and the `maxiter` parameter to a higher number of iterations to see this for youself.
# Data Space Report ## Pittsburgh Bridges Data Set Andy Warhol Bridge - Pittsburgh. Report created by Student Francesco Maria Chiarlo s253666, for A.A 2019/2020. **Abstract**:The aim of this report is to evaluate the effectiveness of distinct, different statistical learning approaches, in particular focusing on their characteristics as well as on their advantages and backwards when applied onto a relatively small dataset as the one employed within this report, that is Pittsburgh Bridgesdataset. **Key words**:Statistical Learning, Machine Learning, Bridge Design. ## TOC: * [Imports Section](#imports-section) * [Dataset's Attributes Description](#attributes-description) * [Data Preparation and Investigation](#data-preparation) * [Learning Models](#learning-models) * [Improvements and Conclusions](#improvements-and-conclusions) * [References](#references) ### Imports Section <a class="anchor" id="imports-section"></a> ```python # =========================================================================== # # STANDARD IMPORTS # =========================================================================== # print(__doc__) from pprint import pprint import warnings warnings.filterwarnings('ignore') import copy import os import sys import time import pandas as pd import numpy as np %matplotlib inline # Matplotlib pyplot provides plotting API import matplotlib as mpl from matplotlib import pyplot as plt import chart_studio.plotly.plotly as py import seaborn as sns; sns.set() ``` Automatically created module for IPython interactive environment ```python # =========================================================================== # # UTILS IMPORTS (Done by myself) # =========================================================================== # from utils.display_utils import display_heatmap from utils.display_utils import show_frequency_distribution_predictors from utils.display_utils import show_frequency_distribution_predictor from utils.display_utils import build_boxplot from utils.display_utils import show_categorical_predictor_values from utils.display_utils import show_cum_variance_vs_components from utils.display_utils import show_histograms_from_heatmap_corr_matrix from utils.preprocessing_utils import preprocess_categorical_variables from utils.preprocessing_utils import preprocessing_data_rescaling from utils.training_utils import sgd_classifier_grid_search from utils.training_utils import naive_bayes_classifier_grid_search from utils.training_utils import svm_linear_classifier_grid_search from utils.training_utils import decision_tree_classifier_grid_search from utils.training_utils import random_forest_classifier_grid_search from utils.training_utils import plot_roc_crossval from utils.training_utils_v2 import fit_by_n_components ``` ```python from itertools import islice ``` ```python # =========================================================================== # # sklearn IMPORT # =========================================================================== # from sklearn.decomposition import PCA # Import scikit-learn classes: models (Estimators). from sklearn.naive_bayes import GaussianNB # Non-parametric Generative Model from sklearn.naive_bayes import MultinomialNB # Non-parametric Generative Model from sklearn.linear_model import LinearRegression # Parametric Linear Discriminative Model from sklearn.linear_model import LogisticRegression # Parametric Linear Discriminative Model from sklearn.linear_model import Ridge, Lasso from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC # Parametric Linear Discriminative "Support Vector Classifier" from sklearn.tree import DecisionTreeClassifier # Non-parametric Model from sklearn.ensemble import BaggingClassifier # Non-parametric Model (Meta-Estimator, that is, an Ensemble Method) from sklearn.ensemble import RandomForestClassifier # Non-parametric Model (Meta-Estimator, that is, an Ensemble Method) ``` ### Dataset's Attributes Description <a class="anchor" id="attributes-description"></a> The analyses that I aim at accomplishing while using as means the methods or approaches provided by both Statistical Learning and Machine Learning fields, concern the dataset Pittsburgh Bridges, and what follows is a overview and brief description of the main characteristics, as well as, basic information about this precise dataset. The Pittsburgh Bridges dataset is a dataset available from the web site called mainly *"UCI Machine Learing Repository"*, which is one of the well known web site that let a large amount of different datasets, from different domains or fields, to be used for machine-learning research and which have been cited in peer-reviewed academic journals. In particular, the dataset I'm going to treat and analyze, which is Pittsburgh Bridges dataset, has been made freely available from the Western Pennsylvania Regional Data Center (WPRDC), which is a project led by the University Center of Social and Urban Research (UCSUR) at the University of Pittsburgh ("University") in collaboration with City of Pittsburgh and The County of Allegheny in Pennsylvania. The WPRDC and the WPRDC Project is supported by a grant from the Richard King Mellon Foundation. In order to be more precise, from the official and dedicated web page, within UCI Machine Learning cite, Pittsburgh Bridges dataset is a dataset that has been created after the works of some co-authors which are: - Yoram Reich & Steven J. Fenves from Department of Civil Engineering and Engineering Design Research Center Carnegie Mellon University Pittsburgh, PA 15213 The Pittsburgh Bridges dataset is made of up to 108 distinct observations and each of that data sample is made of 12 attributes or features where some of them are considered to be continuous properties and other to be categorical or nominal properties. Those variables are the following: - **RIVER**: which is a nominal type variable that can assume the subsequent possible discrete values which are: A, M, O. Where A stands for Allegheny river, while M stands for Monongahela river and lastly O stands for Ohio river. - **LOCATION**: which represents a nominal type variable too, and assume a positive integer value from 1 up to 52 used as categorical attribute. - **ERECTED**: which might be either a numerical or categorical variable, depending on the fact that we want to aggregate a bunch of value under a categorical quantity. What this means is that, basically such attribute is made of date starting from 1818 up to 1986, but we may imagine to aggregate somehow these data within a given category among those suggested, that are CRAFTS, EMERGENING, MATURE, MODERN. - **PURPOSE**: which is a categorical attribute and represents the reason why a particular bridge has been built, which means that this attribute represents what kind of vehicle can cross the bridge or if the bridge has been made just for people. For this reasons the allowd values for this attributes are the following: WALK, AQUEDUCT, RR, HIGHWAY. Three out of four are self explained values, while RR value that might be tricky at first glance, it just stands for railroad. - **LENGTH**: which represents the bridge's length, is a numerical attribute if we just look at the real number values that go from 804 up to 4558, but we can again decide to handle or arrange such values so that they can be grouped into range of values mapped into SHORT, MEDIUM, LONG so that we can refer to a bridge's length by means of these new categorical values. - **LANES**: which is a categorical variable which is represented by numerical values, that are 1, 2, 4, 6 which indicate the number of distinct lanes that a bridge in Pittsburgh city may have. The larger the value the wider the bridge. - **CLEAR-G**: specifies whether a vertical navigation clearance requirement was enforced in the design or not. - **T-OR-D**: which is a nominal attribute, in other words, a categorical attribute that can assume THROUGH, DECK values. In order to be more precise, this samples attribute deals with structural elements of a bridge. In fact, a deck is the surface of a bridge and this structural element, of bridge's superstructure, may be constructed of concrete, steel, open grating, or wood. On the other hand, a through arch bridge, also known as a half-through arch bridge or a through-type arch bridge, is a bridge that is made from materials such as steel or reinforced concrete, in which the base of an arch structure is below the deck but the top rises above it. - **MATERIAL**: which is a categorical or nominal variable and is used to describe the bridge telling which is the main or core material used to build it. This attribute can assume one of the possible, following values which are: WOOD, IRON, STEEL. Furthermore, we expect to see somehow a bit of correlation between the values assumed by the pairs represented by T-OR-D and MATERIAL columns, when looking just to them. - **SPAN**: which is a categorical or nominal value and has been recorded by means of three possible values for each sample, that are SHORT, MEDIUM, LONG. This attribute, within the field of Structural Engineering, is the distance between two intermediate supports for a structure, e.g. a beam or a bridge. A span can be closed by a solid beam or by a rope. The first kind is used for bridges, the second one for power lines, overhead telecommunication lines, some type of antennas or for aerial tramways. - **REL-L**: which is a categorical or nominal variable and stands for relative length of the main span of the bridge to the total crossing length, it can assume three possible values that are S, S-F, F. - Lastly, **TYPE** which indicates as a categorical or nominal attributes what type of bridge each record represents, among the possible 6 distinct classes or types of bridges that are: WOOD, SUSPEN, SIMPLE-T, ARCH, CANTILEV, CONT-T. ### Data Preparation and Investigation <a class="anchor" id="data-preparation"></a> The aim of this chapter is to get in the data, that are available within Pittsburgh Bridge Dataset, in order to investigate a bit more in to detail and generally speaking deeper the main or high level statistics quantities, such as mean, median, standard deviation of each attribute, as well as displaying somehow data distribution for each attribute by means of histogram plots. This phase allows or enables us to decide which should be the best feature to be selected as the target variable, in other word the attribute that will represent the dependent variable with respect to the remaining attributes that instead will play the role of predictors and independent variables, as well. In order to investigate and explore our data we make usage of *Pandas library*. We recall mainly that, in computer programming, Pandas is a software library written for the Python programming language* for *data manipulation and analysis*. In particular, it offers data structures and operations for manipulating numerical tables and time series. It is free software and a interesting and funny things about such tool is that the name is derived from the term "panel data", an econometrics term for data sets that include observations over multiple time periods for the same individuals. We also note that as the analysis proceeds we will introduce other computer programming as well as programming libraries that allow or enable us to fulfill our goals. Initially, once I have downloaded from the provided web page the dataset with the data samples about Pittsburgh Bridge we load the data by means of functions available using python library's pandas. We notice that the overall set of data points is large up to 108 records or rows, which are sorted by Erected attributes, so this means that are sorted in decreasing order from the oldest bridge which has been built in 1818 up to the most modern bridge that has been erected in 1986. Then we display the first 5 rows to get an overview and have a first idea about what is inside the overall dataset, and the result we obtain by means of head() function applied onto the fetched dataset is equals to what follows: ```python # =========================================================================== # # READ INPUT DATASET # =========================================================================== # dataset_path = 'C:\\Users\\Francesco\Documents\\datasets\\pittsburgh_dataset' dataset_name = 'bridges.data.csv' # column_names = ['IDENTIF', 'RIVER', 'LOCATION', 'ERECTED', 'PURPOSE', 'LENGTH', 'LANES', 'CLEAR-G', 'T-OR-D', 'MATERIAL', 'SPAN', 'REL-L', 'TYPE'] column_names = ['RIVER', 'LOCATION', 'ERECTED', 'PURPOSE', 'LENGTH', 'LANES', 'CLEAR-G', 'T-OR-D', 'MATERIAL', 'SPAN', 'REL-L', 'TYPE'] dataset = pd.read_csv(os.path.join(dataset_path, dataset_name), names=column_names, index_col=0) ``` ```python # SHOW SOME STANDARD DATASET INFOS # --------------------------------------------------------------------------- # print('Dataset shape: {}'.format(dataset.shape)) print(dataset.info()) ``` Dataset shape: (108, 12) <class 'pandas.core.frame.DataFrame'> Index: 108 entries, E1 to E109 Data columns (total 12 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 RIVER 108 non-null object 1 LOCATION 108 non-null object 2 ERECTED 108 non-null int64 3 PURPOSE 108 non-null object 4 LENGTH 108 non-null object 5 LANES 108 non-null object 6 CLEAR-G 108 non-null object 7 T-OR-D 108 non-null object 8 MATERIAL 108 non-null object 9 SPAN 108 non-null object 10 REL-L 108 non-null object 11 TYPE 108 non-null object dtypes: int64(1), object(11) memory usage: 11.0+ KB None ```python # SHOWING FIRSTS N-ROWS AS THEY ARE STORED WITHIN DATASET # --------------------------------------------------------------------------- # dataset.head(5) ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>RIVER</th> <th>LOCATION</th> <th>ERECTED</th> <th>PURPOSE</th> <th>LENGTH</th> <th>LANES</th> <th>CLEAR-G</th> <th>T-OR-D</th> <th>MATERIAL</th> <th>SPAN</th> <th>REL-L</th> <th>TYPE</th> </tr> </thead> <tbody> <tr> <th>E1</th> <td>M</td> <td>3</td> <td>1818</td> <td>HIGHWAY</td> <td>?</td> <td>2</td> <td>N</td> <td>THROUGH</td> <td>WOOD</td> <td>SHORT</td> <td>S</td> <td>WOOD</td> </tr> <tr> <th>E2</th> <td>A</td> <td>25</td> <td>1819</td> <td>HIGHWAY</td> <td>1037</td> <td>2</td> <td>N</td> <td>THROUGH</td> <td>WOOD</td> <td>SHORT</td> <td>S</td> <td>WOOD</td> </tr> <tr> <th>E3</th> <td>A</td> <td>39</td> <td>1829</td> <td>AQUEDUCT</td> <td>?</td> <td>1</td> <td>N</td> <td>THROUGH</td> <td>WOOD</td> <td>?</td> <td>S</td> <td>WOOD</td> </tr> <tr> <th>E5</th> <td>A</td> <td>29</td> <td>1837</td> <td>HIGHWAY</td> <td>1000</td> <td>2</td> <td>N</td> <td>THROUGH</td> <td>WOOD</td> <td>SHORT</td> <td>S</td> <td>WOOD</td> </tr> <tr> <th>E6</th> <td>M</td> <td>23</td> <td>1838</td> <td>HIGHWAY</td> <td>?</td> <td>2</td> <td>N</td> <td>THROUGH</td> <td>WOOD</td> <td>?</td> <td>S</td> <td>WOOD</td> </tr> </tbody> </table> </div> What we can notice from just the table above is that there are some attributes that are characterized by a special character that is '?' which stands for a missing value, so by chance there was not possibility to get the value for this attribute, such as for LENGTH and SPAN attributes. Analyzing in more details the dataset we discover that there are up to 6 different attributes, in the majority attributes with categorical or nominal nature such as CLEAR-G, T-OR-D, MATERIAL, SPAN, REL-L, and TYPE that contain at list one row characterized by the fact that one of its attributes is set to assuming '?' value that stands, as we already know for a missing value. Here, we can follow different strategies that depends onto the level of complexity as well as accuracy we want to obtain or achieve for models we are going to fit to the data after having correctly pre-processed them, speaking about what we could do with missing values. In fact one can follow the simplest way and can decide to simply discard those rows that contain at least one attribute with a missing value represented by the '?' symbol. Otherwise one may alos decide to follow a different strategy that aims at keeping also those rows that have some missing values by means of some kind of technique that allows to establish a potential substituting value for the missing one. So, in this setting, that is our analyses, we start by just leaving out those rows that at least contain one attribute that has a missing value, this choice leads us to reduce the size of our dataset from 108 records to 70 remaining samples, with a drop of 38 data examples, which may affect the final results, since we left out more or less the 46\% of the data because of missing values. ```python # INVESTIGATING DATASET IN ORDER TO DETECT NULL VALUES # --------------------------------------------------------------------------- # print('Before preprocessing dataset and handling null values') result = dataset.isnull().values.any() print('There are any null values ? Response: {}'.format(result)) result = dataset.isnull().sum() print('Number of null values for each predictor:\n{}'.format(result)) ``` Before preprocessing dataset and handling null values There are any null values ? Response: False Number of null values for each predictor: RIVER 0 LOCATION 0 ERECTED 0 PURPOSE 0 LENGTH 0 LANES 0 CLEAR-G 0 T-OR-D 0 MATERIAL 0 SPAN 0 REL-L 0 TYPE 0 dtype: int64 ```python # DISCOVERING VALUES WITHIN EACH PREDICTOR DOMAIN # --------------------------------------------------------------------------- # columns_2_avoid = ['ERECTED', 'LENGTH', 'LOCATION', 'LANES'] # columns_2_avoid = None list_columns_2_fix = show_categorical_predictor_values(dataset, columns_2_avoid) ``` RIVER : ['A', 'M', 'O', 'Y'] PURPOSE : ['AQUEDUCT', 'HIGHWAY', 'RR', 'WALK'] CLEAR-G : ['?', 'G', 'N'] T-OR-D : ['?', 'DECK', 'THROUGH'] MATERIAL : ['?', 'IRON', 'STEEL', 'WOOD'] SPAN : ['?', 'LONG', 'MEDIUM', 'SHORT'] REL-L : ['?', 'F', 'S', 'S-F'] TYPE : ['?', 'ARCH', 'CANTILEV', 'CONT-T', 'NIL', 'SIMPLE-T', 'SUSPEN', 'WOOD'] ```python # FIXING, UPDATING NULL VALUES CODED AS '?' SYMBOL # WITHIN EACH CATEGORICAL VARIABLE, IF DETECTED ANY # --------------------------------------------------------------------------- # print('"Before" removing \'?\' rows, Dataset dim:', dataset.shape) for _, predictor in enumerate(list_columns_2_fix): dataset = dataset[dataset[predictor] != '?'] print('"After" removing \'?\' rows, Dataset dim: ', dataset.shape) print('-' * 50) _ = show_categorical_predictor_values(dataset, columns_2_avoid) ``` "Before" removing '?' rows, Dataset dim: (108, 12) "After" removing '?' rows, Dataset dim: (88, 12) -------------------------------------------------- RIVER : ['A', 'M', 'O', 'Y'] PURPOSE : ['AQUEDUCT', 'HIGHWAY', 'RR'] CLEAR-G : ['G', 'N'] T-OR-D : ['DECK', 'THROUGH'] MATERIAL : ['IRON', 'STEEL', 'WOOD'] SPAN : ['LONG', 'MEDIUM', 'SHORT'] REL-L : ['F', 'S', 'S-F'] TYPE : ['ARCH', 'CANTILEV', 'CONT-T', 'SIMPLE-T', 'SUSPEN', 'WOOD'] ```python # INTERMEDIATE RESULT FOUND # --------------------------------------------------------------------------- # preprocess_categorical_variables(dataset, columns_2_avoid) print(dataset.info()) ``` <class 'pandas.core.frame.DataFrame'> Index: 88 entries, E1 to E90 Data columns (total 12 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 RIVER 88 non-null int64 1 LOCATION 88 non-null object 2 ERECTED 88 non-null int64 3 PURPOSE 88 non-null int64 4 LENGTH 88 non-null object 5 LANES 88 non-null object 6 CLEAR-G 88 non-null int64 7 T-OR-D 88 non-null int64 8 MATERIAL 88 non-null int64 9 SPAN 88 non-null int64 10 REL-L 88 non-null int64 11 TYPE 88 non-null int64 dtypes: int64(9), object(3) memory usage: 8.9+ KB None ```python dataset.head(5) ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>RIVER</th> <th>LOCATION</th> <th>ERECTED</th> <th>PURPOSE</th> <th>LENGTH</th> <th>LANES</th> <th>CLEAR-G</th> <th>T-OR-D</th> <th>MATERIAL</th> <th>SPAN</th> <th>REL-L</th> <th>TYPE</th> </tr> </thead> <tbody> <tr> <th>E1</th> <td>2</td> <td>3</td> <td>1818</td> <td>2</td> <td>?</td> <td>2</td> <td>2</td> <td>2</td> <td>3</td> <td>3</td> <td>2</td> <td>6</td> </tr> <tr> <th>E2</th> <td>1</td> <td>25</td> <td>1819</td> <td>2</td> <td>1037</td> <td>2</td> <td>2</td> <td>2</td> <td>3</td> <td>3</td> <td>2</td> <td>6</td> </tr> <tr> <th>E5</th> <td>1</td> <td>29</td> <td>1837</td> <td>2</td> <td>1000</td> <td>2</td> <td>2</td> <td>2</td> <td>3</td> <td>3</td> <td>2</td> <td>6</td> </tr> <tr> <th>E7</th> <td>1</td> <td>27</td> <td>1840</td> <td>2</td> <td>990</td> <td>2</td> <td>2</td> <td>2</td> <td>3</td> <td>2</td> <td>2</td> <td>6</td> </tr> <tr> <th>E8</th> <td>1</td> <td>28</td> <td>1844</td> <td>1</td> <td>1000</td> <td>1</td> <td>2</td> <td>2</td> <td>1</td> <td>3</td> <td>2</td> <td>5</td> </tr> </tbody> </table> </div> The next step is represented by the effort of mapping categorical variables into numerical variables, so that them are comparable with the already existing numerical or continuous variables, and also by mapping the categorical variables into numerical variables we allow or enable us to perform some kind of normalization or just transformation onto the entire dataset in order to let some machine learning algorithm to work better or to take advantage of normalized data within our pre-processed dataset. Furthermore, by transforming first the categorical attributes into a continuous version we are also able to calculate the \textit{heatmap}, which is a very useful way of representing a correlation matrix calculated on the whole dataset. Moreover we have displayed data distribution for each attribute by means of histogram representation to take some useful information about the number of occurrences for each possible value, in particular for those attributes that have a categorical nature. ```python # MAP NUMERICAL VALUES TO INTEGER VALUES # --------------------------------------------------------------------------- # print('Before', dataset.shape) columns_2_map = ['ERECTED', 'LANES'] for _, predictor in enumerate(columns_2_map): dataset = dataset[dataset[predictor] != '?'] dataset[predictor] = np.array(list(map(lambda x: int(x), dataset[predictor].values))) print('After', dataset.shape) print(dataset.info()) print(dataset.head(5)) ``` Before (88, 12) After (80, 12) <class 'pandas.core.frame.DataFrame'> Index: 80 entries, E1 to E90 Data columns (total 12 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 RIVER 80 non-null int64 1 LOCATION 80 non-null object 2 ERECTED 80 non-null int32 3 PURPOSE 80 non-null int64 4 LENGTH 80 non-null object 5 LANES 80 non-null int32 6 CLEAR-G 80 non-null int64 7 T-OR-D 80 non-null int64 8 MATERIAL 80 non-null int64 9 SPAN 80 non-null int64 10 REL-L 80 non-null int64 11 TYPE 80 non-null int64 dtypes: int32(2), int64(8), object(2) memory usage: 7.5+ KB None RIVER LOCATION ERECTED PURPOSE LENGTH LANES CLEAR-G T-OR-D MATERIAL \ E1 2 3 1818 2 ? 2 2 2 3 E2 1 25 1819 2 1037 2 2 2 3 E5 1 29 1837 2 1000 2 2 2 3 E7 1 27 1840 2 990 2 2 2 3 E8 1 28 1844 1 1000 1 2 2 1 SPAN REL-L TYPE E1 3 2 6 E2 3 2 6 E5 3 2 6 E7 2 2 6 E8 3 2 5 ```python # MAP NUMERICAL VALUES TO FLOAT VALUES # --------------------------------------------------------------------------- # # print('Before', dataset.shape) columns_2_map = ['LOCATION', 'LANES', 'LENGTH'] for _, predictor in enumerate(columns_2_map): dataset = dataset[dataset[predictor] != '?'] dataset[predictor] = np.array(list(map(lambda x: float(x), dataset[predictor].values))) # print('After', dataset.shape) # print(dataset.info()) # print(dataset.head(5)) # columns_2_avoid = None # list_columns_2_fix = show_categorical_predictor_values(dataset, None) ``` ```python result = dataset.isnull().values.any() # print('After handling null values\nThere are any null values ? Response: {}'.format(result)) result = dataset.isnull().sum() # print('Number of null values for each predictor:\n{}'.format(result)) dataset.head(5) ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>RIVER</th> <th>LOCATION</th> <th>ERECTED</th> <th>PURPOSE</th> <th>LENGTH</th> <th>LANES</th> <th>CLEAR-G</th> <th>T-OR-D</th> <th>MATERIAL</th> <th>SPAN</th> <th>REL-L</th> <th>TYPE</th> </tr> </thead> <tbody> <tr> <th>E2</th> <td>1</td> <td>25.0</td> <td>1819</td> <td>2</td> <td>1037.0</td> <td>2.0</td> <td>2</td> <td>2</td> <td>3</td> <td>3</td> <td>2</td> <td>6</td> </tr> <tr> <th>E5</th> <td>1</td> <td>29.0</td> <td>1837</td> <td>2</td> <td>1000.0</td> <td>2.0</td> <td>2</td> <td>2</td> <td>3</td> <td>3</td> <td>2</td> <td>6</td> </tr> <tr> <th>E7</th> <td>1</td> <td>27.0</td> <td>1840</td> <td>2</td> <td>990.0</td> <td>2.0</td> <td>2</td> <td>2</td> <td>3</td> <td>2</td> <td>2</td> <td>6</td> </tr> <tr> <th>E8</th> <td>1</td> <td>28.0</td> <td>1844</td> <td>1</td> <td>1000.0</td> <td>1.0</td> <td>2</td> <td>2</td> <td>1</td> <td>3</td> <td>2</td> <td>5</td> </tr> <tr> <th>E9</th> <td>2</td> <td>3.0</td> <td>1846</td> <td>2</td> <td>1500.0</td> <td>2.0</td> <td>2</td> <td>2</td> <td>1</td> <td>3</td> <td>2</td> <td>5</td> </tr> </tbody> </table> </div> ```python dataset.describe(include='all') ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>RIVER</th> <th>LOCATION</th> <th>ERECTED</th> <th>PURPOSE</th> <th>LENGTH</th> <th>LANES</th> <th>CLEAR-G</th> <th>T-OR-D</th> <th>MATERIAL</th> <th>SPAN</th> <th>REL-L</th> <th>TYPE</th> </tr> </thead> <tbody> <tr> <th>count</th> <td>70.000000</td> <td>70.000000</td> <td>70.000000</td> <td>70.000000</td> <td>70.000000</td> <td>70.000000</td> <td>70.000000</td> <td>70.000000</td> <td>70.000000</td> <td>70.000000</td> <td>70.000000</td> <td>70.000000</td> </tr> <tr> <th>mean</th> <td>1.642857</td> <td>25.438571</td> <td>1911.542857</td> <td>2.214286</td> <td>1597.657143</td> <td>2.857143</td> <td>1.257143</td> <td>1.814286</td> <td>2.071429</td> <td>1.742857</td> <td>1.728571</td> <td>3.457143</td> </tr> <tr> <th>std</th> <td>0.723031</td> <td>13.223347</td> <td>36.010339</td> <td>0.478308</td> <td>780.237680</td> <td>1.242785</td> <td>0.440215</td> <td>0.391684</td> <td>0.428054</td> <td>0.629831</td> <td>0.797122</td> <td>1.575958</td> </tr> <tr> <th>min</th> <td>1.000000</td> <td>1.000000</td> <td>1819.000000</td> <td>1.000000</td> <td>840.000000</td> <td>1.000000</td> <td>1.000000</td> <td>1.000000</td> <td>1.000000</td> <td>1.000000</td> <td>1.000000</td> <td>1.000000</td> </tr> <tr> <th>25%</th> <td>1.000000</td> <td>15.250000</td> <td>1891.250000</td> <td>2.000000</td> <td>1000.000000</td> <td>2.000000</td> <td>1.000000</td> <td>2.000000</td> <td>2.000000</td> <td>1.000000</td> <td>1.000000</td> <td>2.000000</td> </tr> <tr> <th>50%</th> <td>1.500000</td> <td>27.000000</td> <td>1915.000000</td> <td>2.000000</td> <td>1325.000000</td> <td>2.000000</td> <td>1.000000</td> <td>2.000000</td> <td>2.000000</td> <td>2.000000</td> <td>2.000000</td> <td>4.000000</td> </tr> <tr> <th>75%</th> <td>2.000000</td> <td>35.750000</td> <td>1935.500000</td> <td>2.000000</td> <td>2000.000000</td> <td>4.000000</td> <td>1.750000</td> <td>2.000000</td> <td>2.000000</td> <td>2.000000</td> <td>2.000000</td> <td>4.000000</td> </tr> <tr> <th>max</th> <td>3.000000</td> <td>49.000000</td> <td>1978.000000</td> <td>3.000000</td> <td>4558.000000</td> <td>6.000000</td> <td>2.000000</td> <td>2.000000</td> <td>3.000000</td> <td>3.000000</td> <td>3.000000</td> <td>6.000000</td> </tr> </tbody> </table> </div> ```python # sns.pairplot(dataset, hue='T-OR-D', size=1.5) ``` ```python columns_2_avoid = ['ERECTED', 'LENGTH', 'LOCATION'] target_col = 'T-OR-D' # show_frequency_distribution_predictors(dataset, columns_2_avoid) # show_frequency_distribution_predictor(dataset, predictor_name='RIVER', columns_2_avoid=columns_2_avoid) # build_boxplot(dataset, predictor_name='RIVER', columns_2_avoid=columns_2_avoid, target_col='T-OR-D') ``` ```python # show_frequency_distribution_predictors(dataset, columns_2_avoid) # show_frequency_distribution_predictor(dataset, predictor_name='T-OR-D', columns_2_avoid=columns_2_avoid) ``` ```python # show_frequency_distribution_predictors(dataset, columns_2_avoid) # show_frequency_distribution_predictor(dataset, predictor_name='CLEAR-G', columns_2_avoid=columns_2_avoid) # build_boxplot(dataset, predictor_name='CLEAR-G', columns_2_avoid=columns_2_avoid, target_col='T-OR-D') ``` ```python # show_frequency_distribution_predictors(dataset, columns_2_avoid) # show_frequency_distribution_predictor(dataset, predictor_name='SPAN', columns_2_avoid=columns_2_avoid) # build_boxplot(dataset, predictor_name='SPAN', columns_2_avoid=columns_2_avoid, target_col='T-OR-D') ``` ```python # show_frequency_distribution_predictors(dataset, columns_2_avoid) # show_frequency_distribution_predictor(dataset, predictor_name='MATERIAL', columns_2_avoid=columns_2_avoid) # build_boxplot(dataset, predictor_name='MATERIAL', columns_2_avoid=columns_2_avoid, target_col='T-OR-D') ``` ```python # show_frequency_distribution_predictors(dataset, columns_2_avoid) # show_frequency_distribution_predictor(dataset, predictor_name='REL-L', columns_2_avoid=columns_2_avoid) ``` ```python # show_frequency_distribution_predictors(dataset, columns_2_avoid) # show_frequency_distribution_predictor(dataset, predictor_name='TYPE', columns_2_avoid=columns_2_avoid) # build_boxplot(dataset, predictor_name='TYPE', columns_2_avoid=columns_2_avoid, target_col='T-OR-D') ``` ```python corr_result = dataset.corr() display_heatmap(corr_result) ``` ```python print(type(corr_result)) corr_result.head(5) ``` <class 'pandas.core.frame.DataFrame'> <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>RIVER</th> <th>LOCATION</th> <th>ERECTED</th> <th>PURPOSE</th> <th>LENGTH</th> <th>LANES</th> <th>CLEAR-G</th> <th>T-OR-D</th> <th>MATERIAL</th> <th>SPAN</th> <th>REL-L</th> <th>TYPE</th> </tr> </thead> <tbody> <tr> <th>RIVER</th> <td>1.000000</td> <td>-0.001115</td> <td>0.273067</td> <td>0.140688</td> <td>0.307933</td> <td>0.023041</td> <td>-0.253686</td> <td>0.171802</td> <td>-0.150515</td> <td>-0.554666</td> <td>-0.246072</td> <td>-0.401553</td> </tr> <tr> <th>LOCATION</th> <td>-0.001115</td> <td>1.000000</td> <td>0.116086</td> <td>0.020901</td> <td>0.273411</td> <td>-0.143143</td> <td>0.001508</td> <td>-0.040010</td> <td>0.043033</td> <td>-0.128955</td> <td>-0.100326</td> <td>-0.069777</td> </tr> <tr> <th>ERECTED</th> <td>0.273067</td> <td>0.116086</td> <td>1.000000</td> <td>-0.064069</td> <td>0.182171</td> <td>0.645548</td> <td>-0.503536</td> <td>-0.352379</td> <td>-0.247947</td> <td>-0.566937</td> <td>-0.152824</td> <td>-0.663815</td> </tr> <tr> <th>PURPOSE</th> <td>0.140688</td> <td>0.020901</td> <td>-0.064069</td> <td>1.000000</td> <td>0.269827</td> <td>-0.215944</td> <td>-0.265488</td> <td>0.060782</td> <td>-0.146627</td> <td>-0.103089</td> <td>0.002715</td> <td>0.041199</td> </tr> <tr> <th>LENGTH</th> <td>0.307933</td> <td>0.273411</td> <td>0.182171</td> <td>0.269827</td> <td>1.000000</td> <td>-0.042498</td> <td>-0.151726</td> <td>-0.344644</td> <td>-0.138829</td> <td>-0.381628</td> <td>-0.293178</td> <td>-0.214064</td> </tr> </tbody> </table> </div> ```python # show_histograms_from_heatmap_corr_matrix(corr_result, row_names=dataset.columns) ``` ```python # Make distinction between Target Variable and Predictors # --------------------------------------------------------------------------- # columns = dataset.columns # List of all attribute names target_col = 'T-OR-D' # Target variable name # Get Target values and map to 0s and 1s y = np.array(list(map(lambda x: 0 if x == 1 else 1, dataset[target_col].values))) print('Summary about Target Variable {target_col}') print('-' * 50) print(dataset['T-OR-D'].value_counts()) # Get Predictors X = dataset.loc[:, dataset.columns != target_col] ``` Summary about Target Variable {target_col} -------------------------------------------------- 2 57 1 13 Name: T-OR-D, dtype: int64 ```python # Standardizing the features # --------------------------------------------------------------------------- # scaler_methods = ['minmax', 'standard', 'norm'] scaler_method = 'standard' rescaledX = preprocessing_data_rescaling(scaler_method, X) ``` shape features matrix X, after normalizing: (70, 11) ### Pricipal Component Analysis After having investigate the data points inside the dataset, I move one to another section of my report where I decide to explore examples that made up the entire dataset using a particular technique in the field of statistical analysis that corresponds, precisely, to so called Principal Component Analysis. In fact, the major objective of this section is understand whether it is possible to transform, by means of some kind of linear transformation given by a mathematical calculation, the original data examples into reprojected representation that allows me to retrieve most useful information to be later exploited at training time. So, lets dive a bit whitin what is and which are main concepts, pros and cons about Principal Component Analysis. Firstly, we know that **Principal Component Analysis**, more shortly PCA, is a statistical procedure that uses an orthogonal transformation to convert a set of observations of possibly correlated variables into a set of values of linearly uncorrelated variables called *principal components*. This transformation is defined in such a way that: - the first principal component has the largest possible variance (that is, accounts for as much of the variability in the data as possible), - and each succeeding component in turn has the highest variance possible under the constraint that it is orthogonal to the preceding components. The resulting vectors, each being a linear combination of the variables and containing n observations, are an uncorrelated orthogonal basis set. PCA is sensitive to the relative scaling of the original variables. PCA is mostly used as a tool in *exploratory data analysis* and for making predictive models, for that reasons I used such a technique here, before going through the different learning technique for producing my models. #### Several Different Implementation From the theory and the filed of research in statistics, we know that out there, there are several different implementation and way of computing principal component analysis, and each adopted technique has different performance as well as numerical stability. The three major derivations are: - PCA by means of an iterative based procedure of extraing pricipal components one after the other selecting each time the one that account for the most of variance along its own axis, within the remainig subspace to be derived. - The second possible way of performing PCA is done via calculation of *Covariance Matrix* applied to attributes, that are our independent predictive variables, used to represent data points. - Lastly, it is used the technique known as *Singular Valued Decomposition* applied to the overall data points within our dataset. Reading scikit-learn documentation, I discovered that PCA's derivation uses the *LAPACK implementation* of the *full SVD* or a *randomized truncated SVD* by the method of *Halko et al. 2009*, depending on the shape of the input data and the number of components to extract. Therefore I will descrive mainly that way of deriving the method with respect to the others that, instead, will be described more briefly and roughly. #### PCA's Iterative based Method Going in order, as depicted briefly above, I start describing PCA obtained by means of iterative based procedure to extract one at a time a new principal componet explointing the data points at hand. We begin, recalling that, PCA is defined as an orthogonal linear transformation that transforms the data to a new coordinate system such that the greatest variance by some scalar projection of the data comes to lie on the first coordinate (called the first principal component), the second greatest variance on the second coordinate, and so on. We suppose to deal with a data matrix X, with column-wise zero empirical mean, where each of the n rows represents a different repetition of the experiment, and each of the p columns gives a particular kind of feature. From a math poitn of view, the transformation is defined by a set of p-dimensional vectors of weights or coefficients $\mathbf {w} _{(k)}=(w_{1},\dots ,w_{p})_{(k)}$ that map each row vector $\mathbf{x}_{(i)}$ of X to a new vector of principal component scores ${\displaystyle \mathbf {t} _{(i)}=(t_{1},\dots ,t_{l})_{(i)}}$, given by: ${\displaystyle {t_{k}}_{(i)}=\mathbf {x} _{(i)}\cdot \mathbf {w} _{(k)}\qquad \mathrm {for} \qquad i=1,\dots ,n\qquad k=1,\dots ,l}$. In this way all the individual variables ${\displaystyle t_{1},\dots ,t_{l}}$ of t considered over the data set successively inherit the maximum possible variance from X, with each coefficient vector w constrained to be a unit vector. More precisely, the first component In order to maximize variance has to satisfy the following expression: ${\displaystyle \mathbf {w} _{(1)}={\underset {\Vert \mathbf {w} \Vert =1}{\operatorname {\arg \,max} }}\,\left\{\sum _{i}\left(t_{1}\right)_{(i)}^{2}\right\}={\underset {\Vert \mathbf {w} \Vert =1}{\operatorname {\arg \,max} }}\,\left\{\sum _{i}\left(\mathbf {x} _{(i)}\cdot \mathbf {w} \right)^{2}\right\}}$ So, with $w_{1}$ found, the first principal component of a data vector $x_{1}$ can then be given as a score $t_{1(i)} = x_{1} ⋅ w_{1}$ in the transformed co-ordinates, or as the corresponding vector in the original variables, $(x_{1} ⋅ w_{1})w_{1}$. The others remainig components are computed as folloes. The kth component can be found by subtracting the first k − 1 principal components from X, as in the following expression: - ${\displaystyle \mathbf {\hat {X}} _{k}=\mathbf {X} -\sum _{s=1}^{k-1}\mathbf {X} \mathbf {w} _{(s)}\mathbf {w} _{(s)}^{\rm {T}}}$ - and then finding the weight vector which extracts the maximum variance from this new data matrix ${\mathbf {w}}_{{(k)}}={\underset {\Vert {\mathbf {w}}\Vert =1}{\operatorname {arg\,max}}}\left\{\Vert {\mathbf {{\hat {X}}}}_{{k}}{\mathbf {w}}\Vert ^{2}\right\}={\operatorname {\arg \,max}}\,\left\{{\tfrac {{\mathbf {w}}^{T}{\mathbf {{\hat {X}}}}_{{k}}^{T}{\mathbf {{\hat {X}}}}_{{k}}{\mathbf {w}}}{{\mathbf {w}}^{T}{\mathbf {w}}}}\right\}$ It turns out that: - from the formulas depicted above me get the remaining eigenvectors of $X^{T}X$, with the maximum values for the quantity in brackets given by their corresponding eigenvalues. Thus the weight vectors are eigenvectors of $X^{T}X$. - The kth principal component of a data vector $x_(i)$ can therefore be given as a score $t_{k(i)} = x_{(i)} ⋅ w_(k)$ in the transformed co-ordinates, or as the corresponding vector in the space of the original variables, $(x_{(i)} ⋅ w_{(k)}) w_{(k)}$, where $w_{(k)}$ is the kth eigenvector of $X^{T}X$. - The full principal components decomposition of X can therefore be given as: ${\displaystyle \mathbf {T} =\mathbf {X} \mathbf {W}}$, where W is a p-by-p matrix of weights whose columns are the eigenvectors of $X^{T}X$. #### Covariance Matrix for PCA analysis PCA made from covarian matrix computation requires the calculation of sample covariance matrix of the dataset as follows: $\mathbf{Q} \propto \mathbf{X}^T \mathbf{X} = \mathbf{W} \mathbf{\Lambda} \mathbf{W}^T$. The empirical covariance matrix between the principal components becomes ${\displaystyle \mathbf {W} ^{T}\mathbf {Q} \mathbf {W} \propto \mathbf {W} ^{T}\mathbf {W} \,\mathbf {\Lambda } \,\mathbf {W} ^{T}\mathbf {W} =\mathbf {\Lambda } }$. #### Singular Value Decomposition for PCA analysis Finally, the principal components transformation can also be associated with another matrix factorization, the singular value decomposition (SVD) of X, ${\displaystyle \mathbf {X} =\mathbf {U} \mathbf {\Sigma } \mathbf {W} ^{T}}$, where more precisely: - Σ is an n-by-p rectangular diagonal matrix of positive numbers $σ_{(k)}$, called the singular values of X; - instead U is an n-by-n matrix, the columns of which are orthogonal unit vectors of length n called the left singular vectors of X; - Then, W is a p-by-p whose columns are orthogonal unit vectors of length p and called the right singular vectors of X. factorizingn the matrix ${X^{T}X}$, it can be written as: ${\begin{aligned}\mathbf {X} ^{T}\mathbf {X} &=\mathbf {W} \mathbf {\Sigma } ^{T}\mathbf {U} ^{T}\mathbf {U} \mathbf {\Sigma } \mathbf {W} ^{T}\\&=\mathbf {W} \mathbf {\Sigma } ^{T}\mathbf {\Sigma } \mathbf {W} ^{T}\\&=\mathbf {W} \mathbf {\hat {\Sigma }} ^{2}\mathbf {W} ^{T}\end{aligned}}$ Where we recall that ${\displaystyle \mathbf {\hat {\Sigma }} }$ is the square diagonal matrix with the singular values of X and the excess zeros chopped off that satisfies ${\displaystyle \mathbf {{\hat {\Sigma }}^{2}} =\mathbf {\Sigma } ^{T}\mathbf {\Sigma } } {\displaystyle \mathbf {{\hat {\Sigma }}^{2}} =\mathbf {\Sigma } ^{T}\mathbf {\Sigma } }$. Comparison with the eigenvector factorization of $X^{T}X$ establishes that the right singular vectors W of X are equivalent to the eigenvectors of $X^{T}X$ , while the singular values $σ_{(k)}$ of X are equal to the square-root of the eigenvalues $λ_{(k)}$ of $X^{T}X$ . At this point we understand that using the singular value decomposition the score matrix T can be written as: $\begin{align} \mathbf{T} & = \mathbf{X} \mathbf{W} \\ & = \mathbf{U}\mathbf{\Sigma}\mathbf{W}^T \mathbf{W} \\ & = \mathbf{U}\mathbf{\Sigma} \end{align}$ so each column of T is given by one of the left singular vectors of X multiplied by the corresponding singular value. This form is also the polar decomposition of T. Efficient algorithms exist to calculate the SVD, as in scikit-learn package, of X without having to form the matrix $X^{T}X$, so computing the SVD is now the standard way to calculate a principal components analysis from a data matrix ```python n_components = rescaledX.shape[1] pca = PCA(n_components=n_components) # pca = PCA(n_components=2) # X_pca = pca.fit_transform(X) pca = pca.fit(rescaledX) X_pca = pca.transform(rescaledX) ``` ```python print(f"Cumulative varation explained(percentage) up to given number of pcs:") tmp_data = [] principal_components = [pc for pc in '2,5,6,7,8,9,10'.split(',')] for _, pc in enumerate(principal_components): n_components = int(pc) cum_var_exp_up_to_n_pcs = np.cumsum(pca.explained_variance_ratio_)[n_components-1] # print(f"Cumulative varation explained up to {n_components} pcs = {cum_var_exp_up_to_n_pcs}") # print(f"# pcs {n_components}: {cum_var_exp_up_to_n_pcs*100:.2f}%") tmp_data.append([n_components, cum_var_exp_up_to_n_pcs * 100]) tmp_df = pd.DataFrame(data=tmp_data, columns=['# PCS', 'Cumulative Varation Explained (percentage)']) tmp_df.head(len(tmp_data)) ``` Cumulative varation explained(percentage) up to given number of pcs: <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th># PCS</th> <th>Cumulative Varation Explained (percentage)</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>2</td> <td>47.738342</td> </tr> <tr> <th>1</th> <td>5</td> <td>75.856460</td> </tr> <tr> <th>2</th> <td>6</td> <td>82.615768</td> </tr> <tr> <th>3</th> <td>7</td> <td>88.413903</td> </tr> <tr> <th>4</th> <td>8</td> <td>92.661938</td> </tr> <tr> <th>5</th> <td>9</td> <td>95.976841</td> </tr> <tr> <th>6</th> <td>10</td> <td>98.432807</td> </tr> </tbody> </table> </div> ```python n_components = rescaledX.shape[1] pca = PCA(n_components=n_components) # pca = PCA(n_components=2) #X_pca = pca.fit_transform(X) pca = pca.fit(rescaledX) X_pca = pca.transform(rescaledX) fig = show_cum_variance_vs_components(pca, n_components) # py.sign_in('franec94', 'QbLNKpC0EZB0kol0aL2Z') # py.iplot(fig, filename='selecting-principal-components {}'.format(scaler_method)) ``` #### Major Pros & Cons of PCA ## Learning Models <a class="anchor" id="learning-models"></a> ```python model = PCA(n_components=2) model.fit(X) X_2D = model.transform(X) df = pd.DataFrame() df['PCA1'] = X_2D[:, 0] df['PCA2'] = X_2D[:, 1] df[target_col] = dataset[target_col].values sns.lmplot("PCA1", "PCA2", hue=target_col, data=df, fit_reg=False) ``` ```python # Parameters to be tested for Cross-Validation Approach pca_kernels_list = ['linear', 'poly', 'rbf', 'cosine',] parameters_sgd_classifier = { 'clf__loss': ('hinge', 'log', 'modified_huber', 'squared_hinge', 'perceptron'), 'clf__penalty': ('l2', 'l1', 'elasticnet'), 'clf__alpha': (1e-1, 1e-2, 1e-3, 1e-4), 'clf__max_iter': (50, 100, 150, 200, 500, 1000, 1500, 2000, 2500), 'clf__learning_rate': ('optimal',), 'clf__tol': (None, 1e-2, 1e-4, 1e-5, 1e-6) } kernel_type = 'svm-rbf-kernel' parameters_svm = { 'clf__gamma': (0.003, 0.03, 0.05, 0.5, 0.7, 1.0, 1.5), 'clf__max_iter':(1e+2, 1e+3, 2 * 1e+3, 5 * 1e+3, 1e+4, 1.5 * 1e+3), 'clf__C': (1e-4, 1e-3, 1e-2, 0.1, 1.0, 10, 1e+2, 1e+3), } parmas_decision_tree = { 'clf__splitter': ('random', 'best'), 'clf__criterion':('gini', 'entropy'), 'clf__max_features': (None, 'auto', 'sqrt', 'log2') } parmas_random_forest = { 'clf__n_estimators': (3, 5, 7, 10, 30, 50, 70, 100, 150, 200), 'clf__criterion':('gini', 'entropy'), 'clf__bootstrap': (True, False) } ``` ```python fit_by_n_components( estimator=GaussianNB(), \ X=X, \ y=y, \ n_components=2, \ clf_type='GaussianNB', \ show_plots=False, # pca_kernels_list=['linear'], verbose=0, ) ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>ACC(cv=3)</th> <th>STD(cv=3)</th> <th>ACC(cv=4)</th> <th>STD(cv=4)</th> <th>ACC(cv=5)</th> <th>STD(cv=5)</th> <th>ACC(cv=10)</th> <th>STD(cv=10)</th> <th>ACC(loo)</th> <th>STD(loo)</th> <th>ACC(Stfd-CV)</th> <th>STD(Stfd-CV)</th> </tr> </thead> <tbody> <tr> <th>linear</th> <td>0.79</td> <td>(+/-) 0.12</td> <td>0.77</td> <td>(+/-) 0.11</td> <td>0.83</td> <td>(+/-) 0.07</td> <td>0.81</td> <td>(+/-) 0.18</td> <td>0.81</td> <td>(+/-) 0.79</td> <td>0.67</td> <td>(+/-) 0.21</td> </tr> <tr> <th>poly</th> <td>0.79</td> <td>(+/-) 0.12</td> <td>0.77</td> <td>(+/-) 0.11</td> <td>0.83</td> <td>(+/-) 0.07</td> <td>0.81</td> <td>(+/-) 0.18</td> <td>0.81</td> <td>(+/-) 0.79</td> <td>0.67</td> <td>(+/-) 0.21</td> </tr> <tr> <th>rbf</th> <td>0.79</td> <td>(+/-) 0.12</td> <td>0.77</td> <td>(+/-) 0.11</td> <td>0.83</td> <td>(+/-) 0.07</td> <td>0.81</td> <td>(+/-) 0.18</td> <td>0.81</td> <td>(+/-) 0.79</td> <td>0.67</td> <td>(+/-) 0.21</td> </tr> <tr> <th>cosine</th> <td>0.79</td> <td>(+/-) 0.12</td> <td>0.77</td> <td>(+/-) 0.11</td> <td>0.83</td> <td>(+/-) 0.07</td> <td>0.81</td> <td>(+/-) 0.18</td> <td>0.81</td> <td>(+/-) 0.79</td> <td>0.67</td> <td>(+/-) 0.21</td> </tr> </tbody> </table> </div> ```python # svm_linear_classifier_grid_search(rescaledX, y, kernel_type, num_features=[2], parameters_svm=parameters_svm) fit_by_n_components( estimator=LogisticRegression(), \ X=X, \ y=y, \ n_components=2, \ clf_type='LogisticRegression', \ show_plots=False, # pca_kernels_list=['linear'], verbose=0, ) ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>ACC(cv=3)</th> <th>STD(cv=3)</th> <th>ACC(cv=4)</th> <th>STD(cv=4)</th> <th>ACC(cv=5)</th> <th>STD(cv=5)</th> <th>ACC(cv=10)</th> <th>STD(cv=10)</th> <th>ACC(loo)</th> <th>STD(loo)</th> <th>ACC(Stfd-CV)</th> <th>STD(Stfd-CV)</th> </tr> </thead> <tbody> <tr> <th>linear</th> <td>0.75</td> <td>(+/-) 0.23</td> <td>0.77</td> <td>(+/-) 0.11</td> <td>0.77</td> <td>(+/-) 0.09</td> <td>0.81</td> <td>(+/-) 0.25</td> <td>0.81</td> <td>(+/-) 0.79</td> <td>0.81</td> <td>(+/-) 0.15</td> </tr> <tr> <th>poly</th> <td>0.75</td> <td>(+/-) 0.23</td> <td>0.77</td> <td>(+/-) 0.11</td> <td>0.77</td> <td>(+/-) 0.09</td> <td>0.81</td> <td>(+/-) 0.25</td> <td>0.81</td> <td>(+/-) 0.79</td> <td>0.81</td> <td>(+/-) 0.15</td> </tr> <tr> <th>rbf</th> <td>0.75</td> <td>(+/-) 0.23</td> <td>0.77</td> <td>(+/-) 0.11</td> <td>0.77</td> <td>(+/-) 0.09</td> <td>0.81</td> <td>(+/-) 0.25</td> <td>0.81</td> <td>(+/-) 0.79</td> <td>0.81</td> <td>(+/-) 0.15</td> </tr> <tr> <th>cosine</th> <td>0.75</td> <td>(+/-) 0.23</td> <td>0.77</td> <td>(+/-) 0.11</td> <td>0.77</td> <td>(+/-) 0.09</td> <td>0.81</td> <td>(+/-) 0.25</td> <td>0.81</td> <td>(+/-) 0.79</td> <td>0.81</td> <td>(+/-) 0.15</td> </tr> </tbody> </table> </div> ```python # svm_linear_classifier_grid_search(rescaledX, y, kernel_type, num_features=[2], parameters_svm=parameters_svm) fit_by_n_components( estimator=KNeighborsClassifier(), \ X=X, \ y=y, \ n_components=2, \ clf_type='KNeighborsClassifier', \ show_plots=False, # pca_kernels_list=['linear'], verbose=0, ) ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>ACC(cv=3)</th> <th>STD(cv=3)</th> <th>ACC(cv=4)</th> <th>STD(cv=4)</th> <th>ACC(cv=5)</th> <th>STD(cv=5)</th> <th>ACC(cv=10)</th> <th>STD(cv=10)</th> <th>ACC(loo)</th> <th>STD(loo)</th> <th>ACC(Stfd-CV)</th> <th>STD(Stfd-CV)</th> </tr> </thead> <tbody> <tr> <th>linear</th> <td>0.81</td> <td>(+/-) 0.11</td> <td>0.81</td> <td>(+/-) 0.23</td> <td>0.81</td> <td>(+/-) 0.21</td> <td>0.79</td> <td>(+/-) 0.28</td> <td>0.79</td> <td>(+/-) 0.82</td> <td>0.81</td> <td>(+/-) 0.11</td> </tr> <tr> <th>poly</th> <td>0.81</td> <td>(+/-) 0.11</td> <td>0.81</td> <td>(+/-) 0.23</td> <td>0.81</td> <td>(+/-) 0.21</td> <td>0.79</td> <td>(+/-) 0.28</td> <td>0.79</td> <td>(+/-) 0.82</td> <td>0.81</td> <td>(+/-) 0.11</td> </tr> <tr> <th>rbf</th> <td>0.81</td> <td>(+/-) 0.11</td> <td>0.81</td> <td>(+/-) 0.23</td> <td>0.81</td> <td>(+/-) 0.21</td> <td>0.79</td> <td>(+/-) 0.28</td> <td>0.79</td> <td>(+/-) 0.82</td> <td>0.81</td> <td>(+/-) 0.11</td> </tr> <tr> <th>cosine</th> <td>0.81</td> <td>(+/-) 0.11</td> <td>0.81</td> <td>(+/-) 0.23</td> <td>0.81</td> <td>(+/-) 0.21</td> <td>0.79</td> <td>(+/-) 0.28</td> <td>0.79</td> <td>(+/-) 0.82</td> <td>0.81</td> <td>(+/-) 0.11</td> </tr> </tbody> </table> </div> ```python fit_by_n_components( estimator=SVC(), \ X=X, \ y=y, \ n_components=12, \ clf_type='SVC', \ show_plots=True) ``` ERROR: Kernel PCA: Linear | SVC predict_proba is not available when probability=False <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>ACC(cv=3)</th> <th>STD(cv=3)</th> <th>ACC(cv=4)</th> <th>STD(cv=4)</th> <th>ACC(cv=5)</th> <th>STD(cv=5)</th> <th>ACC(cv=10)</th> <th>STD(cv=10)</th> <th>ACC(loo)</th> <th>STD(loo)</th> <th>ACC(Stfd-CV)</th> <th>STD(Stfd-CV)</th> </tr> </thead> <tbody> <tr> <th>linear</th> <td>0.79</td> <td>(+/-) 0.05</td> <td>0.77</td> <td>(+/-) 0.11</td> <td>0.79</td> <td>(+/-) 0.14</td> <td>0.77</td> <td>(+/-) 0.25</td> <td>0.75</td> <td>(+/-) 0.87</td> <td>0.77</td> <td>(+/-) 0.10</td> </tr> <tr> <th>poly</th> <td>0.79</td> <td>(+/-) 0.05</td> <td>0.77</td> <td>(+/-) 0.11</td> <td>0.79</td> <td>(+/-) 0.14</td> <td>0.77</td> <td>(+/-) 0.25</td> <td>0.75</td> <td>(+/-) 0.87</td> <td>0.77</td> <td>(+/-) 0.10</td> </tr> <tr> <th>rbf</th> <td>0.79</td> <td>(+/-) 0.05</td> <td>0.77</td> <td>(+/-) 0.11</td> <td>0.79</td> <td>(+/-) 0.14</td> <td>0.77</td> <td>(+/-) 0.25</td> <td>0.75</td> <td>(+/-) 0.87</td> <td>0.77</td> <td>(+/-) 0.10</td> </tr> <tr> <th>cosine</th> <td>0.79</td> <td>(+/-) 0.05</td> <td>0.77</td> <td>(+/-) 0.11</td> <td>0.79</td> <td>(+/-) 0.14</td> <td>0.77</td> <td>(+/-) 0.25</td> <td>0.75</td> <td>(+/-) 0.87</td> <td>0.77</td> <td>(+/-) 0.10</td> </tr> </tbody> </table> </div> ```python fit_by_n_components( estimator=DecisionTreeClassifier(), \ X=X, \ y=y, \ n_components=12, \ clf_type='DecisionTreeClassifier', \ verbose=0, show_plots=False) ``` ==================================================================================================== Kernel PCA: Linear | DecisionTreeClassifier ==================================================================================================== ---------------------------------------------------------------------------------------------------- K-Fold Cross Validation ---------------------------------------------------------------------------------------------------- CV=3 | Accuracy: 0.75 (+/- 0.06) CV=4 | Accuracy: 0.65 (+/- 0.17) CV=5 | Accuracy: 0.71 (+/- 0.13) CV=10 | Accuracy: 0.68 (+/- 0.33) ---------------------------------------------------------------------------------------------------- Leave-One-Out Cross-Validation ---------------------------------------------------------------------------------------------------- Accuracy: 0.77 (+/- 0.84) ---------------------------------------------------------------------------------------------------- Stratified-K-Fold Cross-Validation ---------------------------------------------------------------------------------------------------- Accuracy: 0.75 (+/- 0.24) | Accuract Test: ---------------------------------------------------------------------------------------------------- Fit ---------------------------------------------------------------------------------------------------- accuracy score: 0.8333333333333334 accuracy score (percentage): 83.33% <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>ACC(cv=3)</th> <th>STD(cv=3)</th> <th>ACC(cv=4)</th> <th>STD(cv=4)</th> <th>ACC(cv=5)</th> <th>STD(cv=5)</th> <th>ACC(cv=10)</th> <th>STD(cv=10)</th> <th>ACC(loo)</th> <th>STD(loo)</th> <th>ACC(Stfd-CV)</th> <th>STD(Stfd-CV)</th> </tr> </thead> <tbody> <tr> <th>linear</th> <td>0.75</td> <td>(+/-) 0.06</td> <td>0.65</td> <td>(+/-) 0.17</td> <td>0.71</td> <td>(+/-) 0.13</td> <td>0.68</td> <td>(+/-) 0.33</td> <td>0.77</td> <td>(+/-) 0.84</td> <td>0.75</td> <td>(+/-) 0.24</td> </tr> <tr> <th>poly</th> <td>0.75</td> <td>(+/-) 0.06</td> <td>0.65</td> <td>(+/-) 0.17</td> <td>0.71</td> <td>(+/-) 0.13</td> <td>0.68</td> <td>(+/-) 0.33</td> <td>0.77</td> <td>(+/-) 0.84</td> <td>0.75</td> <td>(+/-) 0.24</td> </tr> <tr> <th>rbf</th> <td>0.75</td> <td>(+/-) 0.06</td> <td>0.65</td> <td>(+/-) 0.17</td> <td>0.71</td> <td>(+/-) 0.13</td> <td>0.68</td> <td>(+/-) 0.33</td> <td>0.77</td> <td>(+/-) 0.84</td> <td>0.75</td> <td>(+/-) 0.24</td> </tr> <tr> <th>cosine</th> <td>0.75</td> <td>(+/-) 0.06</td> <td>0.65</td> <td>(+/-) 0.17</td> <td>0.71</td> <td>(+/-) 0.13</td> <td>0.68</td> <td>(+/-) 0.33</td> <td>0.77</td> <td>(+/-) 0.84</td> <td>0.75</td> <td>(+/-) 0.24</td> </tr> </tbody> </table> </div> ```python fit_by_n_components( estimator=RandomForestClassifier(), \ X=X, \ y=y, \ n_components=12, \ clf_type='RandomForestClassifier', \ show_plots=False) ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>ACC(cv=3)</th> <th>STD(cv=3)</th> <th>ACC(cv=4)</th> <th>STD(cv=4)</th> <th>ACC(cv=5)</th> <th>STD(cv=5)</th> <th>ACC(cv=10)</th> <th>STD(cv=10)</th> <th>ACC(loo)</th> <th>STD(loo)</th> <th>ACC(Stfd-CV)</th> <th>STD(Stfd-CV)</th> </tr> </thead> <tbody> <tr> <th>linear</th> <td>0.81</td> <td>(+/-) 0.06</td> <td>0.79</td> <td>(+/-) 0.13</td> <td>0.77</td> <td>(+/-) 0.09</td> <td>0.79</td> <td>(+/-) 0.13</td> <td>0.79</td> <td>(+/-) 0.82</td> <td>0.77</td> <td>(+/-) 0.10</td> </tr> <tr> <th>poly</th> <td>0.81</td> <td>(+/-) 0.06</td> <td>0.79</td> <td>(+/-) 0.13</td> <td>0.77</td> <td>(+/-) 0.09</td> <td>0.79</td> <td>(+/-) 0.13</td> <td>0.79</td> <td>(+/-) 0.82</td> <td>0.77</td> <td>(+/-) 0.10</td> </tr> <tr> <th>rbf</th> <td>0.81</td> <td>(+/-) 0.06</td> <td>0.79</td> <td>(+/-) 0.13</td> <td>0.77</td> <td>(+/-) 0.09</td> <td>0.79</td> <td>(+/-) 0.13</td> <td>0.79</td> <td>(+/-) 0.82</td> <td>0.77</td> <td>(+/-) 0.10</td> </tr> <tr> <th>cosine</th> <td>0.81</td> <td>(+/-) 0.06</td> <td>0.79</td> <td>(+/-) 0.13</td> <td>0.77</td> <td>(+/-) 0.09</td> <td>0.79</td> <td>(+/-) 0.13</td> <td>0.79</td> <td>(+/-) 0.82</td> <td>0.77</td> <td>(+/-) 0.10</td> </tr> </tbody> </table> </div> ```python # decision_tree_classifier_grid_search(rescaledX, y, num_features=[2], parmas_decision_tree=parmas_decision_tree) ``` ```python # random_forest_classifier_grid_search(rescaledX, y, num_features=[2], parmas_random_forest=parmas_random_forest) ``` ### Naive Bayes Classification Naive Bayes models are a group of extremely fast and simple classification algorithms that are often suitable for very high-dimensional datasets. Because they are so fast and have so few tunable parameters, they end up being very useful as a quick-and-dirty baseline for a classification problem. Here I will provide an intuitive and brief explanation of how naive Bayes classifiers work, followed by its exploitation onto my datasets. I start saying that Naive Bayes classifiers are built on Bayesian classification methods. These rely on Bayes's theorem, which is an equation describing the relationship of conditional probabilities of statistical quantities. n Bayesian classification, we're interested in finding the probability of a label given some observed features, which we can write as P(L | features). Bayes's theorem tells us how to express this in terms of quantities we can compute more directly: $P(L|features)=\frac{P(features|L)}{P(L)P(features)}$ If we are trying to decide between two labels, and we call them L1 and L2, then one way to make this decision is to compute the ratio of the posterior probabilities for each label: $\frac{P(L1 | features)}{P(L2 | features)}=\frac{P(features | L1)P(L1)}{P(features | L2)P(L2)}$ All we need now is some model by which we can compute P(features | $L_{i}$) for each label. Such a model is called a generative model because it specifies the hypothetical random process that generates the data. Specifying this generative model for each label is the main piece of the training of such a Bayesian classifier. The general version of such a training step is a very difficult task, but we can make it simpler through the use of some simplifying assumptions about the form of this model. This is where the "naive" in "naive Bayes" comes in: if we make very naive assumptions about the generative model for each label, we can find a rough approximation of the generative model for each class, and then proceed with the Bayesian classification. Different types of naive Bayes classifiers rest on different naive assumptions about the data, and we will examine a few of these in the following sections. #### Gaussian Naive Bayes Perhaps the easiest naive Bayes classifier to understand is Gaussian naive Bayes. In this classifier, the assumption is that data from each label is drawn from a simple Gaussian distribution. In fact, one extremely fast way to create a simple model is to assume that the data is described by a Gaussian distribution with no covariance between dimensions. This model can be fit by simply finding the mean and standard deviation of the points within each label, which is all you need to define such a distribution. $P(x_i \mid y) = \frac{1}{\sqrt{2\pi\sigma^2_y}} \exp\left(-\frac{(x_i - \mu_y)^2}{2\sigma^2_y}\right)$ The parameters $\sigma_{y}$ and $\mu_{y}$ are estimated usually using maximum likelihood. #### When to Use Naive Bayes Because naive Bayesian classifiers make such stringent assumptions about data, they will generally not perform as well as a more complicated model. That said, they have several advantages: - They are extremely fast for both training and prediction - They provide straightforward probabilistic prediction - They are often very easily interpretable - They have very few (if any) tunable parameters These advantages mean a naive Bayesian classifier is often a good choice as an initial baseline classification. If it performs suitably, then congratulations: you have a very fast, very interpretable classifier for your problem. If it does not perform well, then you can begin exploring more sophisticated models, with some baseline knowledge of how well they should perform. Naive Bayes classifiers tend to perform especially well in one of the following situations: - When the naive assumptions actually match the data (very rare in practice) - For very well-separated categories, when model complexity is less important - For very high-dimensional data, when model complexity is less important The last two points seem distinct, but they actually are related: as the dimension of a dataset grows, it is much less likely for any two points to be found close together (after all, they must be close in every single dimension to be close overall). This means that clusters in high dimensions tend to be more separated, on average, than clusters in low dimensions, assuming the new dimensions actually add information. For this reason, simplistic classifiers like naive Bayes tend to work as well or better than more complicated classifiers as the dimensionality grows: once you have enough data, even a simple model can be very powerful. ### Support Vector Machines Classifier Here, in this section I'm going to exploit a machine learning techinique known as Support Vectors Machines in order to detect and so select the best model I can produce throughout the usage of data points contained within the dataset at hand. So let discuss a bit those kind of classifiers. In machine learning, **support-vector machines**, shortly SVMs, are *supervised learning models* with associated learning algorithms that analyze data used for classification and regression analysis. Given a set of training examples, each marked as belonging to one or the other of two categories, an SVM training algorithm builds a model that assigns new examples to one category or the other, making it a *non-probabilistic binary linear classifier*. An SVM model is a representation of the examples as points in space, mapped so that the examples of the separate categories are divided by a clear gap that is as wide as possible. New examples are then mapped into that same space and predicted to belong to a category based on the side of the gap on which they fall. More formally, a support-vector machine constructs a hyperplane or set of hyperplanes in a high-dimensional space, which can be used for classification, regression. Intuitively, a good separation is achieved by the hyperplane that has the largest distance to the nearest training-data point of any class, so-called *functional margin*, since in general the larger the margin, the lower the *generalization error* of the classifier. #### Mathematical formulation of SVMs Here, I'm going to describe the main mathematical properties and characteristics used to derive from a math point of view the algorithm derived and proven by researches when they have studied SVMs classifiers. I start saying and recalling that A support vector machine constructs a hyper-plane or set of hyper-planes in a high or infinite dimensional space, which can be used for classification, regression or other tasks. Intuitively, a good separation is achieved by the hyper-plane that has the largest distance to the nearest training data points of any class so-called functional margin, since in general the larger the margin the lower the generalization error of the classifier. When demonstrating SVMs classifier algorithm I suppose that We are given a training dataset of *n*n points of the form: \begin{align} (\vec{x_1} y_1),..,(\vec{x_n},y_n) \end{align} where the $y_{1}$ are either 1 or −1, each indicating the class to which the point $\vec{x}_{i}$ belongs. Each $\vec{x}_{i}$is a *p-dimensional real vector*. We want to find the "maximum-margin hyperplane" that divides the group of points $\vec{x}_{i}$ for which $y_{1}$ = 1from the group of points for which $y_{1}$ = − 1, which is defined so that the distance between the hyperplane and the nearest point $\vec{x}_{i}$ from either group is maximized. Any hyperplane can be written as the set of points $\vec{x}_{i}$ satisfying : $\vec{w}_{i}\cdot{\vec{x}_{i}} - b = 0$; where $\vec{w}_{i}$ is the, even if not necessarily, normal vector to the hyperplane. The parameter $\tfrac {b}{\|\vec{w}\|}$ determines the offset of the hyperplane from the origin along the normal vector $\vec{x}_{i}$. Arrived so far, I have to distiguish between two distinct cases which both depende on the nature of data points that generally made up a given dataset. Those two different cases are called *Hard-Margin* and *Soft Margin* and, respectively. The first case, so the ***Hard-Margin*** case, happens just for really optimistics datasets. In fact it is the case when the training data is linearly separable, hence, we can select two parallel hyperplanes that separate the two classes of data, so that the distance between them is as large as possible. The region bounded by these two hyperplanes is called the "margin", and the maximum-margin hyperplane is the hyperplane that lies halfway between them. With a normalized or standardized dataset, these hyperplanes can be described by the equations: - $\vec{w}_{i}\cdot{\vec{x}_{i}} - b = 1$, that is anything on or above this boundary is of one class, with label 1; - and, $\vec{w}_{i}\cdot{\vec{x}_{i}} - b = -1$, that is anything on or above this boundary is of one class, with label -1. We can notice also that the distance between these two hyperplanes is ${\displaystyle {\tfrac {2}{\|{\vec {w}}\|}}}$ so to maximize the distance between the planes we want to minimize ‖ w → ‖ {\displaystyle \|{\vec {w}}\|} \|{\vec {w}}\|. The distance is computed using the distance from a point to a plane equation. We also have to prevent data points from falling into the margin, we add the following constraint: for each *i*: - either, ${\displaystyle {\vec {w}}\cdot {\vec {x}}_{i}-b\geq 1}$, ${\displaystyle y_{i}=1}$; - or, ${\displaystyle {\vec {w}}\cdot {\vec {x}}_{i}-b\leq -1}$, if ${\displaystyle y_{i}=-1}$. These constraints state that each data point must lie on the correct side of the margin. Finally, we collect all the previous observations and define the following optimization problem: - from $y_{i}(\vec{w}_{i}\cdot{\vec{x}_{i}} - b) \geq 1$, for all $1 \leq i \leq n$; - to minimize ${\displaystyle y_{i}({\vec {w}}\cdot {\vec {x}}_{i}-b)\geq 1}$ ${\displaystyle i=1,\ldots ,n}$. The classifier we obtain is made from ${\vec {w}}$ and ${\displaystyle b}$ that solve this problem, and he max-margin hyperplane is completely determined by those ${\vec {x}}_{i}$ that lie nearest to it. These $\vec{x}_{i}$ are called *support vectors*. The other case, so the ***Soft-Margin*** case, convercely happens when the training data is not linearly separable. To deal with such situation, as well as, to extend SVM to cases in which the data are not linearly separable, we introduce the hinge loss function, that is: $max(y_{i}(\vec{w}_{i}\cdot{\vec{x}_{i}} - b))$. Once we have provided the new loss function we go ahead with the new optimization problem that we aim at minimizing that is: \begin{align} {\displaystyle \left[{\frac {1}{n}}\sum _{i=1}^{n}\max \left(0,1-y_{i}({\vec {w}}\cdot {\vec {x}}_{i}-b)\right)\right]+\lambda \lVert {\vec {w}}\rVert ^{2},} \end{align} where the parameter \lambda determines the trade-off between increasing the margin size and ensuring that the ${\vec {x}}_{i}$ lie on the correct side of the margin. Thus, for sufficiently small values of\lambda , the second term in the loss function will become negligible, hence, it will behave similar to the hard-margin SVM, if the input data are linearly classifiable, but will still learn if a classification rule is viable or not. What we notice from last equations written just above is that we deal with a quadratic programming problem, and its solution is provided, detailed below. We start defining a *Primal Problem* as follow: - For each $\{1,\,\ldots ,\,n\}$ we introduce a variable ${\displaystyle \zeta _{i}=\max \left(0,1-y_{i}(w\cdot x_{i}-b)\right)}$. Note that ${\displaystyle \zeta _{i}}$ is the smallest nonnegative number satisfying ${\displaystyle y_{i}(w\cdot x_{i}-b)\geq 1-\zeta _{i}}$; - we can rewrite the optimization problem as follows: ${\displaystyle {\text{minimize }}{\frac {1}{n}}\sum _{i=1}^{n}\zeta _{i}+\lambda \|w\|^{2}}$, ${\displaystyle {\text{subject to }}y_{i}(w\cdot x_{i}-b)\geq 1-\zeta _{i}\,{\text{ and }}\,\zeta _{i}\geq 0,\,{\text{for all }}i.}$ However, by solving for the *Lagrangian dual* of the above problem, one obtains the simplified problem: \begin{align} {\displaystyle {\text{maximize}}\,\,f(c_{1}\ldots c_{n})=\sum _{i=1}^{n}c_{i}-{\frac {1}{2}}\sum _{i=1}^{n}\sum _{j=1}^{n}y_{i}c_{i}(x_{i}\cdot x_{j})y_{j}c_{j},} \\ {\displaystyle {\text{subject to }}\sum _{i=1}^{n}c_{i}y_{i}=0,\,{\text{and }}0\leq c_{i}\leq {\frac {1}{2n\lambda }}\;{\text{for all }}i.} \end{align} - moreover, the variables $c_i$ are defined as ${\displaystyle {\vec {w}}=\sum _{i=1}^{n}c_{i}y_{i}{\vec {x}}_{i}}$. Where, ${\displaystyle c_{i}=0}$ exactly when ${\displaystyle {\vec {x}}_{i}}$ lies on the correct side of the margin, and ${\displaystyle 0<c_{i}<(2n\lambda )^{-1}}$ when ${\vec {x}}_{i}$ lies on the margin's boundary. It follows that ${\displaystyle {\vec {w}}}$ can be written as a linear combination of the support vectors. The offset, ${\displaystyle b}$, can be recovered by finding an ${\vec {x}}_{i}$ on the margin's boundary and solving: ${\displaystyle y_{i}({\vec {w}}\cdot {\vec {x}}_{i}-b)=1\iff b={\vec {w}}\cdot {\vec {x}}_{i}-y_{i}.}$ This is called the *dual problem*. Since the dual maximization problem is a quadratic function of the ${\displaystyle c_{i}}$ subject to linear constraints, it is efficiently solvable by quadratic programming algorithms. Lastly, I will discuss what in the context of SVMs classifier is called as ***Kernel Trick***. Roughly speaking, we know that a possible way of dealing with datasets that are not linearly separable but that can become linearnly separable within an higher dimensional space, or feature space, we can try to remap the original data points into a higher order feature space by means of some kind of remapping function, hence, solve the SVMs classifier optimization problem to find out a linear classifier in that new larger feature space. Then, we project back to the original feature space the solution we have found, reminding that in the hold feature space the decision boundaries founded will be non-linear, but still allow to classify new examples. Usually, especially, dealing with large datasets or with datasets with large set of features this approach becomes computationally intensive and and unfeasible if we run out of memory. So, in other words, the procedure is constrained in time and space, and might become time consuming or even unfeasible because of the large amount of memory we have to exploit. An reasonable alternative is represented by the usage of kernel functions that are function which satisfy ${\displaystyle k({\vec {x}}_{i},{\vec {x}}_{j})=\varphi ({\vec {x}}_{i})\cdot \varphi ({\vec {x}}_{j})}$, where we recall that classification vector ${\vec {w}}$ in the transformed space satisfies ${\displaystyle {\vec {w}}=\sum _{i=1}^{n}c_{i}y_{i}\varphi ({\vec {x}}_{i}),}$ where, the ${\displaystyle c_{i}}$ are obtained by solving the optimization problem: ${\displaystyle {\begin{aligned}{\text{maximize}}\,\,f(c_{1}\ldots c_{n})&=\sum _{i=1}^{n}c_{i}-{\frac {1}{2}}\sum _{i=1}^{n}\sum _{j=1}^{n}y_{i}c_{i}(\varphi ({\vec {x}}_{i})\cdot \varphi ({\vec {x}}_{j}))y_{j}c_{j}\\&=\sum _{i=1}^{n}c_{i}-{\frac {1}{2}}\sum _{i=1}^{n}\sum _{j=1}^{n}y_{i}c_{i}k({\vec {x}}_{i},{\vec {x}}_{j})y_{j}c_{j}\\\end{aligned}}}$ ${\displaystyle {\text{subject to }}\sum _{i=1}^{n}c_{i}y_{i}=0,\,{\text{and }}0\leq c_{i}\leq {\frac {1}{2n\lambda }}\;{\text{for all }}i.}$ The coefficients ${\displaystyle c_{i}}$ can be solved for using quadratic programming, and we can find some index ${\displaystyle i}$ such that ${\displaystyle 0<c_{i}<(2n\lambda )^{-1}}$, so that ${\displaystyle \varphi ({\vec {x}}_{i})}$ lies on the boundary of the margin in the transformed space, and then solve, by substituting doto product between remapped data points with kernel function applied upon the same arguments: ${\displaystyle {\begin{aligned}b={\vec {w}}\cdot \varphi ({\vec {x}}_{i})-y_{i}&=\left[\sum _{j=1}^{n}c_{j}y_{j}\varphi ({\vec {x}}_{j})\cdot \varphi ({\vec {x}}_{i})\right]-y_{i}\\&=\left[\sum _{j=1}^{n}c_{j}y_{j}k({\vec {x}}_{j},{\vec {x}}_{i})\right]-y_{i}.\end{aligned}}}$ Finally, ${\displaystyle {\vec {z}}\mapsto \operatorname {sgn}({\vec {w}}\cdot \varphi ({\vec {z}})-b)=\operatorname {sgn} \left(\left[\sum _{i=1}^{n}c_{i}y_{i}k({\vec {x}}_{i},{\vec {z}})\right]-b\right).}$ What follows is a briefly list of the most commonly used kernel functions. They should be fine tuned, by means of a either grid search or random search approaches, identifying the best set of values to replace whitin the picked kernel function, where the choice depend on the dataset at hand: - Polynomial (homogeneous): ${\displaystyle k({\vec {x_{i}}},{\vec {x_{j}}})=({\vec {x_{i}}}\cdot {\vec {x_{j}}})^{d}}$. - Polynomial (inhomogeneous): ${\displaystyle k({\vec {x_{i}}},{\vec {x_{j}}})=({\vec {x_{i}}}\cdot {\vec {x_{j}}}+1)^{d}}$. - Gaussian radial basis function: ${\displaystyle \gamma =1/(2\sigma ^{2})} {\displaystyle \gamma =1/(2\sigma ^{2})}$. - Hyperbolic tangent: ${\displaystyle k({\vec {x_{i}}},{\vec {x_{j}}})=\tanh(\kappa {\vec {x_{i}}}\cdot {\vec {x_{j}}}+c)}$ for some (not every) ${\displaystyle \kappa >0}$ and ${\displaystyle c<0}$. What follows is the application or use of SVMs classifier for learning a model that best fit the training data in order to be able to classify new instance in a reliable way, selecting the most promising model trained. #### Advantages and Backwards of SVMs Finally, I conclude this section providing a description of major advantages and backwards of such a machine learning technique, that have been noticed by researches who studied SVMs properties. The advantages of support vector machines are: - Effective in high dimensional spaces. - Still effective in cases where number of dimensions is greater than the number of samples. - Uses a subset of training points in the decision function (called support vectors), so it is also memory efficient. - Versatile: different Kernel functions can be specified for the decision function. Common kernels are provided, but it is also possible to specify custom kernels. On the other and, the disadvantages of support vector machines include: - If the number of features is much greater than the number of samples, avoid over-fitting in choosing Kernel functions and regularization term is crucial. - SVMs do not directly provide probability estimates, these are calculated using an expensive five-fold cross-validation (see Scores and probabilities, below). ### Decision Tree Models Decision Trees, for short DTs, are a *non-parametric supervised learning method* used for classification and regression. The goal is to create a model that predicts the value of a target variable by learning simple decision rules inferred from the data features. Their mathematical formulation is generally provided as follows: Given training vectors $x_{i} \in R^{n}$, $i=1,…, l$ and a label vector $y \in R^{l}$, a decision tree recursively partitions the space such that the samples with the same labels are grouped together. Let the data at node $m$ be represented by $Q$. For each candidate split $\theta = (j, t_{m})$ consisting of a feature $j$ and threshold $t_{m}$, partition the data into $Q_{left}(\theta)$ and $Q_{left}(\theta)$ subsets as: \begin{align}\begin{aligned}Q_{left}(\theta) = {(x, y) | x_j <= t_m}\\Q_{right}(\theta) = Q \setminus Q_{left}(\theta)\end{aligned}\end{align} The impurity at $m$ is computed using an impurity function $H()$, the choice of which depends on the task being solved (classification or regression) like: \begin{align} G(Q, \theta) = \frac{n_{left}}{N_m} H(Q_{left}(\theta)) + \frac{n_{right}}{N_m} H(Q_{right}(\theta)) \end{align} Select the parameters that minimises the impurity: $\theta^* = \operatorname{argmin}_\theta G(Q, \theta)$. Recurse for subsets $Q_{left}(\theta^*)$ and $Q_{right}(\theta^*)$ until the maximum allowable depth is reached, $N_m < \min_{samples}$ or N_m = 1. Speaking about *Classification Criteria* referred to the procedure used for learining or fit to the data a decision tree we can state what follows: If a target is a classification outcome taking on values $0,1,…,K-1$, for node $m$, representing a region $R_{m}$ with $N_{m}$ observations, let $p_{mk} = 1/ N_m \sum_{x_i \in R_m} I(y_i = k)$ be the proportion of class $k$ observations in node $m$. So, Common measures of impurity are: - Gini, specified as $H(X_m) = \sum_k p_{mk} (1 - p_{mk})$ - Entropy, definead as $(X_m) = - \sum_k p_{mk} \log(p_{mk})$ where, we recall that $X_{m}$ is the training data in node $m$. #### Decision Tree's Advantages & Bacwards Some advantages of decision trees are: - Simple to understand and to interpret. Trees can be visualised. - Requires little data preparation. Other techniques often require data normalisation, dummy variables need to be created and blank values to be removed. Note however that this module does not support missing values. - The cost of using the tree (i.e., predicting data) is logarithmic in the number of data points used to train the tree. - Able to handle both numerical and categorical data. Other techniques are usually specialised in analysing datasets that have only one type of variable. See algorithms for more information. - Able to handle multi-output problems. - Uses a white box model. If a given situation is observable in a model, the explanation for the condition is easily explained by boolean logic. By contrast, in a black box model (e.g., in an artificial neural network), results may be more difficult to interpret. - Possible to validate a model using statistical tests. That makes it possible to account for the reliability of the model. - Performs well even if its assumptions are somewhat violated by the true model from which the data were generated. The disadvantages of decision trees include: - Decision-tree learners can create over-complex trees that do not generalise the data well. This is called overfitting. Mechanisms such as pruning (not currently supported), setting the minimum number of samples required at a leaf node or setting the maximum depth of the tree are necessary to avoid this problem. - Decision trees can be unstable because small variations in the data might result in a completely different tree being generated. This problem is mitigated by using decision trees within an ensemble. - The problem of learning an optimal decision tree is known to be NP-complete under several aspects of optimality and even for simple concepts. Consequently, practical decision-tree learning algorithms are based on heuristic algorithms such as the greedy algorithm where locally optimal decisions are made at each node. Such algorithms cannot guarantee to return the globally optimal decision tree. This can be mitigated by training multiple trees in an ensemble learner, where the features and samples are randomly sampled with replacement. - There are concepts that are hard to learn because decision trees do not express them easily, such as XOR, parity or multiplexer problems. - Decision tree learners create biased trees if some classes dominate. It is therefore recommended to balance the dataset prior to fitting with the decision tree. ### Ensemble methods The goal of ensemble methods is to combine the predictions of several base estimators built with a given learning algorithm in order to improve generalizability / robustness over a single estimator. Two families of ensemble methods are usually distinguished: - In averaging methods, the driving principle is to build several estimators independently and then to average their predictions. On average, the combined estimator is usually better than any of the single base estimator because its variance is reduced. So, some examples are: Bagging methods, Forests of randomized trees, but still exist more classifiers; - Instead, in boosting methods, base estimators are built sequentially and one tries to reduce the bias of the combined estimator. The motivation is to combine several weak models to produce a powerful ensemble. Hence, some examples are: AdaBoost, Gradient Tree Boosting,but still exist more options. #### Random Forests The **sklearn.ensemble module** includes two averaging algorithms based on randomized decision trees: the RandomForest algorithm and the Extra-Trees method. Both algorithms are perturb-and-combine techniques, specifically designed for trees. This means a diverse set of classifiers is created by introducing randomness in the classifier construction. The prediction of the ensemble is given as the averaged prediction of the individual classifiers. In random forests (see RandomForestClassifier and RandomForestRegressor classes), each tree in the ensemble is built from a sample drawn with replacement (i.e., a bootstrap sample) from the training set. The main parameters to adjust when using these methods is *number of estimators* and *maxima features*. The former is the number of trees in the forest. The larger the better, but also the longer it will take to compute. In addition, note that results will stop getting significantly better beyond a critical number of trees. The latter is the size of the random subsets of features to consider when splitting a node. The lower the greater the reduction of variance, but also the greater the increase in bias. Empirical good default values are maxima features equals to null, that means always considering all features instead of a random subset, for regression problems, and maxima features equals to "sqrt", using a random subset of size sqrt(number of features)) for classification tasks, where number of features is the number of features in the data. The best parameter values should always be cross-validated. We note that the size of the model with the default parameters is $O( M * N * log (N) )$, where $M$ is the number of trees and $N$ is the number of samples. ### Improvements and Conclusions <a class="anchor" id="Improvements-and-conclusions"></a> ### References <a class="anchor" id="references"></a> - Data Domain Information part: - (Deck) https://en.wikipedia.org/wiki/Deck_(bridge) - (Cantilever bridge) https://en.wikipedia.org/wiki/Cantilever_bridge - (Arch bridge) https://en.wikipedia.org/wiki/Deck_(bridge) - Machine Learning part: - (Theory Book) https://jakevdp.github.io/PythonDataScienceHandbook/ - (Decsion Trees) https://scikit-learn.org/stable/modules/tree.html#tree - (SVM) https://scikit-learn.org/stable/modules/svm.html - (PCA) https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html - Chart part: - (Seaborn Charts) https://acadgild.com/blog/data-visualization-using-matplotlib-and-seaborn - Markdown Math part: - https://share.cocalc.com/share/b4a30ed038ee41d868dad094193ac462ccd228e2/Homework%20/HW%201.2%20-%20Markdown%20and%20LaTeX%20Cheatsheet.ipynb?viewer=share - https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Typesetting%20Equations.html ```python ```
module Applications.Example import Common.Util import Common.Interfaces import Specifications.OrderedGroup import Proofs.OrderTheory import Proofs.GroupTheory import Proofs.GroupCancelationLemmas import Proofs.TranslationInvarianceTheory %default total %access public export absoluteValue : (Ringops s, Decidable [s,s] leq) => .OrderedGroupSpec (+) Zero Ng leq -> s -> (a ** leq Zero a) absoluteValue spec x = case decision {rel = leq} x Zero of Yes prf => (Ng x ** invertNegative (partiallyOrderedGroup spec) x prf) No contra => let (positive, _) = orderContra (totalOrder spec) x Zero contra in (x ** positive)
{-# OPTIONS --rewriting #-} {-# OPTIONS --show-implicit #-} module NaturalDeduction-PatternLambdaBug where record ⊤ : Set where data ⊥ : Set where foo : ⦃ _ : ⊤ ⦄ → ⊥ → Set foo = λ {x → {!x!}} {- C-c C-c above generates invalid syntax: foo = λ { } Found an implicit lambda where an explicit lambda was expected when checking that the expression λ {} has type ⊥ → Set Better would have been foo = λ {()} -} -- module DelayMishMash where -- open import Level --public -- using (Level) renaming (zero to lzero; suc to lsuc) -- open import Size public -- open import Prelude.Monad renaming (Monad to RawMonad) -- --open import Category.Monad public -- -- using (RawMonad; module RawMonad) -- open import Data.Empty --public -- using (⊥; ⊥-elim) -- open import Data.List --public -- using (List; []; _∷_; map) -- open import Data.Maybe --public -- using (Maybe; just; nothing) renaming (map to fmap) -- open import Data.Product public -- using (∃; _×_; _,_) renaming (proj₁ to fst; proj₂ to snd) -- --infixr 1 _,_ -- open import Data.Sum --public -- using (_⊎_; [_,_]′) renaming (inj₁ to inl; inj₂ to inr) -- open import Data.Unit --public -- using (⊤) -- open import Function --public -- using (_∘_; case_of_) -- open import Relation.Nullary --public -- using (Dec; yes; no) -- open import Relation.Binary --public -- using (Setoid; module Setoid) -- import Relation.Binary.PreorderReasoning -- module Pre = Relation.Binary.PreorderReasoning -- open import Relation.Binary.PropositionalEquality --public -- using (_≡_; refl; sym; trans; cong; cong₂; subst; module ≡-Reasoning) -- --open ≡-Reasoning renaming (begin_ to proof_) public -- open import Relation.Binary.HeterogeneousEquality --public -- using (_≅_; refl; ≡-to-≅; module ≅-Reasoning) -- renaming (sym to hsym; trans to htrans; cong to hcong; -- cong₂ to hcong₂; subst to hsubst) -- hcong₃ : {A : Set}{B : A → Set}{C : ∀ a → B a → Set}{D : ∀ a b → C a b → Set} -- (f : ∀ a b c → D a b c) -- {a a′ : A} → a ≅ a′ → -- {b : B a}{b′ : B a′} → b ≅ b′ → -- {c : C a b}{c′ : C a′ b′} → c ≅ c′ → -- f a b c ≅ f a′ b′ c′ -- hcong₃ f refl refl refl = refl -- ≅-to-≡ : ∀ {a} {A : Set a} {x y : A} → x ≅ y → x ≡ y -- ≅-to-≡ refl = refl -- mutual -- data Delay (i : Size) (A : Set) : Set where -- now : A → Delay i A -- later : ∞Delay i A → Delay i A -- record ∞Delay (i : Size) (A : Set) : Set where -- coinductive -- field -- force : {j : Size< i} → Delay j A -- open ∞Delay public -- never : ∀{i A} → ∞Delay i A -- force (never {i}) {j} = later (never {j}) -- module Bind where -- mutual -- bindDelay : ∀ {i A B} → Delay i A → (A → Delay i B) → Delay i B -- bindDelay (now a) f = f a -- bindDelay (later a∞) f = later (bind∞Delay a∞ f) -- bind∞Delay : ∀ {i A B} → ∞Delay i A → (A → Delay i B) → ∞Delay i B -- force (bind∞Delay a∞ f) = bindDelay (force a∞) f -- _d>>=_ : ∀ {i A B} → Delay i A → (A → Delay i B) → Delay i B -- _d>>=_ {i} = Bind.bindDelay {i} -- {- -- open import Prelude.Applicative using (Applicative) -- instance delayApplicative : ∀ {i} → Applicative (Delay i) -- Applicative.pure (delayApplicative {i}) x = now x -- Applicative._<*>_ (delayApplicative {i}) (now f) x = x d>>= (now ∘ f) -- Applicative._<*>_ (delayApplicative {i}) (later f) x = {!force f {i}!} -- {- -- Applicative._<*>_ (delayApplicative {i}) f (now x) = {!x!} -- Bind.bindDelay x (λ x₁ → {!!}) -- Applicative._<*>_ (delayApplicative {i}) (now f) (later x) = {!!} -- Bind.bindDelay x (λ x₁ → {!!}) -- Applicative._<*>_ (delayApplicative {i}) (later f) (later x) = {!!} -- Bind.bindDelay x (λ x₁ → {!!}) -- -} -- Applicative.super (delayApplicative {i}) = {!!} -- -} -- {- -- instance delayMonad : ∀ {i} → RawMonad (Delay i) -- delayMonad {i} = record -- { {-return = now -- ; -}_>>=_ = bindDelay {i} -- } where open Bind -- -} -- {- -- module _ {i : Size} where -- open module DelayMonad = RawMonad (delayMonad {i = i}) -- public -- renaming (_⊛_ to _<*>_) -- -} -- open Bind public using () renaming (bind∞Delay to _∞>>=_) -- -- Map for Delay -- dreturn : {i : Size} → {A : Set} → A → Delay i A -- dreturn {i} = Delay.now {i} -- _d<$>_ : ∀ {i A B} (f : A → B) (a : Delay i A) → Delay i B -- f d<$> a = a d>>= λ a → dreturn (f a) -- -- Map for ∞Delay -- _∞<$>_ : ∀ {i A B} (f : A → B) (∞a : ∞Delay i A) → ∞Delay i B -- f ∞<$> ∞a = ∞a ∞>>= λ a → dreturn (f a) -- -- force (f ∞<$> ∞a) = f <$> force ∞a -- -- Double bind -- _=<<2_,_ : ∀ {i A B C} → (A → B → Delay i C) → Delay i A → Delay i B → Delay i C -- f =<<2 x , y = x d>>= λ a → y d>>= λ b → f a b -- mutual -- data _∼_ {i : Size} {A : Set} : (a? b? : Delay ∞ A) → Set where -- ∼now : ∀ a → now a ∼ now a -- ∼later : ∀ {a∞ b∞} (eq : a∞ ∞∼⟨ i ⟩∼ b∞) → later a∞ ∼ later b∞ -- _∼⟨_⟩∼_ = λ {A} a? i b? → _∼_ {i}{A} a? b? -- record _∞∼⟨_⟩∼_ {A} (a∞ : ∞Delay ∞ A) i (b∞ : ∞Delay ∞ A) : Set where -- coinductive -- field -- ∼force : {j : Size< i} → force a∞ ∼⟨ j ⟩∼ force b∞ -- _∞∼_ = λ {i} {A} a∞ b∞ → _∞∼⟨_⟩∼_ {A} a∞ i b∞ -- open _∞∼⟨_⟩∼_ public -- ∼never : ∀{i A} → (never {A = A}) ∞∼⟨ i ⟩∼ never -- ∼force ∼never = ∼later ∼never -- ∼refl : ∀{i A} (a? : Delay ∞ A) → a? ∼⟨ i ⟩∼ a? -- ∞∼refl : ∀{i A} (a∞ : ∞Delay ∞ A) → a∞ ∞∼⟨ i ⟩∼ a∞ -- ∼sym : ∀{i A}{a? b? : Delay ∞ A } → a? ∼⟨ i ⟩∼ b? → b? ∼⟨ i ⟩∼ a? -- ∞∼sym : ∀{i A}{a∞ b∞ : ∞Delay ∞ A} → a∞ ∞∼⟨ i ⟩∼ b∞ → b∞ ∞∼⟨ i ⟩∼ a∞ -- ∼trans : ∀{i A}{a? b? c? : Delay ∞ A} → -- a? ∼⟨ i ⟩∼ b? → b? ∼⟨ i ⟩∼ c? → a? ∼⟨ i ⟩∼ c? -- ∞∼trans : ∀{i A}{a∞ b∞ c∞ : ∞Delay ∞ A} → -- a∞ ∞∼⟨ i ⟩∼ b∞ → b∞ ∞∼⟨ i ⟩∼ c∞ → a∞ ∞∼⟨ i ⟩∼ c∞ -- ∼refl (now a) = ∼now a -- ∼refl (later a∞) = ∼later (∞∼refl a∞) -- ∼force (∞∼refl a∞) = ∼refl (force a∞) -- ∼sym (∼now a) = ∼now a -- ∼sym (∼later eq) = ∼later (∞∼sym eq) -- ∼force (∞∼sym eq) = ∼sym (∼force eq) -- ∼trans (∼now a) (∼now .a) = ∼now a -- ∼trans (∼later eq) (∼later eq′) = ∼later (∞∼trans eq eq′) -- ∼force (∞∼trans eq eq′) = ∼trans (∼force eq) (∼force eq′) -- -- Equality reasoning -- ∼setoid : (i : Size) (A : Set) → Setoid lzero lzero -- ∼setoid i A = record -- { Carrier = Delay ∞ A -- ; _≈_ = _∼_ {i} -- ; isEquivalence = record -- { refl = λ {a?} → ∼refl a? -- ; sym = ∼sym -- ; trans = ∼trans -- } -- } -- ∞∼setoid : (i : Size) (A : Set) → Setoid lzero lzero -- ∞∼setoid i A = record -- { Carrier = ∞Delay ∞ A -- ; _≈_ = _∞∼_ {i} -- ; isEquivalence = record -- { refl = λ {a?} → ∞∼refl a? -- ; sym = ∞∼sym -- ; trans = ∞∼trans -- } -- } -- module ∼-Reasoning {i : Size} {A : Set} where -- open Pre (Setoid.preorder (∼setoid i A)) public -- -- using (begin_; _∎) (_≈⟨⟩_ to _∼⟨⟩_; _≈⟨_⟩_ to _∼⟨_⟩_) -- renaming (_≈⟨⟩_ to _≡⟨⟩_; _≈⟨_⟩_ to _≡⟨_⟩_; _∼⟨_⟩_ to _∼⟨_⟩_; begin_ to proof_) -- module ∞∼-Reasoning {i : Size} {A : Set} where -- open Pre (Setoid.preorder (∞∼setoid i A)) public -- -- using (begin_; _∎) (_≈⟨⟩_ to _∼⟨⟩_; _≈⟨_⟩_ to _∼⟨_⟩_) -- renaming (_≈⟨⟩_ to _≡⟨⟩_; _≈⟨_⟩_ to _≡⟨_⟩_; _∼⟨_⟩_ to _∞∼⟨_⟩_; begin_ to proof_) -- mutual -- bind-assoc : ∀{i A B C} (m : Delay ∞ A) -- {k : A → Delay ∞ B} {l : B → Delay ∞ C} → -- ((m d>>= k) d>>= l) ∼⟨ i ⟩∼ (m d>>= λ a → (k a d>>= l)) -- bind-assoc (now a) = ∼refl _ -- bind-assoc (later a∞) = ∼later (∞bind-assoc a∞) -- ∞bind-assoc : ∀{i A B C} (a∞ : ∞Delay ∞ A) -- {k : A → Delay ∞ B} {l : B → Delay ∞ C} → -- ((a∞ ∞>>= k) ∞>>= l) ∞∼⟨ i ⟩∼ (a∞ ∞>>= λ a → (k a d>>= l)) -- ∼force (∞bind-assoc a∞) = bind-assoc (force a∞) -- bind-cong-l : ∀{i A B}{a? b? : Delay ∞ A} → a? ∼⟨ i ⟩∼ b? → -- (k : A → Delay ∞ B) → (a? d>>= k) ∼⟨ i ⟩∼ (b? d>>= k) -- ∞bind-cong-l : ∀{i A B}{a∞ b∞ : ∞Delay ∞ A} → a∞ ∞∼⟨ i ⟩∼ b∞ → -- (k : A → Delay ∞ B) → (a∞ ∞>>= k) ∞∼⟨ i ⟩∼ (b∞ ∞>>= k) -- bind-cong-r : ∀{i A B}(a? : Delay ∞ A){k l : A → Delay ∞ B} → -- (∀ a → (k a) ∼⟨ i ⟩∼ (l a)) → (a? d>>= k) ∼⟨ i ⟩∼ (a? d>>= l) -- ∞bind-cong-r : ∀{i A B}(a∞ : ∞Delay ∞ A){k l : A → Delay ∞ B} → -- (∀ a → (k a) ∼⟨ i ⟩∼ (l a)) → (a∞ ∞>>= k) ∞∼⟨ i ⟩∼ (a∞ ∞>>= l) -- bind-cong-l (∼now a) k = ∼refl _ -- bind-cong-l (∼later eq) k = ∼later (∞bind-cong-l eq k) -- ∼force (∞bind-cong-l eq k) = bind-cong-l (∼force eq) k -- bind-cong-r (now a) h = h a -- bind-cong-r (later a∞) h = ∼later (∞bind-cong-r a∞ h) -- ∼force (∞bind-cong-r a∞ h) = bind-cong-r (force a∞) h -- open import Prelude.Functor using (Functor; _<$>_) -- {- -- instance FunctorDelay : {i : Size} → Functor (Delay i) -- Functor.fmap (FunctorDelay {i}) {A} {B} f (now x) = {!!} -- Functor.fmap (FunctorDelay {i}) {A} {B} f (later x) = {!!} -- -} -- open import Prelude.Function using (_∘′_) -- map-compose : ∀{i A B C} (a? : Delay ∞ A) {f : A → B} {g : B → C} → -- (g d<$> (f d<$> a?)) ∼⟨ i ⟩∼ ((g ∘ f) d<$> a?) -- map-compose a? = bind-assoc a? -- map-cong : ∀{i A B}{a? b? : Delay ∞ A} (f : A → B) → -- a? ∼⟨ i ⟩∼ b? → (f d<$> a?) ∼⟨ i ⟩∼ (f d<$> b?) -- map-cong f eq = bind-cong-l eq (now ∘ f) -- data _⇓_ {A : Set} : (a? : Delay ∞ A) (a : A) → Set where -- now⇓ : ∀{a} → now a ⇓ a -- later⇓ : ∀{a} {a∞ : ∞Delay ∞ A} → force a∞ ⇓ a → later a∞ ⇓ a -- _⇓ : {A : Set} (x : Delay ∞ A) → Set -- x ⇓ = ∃ λ a → x ⇓ a -- map⇓ : ∀{A B}{a : A}{a? : Delay ∞ A}(f : A → B) → a? ⇓ a → (f d<$> a?) ⇓ f a -- subst∼⇓ : ∀{A}{a? a?′ : Delay ∞ A}{a : A} → a? ⇓ a → a? ∼ a?′ → a?′ ⇓ a -- bind⇓ : ∀{A B}(f : A → Delay ∞ B){?a : Delay ∞ A}{a : A}{b : B} → -- ?a ⇓ a → f a ⇓ b → (?a d>>= f) ⇓ b -- map⇓ f now⇓ = now⇓ -- map⇓ f (later⇓ a⇓) = later⇓ (map⇓ f a⇓) -- subst∼⇓ now⇓ (∼now a) = now⇓ -- subst∼⇓ (later⇓ p) (∼later eq) = later⇓ (subst∼⇓ p (∼force eq)) -- bind⇓ f now⇓ q = q -- bind⇓ f (later⇓ p) q = later⇓ (bind⇓ f p q) -- --infixr 6 _⇒_ -- --infixl 1 _,_ -- module CustomPrelude where -- open import Prelude public -- renaming (_==_ to _≟_) -- TODO ask Agda to rename Eq._==_ to Eq._≟_ -- hiding (force) -- needed by ∞Delay -- {-# BUILTIN REWRITE _≡_ #-} -- --{-# DISPLAY Eq._==_ _ = _≟_ #-} -- open import Container.List renaming (_∈_ to _∈C_; lookup∈ to lookup∈C) public -- _∈C?_ : ∀ {ℓ} {A : Set ℓ} ⦃ _ : Eq A ⦄ (a : A) → (xs : List A) → Dec (a ∈C xs) -- a ∈C? [] = no λ () -- a ∈C? (x ∷ xs) with a ≟ x -- … | yes a≡x rewrite a≡x = yes (zero refl) -- … | no a≢x with a ∈C? xs -- … | yes a∈xs = yes (suc a∈xs) -- … | no a∉xs = no (λ {(zero a≡x) → a≢x a≡x ; (suc a∈xs) → a∉xs a∈xs}) -- data _∈_ {ℓ} {A : Set ℓ} (a : A) : List A → Set ℓ -- where -- here : (as : List A) → a ∈ (a ∷ as) -- there : (x : A) {as : List A} → a ∈ as → a ∈ (x ∷ as) -- _∉_ : ∀ {ℓ} {A : Set ℓ} ⦃ _ : Eq A ⦄ (a : A) → (xs : List A) → Set ℓ -- a ∉ xs = ¬ (a ∈ xs) -- _∈?_ : ∀ {ℓ} {A : Set ℓ} ⦃ _ : Eq A ⦄ (a : A) → (xs : List A) → Dec (a ∈ xs) -- a ∈? [] = no λ () -- a ∈? (x ∷ xs) with a ≟ x -- … | yes a≡x rewrite a≡x = yes (here xs) -- … | no a≢x with a ∈? xs -- … | yes a∈xs = yes (there x a∈xs) -- … | no a∉xs = no (λ {(here _) → a≢x refl ; (there _ a∈xs) → a∉xs a∈xs}) -- _⊆_ : ∀ {ℓ} {A : Set ℓ} → List A → List A → Set ℓ -- R ⊆ S = ∀ {x} → x ∈ R → x ∈ S -- _≢_ : ∀ {ℓ} {A : Set ℓ} → A → A → Set ℓ -- x ≢ y = ¬ (x ≡ y) -- infix 0 _↔_ -- _↔_ : {ℓ¹ : Level} → Set ℓ¹ → {ℓ² : Level} → Set ℓ² → Set (ℓ¹ ⊔ ℓ²) -- P ↔ Q = (P → Q) × (Q → P) -- ∃ : ∀ {ℓᴬ ℓᴮ} {A : Set ℓᴬ} (B : A → Set ℓᴮ) → Set (ℓᴬ ⊔ ℓᴮ) -- ∃ = Σ _ -- ∄ : ∀ {ℓᴬ ℓᴮ} {A : Set ℓᴬ} (B : A → Set ℓᴮ) → Set (ℓᴬ ⊔ ℓᴮ) -- ∄ = ¬_ ∘ ∃ -- infixl 4 _⊎_ -- _⊎_ = Either -- --open import Agda.Builtin.Size public -- open import Size public -- open import Control.Monad.State public -- open import Control.Monad.Identity public -- open import Container.Traversable public -- sequence : ∀ {a b} {A : Set a} {F : Set a → Set b} ⦃ _ : Applicative F ⦄ → List (F A) → F ⊤′ -- sequence [] = pure tt -- sequence (x ∷ xs) = x *> sequence xs -- open import Tactic.Nat public -- open import Tactic.Deriving.Eq public -- mutual -- data Delay (i : Size) (A : Set) : Set where -- now : A → Delay i A -- later : ∞Delay i A → Delay i A -- record ∞Delay (i : Size) (A : Set) : Set where -- coinductive -- field -- force : {j : Size< i} → Delay j A -- open ∞Delay public -- module BindDelay -- where -- mutual -- bindDelay : ∀ {i A B} → Delay i A → (A → Delay i B) → Delay i B -- bindDelay (now a) f = f a -- bindDelay (later ∞a) f = later (bind∞Delay ∞a f) -- bind∞Delay : ∀ {i A B} → ∞Delay i A → (A → Delay i B) → ∞Delay i B -- force (bind∞Delay ∞a f) = bindDelay (force ∞a) f -- module _ -- where -- open BindDelay -- open BindDelay public using () renaming (bind∞Delay to _∞>>=_) -- instance FunctorDelay : {i : Size} → Functor (Delay i) -- Functor.fmap FunctorDelay f x = bindDelay x $ now ∘ f -- instance ApplicativeDelay : {i : Size} → Applicative (Delay i) -- Applicative.pure ApplicativeDelay x = now x -- Applicative._<*>_ ApplicativeDelay (now f) x = f <$> x -- Applicative._<*>_ ApplicativeDelay (later ∞f) x = later ∘ bind∞Delay ∞f $ flip fmap x -- Applicative.super ApplicativeDelay = FunctorDelay -- instance MonadDelay : {i : Size} → Monad (Delay i) -- Monad._>>=_ MonadDelay = bindDelay -- Monad.super MonadDelay = ApplicativeDelay -- mutual -- data _∼_ {i : Size} {A : Set} : (a? b? : Delay ∞ A) → Set where -- ∼now : ∀ a → now a ∼ now a -- ∼later : ∀ {a∞ b∞} (eq : a∞ ∞∼⟨ i ⟩∼ b∞) → later a∞ ∼ later b∞ -- _∼⟨_⟩∼_ = λ {A} a? i b? → _∼_ {i}{A} a? b? -- record _∞∼⟨_⟩∼_ {A} (a∞ : ∞Delay ∞ A) i (b∞ : ∞Delay ∞ A) : Set where -- coinductive -- field -- ∼force : {j : Size< i} → force a∞ ∼⟨ j ⟩∼ force b∞ -- open _∞∼⟨_⟩∼_ public -- _∞∼_ = λ {i} {A} a∞ b∞ → _∞∼⟨_⟩∼_ {A} a∞ i b∞ -- mutual -- ∼refl : ∀{i A} (a? : Delay ∞ A) → a? ∼⟨ i ⟩∼ a? -- ∼refl (now a) = ∼now a -- ∼refl (later a∞) = ∼later (∞∼refl a∞) -- ∞∼refl : ∀{i A} (a∞ : ∞Delay ∞ A) → a∞ ∞∼⟨ i ⟩∼ a∞ -- ∼force (∞∼refl a∞) = ∼refl (force a∞) -- mutual -- ∼sym : ∀{i A}{a? b? : Delay ∞ A } → a? ∼⟨ i ⟩∼ b? → b? ∼⟨ i ⟩∼ a? -- ∼sym (∼now a) = ∼now a -- ∼sym (∼later eq) = ∼later (∞∼sym eq) -- ∞∼sym : ∀{i A}{a∞ b∞ : ∞Delay ∞ A} → a∞ ∞∼⟨ i ⟩∼ b∞ → b∞ ∞∼⟨ i ⟩∼ a∞ -- ∼force (∞∼sym eq) = ∼sym (∼force eq) -- mutual -- ∼trans : ∀{i A}{a? b? c? : Delay ∞ A} → -- a? ∼⟨ i ⟩∼ b? → b? ∼⟨ i ⟩∼ c? → a? ∼⟨ i ⟩∼ c? -- ∼trans (∼now a) (∼now .a) = ∼now a -- ∼trans (∼later eq) (∼later eq′) = ∼later (∞∼trans eq eq′) -- ∞∼trans : ∀{i A}{a∞ b∞ c∞ : ∞Delay ∞ A} → -- a∞ ∞∼⟨ i ⟩∼ b∞ → b∞ ∞∼⟨ i ⟩∼ c∞ → a∞ ∞∼⟨ i ⟩∼ c∞ -- ∼force (∞∼trans eq eq′) = ∼trans (∼force eq) (∼force eq′) -- --∼setoid : (i : Size) (A : Set) → Setoid lzero lzero -- --∞∼setoid : (i : Size) (A : Set) → Setoid lzero lzero -- mutual -- bind-assoc : ∀{i A B C} (m : Delay ∞ A) -- {k : A → Delay ∞ B} {l : B → Delay ∞ C} → -- ((m >>= k) >>= l) ∼⟨ i ⟩∼ (m >>= λ a → (k a >>= l)) -- bind-assoc (now a) = ∼refl _ -- bind-assoc (later a∞) = ∼later (∞bind-assoc a∞) -- ∞bind-assoc : ∀{i A B C} (a∞ : ∞Delay ∞ A) -- {k : A → Delay ∞ B} {l : B → Delay ∞ C} → -- ((a∞ ∞>>= k) ∞>>= l) ∞∼⟨ i ⟩∼ (a∞ ∞>>= λ a → (k a >>= l)) -- ∼force (∞bind-assoc a∞) = bind-assoc (force a∞) -- mutual -- bind-cong-l : ∀{i A B}{a? b? : Delay ∞ A} → a? ∼⟨ i ⟩∼ b? → -- (k : A → Delay ∞ B) → (a? >>= k) ∼⟨ i ⟩∼ (b? >>= k) -- bind-cong-l (∼now a) k = ∼refl _ -- bind-cong-l (∼later eq) k = ∼later (∞bind-cong-l eq k) -- ∞bind-cong-l : ∀{i A B}{a∞ b∞ : ∞Delay ∞ A} → a∞ ∞∼⟨ i ⟩∼ b∞ → -- (k : A → Delay ∞ B) → (a∞ ∞>>= k) ∞∼⟨ i ⟩∼ (b∞ ∞>>= k) -- ∼force (∞bind-cong-l eq k) = bind-cong-l (∼force eq) k -- mutual -- bind-cong-r : ∀{i A B}(a? : Delay ∞ A){k l : A → Delay ∞ B} → -- (∀ a → (k a) ∼⟨ i ⟩∼ (l a)) → (a? >>= k) ∼⟨ i ⟩∼ (a? >>= l) -- bind-cong-r (now a) h = h a -- bind-cong-r (later a∞) h = ∼later (∞bind-cong-r a∞ h) -- ∞bind-cong-r : ∀{i A B}(a∞ : ∞Delay ∞ A){k l : A → Delay ∞ B} → -- (∀ a → (k a) ∼⟨ i ⟩∼ (l a)) → (a∞ ∞>>= k) ∞∼⟨ i ⟩∼ (a∞ ∞>>= l) -- ∼force (∞bind-cong-r a∞ h) = bind-cong-r (force a∞) h -- map-compose : ∀{i A B C} (a? : Delay ∞ A) {f : A → B} {g : B → C} → -- (g <$> (f <$> a?)) ∼⟨ i ⟩∼ ((g ∘ f) <$> a?) -- map-compose a? = bind-assoc a? -- map-cong : ∀{i A B}{a? b? : Delay ∞ A} (f : A → B) → -- a? ∼⟨ i ⟩∼ b? → (f <$> a?) ∼⟨ i ⟩∼ (f <$> b?) -- map-cong f eq = bind-cong-l eq (now ∘ f) -- data _⇓_ {A : Set} : (a? : Delay ∞ A) (a : A) → Set where -- now⇓ : ∀{a} → now a ⇓ a -- later⇓ : ∀{a} {a∞ : ∞Delay ∞ A} → force a∞ ⇓ a → later a∞ ⇓ a -- _⇓ : {A : Set} (x : Delay ∞ A) → Set -- x ⇓ = ∃ λ a → x ⇓ a -- map⇓ : ∀{A B}{a : A}{a? : Delay ∞ A}(f : A → B) → a? ⇓ a → (f <$> a?) ⇓ f a -- map⇓ f now⇓ = now⇓ -- map⇓ f (later⇓ a⇓) = later⇓ (map⇓ f a⇓) -- bind⇓ : ∀{A B}(f : A → Delay ∞ B){?a : Delay ∞ A}{a : A}{b : B} → -- ?a ⇓ a → f a ⇓ b → (?a >>= f) ⇓ b -- bind⇓ f now⇓ q = q -- bind⇓ f (later⇓ p) q = later⇓ (bind⇓ f p q) -- infixl 4 _>>=⇓_ -- _>>=⇓_ : ∀{A B}{f : A → Delay ∞ B}{?a : Delay ∞ A}{a : A}{b : B} → -- ?a ⇓ a → f a ⇓ b → (?a >>= f) ⇓ b -- _>>=⇓_ = bind⇓ _ -- infixl 4 _⇓>>=⇓_ -- _⇓>>=⇓_ : ∀{A B}{f : A → Delay ∞ B}{?a : Delay ∞ A}{b : B} → -- (?a⇓ : ?a ⇓) → f (fst ?a⇓) ⇓ b → (?a >>= f) ⇓ b -- _⇓>>=⇓_ (_ , a⇓) = bind⇓ _ a⇓ -- _⇓Dec>>=⇓_else⇓_ : ∀{A B}{f-yes : A → Delay ∞ B}{f-no : ¬ A → Delay ∞ B}{?a : Delay ∞ (Dec A)}{b : B} → -- (?a⇓ : ?a ⇓) → -- ((a : A) → f-yes a ⇓ b) → -- ((¬a : ¬ A) → f-no ¬a ⇓ b) → -- ((?a >>= (λ { (yes y) → f-yes y ; (no n) → f-no n }))) ⇓ b -- (yes y , y⇓) ⇓Dec>>=⇓ fy⇓ else⇓ fn⇓ = y⇓ >>=⇓ fy⇓ y -- (no n , n⇓) ⇓Dec>>=⇓ fy⇓ else⇓ fn⇓ = n⇓ >>=⇓ fn⇓ n -- _⇓DecEq>>=⇓_else⇓_ : ∀{A : Set} {A₁ A₂ : A} {B}{f-yes : A₁ ≡ A₂ → Delay ∞ B}{f-no : A₁ ≢ A₂ → Delay ∞ B}{?a : Delay ∞ (Dec (A₁ ≡ A₂))}{b : B} → -- (?a⇓ : ?a ⇓) → -- ((eq : A₁ ≡ A₂) → f-yes eq ⇓ b) → -- ((¬eq : A₁ ≢ A₂) → f-no ¬eq ⇓ b) → -- ((?a >>= (λ { (yes refl) → f-yes refl ; (no n) → f-no n }))) ⇓ b -- (yes refl , y⇓) ⇓DecEq>>=⇓ fy⇓ else⇓ fn⇓ = y⇓ >>=⇓ fy⇓ refl -- (no n , n⇓) ⇓DecEq>>=⇓ fy⇓ else⇓ fn⇓ = n⇓ >>=⇓ fn⇓ n -- app⇓ : ∀{A}{B}{f? : Delay ∞ (A → B)}{f : A → B}{x? : Delay ∞ A}{x : A} → f? ⇓ f → x? ⇓ x → (f? <*> x?) ⇓ f x -- app⇓ now⇓ now⇓ = now⇓ -- app⇓ now⇓ (later⇓ x?) = later⇓ $ map⇓ _ x? -- app⇓ (later⇓ f?) now⇓ = later⇓ $ bind⇓ _ f? now⇓ -- app⇓ (later⇓ ⇓f) (later⇓ ⇓x) = later⇓ $ bind⇓ _ ⇓f $ later⇓ $ bind⇓ _ ⇓x now⇓ -- subst∼⇓ : ∀{A}{a? a?′ : Delay ∞ A}{a : A} → a? ⇓ a → a? ∼ a?′ → a?′ ⇓ a -- subst∼⇓ now⇓ (∼now a) = now⇓ -- subst∼⇓ (later⇓ p) (∼later eq) = later⇓ (subst∼⇓ p (∼force eq)) -- {- -- traverse⇓' : ∀{A}{B}{f? : A → Delay ∞ B}{T : Set → Set}⦃ _ : Traversable T ⦄{X : T A} → (∀ x → f? x ⇓) → ∀ (x : T A) → traverse f? x ⇓ -- traverse⇓' x₁ x₂ = {!!} , {!!} -- -} -- {- -- traverse⇓ : ∀{A}{B}{f : A → B}{T : Set → Set}⦃ _ : Traversable T ⦄{X : T A} → (∀ x → f? x ⇓) → ∀ (x : T A) → traverse f x ⇓ -- traverse⇓ x₁ x₂ = {!!} , {!!} -- -} -- traverse-list⇓ : ∀{A}{B} (f? : A → Delay ∞ B) → (∀ x → f? x ⇓) → (xs : List A) → traverse f? xs ⇓ -- traverse-list⇓ f? f?⇓ [] = [] , now⇓ -- traverse-list⇓ f? f?⇓ (x ∷ xs) -- with f?⇓ x | traverse-list⇓ f? f?⇓ xs -- … | y , y⇓ | ys , ys⇓ = y ∷ ys , app⇓ (map⇓ _ y⇓) ys⇓ -- {- -- traverse-vec⇓' : ∀{A}{B}{𝑎} (f? : A → Delay ∞ B) → (∀ x → f? x ⇓) → (xs : Vector A 𝑎) → traverse f? xs ⇓ -- traverse-vec⇓' f? f?⇓ [] = [] , now⇓ -- traverse-vec⇓' f? f?⇓ (x ∷ xs) -- with f?⇓ x | traverse-vec⇓' f? f?⇓ xs -- … | y , y⇓ | ys , ys⇓ = y ∷ ys , app⇓ (map⇓ _ y⇓) ys⇓ -- traverse-vec⇓ : ∀{A}{B}{𝑎} (f : A → B) → (xs : Vector (Delay ∞ A) 𝑎) → traverse {!f!} xs ⇓ -- traverse-vec⇓ = {!!} -- -} -- open CustomPrelude -- -- infix 15 _╱_ -- -- record Sequent (A : Set) ⦃ _ : BeFormula A ⦄ : Set -- -- where -- -- constructor _╱_ -- -- field -- -- statement : A -- -- suppositions : List A -- -- open Sequent -- -- foooo : {A : Set} ⦃ bf : BeFormula A ⦄ {-⦃ hs : HasNegation A ⦄-} {-(x : Sequent A)-} → -- -- (∃ λ (x : A) → x ∈ List.[]) → ⊥ -- -- {- -- -- Dec -- -- (-- Either -- -- (Σ A -- -- (λ x₁ → -- -- --Σ -- -- ({-BeFormula.formula bf -}x₁ ∈ -- -- {-map (BeFormula.formula bf)-} [] {-(suppositions x)-}) -- -- {- -- -- (λ _ → -- -- ⊤ -- -- --BeFormula.formula bf (HasNegation.~ hs x₁) ∈ -- -- --map (BeFormula.formula bf) (suppositions x) -- -- )-} -- -- )) -- -- {-(BeFormula.formula bf (statement x) ∈ -- -- map (BeFormula.formula bf) (suppositions x))-}) -- -- -} -- -- foooo = λ {x → {!x!}} -- -- {- -- -- foooo (statement₁ ╱ []) = λ {x → {!x!}} -- no (λ {x → {!x!}}) -- -- foooo (statement₁ ╱ (x ∷ suppositions₁)) = {!!} -- -- -} -- -- -- TruthValue = Bool -- -- -- -- reification of elements of the domain -- -- -- Element = Nat -- -- -- record VariableName : Set -- -- -- where -- -- -- constructor ⟨_⟩ -- -- -- field -- -- -- name : Nat -- -- -- open VariableName -- -- -- instance EqVariableName : Eq VariableName -- -- -- Eq._==_ EqVariableName _ = decEq₁ (cong name) ∘ (_≟_ on name $ _) -- -- -- record FunctionName : Set -- -- -- where -- -- -- constructor ⟨_⟩ -- -- -- field -- -- -- name : Nat -- -- -- open FunctionName -- -- -- instance EqFunctionName : Eq FunctionName -- -- -- Eq._==_ EqFunctionName _ = decEq₁ (cong name) ∘ (_≟_ on name $ _) -- -- -- record PredicateName : Set -- -- -- where -- -- -- constructor ⟨_⟩ -- -- -- field -- -- -- name : Nat -- -- -- open PredicateName -- -- -- instance EqPredicateName : Eq PredicateName -- -- -- Eq._==_ EqPredicateName _ = decEq₁ (cong name) ∘ (_≟_ on name $ _) -- -- -- record Arity : Set -- -- -- where -- -- -- constructor ⟨_⟩ -- -- -- field -- -- -- arity : Nat -- -- -- open Arity -- -- -- instance EqArity : Eq Arity -- -- -- Eq._==_ EqArity _ = decEq₁ (cong arity) ∘ (_≟_ on arity $ _) -- -- -- Vector : Set → Arity → Set -- -- -- Vector A = Vec A ∘ arity -- -- -- record Elements : Set -- -- -- where -- -- -- constructor ⟨_⟩ -- -- -- field -- -- -- {arity} : Arity -- -- -- elements : Vector Element arity -- -- -- open Elements -- -- -- instance EqElements : Eq Elements -- -- -- Eq._==_ EqElements (⟨_⟩ {𝑎₁} εs₁) (⟨_⟩ {𝑎₂} εs₂) -- -- -- with 𝑎₁ ≟ 𝑎₂ -- -- -- … | no 𝑎₁≢𝑎₂ = no λ {refl → 𝑎₁≢𝑎₂ refl} -- -- -- … | yes refl -- -- -- with εs₁ ≟ εs₂ -- -- -- … | yes refl = yes refl -- -- -- … | no εs₁≢εs₂ = no λ {refl → εs₁≢εs₂ refl} -- -- -- record Interpretation : Set -- -- -- where -- -- -- field -- -- -- μ⟦_⟧ : VariableName → Element -- -- -- 𝑓⟦_⟧ : FunctionName → Elements → Element -- -- -- 𝑃⟦_⟧ : PredicateName → Elements → TruthValue -- -- -- open Interpretation -- -- -- mutual -- -- -- data Term : Set -- -- -- where -- -- -- variable : VariableName → Term -- -- -- function : FunctionName → Terms → Term -- -- -- record Terms : Set -- -- -- where -- -- -- constructor ⟨_⟩ -- -- -- inductive -- -- -- field -- -- -- {arity} : Arity -- -- -- terms : Vector Term arity -- -- -- open Terms -- -- -- termVariable-inj : ∀ {𝑥₁ 𝑥₂} → Term.variable 𝑥₁ ≡ variable 𝑥₂ → 𝑥₁ ≡ 𝑥₂ -- -- -- termVariable-inj refl = refl -- -- -- termFunction-inj₁ : ∀ {𝑓₁ 𝑓₂ τ₁s τ₂s} → Term.function 𝑓₁ τ₁s ≡ function 𝑓₂ τ₂s → 𝑓₁ ≡ 𝑓₂ -- -- -- termFunction-inj₁ refl = refl -- -- -- termFunction-inj₂ : ∀ {𝑓₁ 𝑓₂ τ₁s τ₂s} → Term.function 𝑓₁ τ₁s ≡ function 𝑓₂ τ₂s → τ₁s ≡ τ₂s -- -- -- termFunction-inj₂ refl = refl -- -- -- foo : ∀ a → (ts1 ts2 : Vec Term (arity a)) → (τ₁≡τ₂ : Terms.⟨ ts1 ⟩ ≡ (⟨_⟩ {a} ts2)) → _≡_ {lzero} {Vec Term (arity a)} ts1 ts2 -- -- -- foo a ts1 .ts1 refl = refl -- -- -- mutual -- -- -- EqTerm⇑ : ∀ {i} → (x y : Term) → Delay i ∘ Dec $ x ≡ y -- -- -- EqTerm⇑ (variable _) (variable _) = now (decEq₁ termVariable-inj $ _≟_ _ _) -- -- -- EqTerm⇑ (function 𝑓₁ τ₁s) (function 𝑓₂ τ₂s) = EqTerms⇑ τ₁s τ₂s >>= λ τ₁s≟τ₂s → now $ decEq₂ termFunction-inj₁ termFunction-inj₂ (𝑓₁ ≟ 𝑓₂) τ₁s≟τ₂s -- -- -- EqTerm⇑ (variable _) (function _ _) = now $ no λ () -- -- -- EqTerm⇑ (function _ _) (variable _) = now $ no λ () -- -- -- EqTerms⇑ : ∀ {i} → (x y : Terms) → Delay i ∘ Dec $ x ≡ y -- -- -- EqTerms⇑ (⟨_⟩ {𝑎₁} τ₁s) (⟨_⟩ {𝑎₂} τ₂s) -- -- -- with 𝑎₁ ≟ 𝑎₂ -- -- -- … | no 𝑎₁≢𝑎₂ = now $ no λ {τ₁≡τ₂ → 𝑎₁≢𝑎₂ (cong arity τ₁≡τ₂)} -- -- -- … | yes refl = EqVecTerm⇑ τ₁s τ₂s >>= λ { (yes refl) → now $ yes refl ; (no τ₁s≢τ₂s) → now $ no (λ ⟨τ₁s⟩≡⟨τ₂s⟩ → τ₁s≢τ₂s (foo ⟨ arity 𝑎₁ ⟩ τ₁s τ₂s ⟨τ₁s⟩≡⟨τ₂s⟩)) } -- -- -- EqVecTerm⇑ : ∀ {i} {n} → (x y : Vec Term n) → Delay i ∘ Dec $ x ≡ y -- -- -- EqVecTerm⇑ [] [] = now (yes refl) -- -- -- EqVecTerm⇑ (τ₁ ∷ τ₁s) (τ₂ ∷ τ₂s) = -- -- -- EqTerm⇑ τ₁ τ₂ >>= λ -- -- -- { (yes refl) → EqVecTerm⇑ τ₁s τ₂s >>= λ -- -- -- { (yes refl) → now $ yes refl -- -- -- ; (no τ₁s≢τ₂s) → now $ no λ τ₁₁s≡τ₁₂s → τ₁s≢τ₂s $ vcons-inj-tail τ₁₁s≡τ₁₂s } -- -- -- ; (no τ₁≢τ₂) → now $ no λ τ₁₁s≡τ₂₂s → τ₁≢τ₂ $ vcons-inj-head τ₁₁s≡τ₂₂s } -- -- -- EqVecTerm⇓ : ∀ {n} → (x y : Vec Term n) → EqVecTerm⇑ x y ⇓ -- -- -- EqVecTerm⇓ [] [] = _ , now⇓ -- -- -- EqVecTerm⇓ (variable 𝑥₁ ∷ τ₁s) (variable 𝑥₂ ∷ τ₂s) -- -- -- with 𝑥₁ ≟ 𝑥₂ -- -- -- … | yes refl with EqVecTerm⇓ τ₁s τ₂s -- -- -- EqVecTerm⇓ (variable 𝑥₁ ∷ τ₁s) (variable .𝑥₁ ∷ .τ₁s) | yes refl | (yes refl , snd₁) = _ , snd₁ >>=⇓ now⇓ -- -- -- EqVecTerm⇓ (variable 𝑥₁ ∷ τ₁s) (variable .𝑥₁ ∷ τ₂s) | yes refl | (no x , snd₁) = _ , snd₁ >>=⇓ now⇓ -- -- -- EqVecTerm⇓ (variable 𝑥₁ ∷ τ₁s) (variable 𝑥₂ ∷ τ₂s) | no 𝑥₁≢𝑥₂ = _ , now⇓ -- -- -- EqVecTerm⇓ (variable x ∷ τ₁s) (function x₁ x₂ ∷ τ₂s) = _ , now⇓ -- -- -- EqVecTerm⇓ (function x x₁ ∷ τ₁s) (variable x₂ ∷ τ₂s) = _ , now⇓ -- -- -- EqVecTerm⇓ (function 𝑓₁ (⟨_⟩ {𝑎₁} τ₁s) ∷ τ₁₂s) (function 𝑓₂ (⟨_⟩ {𝑎₂} τ₂s) ∷ τ₂₂s) -- -- -- with 𝑎₁ ≟ 𝑎₂ | 𝑓₁ ≟ 𝑓₂ -- -- -- … | no 𝑎₁≢𝑎₂ | no 𝑓₁≢𝑓₂ = _ , now⇓ -- -- -- … | no 𝑎₁≢𝑎₂ | yes refl = _ , now⇓ -- -- -- … | yes refl | no 𝑓₁≢𝑓₂ -- -- -- with EqVecTerm⇓ τ₁s τ₂s -- -- -- … | (no τ₁s≢τ₂s , τ⇓) = _ , τ⇓ >>=⇓ now⇓ >>=⇓ now⇓ >>=⇓ now⇓ -- -- -- … | (yes refl , τ⇓) = _ , τ⇓ >>=⇓ now⇓ >>=⇓ now⇓ >>=⇓ now⇓ -- -- -- EqVecTerm⇓ (function 𝑓₁ (⟨_⟩ {𝑎₁} τ₁s) ∷ τ₁₂s) (function 𝑓₂ (⟨_⟩ {𝑎₂} τ₂s) ∷ τ₂₂s) | yes refl | yes refl -- -- -- with EqVecTerm⇓ τ₁s τ₂s | EqVecTerm⇓ τ₁₂s τ₂₂s -- -- -- … | (no τ₁s≢τ₂s , τ⇓) | (no τ₁₂s≢τ₂₂s , τs⇓) = _ , τ⇓ >>=⇓ now⇓ >>=⇓ now⇓ >>=⇓ now⇓ -- -- -- … | (yes refl , τ⇓) | (no τ₁₂s≢τ₂₂s , τs⇓) = _ , τ⇓ >>=⇓ now⇓ >>=⇓ now⇓ >>=⇓ (τs⇓ >>=⇓ now⇓) -- -- -- … | (no τ₁s≢τ₂s , τ⇓) | (yes refl , τs⇓) = _ , τ⇓ >>=⇓ now⇓ >>=⇓ now⇓ >>=⇓ now⇓ -- -- -- … | (yes refl , τ⇓) | (yes refl , τs⇓) = _ , τ⇓ >>=⇓ now⇓ >>=⇓ now⇓ >>=⇓ (τs⇓ >>=⇓ now⇓) -- -- -- EqTerms⇓ : (x y : Terms) → EqTerms⇑ x y ⇓ -- -- -- EqTerms⇓ (⟨_⟩ {𝑎₁} τ₁s) (⟨_⟩ {𝑎₂} τ₂s) -- -- -- with 𝑎₁ ≟ 𝑎₂ -- -- -- … | no 𝑎₁≢𝑎₂ = _ , now⇓ -- -- -- … | yes refl -- -- -- with EqVecTerm⇓ τ₁s τ₂s -- -- -- … | (yes refl , τ⇓) = _ , τ⇓ >>=⇓ now⇓ -- -- -- … | (no _ , τ⇓) = _ , τ⇓ >>=⇓ now⇓ -- -- -- EqTerm⇓ : (x y : Term) → EqTerm⇑ x y ⇓ -- -- -- EqTerm⇓ (variable x) (variable x₁) = _ , now⇓ -- -- -- EqTerm⇓ (function _ τ₁s) (function _ τ₂s) -- -- -- with EqTerms⇓ τ₁s τ₂s -- -- -- … | (_ , τ⇓) = _ , τ⇓ >>=⇓ now⇓ -- -- -- EqTerm⇓ (variable x) (function x₁ x₂) = _ , now⇓ -- -- -- EqTerm⇓ (function x x₁) (variable x₂) = _ , now⇓ -- -- -- instance EqTerm : Eq Term -- -- -- EqTerm = record { _==_ = λ x y → fst (EqTerm⇓ x y) } -- -- -- instance EqTerms : Eq Terms -- -- -- Eq._==_ EqTerms x y = fst (EqTerms⇓ x y) -- -- -- mutual -- -- -- τ⇑⟦_⟧ : Interpretation → {i : Size} → Term → Delay i Element -- -- -- τ⇑⟦ I ⟧ (variable 𝑥) = now $ μ⟦ I ⟧ 𝑥 -- -- -- τ⇑⟦ I ⟧ (function 𝑓 τs) = 𝑓⟦ I ⟧ 𝑓 ∘ ⟨_⟩ <$> τs⇑⟦ I ⟧ τs -- -- -- τs⇑⟦_⟧ : Interpretation → {i : Size} → (τs : Terms) → Delay i (Vector Element (arity τs)) -- -- -- τs⇑⟦ I ⟧ ⟨ [] ⟩ = now [] -- -- -- τs⇑⟦ I ⟧ ⟨ τ ∷ τs ⟩ = τ⇑⟦ I ⟧ τ >>= (λ t → τs⇑⟦ I ⟧ ⟨ τs ⟩ >>= λ ts → now (t ∷ ts)) -- -- -- τs⇓⟦_⟧ : (I : Interpretation) → (τs : Terms) → τs⇑⟦ I ⟧ τs ⇓ -- -- -- τs⇓⟦ I ⟧ ⟨ [] ⟩ = _ , now⇓ -- -- -- τs⇓⟦ I ⟧ ⟨ variable 𝑥 ∷ τs ⟩ = _ , τs⇓⟦ I ⟧ ⟨ τs ⟩ ⇓>>=⇓ now⇓ -- -- -- τs⇓⟦ I ⟧ ⟨ function 𝑓₁ τs₁ ∷ τs₂ ⟩ = -- -- -- _ , τs⇓⟦ I ⟧ τs₁ ⇓>>=⇓ now⇓ >>=⇓ (τs⇓⟦ I ⟧ ⟨ τs₂ ⟩ ⇓>>=⇓ now⇓) -- -- -- τ⇓⟦_⟧ : (I : Interpretation) → (τ : Term) → τ⇑⟦ I ⟧ τ ⇓ -- -- -- τ⇓⟦ I ⟧ (variable 𝑥) = _ , now⇓ -- -- -- τ⇓⟦ I ⟧ (function 𝑓 τs) = _ , τs⇓⟦ I ⟧ τs ⇓>>=⇓ now⇓ -- -- -- τ⟦_⟧ : (I : Interpretation) → {i : Size} → (τ : Term) → Element -- -- -- τ⟦ I ⟧ τ = fst (τ⇓⟦ I ⟧ τ) -- -- -- data Formula : Set -- -- -- where -- -- -- atomic : PredicateName → Terms → Formula -- -- -- logical : Formula → -- -- -- Formula → -- -- -- Formula -- -- -- quantified : VariableName → Formula → Formula -- -- -- formulaAtomic-inj₁ : ∀ {𝑃₁ τs₁ 𝑃₂ τs₂} → Formula.atomic 𝑃₁ τs₁ ≡ atomic 𝑃₂ τs₂ → 𝑃₁ ≡ 𝑃₂ -- -- -- formulaAtomic-inj₁ refl = refl -- -- -- formulaAtomic-inj₂ : ∀ {𝑃₁ τs₁ 𝑃₂ τs₂} → Formula.atomic 𝑃₁ τs₁ ≡ atomic 𝑃₂ τs₂ → τs₁ ≡ τs₂ -- -- -- formulaAtomic-inj₂ refl = refl -- -- -- formulaLogical-inj₁ : ∀ {φ₁₁ φ₁₂ φ₂₁ φ₂₂} → Formula.logical φ₁₁ φ₁₂ ≡ logical φ₂₁ φ₂₂ → φ₁₁ ≡ φ₂₁ -- -- -- formulaLogical-inj₁ refl = refl -- -- -- formulaLogical-inj₂ : ∀ {φ₁₁ φ₁₂ φ₂₁ φ₂₂} → Formula.logical φ₁₁ φ₁₂ ≡ logical φ₂₁ φ₂₂ → φ₁₂ ≡ φ₂₂ -- -- -- formulaLogical-inj₂ refl = refl -- -- -- formulaQuantified-inj₁ : ∀ {𝑥₁ φ₁ 𝑥₂ φ₂} → Formula.quantified 𝑥₁ φ₁ ≡ quantified 𝑥₂ φ₂ → 𝑥₁ ≡ 𝑥₂ -- -- -- formulaQuantified-inj₁ refl = refl -- -- -- formulaQuantified-inj₂ : ∀ {𝑥₁ φ₁ 𝑥₂ φ₂} → Formula.quantified 𝑥₁ φ₁ ≡ quantified 𝑥₂ φ₂ → φ₁ ≡ φ₂ -- -- -- formulaQuantified-inj₂ refl = refl -- -- -- instance EqFormula : Eq Formula -- -- -- Eq._==_ EqFormula (atomic 𝑃₁ τs₁) (atomic 𝑃₂ τs₂) = decEq₂ formulaAtomic-inj₁ formulaAtomic-inj₂ (𝑃₁ ≟ 𝑃₂) (τs₁ ≟ τs₂) -- -- -- Eq._==_ EqFormula (logical φ₁₁ φ₁₂) (logical φ₂₁ φ₂₂) = decEq₂ formulaLogical-inj₁ formulaLogical-inj₂ (φ₁₁ ≟ φ₂₁) (φ₁₂ ≟ φ₂₂) -- -- -- Eq._==_ EqFormula (quantified 𝑥₁ φ₁) (quantified 𝑥₂ φ₂) = decEq₂ formulaQuantified-inj₁ formulaQuantified-inj₂ (𝑥₁ ≟ 𝑥₂) (φ₁ ≟ φ₂) -- -- -- Eq._==_ EqFormula (atomic _ _) (logical _ _) = no λ () -- -- -- Eq._==_ EqFormula (atomic _ _) (quantified _ _) = no λ () -- -- -- Eq._==_ EqFormula (logical _ _) (atomic _ _) = no λ () -- -- -- Eq._==_ EqFormula (logical _ _) (quantified _ _) = no λ () -- -- -- Eq._==_ EqFormula (quantified _ _) (atomic _ _) = no λ () -- -- -- Eq._==_ EqFormula (quantified _ _) (logical _ _) = no λ () -- -- -- record HasNegation (A : Set) : Set -- -- -- where -- -- -- field -- -- -- ~ : A → A -- -- -- open HasNegation ⦃ … ⦄ -- -- -- record BeFormula (A : Set) : Set -- -- -- where -- -- -- constructor ⟨_⟩ -- -- -- field -- -- -- formula : A → Formula -- -- -- open BeFormula ⦃ … ⦄ -- -- -- record HasSatisfaction (A : Set) : Set₁ -- -- -- where -- -- -- field -- -- -- _⊨_ : Interpretation → A → Set -- -- -- _⊭_ : Interpretation → A → Set -- -- -- _⊭_ I = ¬_ ∘ I ⊨_ -- -- -- open HasSatisfaction ⦃ … ⦄ -- -- -- record HasDecidableSatisfaction (A : Set) ⦃ _ : HasSatisfaction A ⦄ : Set₁ -- -- -- where -- -- -- field -- -- -- _⊨?_ : (I : Interpretation) → (x : A) → Dec (I ⊨ x) -- -- -- open HasDecidableSatisfaction ⦃ … ⦄ -- -- -- infix 15 _╱_ -- -- -- record Sequent (A : Set) ⦃ _ : BeFormula A ⦄ : Set -- -- -- where -- -- -- constructor _╱_ -- -- -- field -- -- -- statement : A -- -- -- suppositions : List A -- -- -- open Sequent -- -- -- foooo : {A : Set} ⦃ bf : BeFormula A ⦄ {-⦃ hs : HasNegation A ⦄-} (x : Sequent A) → -- -- -- Dec -- -- -- (-- Either -- -- -- (Σ A -- -- -- (λ x₁ → -- -- -- --Σ -- -- -- ({-BeFormula.formula bf -}x₁ ∈ -- -- -- {-map (BeFormula.formula bf)-} (suppositions x)) -- -- -- {- -- -- -- (λ _ → -- -- -- ⊤ -- -- -- --BeFormula.formula bf (HasNegation.~ hs x₁) ∈ -- -- -- --map (BeFormula.formula bf) (suppositions x) -- -- -- )-} -- -- -- )) -- -- -- {-(BeFormula.formula bf (statement x) ∈ -- -- -- map (BeFormula.formula bf) (suppositions x))-}) -- -- -- foooo (statement₁ ╱ []) = no (λ {x → {!x!}}) -- -- -- foooo (statement₁ ╱ (x ∷ suppositions₁)) = {!!} -- -- -- -- record HasValidation (A : Set) : Set₁ -- -- -- -- where -- -- -- -- field -- -- -- -- ⊨_ : A → Set -- -- -- -- ⊭_ : A → Set -- -- -- -- ⊭_ = ¬_ ∘ ⊨_ -- -- -- -- open HasValidation ⦃ … ⦄ -- -- -- -- 𝑃[_♭_] : PredicateName → Terms → Formula -- -- -- -- 𝑃[_♭_] = atomic -- -- -- -- _⊗_ : Formula → Formula → Formula -- -- -- -- _⊗_ = logical -- -- -- -- instance -- -- -- -- HasNegationFormula : HasNegation Formula -- -- -- -- HasNegation.~ HasNegationFormula φ = φ ⊗ φ -- -- -- -- data IsLiteral : Formula → Set -- -- -- -- where -- -- -- -- atomic : (𝑃 : PredicateName) → (τs : Terms) → IsLiteral $ 𝑃[ 𝑃 ♭ τs ] -- -- -- -- logical : (𝑃 : PredicateName) → (τs : Terms) → IsLiteral ∘ ~ $ 𝑃[ 𝑃 ♭ τs ] -- -- -- -- eqIsLiteral : ∀ {φ} → (lf₁ lf₂ : IsLiteral φ) → lf₁ ≡ lf₂ -- -- -- -- eqIsLiteral (atomic 𝑃 τs) (atomic .𝑃 .τs) = refl -- -- -- -- eqIsLiteral (logical 𝑃 τs) (logical .𝑃 .τs) = refl -- -- -- -- instance EqIsLiteral : ∀ {φ} → Eq (IsLiteral φ) -- -- -- -- Eq._==_ EqIsLiteral lf₁ lf₂ = yes (eqIsLiteral lf₁ lf₂) -- -- -- -- record LiteralFormula : Set -- -- -- -- where -- -- -- -- constructor ⟨_⟩ -- -- -- -- field -- -- -- -- {formula} : Formula -- -- -- -- isLiteral : IsLiteral formula -- -- -- -- open LiteralFormula -- -- -- -- instance EqLiteralFormula : Eq LiteralFormula -- -- -- -- Eq._==_ EqLiteralFormula (⟨_⟩ {φ₁} lf₁) (⟨_⟩ {φ₂} lf₂) -- -- -- -- with φ₁ ≟ φ₂ -- -- -- -- … | no φ₁≢φ₂ = no (λ {refl → φ₁≢φ₂ refl}) -- -- -- -- Eq._==_ EqLiteralFormula (⟨_⟩ {φ₁} lf₁) (⟨_⟩ {φ₂} lf₂) | yes refl = case (eqIsLiteral lf₁ lf₂) of λ {refl → yes refl} -- -- -- -- infix 13 _¶_ -- -- -- -- record Problem (A : Set) ⦃ _ : BeFormula A ⦄ : Set -- -- -- -- where -- -- -- -- constructor _¶_ -- -- -- -- field -- -- -- -- inferences : List (Sequent A) -- -- -- -- interest : Sequent A -- -- -- -- open Problem -- -- -- -- record HasSubstantiveDischarge (+ : Set) (- : Set) : Set₁ -- -- -- -- where -- -- -- -- field -- -- -- -- _≽_ : + → - → Set -- -- -- -- open HasSubstantiveDischarge ⦃ … ⦄ -- -- -- -- record HasVacuousDischarge (+ : Set) : Set₁ -- -- -- -- where -- -- -- -- field -- -- -- -- ◁_ : + → Set -- -- -- -- open HasVacuousDischarge ⦃ … ⦄ -- -- -- -- record HasSalvation (A : Set) : Set₁ -- -- -- -- where -- -- -- -- field -- -- -- -- {isVacuouslyDischargable} : Set -- -- -- -- ⦃ hasVacuousDischarge ⦄ : HasVacuousDischarge isVacuouslyDischargable -- -- -- -- ▷_ : A → Set -- -- -- -- open HasSalvation ⦃ … ⦄ -- -- -- -- record HasDecidableSalvation (A : Set) : Set₁ -- -- -- -- where -- -- -- -- field -- -- -- -- ⦃ hasSalvation ⦄ : HasSalvation A -- -- -- -- ▷?_ : (x : A) → Dec $ ▷_ x -- -- -- -- open HasDecidableSalvation ⦃ … ⦄ -- -- -- -- ∀[_♭_] : VariableName → Formula → Formula -- -- -- -- ∀[_♭_] = quantified -- -- -- -- _∧_ : Formula → Formula → Formula -- -- -- -- φ₁ ∧ φ₂ = ~ φ₁ ⊗ ~ φ₂ -- -- -- -- _∨_ : Formula → Formula → Formula -- -- -- -- φ₁ ∨ φ₂ = ~ (φ₁ ⊗ φ₂) -- -- -- -- _⊃_ : Formula → Formula → Formula -- -- -- -- φ₁ ⊃ φ₂ = ~ φ₁ ∨ φ₂ -- -- -- -- _⟷_ : Formula → Formula → Formula -- -- -- -- φ₁ ⟷ φ₂ = (φ₁ ⊗ (φ₂ ⊗ φ₂)) ⊗ ((φ₁ ⊗ φ₁) ⊗ φ₂) -- TODO check that this is logically equivalent to the more verbose, (φ₁ ⊃ φ₂) ∧ (φ₂ ⊃ φ₁) -- -- -- -- record _≞_/_ (𝓘 : Interpretation) (I : Interpretation) (𝑥 : VariableName) : Set -- -- -- -- where -- -- -- -- field -- -- -- -- μEquality : {𝑥′ : VariableName} → 𝑥′ ≢ 𝑥 → μ⟦ 𝓘 ⟧ 𝑥 ≡ μ⟦ I ⟧ 𝑥′ -- -- -- -- 𝑓Equality : (𝑓 : FunctionName) (μs : Elements) → 𝑓⟦ 𝓘 ⟧ 𝑓 μs ≡ 𝑓⟦ I ⟧ 𝑓 μs -- -- -- -- 𝑃Equality : (𝑃 : PredicateName) → (μs : Elements) → 𝑃⟦ 𝓘 ⟧ 𝑃 μs ≡ 𝑃⟦ I ⟧ 𝑃 μs -- -- -- -- instance -- -- -- -- BeFormulaFormula : BeFormula Formula -- -- -- -- BeFormula.formula BeFormulaFormula = id -- -- -- -- BeFormulaLiteralFormula : BeFormula LiteralFormula -- -- -- -- BeFormula.formula BeFormulaLiteralFormula = formula -- -- -- -- instance -- -- -- -- HasNegationLiteralFormula : HasNegation LiteralFormula -- -- -- -- HasNegation.~ HasNegationLiteralFormula ⟨ atomic 𝑃 τs ⟩ = ⟨ logical 𝑃 τs ⟩ -- -- -- -- HasNegation.~ HasNegationLiteralFormula ⟨ logical 𝑃 τs ⟩ = ⟨ atomic 𝑃 τs ⟩ -- -- -- -- HasNegationSequent : {A : Set} ⦃ _ : HasNegation A ⦄ ⦃ _ : BeFormula A ⦄ → HasNegation $ Sequent A -- -- -- -- HasNegation.~ HasNegationSequent ( φᵗ ╱ φˢs ) = ~ φᵗ ╱ φˢs -- -- -- -- instance -- -- -- -- HasSatisfactionList : {A : Set} ⦃ _ : HasSatisfaction A ⦄ → HasSatisfaction $ List A -- -- -- -- HasSatisfaction._⊨_ HasSatisfactionList I [] = ⊤ -- -- -- -- HasSatisfaction._⊨_ HasSatisfactionList I (x ∷ xs) = I ⊨ x × I ⊨ xs -- -- -- -- HasSatisfactionBeFormula : {A : Set} → ⦃ _ : BeFormula A ⦄ → HasSatisfaction A -- -- -- -- HasSatisfaction._⊨_ (HasSatisfactionBeFormula ⦃ beFormula ⦄) = λ I φ → I ⊨φ formula beFormula φ -- -- -- -- where -- -- -- -- _⊨φ_ : Interpretation → Formula → Set -- -- -- -- I ⊨φ (atomic 𝑃 τs) = 𝑃⟦ I ⟧ 𝑃 ⟨ τ⟦ I ⟧ <$> terms τs ⟩ ≡ true -- -- -- -- I ⊨φ (logical φ₁ φ₂) = ¬ I ⊨φ φ₁ × ¬ I ⊨φ φ₂ -- -- -- -- I ⊨φ (quantified 𝑥 φ) = (𝓘 : Interpretation) → 𝓘 ≞ I / 𝑥 → 𝓘 ⊨φ φ -- -- -- -- HasSatisfactionSequent : {A : Set} ⦃ _ : BeFormula A ⦄ → HasSatisfaction $ Sequent A -- -- -- -- HasSatisfaction._⊨_ HasSatisfactionSequent I (φᵗ ╱ φˢs) = I ⊨ φˢs → I ⊨ φᵗ -- -- -- -- instance -- -- -- -- postulate -- -- -- -- HasDecidableSatisfactionFormula : HasDecidableSatisfaction Formula -- -- -- -- instance -- -- -- -- HasValidationBeFormula : {A : Set} ⦃ _ : BeFormula A ⦄ → HasValidation A -- -- -- -- HasValidation.⊨_ HasValidationBeFormula φ = (I : Interpretation) → I ⊨ φ -- -- -- -- HasValidationSequent : {A : Set} ⦃ _ : BeFormula A ⦄ → HasValidation $ Sequent A -- -- -- -- HasValidation.⊨_ HasValidationSequent Φ = (I : Interpretation) → I ⊨ Φ -- -- -- -- HasValidationProblem : {A : Set} ⦃ _ : BeFormula A ⦄ → HasValidation $ Problem A -- -- -- -- HasValidation.⊨_ HasValidationProblem (χs ¶ ι) = (I : Interpretation) → I ⊨ χs → I ⊨ ι -- -- -- -- instance -- -- -- -- HasSubstantiveDischargeBeFormulaBeFormula : {A : Set} ⦃ _ : BeFormula A ⦄ → HasSubstantiveDischarge A A -- -- -- -- HasSubstantiveDischarge._≽_ (HasSubstantiveDischargeBeFormulaBeFormula ⦃ ⟨ beFormula ⟩ ⦄) = _≡_ on beFormula -- _≡_ on (formula beFormula) -- _≡_ -- -- -- -- HasSubstantiveDischargeListBeFormulaBeFormula : {A : Set} ⦃ _ : BeFormula A ⦄ → HasSubstantiveDischarge (List A) A -- -- -- -- HasSubstantiveDischarge._≽_ (HasSubstantiveDischargeListBeFormulaBeFormula ⦃ ⟨ beFormula ⟩ ⦄) +s - = beFormula - ∈ (beFormula <$> +s) -- flip _∈_ -- -- -- -- HasSubstantiveDischargeListFormulaListFormula : {A : Set} ⦃ _ : BeFormula A ⦄ → HasSubstantiveDischarge (List A) (List A) -- -- -- -- HasSubstantiveDischarge._≽_ (HasSubstantiveDischargeListFormulaListFormula ⦃ ⟨ beFormula ⟩ ⦄) = flip $ _⊆_ on fmap beFormula -- flip _⊆_ -- -- -- -- HasSubstantiveDischargeSequentSequent : ∀ {A : Set} ⦃ _ : BeFormula A ⦄ → HasSubstantiveDischarge (Sequent A) (Sequent A) -- -- -- -- HasSubstantiveDischarge._≽_ HasSubstantiveDischargeSequentSequent (+ᵗ ╱ +ᵖs) (-ᵗ ╱ -ᵖs) = +ᵗ ≽ -ᵗ × +ᵖs ≽ -ᵖs -- -- -- -- HasSubstantiveDischargeListSequentSequent : ∀ {A : Set} ⦃ _ : BeFormula A ⦄ → HasSubstantiveDischarge (List $ Sequent A) (Sequent A) -- -- -- -- HasSubstantiveDischarge._≽_ HasSubstantiveDischargeListSequentSequent χs ι = ∃ λ c → (c ∈ χs) × c ≽ ι -- -- -- -- instance -- -- -- -- HasVacuousDischargeList : {A : Set} ⦃ _ : HasSubstantiveDischarge (List A) A ⦄ ⦃ _ : HasNegation A ⦄ → HasVacuousDischarge (List A) -- -- -- -- HasVacuousDischarge.◁_ (HasVacuousDischargeList {A}) xs = ∃ λ (x : A) → xs ≽ x × xs ≽ ~ x -- -- -- -- HasVacuousDischargeSequent : {A : Set} ⦃ _ : BeFormula A ⦄ ⦃ _ : HasNegation A ⦄ → HasVacuousDischarge (Sequent A) -- -- -- -- HasVacuousDischarge.◁_ HasVacuousDischargeSequent (_ ╱ φˢs) = ∃ λ s → (s ∈ φˢs) × (φˢs ≽ s) × (φˢs ≽ ~ s) -- -- -- -- instance -- -- -- -- HasSalvationSequent : {A : Set} ⦃ _ : BeFormula A ⦄ ⦃ _ : HasNegation A ⦄ {-⦃ _ : HasVacuousDischarge $ List A ⦄-} → HasSalvation $ Sequent A -- -- -- -- HasSalvation.isVacuouslyDischargable (HasSalvationSequent {A}) = List A -- -- -- -- HasSalvation.hasVacuousDischarge HasSalvationSequent = HasVacuousDischargeList -- -- -- -- HasSalvation.▷_ HasSalvationSequent (φᵗ ╱ φᵖs) = (◁ φᵖs) ⊎ (φᵖs ≽ φᵗ) -- -- -- -- HasDecidableSalvationSequent : {A : Set} ⦃ bf : BeFormula A ⦄ ⦃ hs : HasNegation A ⦄ -- -- -- -- → HasDecidableSalvation $ Sequent A -- -- -- -- HasDecidableSalvation.hasSalvation HasDecidableSalvationSequent = HasSalvationSequent -- -- -- -- --(HasDecidableSalvation.▷? HasDecidableSalvationSequent) (statement₁ ╱ []) = no (foo2 statement₁) -- -- -- -- HasDecidableSalvation.▷? HasDecidableSalvationSequent = {!!} -- -- -- -- --(HasDecidableSalvation.▷? HasDecidableSalvationSequent) (statement₁ ╱ []) = no (λ {x → {!!}}) -- -- -- -- --(HasDecidableSalvation.▷? HasDecidableSalvationSequent) (statement₁ ╱ (x₂ ∷ suppositions₁)) = {!!} -- -- -- -- -- foo1 : ∀ {A} → ⦃ b : BeFormula A ⦄ ⦃ _ : HasNegation A ⦄ (statement₁ : A) → Σ A -- -- -- -- -- (λ x → -- -- -- -- -- Σ (BeFormula.formula b x ∈ []) -- -- -- -- -- (λ _ → BeFormula.formula b (~ x) ∈ [])) -- -- -- -- -- ⊎ (BeFormula.formula b statement₁ ∈ []) → -- -- -- -- -- ⊥ -- -- -- -- -- foo1 statement₁ (left (fst₁ , () , snd₁)) -- -- -- -- -- foo1 statement₁ (right ()) -- -- -- -- -- foo2 : ∀ {A} → ⦃ b : BeFormula A ⦄ ⦃ _ : HasNegation A ⦄ (statement₁ : A) → ▷ (statement₁ ╱ []) → -- -- -- -- -- ⊥ -- -- -- -- -- foo2 statement₁ (left (fst₁ , () , snd₁)) -- -- -- -- -- foo2 statement₁ (right ())
# This file is part of the ValidatedNumerics.jl package; MIT licensed # zero, one zero{T<:Real}(a::DecoratedInterval{T}) = DecoratedInterval(zero(T)) zero{T<:Real}(::Type{DecoratedInterval{T}}) = DecoratedInterval(zero(T)) one{T<:Real}(a::DecoratedInterval{T}) = DecoratedInterval(one(T)) one{T<:Real}(::Type{DecoratedInterval{T}}) = DecoratedInterval(one(T)) ## Bool functions bool_functions = ( :isempty, :isentire, :isunbounded, :isfinite, :isnai, :isnan, :isthin, :iscommon ) bool_binary_functions = ( :<, :>, :(==), :!=, :⊆, :<=, :interior, :isdisjoint, :precedes, :strictprecedes ) for f in bool_functions @eval $(f)(xx::DecoratedInterval) = $(f)(interval_part(xx)) end for f in bool_binary_functions @eval $(f)(xx::DecoratedInterval, yy::DecoratedInterval) = $(f)(interval_part(xx), interval_part(yy)) end in{T<:Real}(x::T, a::DecoratedInterval) = in(x, interval_part(a)) ## scalar functions: mig, mag and friends scalar_functions = ( :mig, :mag, :infimum, :supremum, :mid, :diam, :radius, :dist, :eps ) for f in scalar_functions @eval $(f){T}(xx::DecoratedInterval{T}) = $f(interval_part(xx)) end ## Arithmetic function; / is treated separately arithm_functions = ( :+, :-, :* ) +(xx::DecoratedInterval) = xx -(xx::DecoratedInterval) = DecoratedInterval(-interval_part(xx), decoration(xx)) for f in arithm_functions @eval function $(f){T}(xx::DecoratedInterval{T}, yy::DecoratedInterval{T}) x = interval_part(xx) y = interval_part(yy) r = $f(x, y) dec = min(decoration(xx), decoration(yy), decoration(r)) DecoratedInterval(r, dec) end end # Division function inv{T}(xx::DecoratedInterval{T}) x = interval_part(xx) dx = decoration(xx) dx = zero(T) ∈ x ? min(dx,trv) : dx r = inv(x) dx = min(decoration(r), dx) DecoratedInterval( r, dx ) end function /{T}(xx::DecoratedInterval{T}, yy::DecoratedInterval{T}) x = interval_part(xx) y = interval_part(yy) r = x / y dy = decoration(yy) dy = zero(T) ∈ y ? min(dy, trv) : dy dy = min(decoration(xx), dy, decoration(r)) DecoratedInterval(r, dy) end ## fma function fma{T}(xx::DecoratedInterval{T}, yy::DecoratedInterval{T}, zz::DecoratedInterval{T}) r = fma(interval_part(xx), interval_part(yy), interval_part(zz)) d = min(decoration(xx), decoration(yy), decoration(zz)) d = min(decoration(r), d) DecoratedInterval(r, d) end # power function must be defined separately and carefully function ^{T}(xx::DecoratedInterval{T}, n::Integer) x = interval_part(xx) r = x^n d = min(decoration(xx), decoration(r)) n < 0 && zero(T) ∈ x && return DecoratedInterval(r, trv) DecoratedInterval(r, d) end function ^{T}(xx::DecoratedInterval{T}, q::AbstractFloat) x = interval_part(xx) r = x^q d = min(decoration(xx), decoration(r)) if x > zero(T) || (x.lo ≥ zero(T) && q > zero(T)) || (isinteger(q) && q > zero(q)) || (isinteger(q) && zero(T) ∉ x) return DecoratedInterval(r, d) end DecoratedInterval(r, trv) end function ^{T, S<:Integer}(xx::DecoratedInterval{T}, q::Rational{S}) x = interval_part(xx) r = x^q d = min(decoration(xx), decoration(r)) if x > zero(T) || (x.lo ≥ zero(T) && q > zero(T)) || (isinteger(q) && q > zero(q)) || (isinteger(q) && zero(T) ∉ x) return DecoratedInterval(r, d) end DecoratedInterval(r, trv) end function ^{T,S}(xx::DecoratedInterval{T}, qq::DecoratedInterval{S}) x = interval_part(xx) q = interval_part(qq) r = x^q d = min(decoration(xx), decoration(qq), decoration(r)) if x > zero(T) || (x.lo ≥ zero(T) && q.lo > zero(T)) || (isthin(q) && isinteger(q.lo) && q.lo > zero(q)) || (isthin(q) && isinteger(q.lo) && zero(T) ∉ x) return DecoratedInterval(r, d) end DecoratedInterval(r, trv) end ## Discontinuous functions (sign, ceil, floor, trunc) and round function sign{T}(xx::DecoratedInterval{T}) r = sign(interval_part(xx)) d = decoration(xx) isthin(r) && return DecoratedInterval(r, d) DecoratedInterval(r, min(d,def)) end function ceil{T}(xx::DecoratedInterval{T}) x = interval_part(xx) r = ceil(x) d = decoration(xx) if isinteger(x.hi) d = min(d, dac) end isthin(r) && return DecoratedInterval(r, d) DecoratedInterval(r, min(d,def)) end function floor{T}(xx::DecoratedInterval{T}) x = interval_part(xx) r = floor(x) d = decoration(xx) if isinteger(x.lo) d = min(d, dac) end isthin(r) && return DecoratedInterval(r, d) DecoratedInterval(r, min(d,def)) end function trunc{T}(xx::DecoratedInterval{T}) x = interval_part(xx) r = trunc(x) d = decoration(xx) if (isinteger(x.lo) && x.lo < zero(T)) || (isinteger(x.hi) && x.hi > zero(T)) d = min(d, dac) end isthin(r) && return DecoratedInterval(r, d) DecoratedInterval(r, min(d,def)) end function round(xx::DecoratedInterval, ::RoundingMode{:Nearest}) x = interval_part(xx) r = round(x) d = decoration(xx) if isinteger(2*x.lo) || isinteger(2*x.hi) d = min(d, dac) end isthin(r) && return DecoratedInterval(r, d) DecoratedInterval(r, min(d,def)) end function round(xx::DecoratedInterval, ::RoundingMode{:NearestTiesAway}) x = interval_part(xx) r = round(x,RoundNearestTiesAway) d = decoration(xx) if isinteger(2*x.lo) || isinteger(2*x.hi) d = min(d, dac) end isthin(r) && return DecoratedInterval(r, d) DecoratedInterval(r, min(d,def)) end round(xx::DecoratedInterval) = round(xx, RoundNearest) round(xx::DecoratedInterval, ::RoundingMode{:ToZero}) = trunc(xx) round(xx::DecoratedInterval, ::RoundingMode{:Up}) = ceil(xx) round(xx::DecoratedInterval, ::RoundingMode{:Down}) = floor(xx) ## Define binary functions with no domain restrictions binary_functions = ( :min, :max ) for f in binary_functions @eval function $(f){T}(xx::DecoratedInterval{T}, yy::DecoratedInterval{T}) r = $f(interval_part(xx), interval_part(yy)) d = min(decoration(r), decoration(xx), decoration(yy)) DecoratedInterval(r, d) end end ## abs abs{T}(xx::DecoratedInterval{T}) = DecoratedInterval(abs(interval_part(xx)), decoration(xx)) ## Other (cancel and set) functions other_functions = ( :cancelplus, :cancelminus, :intersect, :hull, :union ) for f in other_functions @eval $(f){T}(xx::DecoratedInterval{T}, yy::DecoratedInterval{T}) = DecoratedInterval($(f)(interval_part(xx), interval_part(yy)), trv) end @doc """ cancelplus(xx, yy) Decorated interval extension; the result is decorated as `trv`, following the IEEE-1788 Standard (see Sect. 11.7.1, pp 47). """ cancelplus @doc """ cancelminus(xx, yy) Decorated interval extension; the result is decorated as `trv`, following the IEEE-1788 Standard (see Sect. 11.7.1, pp 47). """ cancelminus @doc """ intersect(xx, yy) Decorated interval extension; the result is decorated as `trv`, following the IEEE-1788 Standard (see Sect. 11.7.1, pp 47). """ intersect @doc """ hull(xx, yy) Decorated interval extension; the result is decorated as `trv`, following the IEEE-1788 Standard (see Sect. 11.7.1, pp 47). """ hull @doc """ union(xx, yy) Decorated interval extension; the result is decorated as `trv`, following the IEEE-1788 Standard (see Sect. 11.7.1, pp 47). """ union ## Functions on unrestricted domains; tan and atan2 are treated separately unrestricted_functions =( :exp, :exp2, :exp10, :sin, :cos, :atan, :sinh, :cosh, :tanh, :asinh ) for f in unrestricted_functions @eval function $(f){T}(xx::DecoratedInterval{T}) x = interval_part(xx) r = $f(x) d = min(decoration(r), decoration(xx)) DecoratedInterval(r, d) end end function tan{T}(xx::DecoratedInterval{T}) x = interval_part(xx) r = tan(x) d = min(decoration(r), decoration(xx)) if isunbounded(r) d = min(d, trv) end DecoratedInterval(r, d) end function decay(a::DECORATION) a == com && return dac a == dac && return def a == def && return trv a == trv && return trv ill end function atan2{T}(yy::DecoratedInterval{T}, xx::DecoratedInterval{T}) x = interval_part(xx) y = interval_part(yy) r = atan2(y, x) d = decoration(r) d = min(d, decoration(xx), decoration(yy)) # Check cases when decoration is trv and decays (from com or dac) if zero(T) ∈ y zero(T) ∈ x && return DecoratedInterval(r, trv) if x.hi < zero(T) && y.lo != y.hi && signbit(y.lo) && Int(d) > 2 return DecoratedInterval(r, decay(d)) end end DecoratedInterval(r, d) end # For domains, cf. table 9.1 on page 28 of the standard # Functions with restricted domains: # The function is unbounded at the bounded edges of the domain restricted_functions1 = Dict( :log => [0, ∞], :log2 => [0, ∞], :log10 => [0, ∞], :atanh => [-1, 1] ) # The function is bounded at the bounded edge(s) of the domain restricted_functions2 = Dict( :sqrt => [0, ∞], :asin => [-1, 1], :acos => [-1, 1], :acosh => [1, ∞] ) # Define functions with restricted domains on DecoratedInterval's: for (f, domain) in restricted_functions1 domain = Interval(domain...) @eval function Base.$(f){T}(xx::DecoratedInterval{T}) x = interval_part(xx) r = $(f)(x) d = min(decoration(xx), decoration(r)) x ⪽ $(domain) && return DecoratedInterval(r, d) DecoratedInterval(r, trv) end end for (f, domain) in restricted_functions2 domain = Interval(domain...) @eval function Base.$(f){T}(xx::DecoratedInterval{T}) x = interval_part(xx) r = $(f)(x) d = min(decoration(xx), decoration(r)) x ⊆ $(domain) && return DecoratedInterval(r, d) DecoratedInterval(r, trv) end end
# Introduction In the falling parachutist problem we encountered an error - there was a difference between the numerical calculation and the analytical solution. There are numerous types of errors associated with an engineering mathematical model: 1. Modeling errors: These have to do with the fact that we can never describe reality exactely and/or our model neglects certain effects (e.g. sidewind in the parachutist example). 2. Numerical errors: These have to do directly with the numerical method used and can be generally categorized as * Round-off errors: due to the limited representation of numbers on computers * Truncation error: due to approximating exact mathematical operators ## Errors The basic definition of an error is \begin{equation} \text{True Error = True Value - Approximation} \end{equation} For simplicity, denote the "True Error" as $E_\text{t}$. There is a problem with this definition however - it does not take into account the "magnitude" of the true value. For example, an error of one centimeter is much more significant if we are measuring a rivet rather than a bridge. To fix this, we define the true relative error, $\epsilon_\text{t}$: \begin{equation} \text{True Relative Error} = \frac{\text{True Error}}{\text{True Value}} \end{equation} or \begin{equation} \epsilon_\text{t} = \frac{E_\text{t}}{\text{True Value}} \end{equation} ### Example Suppose that you have the task of measuring the lengths of a bridge and a rivet and come up with 9999 and 9 cm, respectively. If the true values are 10,000 and 10 cm, respectively, compute (a) the true error and (b) the true percent relative error for each case. #### Solution For the bridge, the True Error is: \begin{equation} E_\text{t} = 10,000 - 9999 = 1 \text{cm} \end{equation} while for the rivet \begin{equation} E_\text{t} = 10 - 9 = 1 \text{cm} \end{equation} Both measurements have the same true error. But we known intuitively that the 1 cm is a bigger deal for the rivet. We can show this by using the relative error. For the bridge, we have \begin{equation} \epsilon_\text{t} = \frac{E_\text{t}}{\text{True Value}} \times 100\%= \frac{1}{10,000} \times 100\% = 0.01 \% \end{equation} while for the rivet, \begin{equation} \epsilon_\text{t} = \frac{1}{10}\times 100\% = 10 \% \end{equation} Note that we used the words "True Error" - this is because the definition is based on the "True Value" - but this doesn't make sense since if we know the true value then we don't need an approximation! This definition is still important however because it lays the foundations of error analysis. In addition, when testing any numerical method, we first try it out on problems where the True Value is known (e.g. analytical solution). What we often do is figure out an approximation for the true value or find the best estimate of the true value. Another common situation in numerical methods is iteration: repeating the same task over and over again. What we can do in that case is define an iterative error as the difference between current and previous iterations: \begin{equation} \epsilon_\text{a} = \frac{ \text{current approximation} - \text{previous approximation} }{ \text{current approximation} }\times 100\% \end{equation} The usefulness of this definition is that it allows us to get an idea of how good our approximation is. Specifically, one can use a well known formula to determine the number of significant digits in an error. If your computed error $|\epsilon_\text{a}|$ (in \%) is less than \begin{equation} \epsilon_\text{s} = (0.5\times 10^{2-n})\% \end{equation} then your results are accurate to at least $n$ significant digits. For example, if you want your results to be significant up to at least four digits, ($n = 4$) then your results must satify $ |\epsilon_\text{a}| < 0.5\times10^{-2}\%$ or $ |\epsilon_\text{a}| < 0.005\%$. This formula can be inverted to obtain the number of significant digits. Taking the logarigthm \begin{equation} \log \epsilon_\text{s} = \log 0.5 + 2 - n \end{equation} and \begin{equation} n = \log 0.5 + 2 - \log \epsilon_\text{s} \end{equation} ## Example The exponential function $e^x$ can be approximated with the following (Taylor) series: \begin{equation} e^x = 1 + x + \frac{x^2}{2} + \frac{x^3}{3!} + \frac{x^4}{4!} + \frac{x^5}{5!} + \ldots \end{equation} Compute the true and approximate relative errors when using this formula for 1, 2, 3, 4, 5, and 6 terms. Use this formula to compute $e^{0.5}$ up to four significant digits ### Solution We will first need to define a function that computes the exponential up to a certain number of terms ```python # need to import the factorial and exponential functions from the math module import math from math import factorial, exp def my_exponential(x,n): '''x is the exponent and n is the number of terms''' result = 0.0 # initialize the result to zero for i in range(0,n): # loop over the number of terms: this goes from 0 to n-1 (n terms) result = result + x**i/factorial(i) # add each term at a time return result ``` ```python def sig_fig(error): return math.floor(math.log10(0.5) + 2 - math.log10(error)) ``` ```python # Now run the function for different number of terms oldval = 0.0 x = 0.5 trueval = exp(x) for n in range(1,10): val = my_exponential(x,n) ϵt = abs( (val - trueval)/trueval ) * 100 ϵa = abs( (val - oldval)/val ) * 100 oldval = val print (n,'\t', "%.8f" % val, '\t', "%.8f" % ϵt, '\t', "%.8f" % ϵa, '\t', sig_fig(ϵa)) ``` 1 1.00000000 39.34693403 100.00000000 -1 2 1.50000000 9.02040104 33.33333333 0 3 1.62500000 1.43876780 7.69230769 0 4 1.64583333 0.17516226 1.26582278 1 5 1.64843750 0.01721156 0.15797788 2 6 1.64869792 0.00141649 0.01579529 3 7 1.64871962 0.00010024 0.00131626 4 8 1.64872117 0.00000622 0.00009402 5 9 1.64872127 0.00000034 0.00000588 6 ```python from math import factorial, exp oldval = 0.0 x = 2.0 nterms = 10 for n in range(0,nterms): newval = oldval + x**n/ factorial(n) ϵa = abs( (newval - oldval)/newval) * 100 oldval = newval print(n, ϵa,'%') ``` 0 100.0 % 1 66.66666666666666 % 2 40.0 % 3 21.052631578947363 % 4 9.523809523809527 % 5 3.669724770642201 % 6 1.2084592145015065 % 7 0.34408602150537515 % 8 0.08594757198109124 % 9 0.019095813242941077 % ```python from math import factorial, exp oldval = 0.0 x = 2.0 nterms = 100 tol = 0.01 # percent ϵa = 10000 n = 0 while ϵa > tol: newval = oldval + x**n/ factorial(n) ϵa = abs( (newval - oldval)/newval) * 100 oldval = newval n = n + 1 print(n, ϵa,'%') ``` 1 100.0 % 2 66.66666666666666 % 3 40.0 % 4 21.052631578947363 % 5 9.523809523809527 % 6 3.669724770642201 % 7 1.2084592145015065 % 8 0.34408602150537515 % 9 0.08594757198109124 % 10 0.019095813242941077 % 11 0.0038190167941204627 % ```python def mycos(x, nterms): result = 0.0 for n in range(0,nterms): result += (-1)**n * x**(2*n) / factorial(2*n) return result ``` ```python print(mycos(3, 5), math.cos(3)) ``` ```python ```
State Before: case mpr α : Type u l l' : List α ⊢ l ~r reverse l' → reverse l ~r l' State After: case mpr α : Type u l l' : List α h : l ~r reverse l' ⊢ reverse l ~r l' Tactic: intro h State Before: case mpr α : Type u l l' : List α h : l ~r reverse l' ⊢ reverse l ~r l' State After: no goals Tactic: simpa using h.reverse
# # Copyright (C) 2004-2008 Greg Landrum and Rational Discovery LLC # # @@ All Rights Reserved @@ # This file is part of the RDKit. # The contents are covered by the terms of the BSD license # which is included in the file license.txt, found at the root # of the RDKit source tree. # from __future__ import print_function import math import sys import time import numpy from rdkit import Chem from rdkit import RDLogger as logging from rdkit.Chem import ChemicalFeatures from rdkit.Chem import ChemicalForceFields from rdkit.Chem import rdDistGeom as MolDG from rdkit.Chem.Pharm3D import ExcludedVolume import rdkit.DistanceGeometry as DG from rdkit.ML.Data import Stats _times = {} logger = logging.logger() defaultFeatLength = 2.0 def GetAtomHeavyNeighbors(atom): """ returns a list of the heavy-atom neighbors of the atom passed in: >>> m = Chem.MolFromSmiles('CCO') >>> l = GetAtomHeavyNeighbors(m.GetAtomWithIdx(0)) >>> len(l) 1 >>> isinstance(l[0],Chem.Atom) True >>> l[0].GetIdx() 1 >>> l = GetAtomHeavyNeighbors(m.GetAtomWithIdx(1)) >>> len(l) 2 >>> l[0].GetIdx() 0 >>> l[1].GetIdx() 2 """ res = [] for nbr in atom.GetNeighbors(): if nbr.GetAtomicNum() != 1: res.append(nbr) return res def ReplaceGroup(match, bounds, slop=0.01, useDirs=False, dirLength=defaultFeatLength): """ Adds an entry at the end of the bounds matrix for a point at the center of a multi-point feature returns a 2-tuple: new bounds mat index of point added >>> boundsMat = numpy.array([[0.0,2.0,2.0],[1.0,0.0,2.0],[1.0,1.0,0.0]]) >>> match = [0,1,2] >>> bm,idx = ReplaceGroup(match,boundsMat,slop=0.0) the index is at the end: >>> idx == 3 True and the matrix is one bigger: >>> bm.shape == (4, 4) True but the original bounds mat is not altered: >>> boundsMat.shape == (3, 3) True We make the assumption that the points of the feature form a regular polygon, are listed in order (i.e. pt 0 is a neighbor to pt 1 and pt N-1) and that the replacement point goes at the center: >>> print(', '.join(['%.3f'%x for x in bm[-1]])) 0.577, 0.577, 0.577, 0.000 >>> print(', '.join(['%.3f'%x for x in bm[:,-1]])) 1.155, 1.155, 1.155, 0.000 The slop argument (default = 0.01) is fractional: >>> bm,idx = ReplaceGroup(match,boundsMat) >>> print(', '.join(['%.3f'%x for x in bm[-1]])) 0.572, 0.572, 0.572, 0.000 >>> print(', '.join(['%.3f'%x for x in bm[:,-1]])) 1.166, 1.166, 1.166, 0.000 """ maxVal = -1000.0 minVal = 1e8 nPts = len(match) for i in range(nPts): idx0 = match[i] if i < nPts - 1: idx1 = match[i + 1] else: idx1 = match[0] if idx1 < idx0: idx0, idx1 = idx1, idx0 minVal = min(minVal, bounds[idx1, idx0]) maxVal = max(maxVal, bounds[idx0, idx1]) maxVal *= (1 + slop) minVal *= (1 - slop) scaleFact = 1.0 / (2.0 * math.sin(math.pi / nPts)) minVal *= scaleFact maxVal *= scaleFact replaceIdx = bounds.shape[0] if not useDirs: bm = numpy.zeros((bounds.shape[0] + 1, bounds.shape[1] + 1), numpy.float) else: bm = numpy.zeros((bounds.shape[0] + 2, bounds.shape[1] + 2), numpy.float) bm[0:bounds.shape[0], 0:bounds.shape[1]] = bounds bm[:replaceIdx, replaceIdx] = 1000. if useDirs: bm[:replaceIdx + 1, replaceIdx + 1] = 1000. # set the feature - direction point bounds: bm[replaceIdx, replaceIdx + 1] = dirLength + slop bm[replaceIdx + 1, replaceIdx] = dirLength - slop for idx1 in match: bm[idx1, replaceIdx] = maxVal bm[replaceIdx, idx1] = minVal if useDirs: # set the point - direction point bounds: bm[idx1, replaceIdx + 1] = numpy.sqrt(bm[replaceIdx, replaceIdx + 1] ** 2 + maxVal ** 2) bm[replaceIdx + 1, idx1] = numpy.sqrt(bm[replaceIdx + 1, replaceIdx] ** 2 + minVal ** 2) return bm, replaceIdx def EmbedMol(mol, bm, atomMatch=None, weight=2.0, randomSeed=-1, excludedVolumes=None): """ Generates an embedding for a molecule based on a bounds matrix and adds a conformer (id 0) to the molecule if the optional argument atomMatch is provided, it will be used to provide supplemental weights for the embedding routine (used in the optimization phase to ensure that the resulting geometry really does satisfy the pharmacophore). if the excludedVolumes is provided, it should be a sequence of ExcludedVolume objects >>> m = Chem.MolFromSmiles('c1ccccc1C') >>> bounds = MolDG.GetMoleculeBoundsMatrix(m) >>> bounds.shape == (7, 7) True >>> m.GetNumConformers() 0 >>> EmbedMol(m,bounds,randomSeed=23) >>> m.GetNumConformers() 1 """ nAts = mol.GetNumAtoms() weights = [] if atomMatch: for i in range(len(atomMatch)): for j in range(i + 1, len(atomMatch)): weights.append((i, j, weight)) if excludedVolumes: for vol in excludedVolumes: idx = vol.index # excluded volumes affect every other atom: for i in range(nAts): weights.append((i, idx, weight)) coords = DG.EmbedBoundsMatrix(bm, weights=weights, numZeroFail=1, randomSeed=randomSeed) # for row in coords: # print(', '.join(['%.2f'%x for x in row])) conf = Chem.Conformer(nAts) conf.SetId(0) for i in range(nAts): conf.SetAtomPosition(i, list(coords[i])) if excludedVolumes: for vol in excludedVolumes: vol.pos = numpy.array(coords[vol.index]) print(' % 7.4f % 7.4f % 7.4f Ar 0 0 0 0 0 0 0 0 0 0 0 0' % tuple(coords[-1]), file=sys.stderr) mol.AddConformer(conf) def AddExcludedVolumes(bm, excludedVolumes, smoothIt=True): """ Adds a set of excluded volumes to the bounds matrix and returns the new matrix excludedVolumes is a list of ExcludedVolume objects >>> boundsMat = numpy.array([[0.0,2.0,2.0],[1.0,0.0,2.0],[1.0,1.0,0.0]]) >>> ev1 = ExcludedVolume.ExcludedVolume(([(0,),0.5,1.0],),exclusionDist=1.5) >>> bm = AddExcludedVolumes(boundsMat,(ev1,)) the results matrix is one bigger: >>> bm.shape == (4, 4) True and the original bounds mat is not altered: >>> boundsMat.shape == (3, 3) True >>> print(', '.join(['%.3f'%x for x in bm[-1]])) 0.500, 1.500, 1.500, 0.000 >>> print(', '.join(['%.3f'%x for x in bm[:,-1]])) 1.000, 3.000, 3.000, 0.000 """ oDim = bm.shape[0] dim = oDim + len(excludedVolumes) res = numpy.zeros((dim, dim), numpy.float) res[:oDim, :oDim] = bm for i, vol in enumerate(excludedVolumes): bmIdx = oDim + i vol.index = bmIdx # set values to all the atoms: res[bmIdx, :bmIdx] = vol.exclusionDist res[:bmIdx, bmIdx] = 1000.0 # set values to our defining features: for indices, minV, maxV in vol.featInfo: for index in indices: try: res[bmIdx, index] = minV res[index, bmIdx] = maxV except IndexError: logger.error('BAD INDEX: res[%d,%d], shape is %s' % (bmIdx, index, str(res.shape))) raise IndexError # set values to other excluded volumes: for j in range(bmIdx + 1, dim): res[bmIdx, j:dim] = 0 res[j:dim, bmIdx] = 1000 if smoothIt: DG.DoTriangleSmoothing(res) return res def UpdatePharmacophoreBounds(bm, atomMatch, pcophore, useDirs=False, dirLength=defaultFeatLength, mol=None): """ loops over a distance bounds matrix and replaces the elements that are altered by a pharmacophore **NOTE** this returns the resulting bounds matrix, but it may also alter the input matrix atomMatch is a sequence of sequences containing atom indices for each of the pharmacophore's features. >>> from rdkit import Geometry >>> from rdkit.Chem.Pharm3D import Pharmacophore >>> feats = [ ... ChemicalFeatures.FreeChemicalFeature('HBondAcceptor', 'HAcceptor1', ... Geometry.Point3D(0.0, 0.0, 0.0)), ... ChemicalFeatures.FreeChemicalFeature('HBondDonor', 'HDonor1', ... Geometry.Point3D(2.65, 0.0, 0.0)), ... ] >>> pcophore=Pharmacophore.Pharmacophore(feats) >>> pcophore.setLowerBound(0,1, 1.0) >>> pcophore.setUpperBound(0,1, 2.0) >>> boundsMat = numpy.array([[0.0,3.0,3.0],[2.0,0.0,3.0],[2.0,2.0,0.0]]) >>> atomMatch = ((0,),(1,)) >>> bm = UpdatePharmacophoreBounds(boundsMat,atomMatch,pcophore) In this case, there are no multi-atom features, so the result matrix is the same as the input: >>> bm is boundsMat True this means, of course, that the input boundsMat is altered: >>> print(', '.join(['%.3f'%x for x in boundsMat[0]])) 0.000, 2.000, 3.000 >>> print(', '.join(['%.3f'%x for x in boundsMat[1]])) 1.000, 0.000, 3.000 >>> print(', '.join(['%.3f'%x for x in boundsMat[2]])) 2.000, 2.000, 0.000 """ replaceMap = {} for i, matchI in enumerate(atomMatch): if len(matchI) > 1: bm, replaceIdx = ReplaceGroup(matchI, bm, useDirs=useDirs) replaceMap[i] = replaceIdx for i, matchI in enumerate(atomMatch): mi = replaceMap.get(i, matchI[0]) for j in range(i + 1, len(atomMatch)): mj = replaceMap.get(j, atomMatch[j][0]) if mi < mj: idx0, idx1 = mi, mj else: idx0, idx1 = mj, mi bm[idx0, idx1] = pcophore.getUpperBound(i, j) bm[idx1, idx0] = pcophore.getLowerBound(i, j) return bm def EmbedPharmacophore(mol, atomMatch, pcophore, randomSeed=-1, count=10, smoothFirst=True, silent=False, bounds=None, excludedVolumes=None, targetNumber=-1, useDirs=False): """ Generates one or more embeddings for a molecule that satisfy a pharmacophore atomMatch is a sequence of sequences containing atom indices for each of the pharmacophore's features. - count: is the maximum number of attempts to make a generating an embedding - smoothFirst: toggles triangle smoothing of the molecular bounds matix - bounds: if provided, should be the molecular bounds matrix. If this isn't provided, the matrix will be generated. - targetNumber: if this number is positive, it provides a maximum number of embeddings to generate (i.e. we'll have count attempts to generate targetNumber embeddings). returns: a 3 tuple: 1) the molecular bounds matrix adjusted for the pharmacophore 2) a list of embeddings (molecules with a single conformer) 3) the number of failed attempts at embedding >>> from rdkit import Geometry >>> from rdkit.Chem.Pharm3D import Pharmacophore >>> m = Chem.MolFromSmiles('OCCN') >>> feats = [ ... ChemicalFeatures.FreeChemicalFeature('HBondAcceptor', 'HAcceptor1', ... Geometry.Point3D(0.0, 0.0, 0.0)), ... ChemicalFeatures.FreeChemicalFeature('HBondDonor', 'HDonor1', ... Geometry.Point3D(2.65, 0.0, 0.0)), ... ] >>> pcophore=Pharmacophore.Pharmacophore(feats) >>> pcophore.setLowerBound(0,1, 2.5) >>> pcophore.setUpperBound(0,1, 3.5) >>> atomMatch = ((0,),(3,)) >>> bm,embeds,nFail = EmbedPharmacophore(m,atomMatch,pcophore,randomSeed=23,silent=1) >>> len(embeds) 10 >>> nFail 0 Set up a case that can't succeed: >>> pcophore=Pharmacophore.Pharmacophore(feats) >>> pcophore.setLowerBound(0,1, 2.0) >>> pcophore.setUpperBound(0,1, 2.1) >>> atomMatch = ((0,),(3,)) >>> bm,embeds,nFail = EmbedPharmacophore(m,atomMatch,pcophore,randomSeed=23,silent=1) >>> len(embeds) 0 >>> nFail 10 """ global _times if not hasattr(mol, '_chiralCenters'): mol._chiralCenters = Chem.FindMolChiralCenters(mol) if bounds is None: bounds = MolDG.GetMoleculeBoundsMatrix(mol) if smoothFirst: DG.DoTriangleSmoothing(bounds) bm = bounds.copy() # print '------------' # print 'initial' # for row in bm: # print ' ',' '.join(['% 4.2f'%x for x in row]) # print '------------' bm = UpdatePharmacophoreBounds(bm, atomMatch, pcophore, useDirs=useDirs, mol=mol) if excludedVolumes: bm = AddExcludedVolumes(bm, excludedVolumes, smoothIt=False) if not DG.DoTriangleSmoothing(bm): raise ValueError("could not smooth bounds matrix") # print '------------' # print 'post replace and smooth' # for row in bm: # print ' ',' '.join(['% 4.2f'%x for x in row]) # print '------------' if targetNumber <= 0: targetNumber = count nFailed = 0 res = [] for i in range(count): tmpM = bm[:, :] m2 = Chem.Mol(mol) t1 = time.time() try: if randomSeed <= 0: seed = i * 10 + 1 else: seed = i * 10 + randomSeed EmbedMol(m2, tmpM, atomMatch, randomSeed=seed, excludedVolumes=excludedVolumes) except ValueError: if not silent: logger.info('Embed failed') nFailed += 1 else: t2 = time.time() _times['embed'] = _times.get('embed', 0) + t2 - t1 keepIt = True for idx, stereo in mol._chiralCenters: if stereo in ('R', 'S'): vol = ComputeChiralVolume(m2, idx) if (stereo == 'R' and vol >= 0) or (stereo == 'S' and vol <= 0): keepIt = False break if keepIt: res.append(m2) else: logger.debug('Removed embedding due to chiral constraints.') if len(res) == targetNumber: break return bm, res, nFailed def isNaN(v): """ provides an OS independent way of detecting NaNs This is intended to be used with values returned from the C++ side of things. We can't actually test this from Python (which traps zero division errors), but it would work something like this if we could: >>> isNaN(0) False #>>> isNan(1/0) #True """ if v != v and sys.platform == 'win32': return True elif v == 0 and v == 1 and sys.platform != 'win32': return True return False def OptimizeMol(mol, bm, atomMatches=None, excludedVolumes=None, forceConstant=1200.0, maxPasses=5, verbose=False): """ carries out a UFF optimization for a molecule optionally subject to the constraints in a bounds matrix - atomMatches, if provided, is a sequence of sequences - forceConstant is the force constant of the spring used to enforce the constraints returns a 2-tuple: 1) the energy of the initial conformation 2) the energy post-embedding NOTE that these energies include the energies of the constraints >>> from rdkit import Geometry >>> from rdkit.Chem.Pharm3D import Pharmacophore >>> m = Chem.MolFromSmiles('OCCN') >>> feats = [ ... ChemicalFeatures.FreeChemicalFeature('HBondAcceptor', 'HAcceptor1', ... Geometry.Point3D(0.0, 0.0, 0.0)), ... ChemicalFeatures.FreeChemicalFeature('HBondDonor', 'HDonor1', ... Geometry.Point3D(2.65, 0.0, 0.0)), ... ] >>> pcophore=Pharmacophore.Pharmacophore(feats) >>> pcophore.setLowerBound(0,1, 2.5) >>> pcophore.setUpperBound(0,1, 2.8) >>> atomMatch = ((0,),(3,)) >>> bm,embeds,nFail = EmbedPharmacophore(m,atomMatch,pcophore,randomSeed=23,silent=1) >>> len(embeds) 10 >>> testM = embeds[0] Do the optimization: >>> e1,e2 = OptimizeMol(testM,bm,atomMatches=atomMatch) Optimizing should have lowered the energy: >>> e2 < e1 True Check the constrained distance: >>> conf = testM.GetConformer(0) >>> p0 = conf.GetAtomPosition(0) >>> p3 = conf.GetAtomPosition(3) >>> d03 = p0.Distance(p3) >>> d03 >= pcophore.getLowerBound(0,1)-.01 True >>> d03 <= pcophore.getUpperBound(0,1)+.01 True If we optimize without the distance constraints (provided via the atomMatches argument) we're not guaranteed to get the same results, particularly in a case like the current one where the pharmcophore brings the atoms uncomfortably close together: >>> testM = embeds[1] >>> e1,e2 = OptimizeMol(testM,bm) >>> e2 < e1 True >>> conf = testM.GetConformer(0) >>> p0 = conf.GetAtomPosition(0) >>> p3 = conf.GetAtomPosition(3) >>> d03 = p0.Distance(p3) >>> d03 >= pcophore.getLowerBound(0,1)-.01 True >>> d03 <= pcophore.getUpperBound(0,1)+.01 False """ try: ff = ChemicalForceFields.UFFGetMoleculeForceField(mol) except Exception: logger.info('Problems building molecular forcefield', exc_info=True) return -1.0, -1.0 weights = [] if (atomMatches): for k in range(len(atomMatches)): for i in atomMatches[k]: for l in range(k + 1, len(atomMatches)): for j in atomMatches[l]: weights.append((i, j)) for i, j in weights: if j < i: i, j = j, i minV = bm[j, i] maxV = bm[i, j] ff.AddDistanceConstraint(i, j, minV, maxV, forceConstant) if excludedVolumes: nAts = mol.GetNumAtoms() conf = mol.GetConformer() idx = nAts for exVol in excludedVolumes: assert exVol.pos is not None logger.debug('ff.AddExtraPoint(%.4f,%.4f,%.4f)' % (exVol.pos[0], exVol.pos[1], exVol.pos[2])) ff.AddExtraPoint(exVol.pos[0], exVol.pos[1], exVol.pos[2], True) indices = [] for localIndices, _, _ in exVol.featInfo: indices += list(localIndices) for i in range(nAts): v = numpy.array(conf.GetAtomPosition(i)) - numpy.array(exVol.pos) d = numpy.sqrt(numpy.dot(v, v)) if i not in indices: if d < 5.0: logger.debug('ff.AddDistanceConstraint(%d,%d,%.3f,%d,%.0f)' % (i, idx, exVol.exclusionDist, 1000, forceConstant)) ff.AddDistanceConstraint(i, idx, exVol.exclusionDist, 1000, forceConstant) else: logger.debug('ff.AddDistanceConstraint(%d,%d,%.3f,%.3f,%.0f)' % (i, idx, bm[exVol.index, i], bm[i, exVol.index], forceConstant)) ff.AddDistanceConstraint(i, idx, bm[exVol.index, i], bm[i, exVol.index], forceConstant) idx += 1 ff.Initialize() e1 = ff.CalcEnergy() if isNaN(e1): raise ValueError('bogus energy') if verbose: print(Chem.MolToMolBlock(mol)) for i, _ in enumerate(excludedVolumes): pos = ff.GetExtraPointPos(i) print(' % 7.4f % 7.4f % 7.4f As 0 0 0 0 0 0 0 0 0 0 0 0' % tuple(pos), file=sys.stderr) needsMore = ff.Minimize() nPasses = 0 while needsMore and nPasses < maxPasses: needsMore = ff.Minimize() nPasses += 1 e2 = ff.CalcEnergy() if isNaN(e2): raise ValueError('bogus energy') if verbose: print('--------') print(Chem.MolToMolBlock(mol)) for i, _ in enumerate(excludedVolumes): pos = ff.GetExtraPointPos(i) print(' % 7.4f % 7.4f % 7.4f Sb 0 0 0 0 0 0 0 0 0 0 0 0' % tuple(pos), file=sys.stderr) ff = None return e1, e2 def EmbedOne(mol, name, match, pcophore, count=1, silent=0, **kwargs): """ generates statistics for a molecule's embeddings Four energies are computed for each embedding: 1) E1: the energy (with constraints) of the initial embedding 2) E2: the energy (with constraints) of the optimized embedding 3) E3: the energy (no constraints) the geometry for E2 4) E4: the energy (no constraints) of the optimized free-molecule (starting from the E3 geometry) Returns a 9-tuple: 1) the mean value of E1 2) the sample standard deviation of E1 3) the mean value of E2 4) the sample standard deviation of E2 5) the mean value of E3 6) the sample standard deviation of E3 7) the mean value of E4 8) the sample standard deviation of E4 9) The number of embeddings that failed """ global _times atomMatch = [list(x.GetAtomIds()) for x in match] bm, ms, nFailed = EmbedPharmacophore(mol, atomMatch, pcophore, count=count, silent=silent, **kwargs) e1s = [] e2s = [] e3s = [] e4s = [] d12s = [] d23s = [] d34s = [] for m in ms: t1 = time.time() try: e1, e2 = OptimizeMol(m, bm, atomMatch) except ValueError: pass else: t2 = time.time() _times['opt1'] = _times.get('opt1', 0) + t2 - t1 e1s.append(e1) e2s.append(e2) d12s.append(e1 - e2) t1 = time.time() try: e3, e4 = OptimizeMol(m, bm) except ValueError: pass else: t2 = time.time() _times['opt2'] = _times.get('opt2', 0) + t2 - t1 e3s.append(e3) e4s.append(e4) d23s.append(e2 - e3) d34s.append(e3 - e4) count += 1 try: e1, e1d = Stats.MeanAndDev(e1s) except Exception: e1 = -1.0 e1d = -1.0 try: e2, e2d = Stats.MeanAndDev(e2s) except Exception: e2 = -1.0 e2d = -1.0 try: e3, e3d = Stats.MeanAndDev(e3s) except Exception: e3 = -1.0 e3d = -1.0 try: e4, e4d = Stats.MeanAndDev(e4s) except Exception: e4 = -1.0 e4d = -1.0 if not silent: print('%s(%d): %.2f(%.2f) -> %.2f(%.2f) : %.2f(%.2f) -> %.2f(%.2f)' % (name, nFailed, e1, e1d, e2, e2d, e3, e3d, e4, e4d)) return e1, e1d, e2, e2d, e3, e3d, e4, e4d, nFailed def MatchPharmacophoreToMol(mol, featFactory, pcophore): """ generates a list of all possible mappings of a pharmacophore to a molecule Returns a 2-tuple: 1) a boolean indicating whether or not all features were found 2) a list, numFeatures long, of sequences of features >>> import os.path >>> from rdkit import Geometry, RDConfig >>> from rdkit.Chem.Pharm3D import Pharmacophore >>> fdefFile = os.path.join(RDConfig.RDCodeDir,'Chem/Pharm3D/test_data/BaseFeatures.fdef') >>> featFactory = ChemicalFeatures.BuildFeatureFactory(fdefFile) >>> activeFeats = [ ... ChemicalFeatures.FreeChemicalFeature('Acceptor', Geometry.Point3D(0.0, 0.0, 0.0)), ... ChemicalFeatures.FreeChemicalFeature('Donor',Geometry.Point3D(0.0, 0.0, 0.0))] >>> pcophore= Pharmacophore.Pharmacophore(activeFeats) >>> m = Chem.MolFromSmiles('FCCN') >>> match,mList = MatchPharmacophoreToMol(m,featFactory,pcophore) >>> match True Two feature types: >>> len(mList) 2 The first feature type, Acceptor, has two matches: >>> len(mList[0]) 2 >>> mList[0][0].GetAtomIds() (0,) >>> mList[0][1].GetAtomIds() (3,) The first feature type, Donor, has a single match: >>> len(mList[1]) 1 >>> mList[1][0].GetAtomIds() (3,) """ return MatchFeatsToMol(mol, featFactory, pcophore.getFeatures()) def _getFeatDict(mol, featFactory, features): """ **INTERNAL USE ONLY** >>> import os.path >>> from rdkit import Geometry, RDConfig, Chem >>> fdefFile = os.path.join(RDConfig.RDCodeDir,'Chem/Pharm3D/test_data/BaseFeatures.fdef') >>> featFactory = ChemicalFeatures.BuildFeatureFactory(fdefFile) >>> activeFeats = [ ... ChemicalFeatures.FreeChemicalFeature('Acceptor', Geometry.Point3D(0.0, 0.0, 0.0)), ... ChemicalFeatures.FreeChemicalFeature('Donor',Geometry.Point3D(0.0, 0.0, 0.0))] >>> m = Chem.MolFromSmiles('FCCN') >>> d =_getFeatDict(m,featFactory,activeFeats) >>> sorted(list(d.keys())) ['Acceptor', 'Donor'] >>> donors = d['Donor'] >>> len(donors) 1 >>> donors[0].GetAtomIds() (3,) >>> acceptors = d['Acceptor'] >>> len(acceptors) 2 >>> acceptors[0].GetAtomIds() (0,) >>> acceptors[1].GetAtomIds() (3,) """ molFeats = {} for feat in features: family = feat.GetFamily() if family not in molFeats: matches = featFactory.GetFeaturesForMol(mol, includeOnly=family) molFeats[family] = matches return molFeats def MatchFeatsToMol(mol, featFactory, features): """ generates a list of all possible mappings of each feature to a molecule Returns a 2-tuple: 1) a boolean indicating whether or not all features were found 2) a list, numFeatures long, of sequences of features >>> import os.path >>> from rdkit import RDConfig, Geometry >>> fdefFile = os.path.join(RDConfig.RDCodeDir,'Chem/Pharm3D/test_data/BaseFeatures.fdef') >>> featFactory = ChemicalFeatures.BuildFeatureFactory(fdefFile) >>> activeFeats = [ ... ChemicalFeatures.FreeChemicalFeature('Acceptor', Geometry.Point3D(0.0, 0.0, 0.0)), ... ChemicalFeatures.FreeChemicalFeature('Donor',Geometry.Point3D(0.0, 0.0, 0.0))] >>> m = Chem.MolFromSmiles('FCCN') >>> match,mList = MatchFeatsToMol(m,featFactory,activeFeats) >>> match True Two feature types: >>> len(mList) 2 The first feature type, Acceptor, has two matches: >>> len(mList[0]) 2 >>> mList[0][0].GetAtomIds() (0,) >>> mList[0][1].GetAtomIds() (3,) The first feature type, Donor, has a single match: >>> len(mList[1]) 1 >>> mList[1][0].GetAtomIds() (3,) """ molFeats = _getFeatDict(mol, featFactory, features) res = [] for feat in features: matches = molFeats.get(feat.GetFamily(), []) if len(matches) == 0: return False, None res.append(matches) return True, res def CombiEnum(sequence): """ This generator takes a sequence of sequences as an argument and provides all combinations of the elements of the subsequences: >>> gen = CombiEnum(((1,2),(10,20))) >>> next(gen) [1, 10] >>> next(gen) [1, 20] >>> [x for x in CombiEnum(((1,2),(10,20)))] [[1, 10], [1, 20], [2, 10], [2, 20]] >>> [x for x in CombiEnum(((1,2),(10,20),(100,200)))] [[1, 10, 100], [1, 10, 200], [1, 20, 100], [1, 20, 200], [2, 10, 100], [2, 10, 200], [2, 20, 100], [2, 20, 200]] """ if not len(sequence): yield [] elif len(sequence) == 1: for entry in sequence[0]: yield [entry] else: for entry in sequence[0]: for subVal in CombiEnum(sequence[1:]): yield [entry] + subVal def DownsampleBoundsMatrix(bm, indices, maxThresh=4.0): """ removes rows from a bounds matrix that are that are greater than a threshold value away from a set of other points returns the modfied bounds matrix The goal of this function is to remove rows from the bounds matrix that correspond to atoms that are likely to be quite far from the pharmacophore we're interested in. Because the bounds smoothing we eventually have to do is N^3, this can be a big win >>> boundsMat = numpy.array([[0.0,3.0,4.0],[2.0,0.0,3.0],[2.0,2.0,0.0]]) >>> bm = DownsampleBoundsMatrix(boundsMat,(0,),3.5) >>> bm.shape == (2, 2) True we don't touch the input matrix: >>> boundsMat.shape == (3, 3) True >>> print(', '.join(['%.3f'%x for x in bm[0]])) 0.000, 3.000 >>> print(', '.join(['%.3f'%x for x in bm[1]])) 2.000, 0.000 if the threshold is high enough, we don't do anything: >>> boundsMat = numpy.array([[0.0,4.0,3.0],[2.0,0.0,3.0],[2.0,2.0,0.0]]) >>> bm = DownsampleBoundsMatrix(boundsMat,(0,),5.0) >>> bm.shape == (3, 3) True If there's a max value that's close enough to *any* of the indices we pass in, we'll keep it: >>> boundsMat = numpy.array([[0.0,4.0,3.0],[2.0,0.0,3.0],[2.0,2.0,0.0]]) >>> bm = DownsampleBoundsMatrix(boundsMat,(0,1),3.5) >>> bm.shape == (3, 3) True """ nPts = bm.shape[0] k = numpy.zeros(nPts, numpy.int0) for idx in indices: k[idx] = 1 for i in indices: row = bm[i] for j in range(i + 1, nPts): if not k[j] and row[j] < maxThresh: k[j] = 1 keep = numpy.nonzero(k)[0] bm2 = numpy.zeros((len(keep), len(keep)), numpy.float) for i, idx in enumerate(keep): row = bm[idx] bm2[i] = numpy.take(row, keep) return bm2 def CoarseScreenPharmacophore(atomMatch, bounds, pcophore, verbose=False): """ >>> from rdkit import Geometry >>> from rdkit.Chem.Pharm3D import Pharmacophore >>> feats = [ ... ChemicalFeatures.FreeChemicalFeature('HBondAcceptor', 'HAcceptor1', ... Geometry.Point3D(0.0, 0.0, 0.0)), ... ChemicalFeatures.FreeChemicalFeature('HBondDonor', 'HDonor1', ... Geometry.Point3D(2.65, 0.0, 0.0)), ... ChemicalFeatures.FreeChemicalFeature('Aromatic', 'Aromatic1', ... Geometry.Point3D(5.12, 0.908, 0.0)), ... ] >>> pcophore=Pharmacophore.Pharmacophore(feats) >>> pcophore.setLowerBound(0,1, 1.1) >>> pcophore.setUpperBound(0,1, 1.9) >>> pcophore.setLowerBound(0,2, 2.1) >>> pcophore.setUpperBound(0,2, 2.9) >>> pcophore.setLowerBound(1,2, 2.1) >>> pcophore.setUpperBound(1,2, 3.9) >>> bounds = numpy.array([[0,2,3],[1,0,4],[2,3,0]],numpy.float) >>> CoarseScreenPharmacophore(((0,),(1,)),bounds,pcophore) True >>> CoarseScreenPharmacophore(((0,),(2,)),bounds,pcophore) False >>> CoarseScreenPharmacophore(((1,),(2,)),bounds,pcophore) False >>> CoarseScreenPharmacophore(((0,),(1,),(2,)),bounds,pcophore) True >>> CoarseScreenPharmacophore(((1,),(0,),(2,)),bounds,pcophore) False >>> CoarseScreenPharmacophore(((2,),(1,),(0,)),bounds,pcophore) False # we ignore the point locations here and just use their definitions: >>> feats = [ ... ChemicalFeatures.FreeChemicalFeature('HBondAcceptor', 'HAcceptor1', ... Geometry.Point3D(0.0, 0.0, 0.0)), ... ChemicalFeatures.FreeChemicalFeature('HBondDonor', 'HDonor1', ... Geometry.Point3D(2.65, 0.0, 0.0)), ... ChemicalFeatures.FreeChemicalFeature('Aromatic', 'Aromatic1', ... Geometry.Point3D(5.12, 0.908, 0.0)), ... ChemicalFeatures.FreeChemicalFeature('HBondDonor', 'HDonor1', ... Geometry.Point3D(2.65, 0.0, 0.0)), ... ] >>> pcophore=Pharmacophore.Pharmacophore(feats) >>> pcophore.setLowerBound(0,1, 2.1) >>> pcophore.setUpperBound(0,1, 2.9) >>> pcophore.setLowerBound(0,2, 2.1) >>> pcophore.setUpperBound(0,2, 2.9) >>> pcophore.setLowerBound(0,3, 2.1) >>> pcophore.setUpperBound(0,3, 2.9) >>> pcophore.setLowerBound(1,2, 1.1) >>> pcophore.setUpperBound(1,2, 1.9) >>> pcophore.setLowerBound(1,3, 1.1) >>> pcophore.setUpperBound(1,3, 1.9) >>> pcophore.setLowerBound(2,3, 1.1) >>> pcophore.setUpperBound(2,3, 1.9) >>> bounds = numpy.array([[0,3,3,3],[2,0,2,2],[2,1,0,2],[2,1,1,0]],numpy.float) >>> CoarseScreenPharmacophore(((0,),(1,),(2,),(3,)),bounds,pcophore) True >>> CoarseScreenPharmacophore(((0,),(1,),(3,),(2,)),bounds,pcophore) True >>> CoarseScreenPharmacophore(((1,),(0,),(3,),(2,)),bounds,pcophore) False """ for k in range(len(atomMatch)): if len(atomMatch[k]) == 1: for l in range(k + 1, len(atomMatch)): if len(atomMatch[l]) == 1: idx0 = atomMatch[k][0] idx1 = atomMatch[l][0] if idx1 < idx0: idx0, idx1 = idx1, idx0 if (bounds[idx1, idx0] >= pcophore.getUpperBound(k, l) or bounds[idx0, idx1] <= pcophore.getLowerBound(k, l)): if verbose: print('\t (%d,%d) [%d,%d] fail' % (idx1, idx0, k, l)) print('\t %f,%f - %f,%f' % (bounds[idx1, idx0], pcophore.getUpperBound(k, l), bounds[idx0, idx1], pcophore.getLowerBound(k, l))) # logger.debug('\t >%s'%str(atomMatch)) # logger.debug() # logger.debug('\t %f,%f - %f,%f'%(bounds[idx1,idx0],pcophore.getUpperBound(k,l), # bounds[idx0,idx1],pcophore.getLowerBound(k,l))) return False return True def Check2DBounds(atomMatch, mol, pcophore): """ checks to see if a particular mapping of features onto a molecule satisfies a pharmacophore's 2D restrictions >>> from rdkit import Geometry >>> from rdkit.Chem.Pharm3D import Pharmacophore >>> activeFeats = [ ... ChemicalFeatures.FreeChemicalFeature('Acceptor', Geometry.Point3D(0.0, 0.0, 0.0)), ... ChemicalFeatures.FreeChemicalFeature('Donor',Geometry.Point3D(0.0, 0.0, 0.0))] >>> pcophore= Pharmacophore.Pharmacophore(activeFeats) >>> pcophore.setUpperBound2D(0,1,3) >>> m = Chem.MolFromSmiles('FCC(N)CN') >>> Check2DBounds(((0,),(3,)),m,pcophore) True >>> Check2DBounds(((0,),(5,)),m,pcophore) False """ dm = Chem.GetDistanceMatrix(mol, False, False, False) nFeats = len(atomMatch) for i in range(nFeats): for j in range(i + 1, nFeats): lowerB = pcophore._boundsMat2D[j, i] # lowerB = pcophore.getLowerBound2D(i,j) upperB = pcophore._boundsMat2D[i, j] # upperB = pcophore.getUpperBound2D(i,j) dij = 10000 for atomI in atomMatch[i]: for atomJ in atomMatch[j]: try: dij = min(dij, dm[atomI, atomJ]) except IndexError: print('bad indices:', atomI, atomJ) print(' shape:', dm.shape) print(' match:', atomMatch) print(' mol:') print(Chem.MolToMolBlock(mol)) raise IndexError if dij < lowerB or dij > upperB: return False return True def _checkMatch(match, mol, bounds, pcophore, use2DLimits): """ **INTERNAL USE ONLY** checks whether a particular atom match can be satisfied by a molecule """ atomMatch = ChemicalFeatures.GetAtomMatch(match) if not atomMatch: return None elif use2DLimits: if not Check2DBounds(atomMatch, mol, pcophore): return None if not CoarseScreenPharmacophore(atomMatch, bounds, pcophore): return None return atomMatch def ConstrainedEnum(matches, mol, pcophore, bounds, use2DLimits=False, index=0, soFar=[]): """ Enumerates the list of atom mappings a molecule has to a particular pharmacophore. We do check distance bounds here. """ nMatches = len(matches) if index >= nMatches: yield soFar, [] elif index == nMatches - 1: for entry in matches[index]: nextStep = soFar + [entry] if index != 0: atomMatch = _checkMatch(nextStep, mol, bounds, pcophore, use2DLimits) else: atomMatch = ChemicalFeatures.GetAtomMatch(nextStep) if atomMatch: yield soFar + [entry], atomMatch else: for entry in matches[index]: nextStep = soFar + [entry] if index != 0: atomMatch = _checkMatch(nextStep, mol, bounds, pcophore, use2DLimits) if not atomMatch: continue for val in ConstrainedEnum(matches, mol, pcophore, bounds, use2DLimits=use2DLimits, index=index + 1, soFar=nextStep): if val: yield val def MatchPharmacophore(matches, bounds, pcophore, useDownsampling=False, use2DLimits=False, mol=None, excludedVolumes=None, useDirs=False): """ if use2DLimits is set, the molecule must also be provided and topological distances will also be used to filter out matches """ for match, atomMatch in ConstrainedEnum(matches, mol, pcophore, bounds, use2DLimits=use2DLimits): bm = bounds.copy() bm = UpdatePharmacophoreBounds(bm, atomMatch, pcophore, useDirs=useDirs, mol=mol) if excludedVolumes: localEvs = [] for eV in excludedVolumes: featInfo = [] for i, entry in enumerate(atomMatch): info = list(eV.featInfo[i]) info[0] = entry featInfo.append(info) localEvs.append(ExcludedVolume.ExcludedVolume(featInfo, eV.index, eV.exclusionDist)) bm = AddExcludedVolumes(bm, localEvs, smoothIt=False) sz = bm.shape[0] if useDownsampling: indices = [] for entry in atomMatch: indices.extend(entry) if excludedVolumes: for vol in localEvs: indices.append(vol.index) bm = DownsampleBoundsMatrix(bm, indices) if DG.DoTriangleSmoothing(bm): return 0, bm, match, (sz, bm.shape[0]) return 1, None, None, None def GetAllPharmacophoreMatches(matches, bounds, pcophore, useDownsampling=0, progressCallback=None, use2DLimits=False, mol=None, verbose=False): res = [] nDone = 0 for match in CombiEnum(matches): atomMatch = ChemicalFeatures.GetAtomMatch(match) if atomMatch and use2DLimits and mol: pass2D = Check2DBounds(atomMatch, mol, pcophore) if verbose: print('..', atomMatch) print(' ..Pass2d:', pass2D) else: pass2D = True if atomMatch and pass2D and \ CoarseScreenPharmacophore(atomMatch, bounds, pcophore, verbose=verbose): if verbose: print(' ..CoarseScreen: Pass') bm = bounds.copy() if verbose: print('pre update:') for row in bm: print(' ', ' '.join(['% 4.2f' % x for x in row])) bm = UpdatePharmacophoreBounds(bm, atomMatch, pcophore) if verbose: print('pre downsample:') for row in bm: print(' ', ' '.join(['% 4.2f' % x for x in row])) if useDownsampling: indices = [] for entry in atomMatch: indices += list(entry) bm = DownsampleBoundsMatrix(bm, indices) if verbose: print('post downsample:') for row in bm: print(' ', ' '.join(['% 4.2f' % x for x in row])) if DG.DoTriangleSmoothing(bm): res.append(match) elif verbose: print('cannot smooth') nDone += 1 if progressCallback: progressCallback(nDone) return res def ComputeChiralVolume(mol, centerIdx, confId=-1): """ Computes the chiral volume of an atom We're using the chiral volume formula from Figure 7 of Blaney and Dixon, Rev. Comp. Chem. V, 299-335 (1994) >>> import os.path >>> from rdkit import RDConfig >>> dataDir = os.path.join(RDConfig.RDCodeDir,'Chem/Pharm3D/test_data') R configuration atoms give negative volumes: >>> mol = Chem.MolFromMolFile(os.path.join(dataDir,'mol-r.mol')) >>> Chem.AssignStereochemistry(mol) >>> mol.GetAtomWithIdx(1).GetProp('_CIPCode') 'R' >>> ComputeChiralVolume(mol,1) < 0 True S configuration atoms give positive volumes: >>> mol = Chem.MolFromMolFile(os.path.join(dataDir,'mol-s.mol')) >>> Chem.AssignStereochemistry(mol) >>> mol.GetAtomWithIdx(1).GetProp('_CIPCode') 'S' >>> ComputeChiralVolume(mol,1) > 0 True Non-chiral (or non-specified) atoms give zero volume: >>> ComputeChiralVolume(mol,0) == 0.0 True We also work on 3-coordinate atoms (with implicit Hs): >>> mol = Chem.MolFromMolFile(os.path.join(dataDir,'mol-r-3.mol')) >>> Chem.AssignStereochemistry(mol) >>> mol.GetAtomWithIdx(1).GetProp('_CIPCode') 'R' >>> ComputeChiralVolume(mol,1)<0 True >>> mol = Chem.MolFromMolFile(os.path.join(dataDir,'mol-s-3.mol')) >>> Chem.AssignStereochemistry(mol) >>> mol.GetAtomWithIdx(1).GetProp('_CIPCode') 'S' >>> ComputeChiralVolume(mol,1)>0 True """ conf = mol.GetConformer(confId) Chem.AssignStereochemistry(mol) center = mol.GetAtomWithIdx(centerIdx) if not center.HasProp('_CIPCode'): return 0.0 nbrs = center.GetNeighbors() nbrRanks = [] for nbr in nbrs: rank = int(nbr.GetProp('_CIPRank')) pos = conf.GetAtomPosition(nbr.GetIdx()) nbrRanks.append((rank, pos)) # if we only have three neighbors (i.e. the determining H isn't present) # then use the central atom as the fourth point: if len(nbrRanks) == 3: nbrRanks.append((-1, conf.GetAtomPosition(centerIdx))) nbrRanks.sort() ps = [x[1] for x in nbrRanks] v1 = ps[0] - ps[3] v2 = ps[1] - ps[3] v3 = ps[2] - ps[3] res = v1.DotProduct(v2.CrossProduct(v3)) return res # ------------------------------------ # # doctest boilerplate # def _runDoctests(verbose=None): # pragma: nocover import doctest failed, _ = doctest.testmod(optionflags=doctest.ELLIPSIS + doctest.NORMALIZE_WHITESPACE, verbose=verbose) sys.exit(failed) if __name__ == '__main__': # pragma: nocover _runDoctests()
[STATEMENT] lemma project_set_iff [iff]: "(x \<in> project_set h C) = (\<exists>y. h(x,y) \<in> C)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (x \<in> project_set h C) = (\<exists>y. h (x, y) \<in> C) [PROOF STEP] by (simp add: project_set_def)
(* Copyright (c) 2014, Robert Dockins *) Require Import Setoid. Require Import basics. Require Import categories. Require Import preord. Require Import sets. Require Import finsets. Require Import atoms. Require Import List. (** * Support and finite permutations *) (** The [supported] record equips types with an operation to get a finite set of atoms; this finite set is called the "support." This record contains no axioms about the support, but is inteded to be used with nominal types, as defined in nominal.v. We define [supported] here because it is convenient to have notation for the support of a finite permuatation and disjointness of support before we can define the nominal types. When [x] is an element of a supported type, we write [‖x‖] for the support of [x], and when [y] is also an element of a possibly different supported type, we write [x♯y] to mean that the support of [x] and [y] are disjoint. *) Module Support. Record supported := Supported { carrier :> Type ; support : carrier -> finset atom }. Definition disjoint (A B:supported) (a:A) (b:B) := forall v, v ∈ support A a -> v ∈ support B b -> False. End Support. Arguments Support.support : simpl never. Notation supported := Support.supported. Notation Supported := Support.Supported. Notation "‖ x ‖" := (Support.support _ x) (at level 20, format "‖ x ‖"). Notation "a ♯ b" := (Support.disjoint _ _ a b) (at level 25, no associativity, format "a ♯ b"). Canonical Structure atom_supp := Supported atom (fun x => x::nil). Definition concat A := fold_right (@app A) nil. Notation "'fresh' '[' x , .. , z ']'" := (fresh_atom (concat atom (cons (Support.support _ x) .. (cons (Support.support _ z) nil) ..))). (** Here we define finitely supported permuatations of atoms. Such permutations play an important role in the developement of nominal types. The support of a permutation is a finite set that contains all the atoms _not_ fixed by the permutation. Note: the support may be larger than necessary; that is, it may contain atoms that are nonetheless fixed by the permutation. In other words, for a permutation [p] every atom [v] is either in the support of [p] or else [p v = v]; but it is possible that [v] may both be in the support of [p] and also that [p v = v]. Permutations form a groupoid category (with a single object; hence a group). When [p] and [q] are permuatations, we write [p ∘ q] for the composition, and [p⁻¹] represents the inverse permuatation. [u ⇋ v] is the permuatation that swaps atoms [u] and [v]. Because we only deal with the finitely supported permutations, we can prove interesting "swap induction" principles, where the inductive step must only consider only swapping of two variables. These induction principles witness the fact that every finitely supported permutation is equivelant to a finite composition of swappings. *) Module Perm. Record perm (A B:unit) := Perm { f : atom -> atom ; g : atom -> atom ; support : finset atom ; gf : forall x, g (f x) = x ; fg : forall x, f (g x) = x ; support_axiom : forall v, v ∈ support \/ f v = v }. Arguments f [A B] _ _. Arguments g [A B] _ _. Arguments support [A B] _. Arguments fg [A B] _ _. Arguments gf [A B] _ _. Arguments support_axiom [A B] _ _. Canonical Structure perm_support (A B:unit) : supported := Supported (perm A B) (@support A B). Program Definition eq_mixin (A B:unit) : Eq.mixin_of (perm A B) := Eq.Mixin (perm A B) (fun a b => forall x, f a x = f b x) _ _ _. Solve Obligations with intuition eauto. Next Obligation. simpl; intros. rewrite H. auto. Qed. Canonical Structure eq (A B:unit) : Eq.type := Eq.Pack (perm A B) (eq_mixin A B). Definition ident A : perm A A := Perm A A (fun x => x) (fun x => x) nil (fun x => Logic.eq_refl x) (fun x => Logic.eq_refl x) (fun x => or_intror (Logic.eq_refl x)). Program Definition compose A B C (p1:perm B C) (p2:perm A B) : perm A C := Perm A C (fun x => f p1 (f p2 x)) (fun x => g p2 (g p1 x)) (‖p1‖ ++ ‖p2‖) _ _ _. Next Obligation. simpl; intros. rewrite (gf p1). rewrite (gf p2). auto. Qed. Next Obligation. simpl; intros. rewrite (fg p2). rewrite (fg p1). auto. Qed. Next Obligation. simpl; intros. destruct (support_axiom p2 v). left. apply app_elem; auto. rewrite H. destruct (support_axiom p1 v). left. apply app_elem; auto. right; auto. Qed. Definition comp_mixin : Comp.mixin_of unit perm := Comp.Mixin unit perm ident compose. Canonical Structure comp : Comp.type := Comp.Pack unit perm comp_mixin. Lemma category_axioms : Category.axioms unit perm eq_mixin comp_mixin. Proof. constructor; simpl; intros; auto. hnf; simpl; auto. hnf; simpl; auto. hnf; simpl; auto. hnf; simpl; intro. rewrite H. rewrite H0. auto. Qed. Canonical Structure PERM : category := Category unit perm eq_mixin comp_mixin category_axioms. Program Definition inv A B (p:perm A B) : perm B A:= Perm B A (g p) (f p) (support p) (fg p) (gf p) _. Next Obligation. intros. destruct (support_axiom p v); auto. right. rewrite <- H at 1. apply gf. Qed. Lemma inv_id1 : forall A B (p:perm A B), p ∘ (inv A B p) ≈ id(B). Proof. repeat intro. simpl. apply fg. Qed. Lemma inv_id2 : forall A B (p:perm A B), inv A B p ∘ p ≈ id(A). Proof. repeat intro. simpl. apply gf. Qed. Program Definition groupoid_mixin := Groupoid.Mixin unit perm eq_mixin comp_mixin inv _. Next Obligation. constructor. apply inv_id1. apply inv_id2. Qed. Definition groupoid := Groupoid unit perm eq_mixin comp_mixin category_axioms groupoid_mixin. Lemma f_inj : forall (p:perm tt tt) x y, f p x = f p y -> x = y. Proof. intros. rewrite <- (gf p x). rewrite <- (gf p y). rewrite H; auto. Qed. Lemma g_inj : forall (p:perm tt tt) x y, g p x = g p y -> x = y. Proof. intros. rewrite <- (fg p x). rewrite <- (fg p y). rewrite H; auto. Qed. Program Definition swap (x y:atom) : perm tt tt := Perm tt tt (fun z => if string_dec x z then y else if string_dec y z then x else z) (fun z => if string_dec x z then y else if string_dec y z then x else z) (x::y::nil) _ _ _. Next Obligation. simpl; intros. rename x0 into z. destruct (string_dec x z). destruct (string_dec x y). congruence. destruct (string_dec y y); congruence. destruct (string_dec y z); try congruence. destruct (string_dec x x); congruence. destruct (string_dec x z). congruence. destruct (string_dec y z); try congruence. Qed. Next Obligation. simpl; intros. rename x0 into z. destruct (string_dec x z). destruct (string_dec x y). congruence. destruct (string_dec y y); congruence. destruct (string_dec y z). destruct (string_dec x x); congruence. destruct (string_dec x z). congruence. destruct (string_dec y z); congruence. Qed. Next Obligation. simpl; intros. destruct (string_dec x v). left. apply cons_elem; auto. left. rewrite e; auto. destruct (string_dec y v). left. rewrite e. apply cons_elem; right. apply cons_elem; auto. auto. Qed. Lemma swap_swap (p q:atom) : swap p q ≈ swap q p. Proof. hnf; simpl; intros. destruct (string_dec p x). destruct (string_dec q x); auto. congruence. destruct (string_dec q x); auto. Qed. Lemma assoc (f g h : perm tt tt) : f ∘ (g ∘ h) ≈ (f ∘ g) ∘ h. Proof. hnf; simpl; intros. auto. Qed. Lemma swap_self_inv p q : swap p q ∘ swap p q ≈ id(tt). Proof. hnf; simpl; intros. apply (fg (swap p q)). Qed. Lemma swap_same_id p : swap p p ≈ id(tt). Proof. hnf; simpl; intros. destruct (string_dec p x); auto. Qed. Lemma swap_swizzle (p q r:atom) (Hrp : r <> p) (Hrq : r <> q) (Hpq : p <> q) : swap p r ∘ swap r q ≈ swap r q ∘ swap p q. Proof. intros. hnf. simpl. intros. destruct (string_dec r x). subst x. destruct (string_dec p q); auto. elim Hpq; auto. destruct (string_dec r q). elim Hrq; auto. destruct (string_dec p r). elim Hrp; auto. destruct (string_dec p r). elim Hrp; auto. destruct (string_dec q r). elim Hrq; auto. destruct (string_dec r r); auto. elim n4; auto. destruct (string_dec q x). subst x. destruct (string_dec r r). 2: elim n0. destruct (string_dec p q). elim Hpq; auto. destruct (string_dec p r). elim Hrp; auto. destruct (string_dec r p). elim Hrp; auto. destruct (string_dec q p). elim Hpq; auto. auto. auto. destruct (string_dec p x). subst x. destruct (string_dec r q); auto. destruct (string_dec q q); auto. elim n2; auto. destruct (string_dec r x). contradiction. destruct (string_dec q x); auto. contradiction. Qed. Lemma support_perm (p:perm tt tt) (v:atom) : v ∈ support p <-> f p v ∈ support p. Proof. split; intros. destruct (support_axiom p (f p v)); auto. apply f_inj in H0. rewrite H0. auto. destruct (support_axiom p v); auto. rewrite <- H0. auto. Qed. Lemma support_perm' (p:perm tt tt) (v:atom) : v ∈ support p <-> f (inv tt tt p) v ∈ support p. Proof. split; intros. apply support_perm. simpl. rewrite fg. auto. apply support_perm in H. simpl in H. rewrite fg in H. auto. Qed. End Perm. Canonical Structure Perm.eq. Canonical Structure Perm.comp. Canonical Structure Perm.perm_support. Canonical Structure Perm.PERM. Canonical Structure Perm.groupoid. Notation perm := (Perm.perm tt tt). Notation PERM := Perm.PERM. Coercion Perm.f : Perm.perm >-> Funclass. Notation "u ⇋ v" := (Perm.swap u v) (at level 20, no associativity). (** Permutations with disjoint support commute. *) Lemma perm_commute (p q:perm) : p♯q -> p ∘ q ≈ q ∘ p. Proof. intro. hnf; simpl; intros. destruct (Perm.support_axiom p x). destruct (Perm.support_axiom q x). elim (H x); auto. rewrite H1. destruct (Perm.support_axiom q (p x)). elim (H (p x)); auto. rewrite <- Perm.support_perm; auto. auto. rewrite H0. destruct (Perm.support_axiom p (q x)). destruct (Perm.support_axiom q x). elim (H (q x)); auto. rewrite <- Perm.support_perm; auto. rewrite H2. auto. auto. Qed. (** Swappings commute with any permutation by applying the permuatation to the swapped atoms. *) Lemma swap_commute u w (p:perm) : (p u ⇋ p w) ∘ p ≈ p ∘ (u ⇋ w). Proof. hnf; simpl; intros. destruct (string_dec u x). destruct (string_dec (p u) (p x)); auto. elim n. rewrite e; auto. destruct (string_dec (p u) (p x)); auto. elim n. apply (Perm.f_inj p) in e. auto. destruct (string_dec w x). destruct (string_dec (p w) (p x)); auto. elim n1. rewrite e; auto. destruct (string_dec (p w) (p x)); auto. elim n1. apply (Perm.f_inj p) in e. auto. Qed. Lemma swap_commute' u w (p:perm) : (u ⇋ w) ∘ p ≈ p ∘ (p⁻¹ u ⇋ p⁻¹ w). Proof. rewrite <- swap_commute. simpl. rewrite Perm.fg. rewrite Perm.fg. reflexivity. Qed. (** Here we prove the swapping induction principles. The first decomposes a permutation on the left; the second decomposes on the right. These induction principles are proved by induction on the size of the support set of a permutation. At each step we can reduce the support by applying a swap. *) Require Import Arith. Lemma swap_induction (P:perm -> Prop) : (forall p p', p ≈ p' -> P p -> P p') -> P id -> (forall u v (p:perm), p u = u -> u <> v -> P p -> P (u ⇋ v ∘ p)) -> forall p, P p. Proof. intros Heq Hbase Hind. induction p using (induction_ltof1 perm (fun p => length (Perm.support p))). case_eq (Perm.support p); intros. apply Heq with id(tt). hnf; simpl. intro x. destruct (Perm.support_axiom p x); auto. rewrite H0 in H1. apply nil_elem in H1. elim H1. apply Hbase. set (f' x := (c ⇋ (p c)) (p x)). set (g' x := Perm.g p ((c ⇋ (p c)) x)). assert (Hgf : forall x, g' (f' x) = x). unfold g'; unfold f'. simpl. intro x. destruct (string_dec c (p x)). destruct (string_dec c (p c)). rewrite <- e0. rewrite e. apply Perm.gf. destruct (string_dec (p c) (p c)); auto. rewrite e. apply Perm.gf. elim n0; auto. destruct (string_dec (p c) (p x)); auto. destruct (string_dec c c); auto. rewrite e. apply Perm.gf. elim n0. auto. destruct (string_dec c (p x)). contradiction. destruct (string_dec (p c) (p x)); auto. contradiction. apply Perm.gf. assert (Hfg : forall x, f' (g' x) = x). unfold g'; unfold f'. simpl. intro x. destruct (string_dec c x). subst x. rewrite Perm.fg. destruct (string_dec (p c) (p c)). destruct (string_dec c (p c)); auto. elim n; auto. rewrite Perm.fg. destruct (string_dec (p c) x). rewrite e. destruct (string_dec c c); auto. elim n0. auto. destruct (string_dec c x); auto. contradiction. destruct (string_dec (p c) x); auto. contradiction. assert (Hsupport : forall v, v ∈ (l:finset atom) \/ f' v = v). intros. destruct (Perm.support_axiom p v); auto. rewrite H0 in H1. apply cons_elem in H1. destruct H1. right. apply atom_strong_eq in H1. subst v. unfold f'. simpl. destruct (string_dec (p c) (p c)). destruct (string_dec c (p c)); auto. elim n; auto. auto. right. unfold f'. simpl. rewrite H1. destruct (string_dec c v). subst v; auto. destruct (string_dec (p c) v). rewrite <- H1 in e. apply Perm.f_inj in e. auto. auto. set (p' := Perm.Perm tt tt f' g' l Hgf Hfg Hsupport : perm). destruct (string_dec c (p c)). apply Heq with p'. hnf; simpl. unfold f'; simpl; intros. destruct (string_dec c (p x)). rewrite <- e. rewrite <- e0. auto. destruct (string_dec (p c) (p x)). rewrite <- e0; auto. auto. apply H. hnf; simpl. rewrite H0. simpl. auto. apply Heq with (c ⇋ (p c) ∘ p'). hnf; simpl. intro x. unfold f'. simpl. destruct (string_dec c (p x)). destruct (string_dec c (p c)). rewrite <- e. rewrite <- e0. auto. rewrite <- e. destruct (string_dec (p c) (p c)); auto. elim n1; auto. destruct (string_dec (p c) (p x)); auto. destruct (string_dec c c); auto. elim n1. auto. destruct (string_dec (p c) (p x)); auto. contradiction. destruct (string_dec c (p x)). contradiction. auto. apply Hind. simpl. unfold f'. simpl. destruct (string_dec c (p c)); auto. destruct (string_dec (p c) (p c)); auto. elim n1; auto. auto. apply H. hnf; simpl. rewrite H0. simpl. auto. Qed. Lemma swap_induction' (P:perm -> Prop) : (forall p p', p ≈ p' -> P p -> P p') -> P id -> (forall u v (p:perm), p u = u -> u <> v -> P p -> P (p ∘ u ⇋ v)) -> forall p, P p. Proof. intros. apply swap_induction; auto. intros. apply H with (p0 ∘ (Perm.g p0 u) ⇋ (Perm.g p0 v)). 2: apply H1; auto. symmetry; apply swap_commute'. rewrite Perm.fg. rewrite <- H2 at 2. rewrite Perm.gf. auto. intro. apply Perm.g_inj in H5. elim H3; auto. Qed.
section "Kruskal Implementation" theory Kruskal_Impl imports Kruskal.Kruskal_Refine Refine_Imperative_HOL.IICF begin subsection \<open>Refinement III: concrete edges\<close> text \<open>Given a concrete representation of edges and their endpoints as a pair, we refine Kruskal's algorithm to work on these concrete edges.\<close> locale Kruskal_concrete = Kruskal_interface E V vertices joins forest connected weight for E V vertices joins forest connected and weight :: "'edge \<Rightarrow> int" + fixes \<alpha> :: "'cedge \<Rightarrow> 'edge" and endpoints :: "'cedge \<Rightarrow> ('a*'a) nres" assumes endpoints_refine: "\<alpha> xi = x \<Longrightarrow> endpoints xi \<le> \<Down> Id (a_endpoints x)" begin definition wsorted' where "wsorted' == sorted_wrt (\<lambda>x y. weight (\<alpha> x) \<le> weight (\<alpha> y))" lemma wsorted_map\<alpha>[simp]: "wsorted' s \<Longrightarrow> wsorted (map \<alpha> s)" by(auto simp: wsorted'_def sorted_wrt_map) definition "obtain_sorted_carrier' == SPEC (\<lambda>L. wsorted' L \<and> \<alpha> ` set L = E)" abbreviation concrete_edge_rel :: "('cedge \<times> 'edge) set" where "concrete_edge_rel \<equiv> br \<alpha> (\<lambda>_. True)" lemma obtain_sorted_carrier'_refine: "(obtain_sorted_carrier', obtain_sorted_carrier) \<in> \<langle>\<langle>concrete_edge_rel\<rangle>list_rel\<rangle>nres_rel" unfolding obtain_sorted_carrier'_def obtain_sorted_carrier_def apply refine_vcg apply (auto intro!: RES_refine simp: ) subgoal for s apply(rule exI[where x="map \<alpha> s"]) by(auto simp: map_in_list_rel_conv in_br_conv) done definition kruskal2 where "kruskal2 \<equiv> do { l \<leftarrow> obtain_sorted_carrier'; let initial_union_find = per_init V; (per, spanning_forest) \<leftarrow> nfoldli l (\<lambda>_. True) (\<lambda>ce (uf, T). do { ASSERT (\<alpha> ce \<in> E); (a,b) \<leftarrow> endpoints ce; ASSERT (a\<in>V \<and> b\<in>V \<and> a \<in> Domain uf \<and> b \<in> Domain uf ); if \<not> per_compare uf a b then do { let uf = per_union uf a b; ASSERT (ce \<notin> set T); RETURN (uf, T@[ce]) } else RETURN (uf,T) }) (initial_union_find, []); RETURN spanning_forest }" lemma lst_graph_rel_empty[simp]: "([], {}) \<in> \<langle>concrete_edge_rel\<rangle>list_set_rel" unfolding list_set_rel_def apply(rule relcompI[where b="[]"]) by (auto simp add: in_br_conv) lemma loop_initial_rel: "((per_init V, []), per_init V, {}) \<in> Id \<times>\<^sub>r \<langle>concrete_edge_rel\<rangle>list_set_rel" by simp lemma concrete_edge_rel_list_set_rel: "(a, b) \<in> \<langle>concrete_edge_rel\<rangle>list_set_rel \<Longrightarrow> \<alpha> ` (set a) = b" by (auto simp: in_br_conv list_set_rel_def dest: list_relD2) theorem kruskal2_refine: "(kruskal2, kruskal1)\<in>\<langle>\<langle>concrete_edge_rel\<rangle>list_set_rel\<rangle>nres_rel" unfolding kruskal1_def kruskal2_def Let_def apply (refine_rcg obtain_sorted_carrier'_refine[THEN nres_relD] endpoints_refine loop_initial_rel) by (auto intro!: list_set_rel_append dest: concrete_edge_rel_list_set_rel simp: in_br_conv) end subsection \<open>Refinement to Imperative/HOL with Sepref-Tool\<close> text \<open>Given implementations for the operations of getting a list of concrete edges and getting the endpoints of a concrete edge we synthesize Kruskal in Imperative/HOL.\<close> locale Kruskal_Impl = Kruskal_concrete E V vertices joins forest connected weight \<alpha> endpoints for E V vertices joins forest connected and weight :: "'edge \<Rightarrow> int" and \<alpha> and endpoints :: "nat \<times> int \<times> nat \<Rightarrow> (nat \<times> nat) nres" + fixes getEdges :: "(nat \<times> int \<times> nat) list nres" and getEdges_impl :: "(nat \<times> int \<times> nat) list Heap" and superE :: "(nat \<times> int \<times> nat) set" and endpoints_impl :: "(nat \<times> int \<times> nat) \<Rightarrow> (nat \<times> nat) Heap" assumes getEdges_refine: "getEdges \<le> SPEC (\<lambda>L. \<alpha> ` set L = E \<and> (\<forall>(a,wv,b)\<in>set L. weight (\<alpha> (a,wv,b)) = wv) \<and> set L \<subseteq> superE)" and getEdges_impl: "(uncurry0 getEdges_impl, uncurry0 getEdges) \<in> unit_assn\<^sup>k \<rightarrow>\<^sub>a list_assn (nat_assn \<times>\<^sub>a int_assn \<times>\<^sub>a nat_assn)" and max_node_is_Max_V: "E = \<alpha> ` set la \<Longrightarrow> max_node la = Max (insert 0 V)" and endpoints_impl: "( endpoints_impl, endpoints) \<in> (nat_assn \<times>\<^sub>a int_assn \<times>\<^sub>a nat_assn)\<^sup>k \<rightarrow>\<^sub>a (nat_assn \<times>\<^sub>a nat_assn)" begin lemma this_loc: "Kruskal_Impl E V vertices joins forest connected weight \<alpha> endpoints getEdges getEdges_impl superE endpoints_impl" by unfold_locales subsubsection \<open>Refinement IV: given an edge set\<close> text \<open>We now assume to have an implementation of the operation to obtain a list of the edges of a graph. By sorting this list we refine @{term obtain_sorted_carrier'}.\<close> definition "obtain_sorted_carrier'' = do { l \<leftarrow> SPEC (\<lambda>L. \<alpha> ` set L = E \<and> (\<forall>(a,wv,b)\<in>set L. weight (\<alpha> (a,wv,b)) = wv) \<and> set L \<subseteq> superE); SPEC (\<lambda>L. sorted_wrt edges_less_eq L \<and> set L = set l) }" lemma wsorted'_sorted_wrt_edges_less_eq: assumes "\<forall>(a,wv,b)\<in>set s. weight (\<alpha> (a,wv,b)) = wv" "sorted_wrt edges_less_eq s" shows "wsorted' s" using assms apply - unfolding wsorted'_def unfolding edges_less_eq_def apply(rule sorted_wrt_mono_rel ) by (auto simp: case_prod_beta) lemma obtain_sorted_carrier''_refine: "(obtain_sorted_carrier'', obtain_sorted_carrier') \<in> \<langle>Id\<rangle>nres_rel" unfolding obtain_sorted_carrier''_def obtain_sorted_carrier'_def apply refine_vcg apply(auto simp: in_br_conv wsorted'_sorted_wrt_edges_less_eq distinct_map map_in_list_rel_conv) done definition "obtain_sorted_carrier''' = do { l \<leftarrow> getEdges; RETURN (quicksort_by_rel edges_less_eq [] l, max_node l) }" definition "add_size_rel = br fst (\<lambda>(l,n). n= Max (insert 0 V))" lemma obtain_sorted_carrier'''_refine: "(obtain_sorted_carrier''', obtain_sorted_carrier'') \<in> \<langle>add_size_rel\<rangle>nres_rel" unfolding obtain_sorted_carrier'''_def obtain_sorted_carrier''_def apply (refine_rcg getEdges_refine) by (auto intro!: RETURN_SPEC_refine simp: quicksort_by_rel_distinct sort_edges_correct add_size_rel_def in_br_conv max_node_is_Max_V dest!: distinct_mapI) lemmas osc_refine = obtain_sorted_carrier'''_refine[FCOMP obtain_sorted_carrier''_refine, to_foparam, simplified] definition kruskal3 :: "(nat \<times> int \<times> nat) list nres" where "kruskal3 \<equiv> do { (sl,mn) \<leftarrow> obtain_sorted_carrier'''; let initial_union_find = per_init' (mn + 1); (per, spanning_forest) \<leftarrow> nfoldli sl (\<lambda>_. True) (\<lambda>ce (uf, T). do { ASSERT (\<alpha> ce \<in> E); (a,b) \<leftarrow> endpoints ce; ASSERT (a \<in> Domain uf \<and> b \<in> Domain uf); if \<not> per_compare uf a b then do { let uf = per_union uf a b; ASSERT (ce\<notin>set T); RETURN (uf, T@[ce]) } else RETURN (uf,T) }) (initial_union_find, []); RETURN spanning_forest }" lemma endpoints_spec: "endpoints ce \<le> SPEC (\<lambda>_. True)" by(rule order.trans[OF endpoints_refine], auto) lemma kruskal3_subset: shows "kruskal3 \<le>\<^sub>n SPEC (\<lambda>T. distinct T \<and> set T \<subseteq> superE )" unfolding kruskal3_def obtain_sorted_carrier'''_def apply (refine_vcg getEdges_refine[THEN leof_lift] endpoints_spec[THEN leof_lift] nfoldli_leof_rule[where I="\<lambda>_ _ (_, T). distinct T \<and> set T \<subseteq> superE "]) apply auto subgoal by (metis append_self_conv in_set_conv_decomp set_quicksort_by_rel subset_iff) subgoal by blast done definition per_supset_rel :: "('a per \<times> 'a per) set" where "per_supset_rel \<equiv> {(p1,p2). p1 \<inter> Domain p2 \<times> Domain p2 = p2 \<and> p1 - (Domain p2 \<times> Domain p2) \<subseteq> Id}" lemma per_supset_rel_dom: "(p1, p2) \<in> per_supset_rel \<Longrightarrow> Domain p1 \<supseteq> Domain p2" by (auto simp: per_supset_rel_def) lemma per_supset_compare: "(p1, p2) \<in> per_supset_rel \<Longrightarrow> x1\<in>Domain p2 \<Longrightarrow> x2\<in>Domain p2 \<Longrightarrow> per_compare p1 x1 x2 \<longleftrightarrow> per_compare p2 x1 x2" by (auto simp: per_supset_rel_def) lemma per_supset_union: "(p1, p2) \<in> per_supset_rel \<Longrightarrow> x1\<in>Domain p2 \<Longrightarrow> x2\<in>Domain p2 \<Longrightarrow> (per_union p1 x1 x2, per_union p2 x1 x2) \<in> per_supset_rel" apply (clarsimp simp: per_supset_rel_def per_union_def Domain_unfold ) apply (intro subsetI conjI) apply blast apply force done lemma per_initN_refine: "(per_init' (Max (insert 0 V) + 1), per_init V) \<in> per_supset_rel" unfolding per_supset_rel_def per_init'_def per_init_def max_node_def by (auto simp: less_Suc_eq_le ) theorem kruskal3_refine: "(kruskal3, kruskal2)\<in>\<langle>Id\<rangle>nres_rel" unfolding kruskal2_def kruskal3_def Let_def apply (refine_rcg osc_refine[THEN nres_relD] ) supply RELATESI[where R="per_supset_rel::(nat per \<times> _) set", refine_dref_RELATES] apply refine_dref_type subgoal by (simp add: add_size_rel_def in_br_conv) subgoal using per_initN_refine by (simp add: add_size_rel_def in_br_conv) by (auto simp add: add_size_rel_def in_br_conv per_supset_compare per_supset_union dest: per_supset_rel_dom simp del: per_compare_def ) subsubsection \<open>Synthesis of Kruskal by SepRef\<close> lemma [sepref_import_param]: "(sort_edges,sort_edges)\<in>\<langle>Id\<times>\<^sub>rId\<times>\<^sub>rId\<rangle>list_rel \<rightarrow>\<langle>Id\<times>\<^sub>rId\<times>\<^sub>rId\<rangle>list_rel" by simp lemma [sepref_import_param]: "(max_node, max_node) \<in> \<langle>Id\<times>\<^sub>rId\<times>\<^sub>rId\<rangle>list_rel \<rightarrow> nat_rel" by simp sepref_register "getEdges" :: "(nat \<times> int \<times> nat) list nres" sepref_register "endpoints" :: "(nat \<times> int \<times> nat) \<Rightarrow> (nat*nat) nres" declare getEdges_impl [sepref_fr_rules] declare endpoints_impl [sepref_fr_rules] schematic_goal kruskal_impl: "(uncurry0 ?c, uncurry0 kruskal3 ) \<in> (unit_assn)\<^sup>k \<rightarrow>\<^sub>a list_assn (nat_assn \<times>\<^sub>a int_assn \<times>\<^sub>a nat_assn)" unfolding kruskal3_def obtain_sorted_carrier'''_def unfolding sort_edges_def[symmetric] apply (rewrite at "nfoldli _ _ _ (_,rewrite_HOLE)" HOL_list.fold_custom_empty) by sepref concrete_definition (in -) kruskal uses Kruskal_Impl.kruskal_impl prepare_code_thms (in -) kruskal_def lemmas kruskal_refine = kruskal.refine[OF this_loc] txt \<open>These should probably be moved to \<^locale>\<open>Kruskal_interface\<close>'s initial usage in \<^theory>\<open>Kruskal.Kruskal\<close>...\<close> abbreviation (in Kruskal_interface) "MSF == minBasis" abbreviation (in Kruskal_interface) "SpanningForest == basis" lemmas (in Kruskal_interface) SpanningForest_def = basis_def lemmas (in Kruskal_interface) MSF_def = minBasis_def lemmas kruskal3_ref_spec_ = kruskal3_refine[FCOMP kruskal2_refine, FCOMP kruskal1_refine, FCOMP kruskal0_refine, FCOMP minWeightBasis_refine] lemma kruskal3_ref_spec': "(uncurry0 kruskal3, uncurry0 (SPEC (\<lambda>r. MSF (\<alpha> ` set r)))) \<in> unit_rel \<rightarrow>\<^sub>f \<langle>Id\<rangle>nres_rel" unfolding fref_def apply auto apply(rule nres_relI) apply(rule order.trans[OF kruskal3_ref_spec_[unfolded fref_def, simplified, THEN nres_relD]]) by (auto simp: conc_fun_def list_set_rel_def in_br_conv dest!: list_relD2) lemma kruskal3_ref_spec: "(uncurry0 kruskal3, uncurry0 (SPEC (\<lambda>r. distinct r \<and> set r \<subseteq> superE \<and> MSF (\<alpha> ` set r)))) \<in> unit_rel \<rightarrow>\<^sub>f \<langle>Id\<rangle>nres_rel" unfolding fref_def apply auto apply(rule nres_relI) apply simp using SPEC_rule_conj_leofI2[OF kruskal3_subset kruskal3_ref_spec' [unfolded fref_def, simplified, THEN nres_relD, simplified]] by simp lemma [fcomp_norm_simps]: "list_assn (nat_assn \<times>\<^sub>a int_assn \<times>\<^sub>a nat_assn) = id_assn" by (auto simp: list_assn_pure_conv) lemmas kruskal_ref_spec = kruskal_refine[FCOMP kruskal3_ref_spec] text \<open>The final correctness lemma for Kruskal's algorithm. \<close> lemma kruskal_correct_forest: shows "<emp> kruskal getEdges_impl endpoints_impl () <\<lambda>r. \<up>( distinct r \<and> set r \<subseteq> superE \<and> MSF (set (map \<alpha> r)))>\<^sub>t" proof - show ?thesis using kruskal_ref_spec[to_hnr] unfolding hn_refine_def apply clarsimp apply (erule cons_post_rule) by (sep_auto simp: hn_ctxt_def pure_def list_set_rel_def in_br_conv dest: list_relD) qed end \<comment> \<open>locale @{text Kruskal_Impl}\<close> end
options(tidyverse.quiet = TRUE) library(httr) library(xml2) library(ipaddress) library(jsonlite, include.only = c("fromJSON")) # nolint ; tho we're not using "flatten()" it can cause a name collision in other settings library(tidyverse) # all the providers have different ways of providing ranges. yay? aws <- jsonlite::fromJSON("https://ip-ranges.amazonaws.com/ip-ranges.json") tibble::tibble( cloud = "AWS", range = aws$prefixes$ip_prefix ) -> aws_ranges httr::GET( url = "https://www.microsoft.com/en-us/download/confirmation.aspx?id=56519", httr::user_agent( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4688.0 Safari/537.36 Edg/97.0.1069.0" # nolint ) ) %>% httr::content(as = "parsed", encoding = "UTF-8") %>% xml2::xml_find_all(".//a[contains(@class, 'failoverLink') and contains(@href,'download.microsoft.com/download/')]/@href") %>% # nolint xml2::xml_text() %>% jsonlite::fromJSON() -> azure tibble::tibble( cloud = "Azure", range = unlist(azure$values$properties$addressPrefixes) ) -> azure_ranges gcp <- jsonlite::fromJSON("https://www.gstatic.com/ipranges/cloud.json") tibble::tibble( cloud = "GCP", range = gcp$prefixes$ipv4Prefix ) -> gcp_ranges ora <- jsonlite::fromJSON("https://docs.cloud.oracle.com/en-us/iaas/tools/public_ip_ranges.json") # nolint tibble::tibble( cloud = "Oracle Cloud", range = unlist(purrr::map(ora$regions$cidrs, "cidr")) ) -> ora_ranges suppressMessages(readr::local_edition(1)) readr::read_csv( file = "http://digitalocean.com/geo/google.csv", col_names = c("range", "country", "region", "city", "postcode"), col_types = readr::cols( range = readr::col_character(), country = readr::col_character(), region = readr::col_character(), city = readr::col_character(), postcode = readr::col_character() )) -> digo tibble( cloud = "DigitalOcean", range = digo$range ) -> digo_ranges # Rackspace requires a bit more effort. You'll need an # IP2Location token (free) in an IP2LOCATION_TOKEN # environment variable. Delete any existin IP2Location # files for this part to kick in. They don't come with # the repo b/c of licensing and Rackspace will not be # included in the mmdb file if the files aren't present. # i.e. you should do one manual download of the ZIP file # and name it "ip2location-lite-asn.zip" in this directory. # # also, it won't be re-downloaded if the last download was # recent (within a week). if (file.exists("ip2location-lite-asn.zip")) { if (as.numeric(Sys.time() - file.info("ip2location-lite-asn.zip")$mtime, "days") >= 7) { httr::GET( url = "https://www.ip2location.com/download/", query = list( token = Sys.getenv("IP2LOCATION_TOKEN"), file = "DBASNLITE" ), httr::write_disk( path = "ip2location-lite-asn.zip", overwrite = TRUE ) ) -> res } unzip("ip2location-lite-asn.zip") readr::read_csv( file = "IP2LOCATION-LITE-ASN.CSV", col_names = c("from", "to", "cidr", "asn", "aso"), col_types = readr::cols( from = readr::col_double(), to = readr::col_double(), cidr = readr::col_character(), asn = readr::col_character(), aso = readr::col_character() ) ) -> ip2l ip2l %>% dplyr::filter( grepl("rackspace", aso, ignore.case = TRUE) ) %>% dplyr::select(range = cidr) %>% dplyr::mutate(cloud = "Rackspace") -> rack_ranges } else { rack_ranges = data.frame(range = character(0), cloud = character(0)) } # Put them all together and write it out dplyr::bind_rows( aws_ranges, azure_ranges, gcp_ranges, ora_ranges, digo_ranges, rack_ranges ) %>% dplyr::mutate( range = ipaddress::as_ip_network(range) ) %>% dplyr::filter( ipaddress::is_ipv4(range) ) %>% readr::write_csv("clouds.csv")
#!/usr/bin/env bash #= exec julia --project="$(realpath $(dirname $(dirname $0)))" --color=yes --startup-file=no -e "include(popfirst!(ARGS))" \ "${BASH_SOURCE[0]}" "$@" =# """ ```julia struct FinitePolynomial <: FiniteField ``` Has parameters `p`, which is an abstract polynomial, and `n` which is the modulus of the field under which the molynomial is defined. --- ```julia FinitePolynomial(p::AbstractPolynomial, n::Int) ``` A constructor method for `FinitePolynomial`. Takes in a polynomial `p` and a number `n`, and constructs a polynomial under modulo n. """ struct FinitePolynomial <: FiniteField p::AbstractPolynomial n::Int function FinitePolynomial(p::AbstractPolynomial, n::Int) p = Polynomial(mod.(p.coeffs, n)) new(p, n) end end """ ```julia mod(p::Polynomial, n::Int) -> Polynomial ``` Uses the `FinitePolynomial` constructor to return a polynomial `p` under modulus `n`. Parameters: - `p::Polynomial`: The input polynomial. - `n::Int`: The modulus of the field. Returns - Polynomial: A polynomial modulo n. """ Base.mod(p::Polynomial, n::Int) = FinitePolynomial(p, n).p """ ```julia Polynomial(A::Union{NTuple{N, T}, Vector{T}}, n::Int) -> Polynomial ``` Constructs a polynomial under modulo `n`. Parameters: - `A::Union{Tuple, AbstractArray}`: The polynomial coefficients. - `n::Int`: The modulus of the field. Returns - `Polynomial`: A polynomial modulo n. """ Polynomial(A::Union{NTuple{N, T}, Vector{T}}, n::Int) where {N, T} = mod(Polynomial(A), n) """ ```julia list_polys(n::Int, m::Int) -> Array ``` Lists all polynomials of degree less than to `n` under modulo `m`. Parameters: - `n::Int`: Highest degree of polynomial. - `m::Int`: The modulus of the field. Returns: - `Array`: An array of polynomials of degree less than n, under modulo m. """ function list_polys(n::Int, m::Int) return collect(Polynomial(collect(t)) for t in Iterators.product([0:(m-1) for i in 1:n]...)) end """ ```julia multiplication_table(degree::Int, modulo::Int) -> Matrix ``` Returns a table (matrix) of the multiplication of all combinations of polynomials for degree less than `degree`, under modulo `modulo`. Parameters: - `degree::Int`: Highest degree of polynomial. - `modulo::Int`: The modulus of the field. Returns: - `Matrix`: A multiplication table of all polynomials with degree less than n, under modulus. --- ### Examples ```julia julia> julia> multiplication_table(2, 3) # multiplication table of all polynomials of degree less than 3 modulo 2 9×9 Array{Polynomial,2}: Polynomial(0) Polynomial(0) Polynomial(0) … Polynomial(0) Polynomial(0) Polynomial(0) Polynomial(1) Polynomial(2) Polynomial(1 + 2*x) Polynomial(2 + 2*x) Polynomial(0) Polynomial(2) Polynomial(1) Polynomial(2 + x) Polynomial(1 + x) Polynomial(0) Polynomial(x) Polynomial(2*x) Polynomial(x + 2*x^2) Polynomial(2*x + 2*x^2) Polynomial(0) Polynomial(1 + x) Polynomial(2 + 2*x) Polynomial(1 + 2*x^2) Polynomial(2 + x + 2*x^2) Polynomial(0) Polynomial(2 + x) Polynomial(1 + 2*x) … Polynomial(2 + 2*x + 2*x^2) Polynomial(1 + 2*x^2) Polynomial(0) Polynomial(2*x) Polynomial(x) Polynomial(2*x + x^2) Polynomial(x + x^2) Polynomial(0) Polynomial(1 + 2*x) Polynomial(2 + x) Polynomial(1 + x + x^2) Polynomial(2 + x^2) Polynomial(0) Polynomial(2 + 2*x) Polynomial(1 + x) Polynomial(2 + x^2) Polynomial(1 + 2*x + x^2) ``` """ function multiplication_table(degree::Int, modulo::Int) polys = list_polys(degree, modulo) number_of_polys = length(polys) poly_matrix = Matrix{Polynomial}(undef, number_of_polys, number_of_polys) for i in 1:number_of_polys, j in 1:number_of_polys poly_matrix[i,j] = mod(polys[i] * polys[j], modulo) end return poly_matrix end function __list_span_inner(modulo::Int, u̲::Vector{T}...) where T <: Number n_vec = length(u̲) span = Vector{T}[zero(u̲[1])] for n in 1:n_vec new_span = copy(span) for v in span, λ in 1:(modulo - 1) w̲ = mod.(v + λ * u̲[n], modulo) if w̲ ∉ new_span push!(new_span, w̲) end end span = new_span end return span end """ ```julia list_span(u̲::Vector, v̲::Vector,... modulo::Int) -> Array ``` Given any number of vectors `u̲`, `v̲`,... , prints all linear combinations of those vectors, modulo `modulo`. Parameters: - `u̲::Vector`: One vector. - `v̲::Vector`: Another vector. - `...`: Other vectors. - `modulo::Int`: The modulus of the field. Returns: - `Array`: All vectors in the span of u̲ and v̲, under modulo. --- ### Examples ```julia julia> list_span([2, 1, 1], [1, 1, 1], 3) # list the span of two vectors modulo 3 9-element Array{Array{T,1} where T,1}: [0, 0, 0] [1, 1, 1] [2, 2, 2] [2, 1, 1] [0, 2, 2] [1, 0, 0] [1, 2, 2] [2, 0, 0] [0, 1, 1] ``` """ list_span(args...) = __list_span_inner(last(args), args[1:end-1]...) """ ```julia islinear(C::Vector, modulo::Int; verbose::Bool = false) -> Bool ``` Determines whether a code `C` is a linear code (i.e., if it is closed under addition, scalar multiplication, and has the zero vector in it). Parameters: - `C::Vector`: A code, typically consisting of multiple vectors or strings. - `modulo::Int`: The modulus of the field under which you are working. - `verbose::Bool` (kwarg): print the point at which C fails, if it does. Returns: - `Bool`: Whether or not the code `C` is linear (true or false). --- ### Examples ```julia julia> islinear([[0,0,0],[1,1,1],[1,0,1],[1,1,0]], 2) # checks whether a vector of vectors is linear/a subspace (modulo 2) false ``` """ function islinear(C::Vector, modulo::Int; verbose::Bool = false) allequal_length(C) || return false # not all codes are of the same length block_length = length(C[1]) 𝟎 = fill(0, block_length) if 𝟎 ∉ C verbose && println("The zero vector 0̲ is not in C.\n") return false # the zero vector is not in the code end for c̲ ∈ C for λ in 0:modulo-1 if mod.(λ*c̲, modulo) ∉ C verbose && println(λ, " ⋅ ", c̲, " = ", mod.(λ*c̲, modulo), " ∉ C\n") return false # this code isn't closed under scalar multiplication end end for c̲ ∈ C, c̲′ ∈ C if c̲ ≠ c̲′ if mod.(c̲ + c̲′, modulo) ∉ C verbose && println(c̲, " + ", c̲′, " = ", mod.(c̲ + c̲′, modulo), " ∉ C\n") return false # this code isn't closed under addition end end end end verbose && println() return true end """ ```julia isirreducible(f::AbstractPolynomial, modulo::Int) -> Bool ``` Checks if a polynomial is irreducible. Parameters: - `f::Polynomial`: The polynomial you need to check. - `modulo::Int`: The modulus under which you are working. Returns: - `Bool`: Whether or not the polynomial is irreducible (true or false). --- ### Examples ```julia julia> isirreducible(Polynomial([1, 1, 0, 0, 1]), 2) # is 1 + x + x^4 mod 2 irreducible? true ``` """ function isirreducible(f::Polynomial, modulo::Int) deg = length(f.coeffs) - 1 f = mod(f, deg) polys = list_polys(deg, modulo) for a in polys, b in polys isequal(f, mod(a*b, modulo)) && return false end return true end """ ```julia normal_form!(M::AbstractArray{Int}, n::Int) -> Matrix{Int} ``` Convert a matrix M into normal form under modulo n via Gauss-Jordan elimination. *This directly changes the matrix M. Use `normal_form` for a non-mutating version of this function.* Parameters: - `M::AbstractArray{Int}`: A matrix of Ints. - `n::Int`: The modulus of the finite field. Returns: - `Matrix{Int}`: A matrix in normal form from Gauss-Jordan elimination. --- ### Examples ```julia julia> normal_form!([1 2 0 1 2 1 2; 2 2 2 0 1 1 1; 1 0 1 1 2 1 2; 0 1 0 1 1 2 2], 3) # computes rref colswap = false 4×7 Array{Int64,2}: 1 0 0 0 2 2 2 0 1 0 0 2 0 1 0 0 1 0 1 0 2 0 0 0 1 2 2 1 ``` """ function normal_form!(M::AbstractArray{Int}, n::Int) return rref!(M, n, colswap = false) end """ ```julia normal_form(M::AbstractArray{Int}, n::Int) -> Matrix{Int} ``` Convert a matrix M into normal form under modulo n via Gauss-Jordan elimination. Parameters: - `M::AbstractArray{Int}`: A matrix of Ints. - `n::Int`: The modulus of the finite field. Returns: - `Matrix{Int}`: A matrix in normal form from Gauss-Jordan elimination. --- ### Examples ```julia julia> normal_form([1 2 0 1 2 1 2; 2 2 2 0 1 1 1; 1 0 1 1 2 1 2; 0 1 0 1 1 2 2], 3) # computes rref colswap = false 4×7 Array{Int64,2}: 1 0 0 0 2 2 2 0 1 0 0 2 0 1 0 0 1 0 1 0 2 0 0 0 1 2 2 1 ``` """ function normal_form(M::AbstractArray{Int}, n::Int) normal_form!(copy(M), n) end """ ```julia equivalent_code!(M::AbstractArray{Int}, n::Int) -> Matrix{Int} ``` Peforms Gauss-Jordan elimination on a matrix M, but allows for column swapping. This constructs an "equivalent" matrix. *This directly changes the matrix M. Use `equivalent_code` for a non-mutating version of this function.* Parameters: - `M::AbstractArray{Int}`: A matrix of Ints. - `n::Int`: The modulus of the finite field. Returns: - `Matrix{Int}`: A which represents an "equivalent" code to that of the matrix M. --- ### Examples ```julia julia> equivalent_code!([1 2 0 1 2 1 2; 2 2 2 0 1 1 1; 1 0 1 1 2 1 2; 0 1 0 1 1 2 2], 3) # computes rref colswap = true 4×7 Array{Int64,2}: 1 0 0 0 2 2 2 0 1 0 0 2 0 1 0 0 1 0 1 0 2 0 0 0 1 2 2 1 ``` """ function equivalent_code!(M::AbstractArray{Int}, n::Int) return rref!(M, n, colswap=true) end """ ```julia equivalent_code(M::AbstractArray{Int}, n::Int) -> Matrix{Int} ``` Peforms Gauss-Jordan elimination on a matrix M, but allows for column swapping. Parameters: - `M::AbstractArray{Int}`: A matrix of Ints. - `n::Int`: The modulus of the finite field. Returns: - `Matrix{Int}`: A which represents an "equivalent" code to that of the matrix M. --- ### Examples ```julia julia> equivalent_code([1 2 0 1 2 1 2; 2 2 2 0 1 1 1; 1 0 1 1 2 1 2; 0 1 0 1 1 2 2], 3) # computes rref colswap = true 4×7 Array{Int64,2}: 1 0 0 0 2 2 2 0 1 0 0 2 0 1 0 0 1 0 1 0 2 0 0 0 1 2 2 1 ``` """ function equivalent_code(M::AbstractArray{Int}, n::Int) equivalent_code!(copy(M), n) end """ ```julia generator!(M::AbstractArray{Int}, n::Int; colswap::Bool = true) -> Matrix{Int} ``` Constructs a generator matrix of the code, depending on if you allow for column swapping or not. This function uses `normal_form!` or `equivalent_code!`. *This directly changes the matrix M. Use `generator` for a non-mutating version of this function.* Parameters: - `M::AbstractArray{Int}`: A matrix of Ints. - `n::Int`: The modulus of the finite field. - `colswap::Bool` (kwarg): A boolean flag indicating whether or not you allow for swapping of columns when constructing the generating matrix. Returns: - `Matrix{Int}`: A generating matrix. """ function generator!(M::AbstractArray{Int}, n::Int; colswap::Bool = false) return ifelse(colswap, equivalent_code!(M, n), normal_form!(M, n)) end """ ```julia generator(M::AbstractArray{Int}, n::Int; colswap::Bool = true) -> Matrix{Int} ``` Constructs a generator matrix of the code, depending on if you allow for column swapping or not. This function uses `normal_form` or `equivalent_code`. Parameters: - `M::AbstractArray{Int}`: A matrix of Ints. - `n::Int`: The modulus of the finite field. - `colswap::Bool` (kwarg): A boolean flag indicating whether or not you allow for swapping of columns when constructing the generating matrix. Returns: - `Matrix{Int}`: A generating matrix. """ function generator(M::AbstractArray{Int}, n::Int; colswap::Bool = true) generator!(copy(M), n, colswap=colswap) end """ ```julia parity_check(M::AbstractArray{Int}, n::Int) -> Matrix{Int} ``` Constructs a parity check matrix. This is calculated from taking the non-identity part of a matrix in normal form (or equivalent &mdash; see `generator`), transposing it, multiplying it by negative one, and appending to it an appropriate sized identity matrix. Parameters: - `M::AbstractArray{Int}`: A matrix of Ints. - `n::Int`: The modulus of the finite field. Returns: - `Matrix{Int}`: A parity check matrix. """ function parity_check(M::AbstractArray{Int}, n::Int) has_identity_on_left(M) || throw(error("This matrix is not in normal form. Use normal_form or equivalent_code.")) minus_Dᵀ = mod.(-one(Int) .* transpose(M[:, (size(M, 1) + 1):end]), n) return H = Int[minus_Dᵀ I(size(minus_Dᵀ, 1))] end """ ```julia syndrome(v̲::Vector, Hᵀ::AbstractArray{Int}, n::Int) -> Matrix{Int} ``` Calculates the syndrome of a given word v̲ and a parity check matrix, transposed (Hᵀ), under modulo n. Parameters: - `v̲::Vector`: A word in the code. - `Hᵀ::AbstractArray{Int}`: The transpose of a parity check matrix. Returns: - `Vector`: The syndrome of a word in the code. --- ### Examples ```julia julia> syndrome([0, 2, 1, 2, 0, 1, 0], [1 1 1; 1 0 2; 2 0 1; 1 1 2; 1 0 0; 0 1 0; 0 0 1], 3) 1×3 Array{Int64,2}: 0 0 0 julia> syndrome([0, 2, 1, 2, 0, 1, 0], transpose(parity_check([1 0 0 0 2 2 2; 0 1 0 0 2 0 1; 0 0 1 0 1 0 2; 0 0 0 1 2 2 1], 3)), 3) 1×3 Array{Int64,2}: 0 0 0 ``` """ function syndrome(v̲::Vector, Hᵀ::AbstractArray{Int}, n::Int) return mod.(v̲' * Hᵀ, n) end """ ```julia isincode(v̲::Vector, Hᵀ::AbstractArray{Int}, n::Int) -> Bool ``` If the syndrome of a code is the zero vector, then the word used to calculate the syndrome is in the code. Parameters: - `v̲::Vector`: A word. - `Hᵀ::AbstractArray{Int}`: The transpose of a parity check matrix. Returns: - `Bool`: If the word is in the code or not (true or false). --- ### Examples ```julia julia> isincode([0, 2, 1, 2, 0, 1, 0], transpose(parity_check([1 0 0 0 2 2 2; 0 1 0 0 2 0 1; 0 0 1 0 1 0 2; 0 0 0 1 2 2 1], 3)), 3) # tests if the syndrome is equal to the zero vector, and is thus in the code true ``` """ function isincode(v̲::Vector, Hᵀ::AbstractArray{Int}, n::Int) return iszero(syndrome(v̲, Hᵀ, n)) end
universe u v def Slices (A : Type u) : Type u := Array $ Subarray A def slice {A : Type u} (as : Array A) (ranges : Array ((Fin (as.size + 1)) × (Fin (as.size+1)))) : Slices A := Array.map (fun (start, stop) => as.toSubarray start.val stop.val ) ranges /- Bounded Nat -/ -- def BNat (min max : Nat) (h : min ≤ max) := {n : Fin (max + 1) // GE.ge n.val min } structure BNat (min max : Nat) (isMinMax : LE.le min max)where val : Nat isLe : LE.le val max isGe : GE.ge val min -- def BNat.mk {min max : Nat} {h : min ≤ max} (n : Nat) (h1 : LE.le n max) (h2 : GE.ge n min) : BNat min max h := -- let f : Fin (max + 1) := ⟨n, by -- rw [Nat.add_one] -- apply Nat.lt_succ_of_le -- apply h1 -- ⟩ -- ⟨f, by apply h2⟩ @[simp] theorem ge_is_le (n m : Nat) : n ≥ m → m ≤ n := by intro h exact h @[simp] theorem ge_refl (n : Nat) : n ≥ n := by apply ge_is_le; apply Nat.le_refl instance {min max} {h : min ≤ max}: Inhabited (BNat min max h) := ⟨BNat.mk min h (by simp)⟩ instance Nat_toBNat {min max n : Nat} {h : min ≤ max} (h1 : LE.le n max ∧ GE.ge n min) : OfNat (BNat min max h) n := ⟨BNat.mk n h1.left h1.right⟩ theorem BNat.eq_of_val_eq {max min} {h : min ≤ max} : ∀ {i j : BNat min max h}, Eq i.val j.val → Eq i j | ⟨v, lt, gt⟩, ⟨_, _, _⟩, rfl => rfl theorem BNat.val_eq_of_eq {max min} {h1 : min ≤ max} {i j : BNat min max h1} (h : Eq i j) : Eq i.val j.val := h ▸ rfl theorem BNat.ne_of_val_ne {max min} {h1 : min ≤ max} {i j : BNat min max h1} (h : Not (Eq i.val j.val)) : Not (Eq i j) := fun h' => absurd (val_eq_of_eq h') h @[simp] theorem BNat.succ_le {max min} {h1 : min ≤ max} (n : BNat min max h1) (h : n.val < max): Nat.succ n.val ≤ max := h instance (max min : Nat) (h1 : min ≤ max): DecidableEq (BNat min max h1) := fun i j => match decEq i.val j.val with | isTrue h => isTrue (BNat.eq_of_val_eq h) | isFalse h => isFalse (BNat.ne_of_val_ne h) instance {min max} {h : min ≤ max} : LT (BNat min max h) where lt a b := LT.lt a.val b.val instance {min max} {h : min ≤ max} : LE (BNat min max h) where le a b := LE.le a.val b.val instance BNat.decLt {min max} {h : min ≤ max} (a b : BNat min max h) : Decidable (LT.lt a b) := Nat.decLt .. instance BNat.decLe {min max} {h : min ≤ max} (a b : BNat min max h) : Decidable (LE.le a b) := Nat.decLe .. theorem range_terminates {min max} {h : min ≤ max} (n : BNat min max h): max - Nat.succ n.val ≤ max - n.val := by sorry @[inline] def BNat.range {min max} {h' : min ≤ max} : List $ BNat min max h' := let rec @[specialize] it : BNat min max h' → (List $ BNat min max h') := (λ n => if h : n.val < max then List.cons n $ it { val := Nat.succ n.val , isLe := (by apply h) , isGe := (by apply ge_is_le apply Nat.le_of_lt apply Nat.lt_succ_of_le apply n.isGe ) } else [BNat.mk n.val (by apply n.isLe) n.isGe] ) it (BNat.mk min h' (by apply ge_refl)) termination_by measure λ b => b.snd.fst - b.snd.snd.snd.val decreasing_by exact ⟨range_terminates⟩ @[simp] theorem add_le_cancel_right (m n k: Nat) : m ≤ n → m + k ≤ n + k := by intro h' apply Nat.add_le_add_right apply h' @[simp] theorem mul_ge_one_of_ge_one {a b c : Nat} (ha : a ≥ c ) (hb : b ≥ 1) : a * b ≥ c := --have h1 := Nat.le_refl a ▸ apply ha -- inductive a hs -- induction a-1 with -- | zero => -- apply ha -- | succ n => -- apply ha -- calc -- ha -- ... = a * 1 : (mul_one a).symm -- ... ≤ a * b : mul_le_mul_left' hb a by sorry -- rw [Nat.mul_le_mul] -- rw [] -- ) it -- instance (b : BNat min max) : Sub Nat b := @[simp] theorem one_le_size {h w : Nat} (ax : h ≥ 1 ∧ w ≥ 1) : 1 ≤ h * w := by apply mul_ge_one_of_ge_one apply ax.left apply ax.right
This 2-Burner Cooktop Griddle is safe for use on gas and electric cooktops and ranges, even those with a smooth glass surface. Fits over two burners/elements to expand cooking surface. Commercial-grade, cast aluminum surface conducts heat quickly and evenly. 2-Burner Cooktop Griddle is rated 5.0 out of 5 by 1. Rated 5 out of 5 by Donnier from Best griddle made I bought this 12 years ago and is steal working excellently and looks good. I have cooked hash-browns, bacon, grilled cheese sandwiches, pan-cakes 4 to 5 at a time. My family is getting bigger now with grand kids and I can't make the pan-cakes fast enough and that's why I am getting another Griddle.
State Before: n k : ℕ h : k < n ⊢ (n - k) * ascFactorial (n - k) k = ascFactorial (n - (k + 1)) (k + 1) State After: n k : ℕ h : k < n t : ℕ := n - succ k ⊢ (n - k) * ascFactorial (n - k) k = ascFactorial (n - (k + 1)) (k + 1) Tactic: let t := n - k.succ State Before: n k : ℕ h : k < n t : ℕ := n - succ k ⊢ (n - k) * ascFactorial (n - k) k = ascFactorial (n - (k + 1)) (k + 1) State After: n k : ℕ h : k < n t : ℕ := n - succ k ht : t = n - succ k := rfl ⊢ (n - k) * ascFactorial (n - k) k = ascFactorial (n - (k + 1)) (k + 1) Tactic: let ht : t = n - k.succ := rfl State Before: n k : ℕ h : k < n t : ℕ := n - succ k ht : t = n - succ k := rfl ⊢ (n - k) * ascFactorial (n - k) k = ascFactorial (n - (k + 1)) (k + 1) State After: n k : ℕ h : k < n t : ℕ := n - succ k ht : t = n - succ k := rfl h' : n - k = succ t ⊢ (n - k) * ascFactorial (n - k) k = ascFactorial (n - (k + 1)) (k + 1) case h' n k : ℕ h : k < n t : ℕ := n - succ k ht : t = n - succ k := rfl ⊢ n - k = succ t Tactic: suffices h' : n - k = t.succ State Before: case h' n k : ℕ h : k < n t : ℕ := n - succ k ht : t = n - succ k := rfl ⊢ n - k = succ t State After: no goals Tactic: rw [ht, succ_eq_add_one, ← tsub_tsub_assoc (succ_le_of_lt h) (succ_pos _), succ_sub_one] State Before: n k : ℕ h : k < n t : ℕ := n - succ k ht : t = n - succ k := rfl h' : n - k = succ t ⊢ (n - k) * ascFactorial (n - k) k = ascFactorial (n - (k + 1)) (k + 1) State After: no goals Tactic: rw [← ht, h', succ_ascFactorial, ascFactorial_succ]
#include <boost/spirit/home/karma/operator/kleene.hpp>
lemma convex_halfspace_abs_le: "convex {x. \<bar>inner a x\<bar> \<le> b}"
using FactCheck facts("First facts group") do @fact 1 --> 1 "First group first test" @fact 2 --> 1 "First group second failing test" end facts("Second facts group") do @fact 1 --> 1 "Second group first test" @fact 2 --> 2 #Nameless fact end facts() do #Nameless group @fact 1 --> 1 #Nameless fact @fact 2 --> 1 #Failing nameless fact in nameless group end facts() do end
module Processor import Hardware incPC : Memory -> Memory incPC m = updtRD PC (1 + toRD PC m) m getInstruction : Int -> Memory -> Instruction getInstruction 0 (MkMemory regs' (instr :: asm')) = instr getInstruction i (MkMemory regs' (instr :: asm')) = getInstruction (i - 1) (MkMemory regs' asm') outOfBounds : Int -> Memory -> Bool outOfBounds i (MkMemory regs' instrs) = cast i >= length instrs export evaluator : Memory -> Memory evaluator mem = if outOfBounds (pc $ regs mem) mem then mem else case getInstruction (pc $ regs mem) mem of ADD r r' r'' => evaluator $ incPC $ (updtRD r ((toRD r' mem) + (toRD r'' mem)) mem) -- SHA3 : Register -> Register -> ISA ADDRESS r => evaluator $ incPC mem -- todo LOAD r r' => evaluator $ incPC mem -- todo JUMPI r i => evaluator $ updtRD PC ((if (toRD r mem) == 0 then 1 else i) + toRD PC mem) mem EQUAL r r' r'' => evaluator $ incPC $ updtRD r (if (toRD r' mem) == (toRD r'' mem) then 1 else 0) mem NOT r r' => evaluator $ incPC $ updtRD r (if (toRD r' mem) == 0 then 1 else 0) mem STOP => mem -- todo DATA i => mem -- todo
from __future__ import division from __future__ import absolute_import import os.path as osp import scipy.io as sio from .utils import (load, make_abs_path) _base_dir = make_abs_path(__file__, '../configs') _key_pts = load(osp.join(_base_dir, 'keypoints_sim.npy')) w_shp = load(osp.join(_base_dir, 'w_shp_sim.npy')) w_exp = load(osp.join(_base_dir, 'w_exp_sim.npy')) # simplified version _param_meta = load(osp.join(_base_dir, 'param_whitening.pkl')) # param_mean and param_std are used for re-whitening param_mean = _param_meta.get('param_mean') param_std = _param_meta.get('param_std') u_shp = load(osp.join(_base_dir, 'u_shp.npy')) u_exp = load(osp.join(_base_dir, 'u_exp.npy')) u = u_shp + u_exp # w = np.concatenate((w_shp, w_exp), axis=1) # w_base = w[keypoints] # w_norm = np.linalg.norm(w, axis=0) # w_base_norm = np.linalg.norm(w_base, axis=0) # for inference # dim = w_shp.shape[0] // 3 u_base = u[_key_pts].reshape(-1, 1) w_shp_base = w_shp[_key_pts] w_exp_base = w_exp[_key_pts] std_size = 120 # for the refined mesh _param_mesh = sio.loadmat(osp.join(_base_dir, 'param_mesh.mat')) w_shp = _param_mesh['w'][:, 0:40] w_exp = _param_mesh['w_exp'][:, 0:10] u = _param_mesh['mu_shape'] + _param_mesh['mu_exp'] tri = _param_mesh['tri']
lemma holomorphic_uniform_limit: assumes cont: "eventually (\<lambda>n. continuous_on (cball z r) (f n) \<and> (f n) holomorphic_on ball z r) F" and ulim: "uniform_limit (cball z r) f g F" and F: "\<not> trivial_limit F" obtains "continuous_on (cball z r) g" "g holomorphic_on ball z r"
#define BOOST_TEST_MODULE test_standard_license #include <boost/test/unit_test.hpp> #include <boost/filesystem.hpp> #include "../../src/tools/license-generator/license-generator.h" #include "../../src/library/api/license++.h" #include <build_properties.h> #include "../../src/library/ini/SimpleIni.h" #include "generate-license.h" #include "../../src/library/base/FileUtils.hpp" namespace test { namespace fs = boost::filesystem; using namespace license; using namespace std; BOOST_AUTO_TEST_CASE( standard_lic_file ) { const string licLocation(PROJECT_TEST_TEMP_DIR "/standard_license.lic"); const vector<string> extraArgs; generate_license(licLocation, extraArgs); /* */ LicenseInfo license; LicenseLocation licenseLocation; licenseLocation.licenseFileLocation = licLocation.c_str(); licenseLocation.licenseData = nullptr; const EVENT_TYPE result = acquire_license("TEST", &licenseLocation, &license); BOOST_CHECK_EQUAL(result, LICENSE_OK); BOOST_CHECK_EQUAL(license.has_expiry, false); BOOST_CHECK_EQUAL(license.linked_to_pc, false); } /** * Pass the license data to the application. */ BOOST_AUTO_TEST_CASE( b64_environment_variable ) { const string licLocation(PROJECT_TEST_TEMP_DIR "/standard_env_license.lic"); const vector<string> extraArgs; generate_license(licLocation, extraArgs); const string licensestr(license::get_file_contents(licLocation.c_str(), MAX_LICENSE_LENGTH)); /* */ LicenseInfo license; LicenseLocation licenseLocation; licenseLocation.licenseFileLocation = nullptr; licenseLocation.licenseData = licensestr.c_str(); const EVENT_TYPE result = acquire_license("TEST", &licenseLocation, &license); BOOST_CHECK_EQUAL(result, LICENSE_OK); BOOST_CHECK_EQUAL(license.has_expiry, false); BOOST_CHECK_EQUAL(license.linked_to_pc, false); } BOOST_AUTO_TEST_CASE( pc_identifier ) { const string licLocation(PROJECT_TEST_TEMP_DIR "/pc_identifier.lic"); const vector<string> extraArgs = { "-s", "Jaaa-aaaa-MG9F-ZhB1" }; generate_license(licLocation, extraArgs); LicenseInfo license; LicenseLocation licenseLocation; licenseLocation.licenseFileLocation = licLocation.c_str(); licenseLocation.licenseData = ""; const EVENT_TYPE result = acquire_license("TEST", &licenseLocation, &license); BOOST_CHECK_EQUAL(result, IDENTIFIERS_MISMATCH); BOOST_CHECK_EQUAL(license.has_expiry, false); BOOST_CHECK_EQUAL(license.linked_to_pc, true); } }
During this time , Zhou Tong also has an additional disciple named Wu Song . Wu Song becomes famous for killing a man @-@ eating tiger with his bare hands and is appointed as a constable in his native Shandong . The county magistrate Sun <unk> later sends Wu on a mission to Kaifeng with precious tiger bone balm in order to curry favor with influential personages . During his stay in the capital , he makes the acquaintance of Zhou . Zhou finds Wu to be a man of great strength , but feels that he lacks refinement in his martial technique and , therefore , offers guidance for Wu 's training . Unfortunately , these two men only interact for a brief two months before Wu has to return home , never to see Zhou again .
Formal statement is: lemma exp_two_pi_i [simp]: "exp (2 * of_real pi * \<i>) = 1" Informal statement is: $e^{2\pi i} = 1$.
[STATEMENT] lemma (in Group) lcsTr6:"\<lbrakk>G \<guillemotright> H; a \<in> carrier G; b \<in> carrier G; (\<rho> a) \<cdot> b \<in> H; x \<in> a \<diamondsuit> H\<rbrakk> \<Longrightarrow> x \<in> b \<diamondsuit> H" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>G \<guillemotright> H ; a \<in> carrier G; b \<in> carrier G; \<rho> a \<cdot> b \<in> H; x \<in> a \<diamondsuit> H\<rbrakk> \<Longrightarrow> x \<in> b \<diamondsuit> H [PROOF STEP] by (frule lcsTr5[of "H" "a" "b" "x"], assumption+, subst lcs_mem_ldiv, assumption+, rule mem_lcs, assumption+)
statesInfo <- read.csv('stateData.csv') subset(statesInfo, state.region == 1) stateSubset <- statesInfo[statesInfo$illiteracy == 0.5, ] dim(stateSubset) str(stateSubset) stateSubset
-- Andreas, 2013-09-17 catches a bug in constraint solving -- with meta-variables applied to underapplied record constructors -- {-# OPTIONS --show-implicit -v tc.meta.assign:50 -v tc.conv.elim:30 #-} module Issue889 where record Monad (M : Set → Set) : Set₁ where field return : ∀ {A} → A → M A _>>=_ : ∀ {A} {B : M A → Set} (m : M A) → ((x : A) → M (B (return x))) → M (B m) record Σ (A : Set) (B : A → Set) : Set where constructor _,_ field proj₁ : A proj₂ : B proj₁ _×_ : (A B : Set) → Set A × B = Σ A λ _ → B State : Set → Set → Set State S X = S → X × S -- Here is the underapplied record constructor -- (made underapplied by eta-contraction, resp.). state-return : ∀ {S X} → X → State S X state-return x = _,_ x -- λ s → x , s -- When giving the @_>>=_@ function to the record goal we get: -- -- An internal error has occurred. Please report this as a bug. -- Location of the error: src/full/Agda/TypeChecking/Conversion.hs:524 state-monad : ∀ {S} → Monad (State S) state-monad {S} = record { return = state-return; _>>=_ = {!_>>=_!} } where postulate _>>=_ : ∀ {A} {B : State S A → Set} (m : State S A) → ((x : A) → State S (B (state-return x))) → State S (B m) -- Bug arises when checking -- _B (state-return x) = B (state-return x) -- _B (_,_ x) = B (_,_ x) -- then Agda does something special for record constructors -- [Miller unification in the presence of records] -- (now only done for FULLY APPLIED record constructors!) -- and produces some garbage solution for _B. ------------------------------------------------------------------------ -- Note that if we define the product type using data instead of -- record then it works: data _×′_ (A B : Set) : Set where _,_ : A → B → A ×′ B State′ : Set → Set → Set State′ S X = S → X ×′ S state-return′ : ∀ {S X} → X → State′ S X state-return′ x = λ s → x , s state-monad′ : ∀ {S} → Monad (State′ S) state-monad′ {S} = record { return = state-return′; _>>=_ = _>>=_ } where postulate _>>=_ : ∀ {A} {B : State′ S A → Set} (m : State′ S A) → ((x : A) → State′ S (B (state-return′ x))) → State′ S (B m)
type FigureFigure{T<:Integer} r::Array{T,1} rnmax::T snmax::T snext::T end function grow!{T<:Integer}(ff::FigureFigure{T}, rnmax::T=100) ff.rnmax < rnmax || return nothing append!(ff.r, zeros(T, (rnmax-ff.rnmax))) snext = ff.snext for i in (ff.rnmax+1):rnmax ff.r[i] = ff.r[i-1] + snext snext += 1 while snext in ff.r snext += 1 end end ff.rnmax = rnmax ff.snmax = ff.r[end] - rnmax ff.snext = snext return nothing end function FigureFigure{T<:Integer}(rnmax::T=10) ff = FigureFigure([1], 1, 0, 2) grow!(ff, rnmax) return ff end function FigureFigure{T<:Integer}(rnmax::T, snmax::T) ff = FigureFigure(rnmax) while ff.snmax < snmax grow!(ff, 2ff.rnmax) end return ff end function make_ffr{T<:Integer}(nmax::T=10) ff = FigureFigure(nmax) function ffr{T<:Integer}(n::T) if n > ff.rnmax grow!(ff, 2n) end ff.r[n] end end function make_ffs{T<:Integer}(nmax::T=100) ff = FigureFigure(13, nmax) function ffs{T<:Integer}(n::T) while ff.snmax < n grow!(ff, 2ff.rnmax) end s = n for r in ff.r r <= s || return s s += 1 end end end
#! /usr/bin/env python2 ############################################################ # Program is part of PySAR v1.0 # # Copyright(c) 2013, Heresh Fattahi # # Author: Heresh Fattahi # ############################################################ # Yunjun, Jun 2016: merge functions for interferograms, timeseries # into one, and use read() for all the others # Yunjun, Aug 2016: add remove*multiple_surface() # Recommend usage: # import pysar._remove_surface as rm import os import time import h5py import numpy as np import pysar._datetime as ptime import pysar._readfile as readfile import pysar._writefile as writefile ################################################################## def remove_data_surface(data, mask, surf_type='plane'): '''Remove surface from input data matrix based on pixel marked by mask''' mask[np.isnan(data)] = 0 mask = mask.flatten(1) z = data.flatten(1) ndx= mask !=0 x = range(0,np.shape(data)[1]) y = range(0,np.shape(data)[0]) x1,y1 = np.meshgrid(x,y) points = np.vstack((y1.flatten(1),x1.flatten(1))).T if surf_type=='quadratic': G = np.array([points[:,0]**2,points[:,1]**2,points[:,0],points[:,1],points[:,0]*points[:,1],\ np.ones(np.shape(points)[0])],np.float32).T elif surf_type=='plane': G = np.array([points[:,0],points[:,1],\ np.ones(np.shape(points)[0])],np.float32).T elif surf_type == 'quadratic_range': G = np.array([points[:,1]**2,points[:,1],\ np.ones(np.shape(points)[0])],np.float32).T elif surf_type == 'quadratic_azimuth': G = np.array([points[:,0]**2,points[:,0],\ np.ones(np.shape(points)[0])],np.float32).T elif surf_type=='plane_range': G = np.array([points[:,1],\ np.ones(np.shape(points)[0])],np.float32).T elif surf_type=='plane_azimuth': G = np.array([points[:,0],\ np.ones(np.shape(points)[0])],np.float32).T z = z[ndx] G = G[ndx] G1=np.linalg.pinv(G) plane = np.dot(G1,z) if surf_type == 'quadratic': zplane = plane[0]*y1**2 + plane[1]*x1**2 + plane[2]*y1 + plane[3]*x1 + plane[4]*y1*x1 + plane[5] elif surf_type =='plane': zplane = plane[0]*y1 + plane[1]*x1 + plane[2] elif surf_type == 'quadratic_range': zplane = plane[0]*x1**2 + plane[1]*x1 + plane[2] elif surf_type == 'quadratic_azimuth': zplane = plane[0]*y1**2 + plane[1]*y1 + plane[2] elif surf_type == 'plane_range': zplane = plane[0]*x1 + plane[1] elif surf_type == 'plane_azimuth': zplane = plane[0]*y1 + plane[1] ''' ## Some notes from _pysar_utilities.py remove_surface_velocity() print '%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%' print 'Plane parameters:' if surf_type == 'plane_range': print 'range gradient = ' + str(1000*plane[0][0]) + ' mm/yr/pixel' width= float(h5file['velocity'].attrs['WIDTH']) MaxRamp=width*1000*plane[0][0] print 'Maximum ramp in range direction = ' + str(MaxRamp) + ' mm/yr' h5flat['velocity'].attrs['Range_Gradient'] = str(1000*plane[0][0]) + ' mm/yr/pixel' h5flat['velocity'].attrs['Range_Ramp'] = str(MaxRamp) + ' mm/yr' elif surf_type == 'plane_azimuth': print 'azimuth gradient = ' + str(1000*plane[0][0]) + ' mm/yr/pixel' length= float(h5file['velocity'].attrs['FILE_LENGTH']) MaxRamp=length*1000*plane[0][0] h5flat['velocity'].attrs['Azimuth_Gradient'] = str(1000*plane[0][0]) + ' mm/yr/pixel' h5flat['velocity'].attrs['Azimuth_Ramp'] = str(MaxRamp) +' mm/yr' print 'Maximum ramp in azimuth direction = '+ str(MaxRamp) + ' mm/yr' print '%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%' ''' data_n = data - zplane data_n[data == 0.] = 0. data_n = np.array(data_n,data.dtype) zplane = np.array(zplane,data.dtype) return data_n, zplane ################################################################## def remove_data_multiple_surface(data, mask, surf_type, ysub): ## ysub = [0,2400,2000,6800] dataOut = np.zeros(data.shape,data.dtype) dataOut[:] = np.nan surfaceNum = len(ysub)/2 ## 1st Mask print 'removing 1st surface ...' i = 0 mask_i = np.zeros(data.shape,data.dtype) mask_i[ysub[2*i]:ysub[2*i+1],:] = mask[ysub[2*i]:ysub[2*i+1],:] dataOut_i,ramp_i = remove_data_surface(data,mask_i,surf_type) dataOut[ysub[2*i]:ysub[2*i+1],:] = dataOut_i[ysub[2*i]:ysub[2*i+1],:] ## 2 - last Masks for i in range(1,surfaceNum): print 'removing '+str(i+1)+'th surface ...' mask_i = np.zeros(data.shape,data.dtype) mask_i[ysub[2*i]:ysub[2*i+1],:] = mask[ysub[2*i]:ysub[2*i+1],:] dataOut_i,ramp_i = remove_data_surface(data,mask_i,surf_type) if ysub[2*i] < ysub[2*i-1]: dataOut[ysub[2*i]:ysub[2*i-1],:] += dataOut_i[ysub[2*i]:ysub[2*i-1],:] dataOut[ysub[2*i]:ysub[2*i-1],:] /= 2 dataOut[ysub[2*i-1]:ysub[2*i+1],:] = dataOut_i[ysub[2*i-1]:ysub[2*i+1],:] else: dataOut[ysub[2*i]:ysub[2*i+1],:] = dataOut_i[ysub[2*i]:ysub[2*i+1],:] return dataOut ################################################################## def remove_surface(File, surf_type, maskFile=None, outFile=None, ysub=None): start = time.time() atr = readfile.read_attribute(File) # Output File Name if not outFile: outFile = os.path.splitext(File)[0]+'_'+surf_type+os.path.splitext(File)[1] if maskFile: Mask = readfile.read(maskFile)[0] print 'read mask file: '+maskFile else: Mask = np.ones((int(atr['FILE_LENGTH']), int(atr['WIDTH']))) print 'use mask of the whole area' ##### Input File Info atr = readfile.read_attribute(File) k = atr['FILE_TYPE'] print 'Input file is '+k print 'remove ramp type: '+surf_type ## Multiple Datasets File if k in ['interferograms','coherence','wrapped','timeseries']: h5file = h5py.File(File,'r') epochList = sorted(h5file[k].keys()) epoch_num = len(epochList) prog_bar = ptime.progress_bar(maxValue=epoch_num) h5flat = h5py.File(outFile,'w') group = h5flat.create_group(k) print 'writing >>> '+outFile if k in ['timeseries']: print 'number of acquisitions: '+str(len(epochList)) for i in range(epoch_num): epoch = epochList[i] data = h5file[k].get(epoch)[:] if not ysub: data_n,ramp = remove_data_surface(data, Mask, surf_type) else: data_n = remove_data_multiple_surface(data, Mask, surf_type, ysub) dset = group.create_dataset(epoch, data=data_n, compression='gzip') prog_bar.update(i+1, suffix=epoch) for key,value in h5file[k].attrs.iteritems(): group.attrs[key] = value elif k in ['interferograms','wrapped','coherence']: print 'number of interferograms: '+str(len(epochList)) date12_list = ptime.list_ifgram2date12(epochList) for i in range(epoch_num): epoch = epochList[i] data = h5file[k][epoch].get(epoch)[:] if not ysub: data_n,ramp = remove_data_surface(data,Mask,surf_type) else: data_n = remove_data_multiple_surface(data, Mask, surf_type, ysub) gg = group.create_group(epoch) dset = gg.create_dataset(epoch, data=data_n, compression='gzip') for key,value in h5file[k][epoch].attrs.iteritems(): gg.attrs[key] = value prog_bar.update(i+1, suffix=date12_list[i]) ## Single Dataset File else: data,atr = readfile.read(File) print 'Removing '+surf_type+' from '+k if not ysub: data_n,ramp = remove_data_surface(data, Mask, surf_type) else: data_n = remove_data_multiple_surface(data, Mask, surf_type, ysub) print 'writing >>> '+outFile writefile.write(data_n,atr,outFile) try: h5file.close() h5flat.close() prog_bar.close() except: pass print 'Remove '+surf_type+' took ' + str(time.time()-start) +' secs' return outFile
------------------------------------------------------------------------ -- The Agda standard library -- -- The identity function ------------------------------------------------------------------------ {-# OPTIONS --without-K --safe #-} module Function.Construct.Composition where open import Data.Product using (_,_) open import Function open import Level open import Relation.Binary private variable a b c ℓ₁ ℓ₂ ℓ₃ : Level A : Set a B : Set b C : Set c ------------------------------------------------------------------------ -- Properties module _ (≈₁ : Rel A ℓ₁) (≈₂ : Rel B ℓ₂) (≈₃ : Rel C ℓ₃) {f : A → B} {g : B → C} where congruent : Congruent ≈₁ ≈₂ f → Congruent ≈₂ ≈₃ g → Congruent ≈₁ ≈₃ (g ∘ f) congruent f-cong g-cong = g-cong ∘ f-cong injective : Injective ≈₁ ≈₂ f → Injective ≈₂ ≈₃ g → Injective ≈₁ ≈₃ (g ∘ f) injective f-inj g-inj = f-inj ∘ g-inj surjective : Transitive ≈₃ → Congruent ≈₂ ≈₃ g → Surjective ≈₁ ≈₂ f → Surjective ≈₂ ≈₃ g → Surjective ≈₁ ≈₃ (g ∘ f) surjective trans g-cong f-sur g-sur x with g-sur x ... | y , fy≈x with f-sur y ... | z , fz≈y = z , trans (g-cong fz≈y) fy≈x bijective : Transitive ≈₃ → Congruent ≈₂ ≈₃ g → Bijective ≈₁ ≈₂ f → Bijective ≈₂ ≈₃ g → Bijective ≈₁ ≈₃ (g ∘ f) bijective trans g-cong (f-inj , f-sur) (g-inj , g-sur) = injective f-inj g-inj , surjective trans g-cong f-sur g-sur module _ (≈₁ : Rel A ℓ₁) (≈₂ : Rel B ℓ₂) (≈₃ : Rel C ℓ₃) (f : A → B) {f⁻¹ : B → A} {g : B → C} (g⁻¹ : C → B) where inverseˡ : Transitive ≈₃ → Congruent ≈₂ ≈₃ g → Inverseˡ ≈₁ ≈₂ f f⁻¹ → Inverseˡ ≈₂ ≈₃ g g⁻¹ → Inverseˡ ≈₁ ≈₃ (g ∘ f) (f⁻¹ ∘ g⁻¹) inverseˡ trn g-cong f-inv g-inv x = trn (g-cong (f-inv _)) (g-inv x) inverseʳ : Transitive ≈₁ → Congruent ≈₂ ≈₁ f⁻¹ → Inverseʳ ≈₁ ≈₂ f f⁻¹ → Inverseʳ ≈₂ ≈₃ g g⁻¹ → Inverseʳ ≈₁ ≈₃ (g ∘ f) (f⁻¹ ∘ g⁻¹) inverseʳ trn f⁻¹-cong f-inv g-inv x = trn (f⁻¹-cong (g-inv _)) (f-inv x) inverseᵇ : Transitive ≈₁ → Transitive ≈₃ → Congruent ≈₂ ≈₃ g → Congruent ≈₂ ≈₁ f⁻¹ → Inverseᵇ ≈₁ ≈₂ f f⁻¹ → Inverseᵇ ≈₂ ≈₃ g g⁻¹ → Inverseᵇ ≈₁ ≈₃ (g ∘ f) (f⁻¹ ∘ g⁻¹) inverseᵇ trn₁ trn₃ g-cong f⁻¹-cong (f-invˡ , f-invʳ) (g-invˡ , g-invʳ) = inverseˡ trn₃ g-cong f-invˡ g-invˡ , inverseʳ trn₁ f⁻¹-cong f-invʳ g-invʳ ------------------------------------------------------------------------ -- Structures module _ {≈₁ : Rel A ℓ₁} {≈₂ : Rel B ℓ₂} {≈₃ : Rel C ℓ₃} {f : A → B} {g : B → C} where isCongruent : IsCongruent ≈₁ ≈₂ f → IsCongruent ≈₂ ≈₃ g → IsCongruent ≈₁ ≈₃ (g ∘ f) isCongruent f-cong g-cong = record { cong = G.cong ∘ F.cong ; isEquivalence₁ = F.isEquivalence₁ ; isEquivalence₂ = G.isEquivalence₂ } where module F = IsCongruent f-cong; module G = IsCongruent g-cong isInjection : IsInjection ≈₁ ≈₂ f → IsInjection ≈₂ ≈₃ g → IsInjection ≈₁ ≈₃ (g ∘ f) isInjection f-inj g-inj = record { isCongruent = isCongruent F.isCongruent G.isCongruent ; injective = injective ≈₁ ≈₂ ≈₃ F.injective G.injective } where module F = IsInjection f-inj; module G = IsInjection g-inj isSurjection : IsSurjection ≈₁ ≈₂ f → IsSurjection ≈₂ ≈₃ g → IsSurjection ≈₁ ≈₃ (g ∘ f) isSurjection f-surj g-surj = record { isCongruent = isCongruent F.isCongruent G.isCongruent ; surjective = surjective ≈₁ ≈₂ ≈₃ G.Eq₂.trans G.cong F.surjective G.surjective } where module F = IsSurjection f-surj; module G = IsSurjection g-surj isBijection : IsBijection ≈₁ ≈₂ f → IsBijection ≈₂ ≈₃ g → IsBijection ≈₁ ≈₃ (g ∘ f) isBijection f-bij g-bij = record { isInjection = isInjection F.isInjection G.isInjection ; surjective = surjective ≈₁ ≈₂ ≈₃ G.Eq₂.trans G.cong F.surjective G.surjective } where module F = IsBijection f-bij; module G = IsBijection g-bij module _ {≈₁ : Rel A ℓ₁} {≈₂ : Rel B ℓ₂} {≈₃ : Rel C ℓ₃} {f : A → B} {g : B → C} {f⁻¹ : B → A} {g⁻¹ : C → B} where isLeftInverse : IsLeftInverse ≈₁ ≈₂ f f⁻¹ → IsLeftInverse ≈₂ ≈₃ g g⁻¹ → IsLeftInverse ≈₁ ≈₃ (g ∘ f) (f⁻¹ ∘ g⁻¹) isLeftInverse f-invˡ g-invˡ = record { isCongruent = isCongruent F.isCongruent G.isCongruent ; cong₂ = congruent ≈₃ ≈₂ ≈₁ G.cong₂ F.cong₂ ; inverseˡ = inverseˡ ≈₁ ≈₂ ≈₃ f _ G.Eq₂.trans G.cong₁ F.inverseˡ G.inverseˡ } where module F = IsLeftInverse f-invˡ; module G = IsLeftInverse g-invˡ isRightInverse : IsRightInverse ≈₁ ≈₂ f f⁻¹ → IsRightInverse ≈₂ ≈₃ g g⁻¹ → IsRightInverse ≈₁ ≈₃ (g ∘ f) (f⁻¹ ∘ g⁻¹) isRightInverse f-invʳ g-invʳ = record { isCongruent = isCongruent F.isCongruent G.isCongruent ; cong₂ = congruent ≈₃ ≈₂ ≈₁ G.cong₂ F.cong₂ ; inverseʳ = inverseʳ ≈₁ ≈₂ ≈₃ _ g⁻¹ F.Eq₁.trans F.cong₂ F.inverseʳ G.inverseʳ } where module F = IsRightInverse f-invʳ; module G = IsRightInverse g-invʳ isInverse : IsInverse ≈₁ ≈₂ f f⁻¹ → IsInverse ≈₂ ≈₃ g g⁻¹ → IsInverse ≈₁ ≈₃ (g ∘ f) (f⁻¹ ∘ g⁻¹) isInverse f-inv g-inv = record { isLeftInverse = isLeftInverse F.isLeftInverse G.isLeftInverse ; inverseʳ = inverseʳ ≈₁ ≈₂ ≈₃ _ g⁻¹ F.Eq₁.trans F.cong₂ F.inverseʳ G.inverseʳ } where module F = IsInverse f-inv; module G = IsInverse g-inv ------------------------------------------------------------------------ -- Setoid bundles module _ {R : Setoid a ℓ₁} {S : Setoid b ℓ₂} {T : Setoid c ℓ₃} where open Setoid renaming (_≈_ to ≈) injection : Injection R S → Injection S T → Injection R T injection inj₁ inj₂ = record { f = G.f ∘ F.f ; cong = congruent (≈ R) (≈ S) (≈ T) F.cong G.cong ; injective = injective (≈ R) (≈ S) (≈ T) F.injective G.injective } where module F = Injection inj₁; module G = Injection inj₂ surjection : Surjection R S → Surjection S T → Surjection R T surjection surj₁ surj₂ = record { f = G.f ∘ F.f ; cong = congruent (≈ R) (≈ S) (≈ T) F.cong G.cong ; surjective = surjective (≈ R) (≈ S) (≈ T) G.Eq₂.trans G.cong F.surjective G.surjective } where module F = Surjection surj₁; module G = Surjection surj₂ bijection : Bijection R S → Bijection S T → Bijection R T bijection bij₁ bij₂ = record { f = G.f ∘ F.f ; cong = congruent (≈ R) (≈ S) (≈ T) F.cong G.cong ; bijective = bijective (≈ R) (≈ S) (≈ T) (trans T) G.cong F.bijective G.bijective } where module F = Bijection bij₁; module G = Bijection bij₂ equivalence : Equivalence R S → Equivalence S T → Equivalence R T equivalence equiv₁ equiv₂ = record { f = G.f ∘ F.f ; g = F.g ∘ G.g ; cong₁ = congruent (≈ R) (≈ S) (≈ T) F.cong₁ G.cong₁ ; cong₂ = congruent (≈ T) (≈ S) (≈ R) G.cong₂ F.cong₂ } where module F = Equivalence equiv₁; module G = Equivalence equiv₂ leftInverse : LeftInverse R S → LeftInverse S T → LeftInverse R T leftInverse invˡ₁ invˡ₂ = record { f = G.f ∘ F.f ; g = F.g ∘ G.g ; cong₁ = congruent (≈ R) (≈ S) (≈ T) F.cong₁ G.cong₁ ; cong₂ = congruent (≈ T) (≈ S) (≈ R) G.cong₂ F.cong₂ ; inverseˡ = inverseˡ (≈ R) (≈ S) (≈ T) F.f _ (trans T) G.cong₁ F.inverseˡ G.inverseˡ } where module F = LeftInverse invˡ₁; module G = LeftInverse invˡ₂ rightInverse : RightInverse R S → RightInverse S T → RightInverse R T rightInverse invʳ₁ invʳ₂ = record { f = G.f ∘ F.f ; g = F.g ∘ G.g ; cong₁ = congruent (≈ R) (≈ S) (≈ T) F.cong₁ G.cong₁ ; cong₂ = congruent (≈ T) (≈ S) (≈ R) G.cong₂ F.cong₂ ; inverseʳ = inverseʳ (≈ R) (≈ S) (≈ T) _ G.g (trans R) F.cong₂ F.inverseʳ G.inverseʳ } where module F = RightInverse invʳ₁; module G = RightInverse invʳ₂ inverse : Inverse R S → Inverse S T → Inverse R T inverse inv₁ inv₂ = record { f = G.f ∘ F.f ; f⁻¹ = F.f⁻¹ ∘ G.f⁻¹ ; cong₁ = congruent (≈ R) (≈ S) (≈ T) F.cong₁ G.cong₁ ; cong₂ = congruent (≈ T) (≈ S) (≈ R) G.cong₂ F.cong₂ ; inverse = inverseᵇ (≈ R) (≈ S) (≈ T) _ G.f⁻¹ (trans R) (trans T) G.cong₁ F.cong₂ F.inverse G.inverse } where module F = Inverse inv₁; module G = Inverse inv₂ ------------------------------------------------------------------------ -- Propositional bundles infix 8 _∘-↣_ _∘-↠_ _∘-⤖_ _∘-⇔_ _∘-↩_ _∘-↪_ _∘-↔_ _∘-↣_ : A ↣ B → B ↣ C → A ↣ C _∘-↣_ = injection _∘-↠_ : A ↠ B → B ↠ C → A ↠ C _∘-↠_ = surjection _∘-⤖_ : A ⤖ B → B ⤖ C → A ⤖ C _∘-⤖_ = bijection _∘-⇔_ : A ⇔ B → B ⇔ C → A ⇔ C _∘-⇔_ = equivalence _∘-↩_ : A ↩ B → B ↩ C → A ↩ C _∘-↩_ = leftInverse _∘-↪_ : A ↪ B → B ↪ C → A ↪ C _∘-↪_ = rightInverse _∘-↔_ : A ↔ B → B ↔ C → A ↔ C _∘-↔_ = inverse
## ----load packages, echo = FALSE----------------------------------------- library(tidyverse) library(lubridate) library(gapminder) ## ----select a subset of the observations--------------------------------- load(here::here("data/french_fries.rda")) french_fries %>% filter(subject == 3, time == 1) ## ----order the observations---------------------------------------------- french_fries %>% arrange(desc(rancid)) %>% head ## ----select a subset of the variables------------------------------------ french_fries %>% select(time, treatment, subject, rep, potato) %>% head ## ----summarize observations into one-number statistic-------------------- french_fries %>% summarise(mean_rancid = mean(rancid, na.rm=TRUE), sd_rancid = sd(rancid, na.rm = TRUE)) ## ----summarise and group_by---------------------------------------------- french_fries %>% group_by(time, treatment) %>% summarise(mean_rancid = mean(rancid), sd_rancid = sd(rancid)) ## ----checking design completeness---------------------------------------- french_fries %>% group_by(subject) %>% summarize(n = n()) ## ----counts for subject by time------------------------------------------ french_fries %>% na.omit() %>% count(subject, time) %>% spread(time, n) ## ----do scores change over time, fig.show='hide'------------------------- ff.m <- french_fries %>% gather(type, rating, -subject, -time, -treatment, -rep) ggplot(data=ff.m, aes(x=time, y=rating, colour=treatment)) + geom_point() + facet_grid(subject~type) ## ----get means over reps, and connect the dots, fig.show='hide'---------- ff.m.av <- ff.m %>% group_by(subject, time, type, treatment) %>% summarise(rating=mean(rating)) ggplot(data=ff.m, aes(x=time, y=rating, colour=treatment)) + facet_grid(subject~type) + geom_line(data=ff.m.av, aes(group=treatment)) ## ----first look at gapminder data---------------------------------------- library(gapminder) ggplot(data=gapminder, aes(x=year, y=lifeExp, group=country)) + geom_line() ## ----using models as exploratory tools, echo=FALSE, fig.width=6.5, fig.height=5---- library(dplyr) library(tidyr) library(purrr) gapminder2 <- gapminder %>% mutate(year = year-1950) by_country <- gapminder2 %>% group_by(continent, country) %>% nest() by_country <- by_country %>% mutate( model = purrr::map(data, ~ lm(lifeExp ~ year, data = .)) ) by_country <- by_country %>% unnest(model %>% purrr::map(broom::tidy)) country_coefs <- by_country %>% select(continent, country, term, estimate) %>% spread(term, estimate) p <- ggplot(data=country_coefs, aes(x=`(Intercept)`, y=year, colour=continent, label=country)) + geom_point() + scale_colour_brewer(palette="Dark2") + xlab("Average Life Expectancy in 1950") + ylab("Average Gain in Life Expectancy per Year") plotly::ggplotly(p) ## ----start with a single country----------------------------------------- usa <- gapminder %>% filter(country=="United States") head(usa) ## ----life expectancy in the U.S. since 1950------------------------------ ggplot(data=usa, aes(x=year, y=lifeExp)) + geom_point() + geom_smooth(method="lm") ## ------------------------------------------------------------------------ usa.lm <- lm(lifeExp~year, data=usa) usa.lm ## ------------------------------------------------------------------------ gapminder <- gapminder %>% mutate(year = year-1950) ## ----nesting data-------------------------------------------------------- by_country <- gapminder %>% group_by(continent, country) %>% nest() head(by_country) ## ----fitting multiple models--------------------------------------------- by_country$model <- by_country$data %>% purrr::map(~lm(lifeExp~year, data=.)) head(by_country) ## ----broom again--------------------------------------------------------- broom::tidy(by_country$model[[1]]) ## ----extract all countries automatically--------------------------------- by_country$coefs <- by_country$model %>% purrr::map(broom::tidy) by_country ## ----get the coefficients into one data set------------------------------ by_country_coefs <- by_country %>% unnest(coefs) by_country_coefs ## ----and finally a visualization----------------------------------------- coefs <- by_country_coefs %>% select(country, continent, term, estimate) %>% spread(term, estimate) ggplot(data=coefs, aes(x=`(Intercept)`, y=year, colour=continent)) + geom_point()
# day 12: Stochastic Gradient Descent # Objectives * See how Stochastic Gradient Descent can be used on a simple model (1-dim. linear regression) * See how SGD can be used on a complex model (MLPClassifier) * Understand impact of batch size and learning rate (aka step size) # Outline * [Review: Loss and Gradient for 1-dim. Linear Regression](#part1) * [Part 1: Stochastic Estimates of the Loss](#part1) * [Part 2: Stochastic Estimates of the Gradient](#part2) * [Part 3: Stochastic Gradient Descent Algorithm in a few lines of Python](#part3) * [Part 4: Using sklearn code to train MLPClassifier with SGD](#part4) # Takeaways * Stochastic estimates of loss functions are possible when the function is *additive* over training examples * Stochastic gradient descent is a simple algorithm that can be implemented in a few lines of Python * * Practical issues include selecting step size and batch size $B$ * Selecting batch size trades off two things: * * Runtime cost of computing each gradient estimate (scales with $O(B)$, so smaller is better) * * Quality of the estimate (larger $B$ leads to less variance) ```python import numpy as np ``` ```python import sklearn.neural_network ``` ```python # import plotting libraries import matplotlib import matplotlib.pyplot as plt %matplotlib inline plt.style.use('seaborn') # pretty matplotlib plots import seaborn as sns sns.set('notebook', font_scale=1.25, style='whitegrid') ``` # Create simple dataset: y = 1.234 * x + noise We will *intentionally* create a toy dataset where we know that a good solution has slope near 1.234. We'll generate N = 1000 examples. Naturally, the best slope for the finite dataset we create won't be exactly 1.234 (because of the noise added plus the fact that our dataset size is limited). ```python def create_dataset(N=1000, slope=1.234, noise_stddev=0.1, random_state=0): random_state = np.random.RandomState(int(random_state)) # input features x_N = np.linspace(-2, 2, N) # output features y_N = slope * x_N + random_state.randn(N) * noise_stddev return x_N, y_N ``` ```python xtrain_N, ytrain_N = create_dataset(N=1000, noise_stddev=0.3) ``` ```python fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(5,5)) plt.plot(xtrain_N, ytrain_N, 'k.'); plt.xlabel('x'); plt.ylabel('y'); ``` # Review: Gradient Descent for 1-dim. Linear Regression ## Define prediction model Consider the *simplest* linear regression model. A single weight parameter $w \in \mathbb{R}$ representing the slope of the prediction line. No bias/intercept. To make predictions, we just compute the weight multiplied by the input feature $$ \hat{y}(x) = w \cdot x $$ ## Define loss function We want to minimize the total *squared error* across all N observed data examples (input features $x_n$, output responses $y_n$) Given a full dataset of $N$ examples, we can compute the loss as: \begin{align} \min_{w \in \mathbb{R}} ~~ &\ell(w) \\ \text{calc_loss}(w) = \ell(w) &= \frac{1}{N} \sum_{n=1}^N \frac{1}{2} (y_n - w x_n)^2 \end{align} Given a random minibatch of $B$ examples, we can *estimate* the loss as: \begin{align} \text{estimate_loss}(w) = &= \frac{1}{B} \sum_{n=1}^B \frac{1}{2} (y_n - w x_n)^2 \end{align} ### Exercise 1A: Complete the code below You should make it match the math expression above. ```python def calc_loss(w, xbatch_B, ybatch_B): ''' Compute loss for slope-only least-squares linear regression Will compute the estimate of the loss given a minibatch of x,y values Args ---- w : float Value of slope parameter Returns ------- loss : float Mean of squared error loss at provided w value ''' B = xbatch_B.shape[0] yhat_B = xbatch_B * w half_mean_squared_error = 0.5 * np.mean(np.square(ybatch_B - yhat_B)) return half_mean_squared_error ``` ### Define the gradient function Given a full dataset of $N$ examples, we can compute the gradient as: \begin{align} \text{calc_grad}(w) = \ell'(w) &= \frac{1}{N} \frac{\partial}{\partial w} [ \sum_{n=1}^N \frac{1}{2} (y_n - w x_n)^2] \\ &= \frac{1}{N} \sum_{n=1}^N (y_n - w x_n) (-x_n) \\ &= \frac{1}{N} \sum_{n=1}^N (w x_n - y_n) (x_n) \\ &= w \left( \frac{1}{N} \sum_{n=1}^N x_n^2 \right) - \frac{1}{N} \sum_{n=1}^N y_n x_n \end{align} Given a random minibatch of $B$ examples, we can *estimate* the gradient using: \begin{align} \text{estimate_grad}(w) &= \frac{1}{B} \frac{\partial}{\partial w} [ \sum_{n=1}^B \frac{1}{2} (y_n - w x_n)^2] \\ &= w \left( \frac{1}{B} \sum_{n=1}^B x_n^2 \right) - \frac{1}{B} \sum_{n=1}^B y_n x_n \end{align} Below, we've implemented the gradient calculation in code for you ```python def calc_grad(w, xbatch_B, ybatch_B): ''' Compute gradient for slope-only least-squares linear regression Will compute a deterministic estimate of the gradient given a minibatch of x,y values Args ---- w : float Value of slope parameter Returns ------- g : float Value of derivative of loss function at provided w value ''' g = w * np.mean(np.square(xbatch_B)) - np.mean(xbatch_B * ybatch_B) return g ``` # Part 1: Stochastic estimates of the loss ### Plot whole-dataset loss evaluated at each w from -3 to 8 We should see a "bowl" shape with one *global* minima, because our optimization problem is "convex" ```python G = 101 w_grid = np.linspace(-3, 8, G) # create array of 300 values between -3 and 8 print(w_grid) ``` [-3. -2.89 -2.78 -2.67 -2.56 -2.45 -2.34 -2.23 -2.12 -2.01 -1.9 -1.79 -1.68 -1.57 -1.46 -1.35 -1.24 -1.13 -1.02 -0.91 -0.8 -0.69 -0.58 -0.47 -0.36 -0.25 -0.14 -0.03 0.08 0.19 0.3 0.41 0.52 0.63 0.74 0.85 0.96 1.07 1.18 1.29 1.4 1.51 1.62 1.73 1.84 1.95 2.06 2.17 2.28 2.39 2.5 2.61 2.72 2.83 2.94 3.05 3.16 3.27 3.38 3.49 3.6 3.71 3.82 3.93 4.04 4.15 4.26 4.37 4.48 4.59 4.7 4.81 4.92 5.03 5.14 5.25 5.36 5.47 5.58 5.69 5.8 5.91 6.02 6.13 6.24 6.35 6.46 6.57 6.68 6.79 6.9 7.01 7.12 7.23 7.34 7.45 7.56 7.67 7.78 7.89 8. ] ```python loss_grid = np.zeros(G) for gg in range(G): loss_grid[gg] = calc_loss(w_grid[gg], xtrain_N, ytrain_N) plt.plot(w_grid, loss_grid, 'b.-'); plt.xlabel('w'); plt.ylabel('loss(w)'); plt.ylim([0, 35]); ``` ### Discussion 1a: Visually, at what value of $w$ does the loss function have a minima? Is it near where you would expect (hint: look above for the "true" slope value used to generate the data) ```python ``` ### Sampling a minibatch of size B We have provided some starter code that samples a minibatch of B examples from a training set of N examples Uses a provided `random_state` pseudo-random number generator, which defaults to numpy's if not specified. ```python def draw_minibatch(xtrain_N, ytrain_N, batch_size=100, random_state=np.random): ''' Sample a minibatch of desired size from provided training set Returns ------- xbatch_B : 1D array, size (B,) x values of minibatch ybatch_B : 1D array, size (B,) y values of minibatch ''' N = ytrain_N.size selected_row_ids = random_state.choice(np.arange(N), size=batch_size, replace=False) xbatch_B = xtrain_N[selected_row_ids].copy() ybatch_B = ytrain_N[selected_row_ids].copy() return xbatch_B, ybatch_B ``` ### Show several minibatches of size 1 ```python draw_minibatch(xtrain_N, ytrain_N, 1) ``` (array([1.80780781]), array([2.30416787])) ```python draw_minibatch(xtrain_N, ytrain_N, 1) ``` (array([-0.44244244]), array([-0.49670565])) ```python draw_minibatch(xtrain_N, ytrain_N, 1) ``` (array([1.67167167]), array([1.98366164])) ### Show example minibatch of size 500 ```python xbatch_B, ybatch_B = draw_minibatch(xtrain_N, ytrain_N, 500) print("Showing first 5 entries of x array of shape %s" % str(xbatch_B.shape)) print(xbatch_B[:5]) print("Showing first 5 entries of y array of shape %s" % str(ybatch_B.shape)) print(ybatch_B[:5]) ``` Showing first 5 entries of x array of shape (500,) [-1.11111111 -0.27827828 -0.1021021 0.88688689 -0.16616617] Showing first 5 entries of y array of shape (500,) [-1.5101899 -0.48344906 0.39566781 0.9413306 -0.14525899] ### Exercise 1b: Would you expect the loss on the minibatch to be better at $w=1.0$ or at $w = -1.0$? TODO write answer here to guess, then use code below to figure it out. Show the loss at this random minibatch when $w = 1.0$ ```python calc_loss(1.0, xbatch_B, ybatch_B) ``` 0.07291125339530102 Show the loss at this random minibatch when w = -2.0 ```python calc_loss(-1.0, xbatch_B, ybatch_B) ``` 3.264773935155204 ### Exercise 1c: Can you draw a random minibatch of size 25 and display *all* of it? ```python xbatch_25, ybatch_25 = None, None # TODO use draw_minibatch print("Showing x array") print(xbatch_25) print("Showing y array") print(ybatch_25) ``` Showing x array None Showing y array None ### Exercise 1d: What is the loss at your minibatch at $w=1.0$ and $w = 1.5$? ```python # TODO your code here, call calc_loss ``` ```python ``` ## Plot: Compute the *stochastic estimate* of loss as a function of $w$, using batch size 50 We'll make 3 lines, for 3 separate *trials* of this procedure, so we can see how much each trial's curve might vary ```python for trial in range(3): random_state = np.random.RandomState(trial) # set seed based on the trial id stoch_loss_grid = np.zeros(G) for gg in range(G): xbatch_B, ybatch_B = draw_minibatch(xtrain_N, ytrain_N, batch_size=50, random_state=random_state) stoch_loss_grid[gg] = calc_loss(w_grid[gg], xbatch_B, ybatch_B) plt.plot(w_grid, stoch_loss_grid, '.-', label='Trial %d' % trial); plt.xlabel('w'); plt.ylabel('loss(w)'); plt.ylim([0, 35]); ``` ## Exercise 1e: Compute stochastic estimate of loss as function of w, for batch_size = 5 ```python for trial in range(3): random_state = np.random.RandomState(trial) # set seed based on the trial id stoch_loss_grid = np.zeros(G) for gg in range(G): xbatch_B, ybatch_B = None, None # TODO use draw_minibatch stoch_loss_grid[gg] = 0.0 # TODO use calc_loss at the current batch plt.plot(w_grid, stoch_loss_grid, '.-', label='Trial %d' % trial); plt.xlabel('w'); plt.ylabel('loss(w)'); ``` ## Exercise 1f: Compute stochastic estimate of loss as function of w, for batch_size = 1 Repeat the above for batch_size = 1 ```python ``` ## Discussion 1f: What can you say about the *variance* of the stochastic estimates How does variance change as a function of batch size ? ## Part 2: Stochastic estimates of the gradient ## Sanity check: plot whole dataset gradient evaluated at each w from -3 to 8 ```python grad_grid = np.zeros(G) for gg in range(G): grad_grid[gg] = calc_grad(w_grid[gg], xtrain_N, ytrain_N) plt.plot(w_grid, grad_grid, 'b.-'); plt.xlabel('w'); plt.ylabel('grad(w)'); plt.ylim([-7, 9]); ``` ## Plot: Compute the *stochastic estimate* of grad as a function of $w$, using batch size 50 ```python for trial in range(3): random_state = np.random.RandomState(trial) # set seed based on the trial id stoch_grad_grid = np.zeros(G) for gg in range(G): xbatch_B, ybatch_B = draw_minibatch(xtrain_N, ytrain_N, batch_size=50, random_state=random_state) stoch_grad_grid[gg] = calc_grad(w_grid[gg], xbatch_B, ybatch_B) plt.plot(w_grid, stoch_grad_grid, '.-', label='Trial %d' % trial); plt.xlabel('w'); plt.ylabel('grad(w)'); plt.ylim([-7, 9]); ``` ## Exercise 2a: Repeat the above plot at batch_size = 5 ```python for trial in range(3): random_state = np.random.RandomState(trial) # set seed based on the trial id stoch_grad_grid = np.zeros(G) for gg in range(G): xbatch_B, ybatch_B = None, None # TODO use draw_minibatch stoch_grad_grid[gg] = 0.0 # TODO use calc_grad plt.plot(w_grid, stoch_grad_grid, '.-', label='Trial %d' % trial); plt.xlabel('w'); plt.ylabel('grad(w)'); plt.ylim([-7, 9]); ``` ## Exercise 2c: Repeat the above plot at batch_size = 1 TODO copy code from above. ```python # TODO ``` ## Discussion 2d: What happens to the variance of the grad estimate as batch_size increases? ## Discussion 2d: What happens to the cost of computing the estimate as batch_size increases? ## Part 3: Stochastic Gradient Descent (GD) as an algorithm in Python ### Define minimize_via_sgd algorithm Can you understand what each step of this algorithm does? ```python def minimize_via_sgd(xtrain_N, ytrain_N, init_w=0.0, batch_size=10, step_size=0.001, max_iters=100, random_state=0): ''' Perform minimization of provided loss function via gradient descent Each "iteration" performs one or more gradient updates, until total training set has been "seen" Args ---- xtrain_N : numpy array, shape (N,) ytrain_N : numpy array, shape (N,) init_w : float batch_size : int step_size : float max_iters : positive int Return ---- wopt: float array of optimized weights that approximately gives the least error info_dict : dict Contains information about the optimization procedure useful for debugging Entries include: * trace_loss_list : list of loss values * trace_grad_list : list of gradient values ''' N = int(ytrain_N.size) B = int(batch_size) if isinstance(random_state, int): random_state = np.random.RandomState(random_state) w = 1.0 * init_w # Create some lists to track progress over time (for debugging) trace_loss_list = [] trace_w_list = [] trace_grad_list = [] step_id = 0 for iter_id in range(max_iters): n_examples_seen_this_iter = 0 while n_examples_seen_this_iter < N: xbatch_B, ybatch_B = draw_minibatch(xtrain_N, ytrain_N, batch_size, random_state=random_state) n_examples_seen_this_iter += batch_size loss = calc_loss(w, xbatch_B, ybatch_B) grad = calc_grad(w, xbatch_B, ybatch_B) w = w - step_size * grad step_id += 1 print(" iter %5d/%d done | step %5d | w % 13.5f | loss % 13.4f | grad % 13.4f" % ( iter_id, max_iters, step_id, w, loss, grad)) trace_loss_list.append(loss) trace_w_list.append(w) trace_grad_list.append(grad) wopt = w info_dict = dict( trace_loss_list=trace_loss_list, trace_w_list=trace_w_list, trace_grad_list=trace_grad_list) return wopt, info_dict ``` ### Discussion 2a: Which line of the above function does the *parameter update* happen? Remember, in math, the parameter update of gradient descent is this: $$ w \gets w - \alpha \nabla_w \ell(w) $$ where $\alpha > 0$ is the step size. In words, this math says *move* the parameter $w$ from its current value a *small step* in the "downhill" direction (indicated by gradient). TODO write down here which line above *you* think it is, then discuss with your group ```python ``` ### Try it! Run SGD with step_size = 0.01 and batch_size = 200 Running the cell below will have the following effects: 1) one line will be printed for every iteration, indicating the current w value and its associated loss 2) the "optimal" value of w will be stored in the variable named `wopt` returned by this function 3) a dictionary of information useful for debugging will be stored in the `info_dict` returned by this function ```python wopt, info_dict = minimize_via_sgd(xtrain_N, ytrain_N, step_size=0.01, batch_size=200); ``` iter 0/100 done | step 5 | w 0.08015 | loss 1.0488 | grad -1.7202 iter 1/100 done | step 10 | w 0.15328 | loss 0.8576 | grad -1.4773 iter 2/100 done | step 15 | w 0.22259 | loss 0.7444 | grad -1.3535 iter 3/100 done | step 20 | w 0.28735 | loss 0.6190 | grad -1.2232 iter 4/100 done | step 25 | w 0.35058 | loss 0.5804 | grad -1.2300 iter 5/100 done | step 30 | w 0.40936 | loss 0.5670 | grad -1.2455 iter 6/100 done | step 35 | w 0.46134 | loss 0.4426 | grad -1.0366 iter 7/100 done | step 40 | w 0.51053 | loss 0.3971 | grad -0.9791 iter 8/100 done | step 45 | w 0.55889 | loss 0.3367 | grad -0.8819 iter 9/100 done | step 50 | w 0.60231 | loss 0.3295 | grad -0.8519 iter 10/100 done | step 55 | w 0.64268 | loss 0.2927 | grad -0.8156 iter 11/100 done | step 60 | w 0.68140 | loss 0.2557 | grad -0.7506 iter 12/100 done | step 65 | w 0.71875 | loss 0.2472 | grad -0.7419 iter 13/100 done | step 70 | w 0.75133 | loss 0.1835 | grad -0.5930 iter 14/100 done | step 75 | w 0.78277 | loss 0.1722 | grad -0.5639 iter 15/100 done | step 80 | w 0.81064 | loss 0.1731 | grad -0.5796 iter 16/100 done | step 85 | w 0.83925 | loss 0.1716 | grad -0.6222 iter 17/100 done | step 90 | w 0.86445 | loss 0.1464 | grad -0.5074 iter 18/100 done | step 95 | w 0.88863 | loss 0.1269 | grad -0.4665 iter 19/100 done | step 100 | w 0.91101 | loss 0.1231 | grad -0.4666 iter 20/100 done | step 105 | w 0.93204 | loss 0.1004 | grad -0.4243 iter 21/100 done | step 110 | w 0.95136 | loss 0.0874 | grad -0.3560 iter 22/100 done | step 115 | w 0.97035 | loss 0.0987 | grad -0.3765 iter 23/100 done | step 120 | w 0.98704 | loss 0.0808 | grad -0.2952 iter 24/100 done | step 125 | w 1.00346 | loss 0.0852 | grad -0.3169 iter 25/100 done | step 130 | w 1.01760 | loss 0.0784 | grad -0.3205 iter 26/100 done | step 135 | w 1.03255 | loss 0.0701 | grad -0.2819 iter 27/100 done | step 140 | w 1.04555 | loss 0.0659 | grad -0.2295 iter 28/100 done | step 145 | w 1.05768 | loss 0.0687 | grad -0.2576 iter 29/100 done | step 150 | w 1.06847 | loss 0.0614 | grad -0.2003 iter 30/100 done | step 155 | w 1.07939 | loss 0.0661 | grad -0.2469 iter 31/100 done | step 160 | w 1.08989 | loss 0.0582 | grad -0.2022 iter 32/100 done | step 165 | w 1.10010 | loss 0.0630 | grad -0.2164 iter 33/100 done | step 170 | w 1.10851 | loss 0.0565 | grad -0.1732 iter 34/100 done | step 175 | w 1.11634 | loss 0.0552 | grad -0.1632 iter 35/100 done | step 180 | w 1.12382 | loss 0.0565 | grad -0.1650 iter 36/100 done | step 185 | w 1.12964 | loss 0.0494 | grad -0.1079 iter 37/100 done | step 190 | w 1.13630 | loss 0.0470 | grad -0.1289 iter 38/100 done | step 195 | w 1.14222 | loss 0.0478 | grad -0.1077 iter 39/100 done | step 200 | w 1.14832 | loss 0.0590 | grad -0.1447 iter 40/100 done | step 205 | w 1.15326 | loss 0.0419 | grad -0.1074 iter 41/100 done | step 210 | w 1.15853 | loss 0.0460 | grad -0.0721 iter 42/100 done | step 215 | w 1.16395 | loss 0.0509 | grad -0.1238 iter 43/100 done | step 220 | w 1.16902 | loss 0.0426 | grad -0.1063 iter 44/100 done | step 225 | w 1.17258 | loss 0.0459 | grad -0.0702 iter 45/100 done | step 230 | w 1.17556 | loss 0.0466 | grad -0.0392 iter 46/100 done | step 235 | w 1.17890 | loss 0.0428 | grad -0.0586 iter 47/100 done | step 240 | w 1.18149 | loss 0.0433 | grad -0.0558 iter 48/100 done | step 245 | w 1.18422 | loss 0.0477 | grad -0.0653 iter 49/100 done | step 250 | w 1.18750 | loss 0.0428 | grad -0.0637 iter 50/100 done | step 255 | w 1.19068 | loss 0.0525 | grad -0.0635 iter 51/100 done | step 260 | w 1.19410 | loss 0.0478 | grad -0.0637 iter 52/100 done | step 265 | w 1.19610 | loss 0.0371 | grad -0.0345 iter 53/100 done | step 270 | w 1.19875 | loss 0.0444 | grad -0.0442 iter 54/100 done | step 275 | w 1.20074 | loss 0.0458 | grad -0.0389 iter 55/100 done | step 280 | w 1.20295 | loss 0.0467 | grad -0.0212 iter 56/100 done | step 285 | w 1.20470 | loss 0.0410 | grad -0.0131 iter 57/100 done | step 290 | w 1.20604 | loss 0.0386 | grad -0.0209 iter 58/100 done | step 295 | w 1.20676 | loss 0.0387 | grad -0.0180 iter 59/100 done | step 300 | w 1.20872 | loss 0.0407 | grad -0.0393 iter 60/100 done | step 305 | w 1.20974 | loss 0.0391 | grad -0.0075 iter 61/100 done | step 310 | w 1.21074 | loss 0.0448 | grad -0.0445 iter 62/100 done | step 315 | w 1.21162 | loss 0.0469 | grad 0.0055 iter 63/100 done | step 320 | w 1.21239 | loss 0.0385 | grad 0.0217 iter 64/100 done | step 325 | w 1.21317 | loss 0.0404 | grad -0.0250 iter 65/100 done | step 330 | w 1.21514 | loss 0.0422 | grad -0.0427 iter 66/100 done | step 335 | w 1.21667 | loss 0.0505 | grad -0.0682 iter 67/100 done | step 340 | w 1.21734 | loss 0.0441 | grad -0.0089 iter 68/100 done | step 345 | w 1.21843 | loss 0.0487 | grad -0.0520 iter 69/100 done | step 350 | w 1.21968 | loss 0.0426 | grad -0.0217 iter 70/100 done | step 355 | w 1.22061 | loss 0.0451 | grad -0.0162 iter 71/100 done | step 360 | w 1.22148 | loss 0.0494 | grad -0.0131 iter 72/100 done | step 365 | w 1.22243 | loss 0.0432 | grad -0.0476 iter 73/100 done | step 370 | w 1.22310 | loss 0.0359 | grad -0.0035 iter 74/100 done | step 375 | w 1.22355 | loss 0.0445 | grad -0.0733 iter 75/100 done | step 380 | w 1.22387 | loss 0.0475 | grad -0.0229 iter 76/100 done | step 385 | w 1.22515 | loss 0.0418 | grad -0.0054 iter 77/100 done | step 390 | w 1.22519 | loss 0.0457 | grad 0.0189 iter 78/100 done | step 395 | w 1.22512 | loss 0.0411 | grad 0.0211 iter 79/100 done | step 400 | w 1.22509 | loss 0.0423 | grad -0.0424 iter 80/100 done | step 405 | w 1.22611 | loss 0.0435 | grad -0.0184 iter 81/100 done | step 410 | w 1.22761 | loss 0.0454 | grad -0.0352 iter 82/100 done | step 415 | w 1.22761 | loss 0.0444 | grad 0.0206 iter 83/100 done | step 420 | w 1.22788 | loss 0.0434 | grad 0.0002 iter 84/100 done | step 425 | w 1.22852 | loss 0.0393 | grad -0.0144 iter 85/100 done | step 430 | w 1.22787 | loss 0.0438 | grad -0.0081 iter 86/100 done | step 435 | w 1.22866 | loss 0.0451 | grad -0.0259 iter 87/100 done | step 440 | w 1.22834 | loss 0.0410 | grad 0.0073 iter 88/100 done | step 445 | w 1.22975 | loss 0.0406 | grad -0.0768 iter 89/100 done | step 450 | w 1.23034 | loss 0.0427 | grad -0.0344 iter 90/100 done | step 455 | w 1.23006 | loss 0.0496 | grad -0.0083 iter 91/100 done | step 460 | w 1.23052 | loss 0.0438 | grad -0.0056 iter 92/100 done | step 465 | w 1.23073 | loss 0.0441 | grad 0.0013 iter 93/100 done | step 470 | w 1.23094 | loss 0.0471 | grad 0.0267 iter 94/100 done | step 475 | w 1.23106 | loss 0.0392 | grad 0.0114 iter 95/100 done | step 480 | w 1.23164 | loss 0.0459 | grad 0.0033 iter 96/100 done | step 485 | w 1.23252 | loss 0.0481 | grad -0.0301 iter 97/100 done | step 490 | w 1.23304 | loss 0.0368 | grad -0.0023 iter 98/100 done | step 495 | w 1.23335 | loss 0.0429 | grad -0.0010 iter 99/100 done | step 500 | w 1.23343 | loss 0.0513 | grad -0.0131 ```python fig, axes = plt.subplots(nrows=1, ncols=3, sharex=True, sharey=False, figsize=(12,3)) axes[0].plot(info_dict['trace_loss_list'], '.-'); axes[0].set_title('loss'); axes[1].plot(info_dict['trace_grad_list'], '.-'); axes[1].set_title('grad'); axes[2].plot(info_dict['trace_w_list'], '.-'); axes[2].set_title('w'); ``` ### Discussion 2b: Does it appear from the *parameter* values in trace above that the SGD procedure converged? ### Discussion 2c: Does it appear from the *loss* values in trace above that the SGD procedure converged? ### Discussion 2d: Does it appear from the *grad* values in trace above that the SGD procedure converged? ```python ``` ```python ``` ## Try with smaller batch_size = 10 ```python wopt, info_dict = minimize_via_sgd(xtrain_N, ytrain_N, step_size=0.01, batch_size=10); ``` iter 0/100 done | step 100 | w 0.91625 | loss 0.1191 | grad -0.3511 iter 1/100 done | step 200 | w 1.14951 | loss 0.0377 | grad 0.0505 iter 2/100 done | step 300 | w 1.20424 | loss 0.0991 | grad 0.1091 iter 3/100 done | step 400 | w 1.23031 | loss 0.0381 | grad 0.0042 iter 4/100 done | step 500 | w 1.23886 | loss 0.0511 | grad -0.2389 iter 5/100 done | step 600 | w 1.24595 | loss 0.0859 | grad -0.1187 iter 6/100 done | step 700 | w 1.25205 | loss 0.0334 | grad 0.1019 iter 7/100 done | step 800 | w 1.23007 | loss 0.0334 | grad -0.0147 iter 8/100 done | step 900 | w 1.22628 | loss 0.0573 | grad 0.0265 iter 9/100 done | step 1000 | w 1.23810 | loss 0.0412 | grad 0.0452 iter 10/100 done | step 1100 | w 1.22357 | loss 0.0227 | grad 0.0010 iter 11/100 done | step 1200 | w 1.23342 | loss 0.0515 | grad -0.0504 iter 12/100 done | step 1300 | w 1.24008 | loss 0.0484 | grad -0.2045 iter 13/100 done | step 1400 | w 1.24485 | loss 0.0738 | grad -0.0568 iter 14/100 done | step 1500 | w 1.23728 | loss 0.0317 | grad 0.0817 iter 15/100 done | step 1600 | w 1.22575 | loss 0.0404 | grad 0.0695 iter 16/100 done | step 1700 | w 1.22235 | loss 0.0293 | grad 0.1196 iter 17/100 done | step 1800 | w 1.22595 | loss 0.0330 | grad -0.1241 iter 18/100 done | step 1900 | w 1.23493 | loss 0.0149 | grad 0.0567 iter 19/100 done | step 2000 | w 1.23858 | loss 0.0361 | grad -0.0242 iter 20/100 done | step 2100 | w 1.23371 | loss 0.0423 | grad 0.0176 iter 21/100 done | step 2200 | w 1.23280 | loss 0.0428 | grad -0.0151 iter 22/100 done | step 2300 | w 1.24703 | loss 0.0544 | grad -0.0138 iter 23/100 done | step 2400 | w 1.24159 | loss 0.0544 | grad 0.0364 iter 24/100 done | step 2500 | w 1.24189 | loss 0.0278 | grad -0.0217 iter 25/100 done | step 2600 | w 1.23713 | loss 0.0509 | grad 0.0451 iter 26/100 done | step 2700 | w 1.23292 | loss 0.0502 | grad 0.1502 iter 27/100 done | step 2800 | w 1.23131 | loss 0.0266 | grad -0.0233 iter 28/100 done | step 2900 | w 1.23236 | loss 0.0267 | grad 0.0038 iter 29/100 done | step 3000 | w 1.22569 | loss 0.0350 | grad -0.0734 iter 30/100 done | step 3100 | w 1.22976 | loss 0.0349 | grad 0.0029 iter 31/100 done | step 3200 | w 1.23033 | loss 0.0173 | grad 0.0927 iter 32/100 done | step 3300 | w 1.23814 | loss 0.0387 | grad 0.0252 iter 33/100 done | step 3400 | w 1.23415 | loss 0.0182 | grad -0.0323 iter 34/100 done | step 3500 | w 1.23714 | loss 0.0549 | grad 0.1117 iter 35/100 done | step 3600 | w 1.23755 | loss 0.0294 | grad -0.0801 iter 36/100 done | step 3700 | w 1.23231 | loss 0.0303 | grad 0.1700 iter 37/100 done | step 3800 | w 1.23270 | loss 0.0449 | grad 0.0136 iter 38/100 done | step 3900 | w 1.22366 | loss 0.0325 | grad 0.0768 iter 39/100 done | step 4000 | w 1.22075 | loss 0.0216 | grad -0.0362 iter 40/100 done | step 4100 | w 1.23983 | loss 0.0784 | grad -0.1227 iter 41/100 done | step 4200 | w 1.22596 | loss 0.0632 | grad 0.1253 iter 42/100 done | step 4300 | w 1.23038 | loss 0.0280 | grad -0.1657 iter 43/100 done | step 4400 | w 1.23377 | loss 0.0390 | grad -0.1455 iter 44/100 done | step 4500 | w 1.22033 | loss 0.0512 | grad -0.1874 iter 45/100 done | step 4600 | w 1.22807 | loss 0.0153 | grad 0.0763 iter 46/100 done | step 4700 | w 1.23235 | loss 0.0493 | grad -0.2164 iter 47/100 done | step 4800 | w 1.22289 | loss 0.0420 | grad -0.1002 iter 48/100 done | step 4900 | w 1.22318 | loss 0.0355 | grad 0.0695 iter 49/100 done | step 5000 | w 1.22875 | loss 0.0320 | grad 0.0094 iter 50/100 done | step 5100 | w 1.21265 | loss 0.0573 | grad 0.0005 iter 51/100 done | step 5200 | w 1.23306 | loss 0.0531 | grad -0.1133 iter 52/100 done | step 5300 | w 1.23758 | loss 0.0500 | grad 0.0407 iter 53/100 done | step 5400 | w 1.23312 | loss 0.0659 | grad 0.0761 iter 54/100 done | step 5500 | w 1.23100 | loss 0.0128 | grad -0.0745 iter 55/100 done | step 5600 | w 1.23669 | loss 0.0392 | grad 0.0078 iter 56/100 done | step 5700 | w 1.24015 | loss 0.0410 | grad -0.0476 iter 57/100 done | step 5800 | w 1.22657 | loss 0.0248 | grad 0.0298 iter 58/100 done | step 5900 | w 1.22985 | loss 0.0573 | grad 0.0474 iter 59/100 done | step 6000 | w 1.22832 | loss 0.0259 | grad -0.0250 iter 60/100 done | step 6100 | w 1.23766 | loss 0.0662 | grad -0.0484 iter 61/100 done | step 6200 | w 1.23839 | loss 0.0862 | grad -0.2737 iter 62/100 done | step 6300 | w 1.23734 | loss 0.0323 | grad -0.0365 iter 63/100 done | step 6400 | w 1.23474 | loss 0.0286 | grad -0.0304 iter 64/100 done | step 6500 | w 1.24034 | loss 0.0578 | grad 0.1138 iter 65/100 done | step 6600 | w 1.23524 | loss 0.0212 | grad 0.0872 iter 66/100 done | step 6700 | w 1.22606 | loss 0.0438 | grad 0.1876 iter 67/100 done | step 6800 | w 1.23196 | loss 0.0306 | grad -0.0178 iter 68/100 done | step 6900 | w 1.23354 | loss 0.0525 | grad -0.0704 iter 69/100 done | step 7000 | w 1.22663 | loss 0.0442 | grad -0.0648 iter 70/100 done | step 7100 | w 1.22977 | loss 0.0419 | grad 0.0042 iter 71/100 done | step 7200 | w 1.23995 | loss 0.0629 | grad 0.0045 iter 72/100 done | step 7300 | w 1.22573 | loss 0.0197 | grad 0.0462 iter 73/100 done | step 7400 | w 1.22610 | loss 0.0434 | grad 0.1277 iter 74/100 done | step 7500 | w 1.22869 | loss 0.0187 | grad -0.0309 iter 75/100 done | step 7600 | w 1.22590 | loss 0.0532 | grad 0.0942 iter 76/100 done | step 7700 | w 1.22963 | loss 0.0493 | grad 0.1311 iter 77/100 done | step 7800 | w 1.23985 | loss 0.0852 | grad 0.0897 iter 78/100 done | step 7900 | w 1.23384 | loss 0.0514 | grad 0.0544 iter 79/100 done | step 8000 | w 1.23430 | loss 0.0295 | grad -0.1374 iter 80/100 done | step 8100 | w 1.22765 | loss 0.0141 | grad -0.0433 iter 81/100 done | step 8200 | w 1.23420 | loss 0.0216 | grad -0.0395 iter 82/100 done | step 8300 | w 1.22563 | loss 0.0665 | grad -0.1015 iter 83/100 done | step 8400 | w 1.24080 | loss 0.0364 | grad 0.0033 iter 84/100 done | step 8500 | w 1.23774 | loss 0.0632 | grad -0.0353 iter 85/100 done | step 8600 | w 1.23484 | loss 0.0781 | grad -0.0488 iter 86/100 done | step 8700 | w 1.23275 | loss 0.0117 | grad -0.0342 iter 87/100 done | step 8800 | w 1.23411 | loss 0.0321 | grad 0.0455 iter 88/100 done | step 8900 | w 1.22806 | loss 0.0688 | grad -0.0674 iter 89/100 done | step 9000 | w 1.23307 | loss 0.0222 | grad 0.1727 iter 90/100 done | step 9100 | w 1.23491 | loss 0.0251 | grad -0.0312 iter 91/100 done | step 9200 | w 1.23106 | loss 0.0519 | grad 0.0098 iter 92/100 done | step 9300 | w 1.23303 | loss 0.0437 | grad -0.1625 iter 93/100 done | step 9400 | w 1.23277 | loss 0.0708 | grad -0.2593 iter 94/100 done | step 9500 | w 1.22882 | loss 0.0636 | grad 0.0411 iter 95/100 done | step 9600 | w 1.24039 | loss 0.0208 | grad -0.0708 iter 96/100 done | step 9700 | w 1.23499 | loss 0.0839 | grad 0.0251 iter 97/100 done | step 9800 | w 1.23123 | loss 0.0467 | grad 0.0922 iter 98/100 done | step 9900 | w 1.23677 | loss 0.0182 | grad 0.0165 iter 99/100 done | step 10000 | w 1.22925 | loss 0.0492 | grad 0.0620 ```python fig, axes = plt.subplots(nrows=1, ncols=3, sharex=True, sharey=False, figsize=(12,3)) axes[0].plot(info_dict['trace_loss_list'], '.-'); axes[0].set_title('loss'); axes[1].plot(info_dict['trace_grad_list'], '.-'); axes[1].set_title('grad'); axes[2].plot(info_dict['trace_w_list'], '.-'); axes[2].set_title('w'); ``` ### Try with even smaller batch_size of 1 ```python # TODO write code here ``` ### Discussion 3b: What happens here with this smaller batch size? Is it converging? # Part 5: SGD for MLPClassifier Let's revisit the XOR dataset from our previous lab, and try SGD for it. ```python def make_xor_dataset(n_per_blob=50, stddev=0.4, random_state=0): random_state = np.random.RandomState(random_state) cov_22 = np.square(stddev) * np.eye(2) x_00 = random_state.multivariate_normal([-1, -1], cov_22, size=n_per_blob) x_01 = random_state.multivariate_normal([-1, +1], cov_22, size=n_per_blob) x_10 = random_state.multivariate_normal([+1, -1], cov_22, size=n_per_blob) x_11 = random_state.multivariate_normal([+1, +1], cov_22, size=n_per_blob) N = n_per_blob * 4 x_N2 = np.vstack([x_00, x_11, x_01, x_10]) assert x_N2.shape == (N, 2) y_N = np.hstack([np.ones(N//2), np.zeros(N//2)]).astype(np.int32) assert y_N.shape == (N,) # Shuffle the order perm_ids = random_state.permutation(N) x_N2 = x_N2[perm_ids].copy() y_N = y_N[perm_ids].copy() return x_N2, y_N ``` ```python x_tr_N2, y_tr_N = make_xor_dataset(n_per_blob=50) ``` ```python plt.figure(figsize=(4,4)) plt.plot(x_tr_N2[y_tr_N==0,0], x_tr_N2[y_tr_N==0,1], 'rx', label='y=0', mew=2); plt.plot(x_tr_N2[y_tr_N==1,0], x_tr_N2[y_tr_N==1,1], 'b+', label='y=1', mew=2); plt.xlabel('x_1'); plt.ylabel('x_2'); plt.legend(bbox_to_anchor=(1.0, 0.5)); ``` # Setup: Create Utility function for visualizing classifier predictions You do NOT need to understand the details of this function. We'll just use it as is. ```python def plot_pretty_probabilities_for_clf( clf, ax=None, x1_grid=(-2.1, 2.1, 50), x2_grid=(-2.1, 2.1, 50), x1_ticks=[-1, 0, 1], x2_ticks=[-1, 0, 1], do_show_colorbar=False, c_ticks=np.asarray([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]), c_num_levels=100, ): ''' Display predicted probabilities from classifier as color contour plot Args ---- clf : sklearn object that implements classifier API ax : matplotlib axis handle, or None If provided, will use axis handle as primary axis to plot on. If None, will use the current handle, or make new one as necessary. x1_grid : tuple-like or array-like If tuple of length 3, interpreted as args to np.linspace Otherwise, cast to array and assumed to be a 1d grid of x1 values x2_grid : tuple-like or array-like If tuple of length 3, interpreted as args to np.linspace Otherwise, cast to array and assumed to be a 1d grid of x2 values ''' # Activate the current axis, if necessary if ax is None: cur_ax = plt.gca() else: cur_ax = ax plt.sca(cur_ax) # Create dense grid of x1 and x2 values # useful for visualizing probabilities if isinstance(x1_grid, tuple) and len(x1_grid) == 3: x1_grid = np.linspace(x1_grid[0], x1_grid[1], x1_grid[2]) if isinstance(x2_grid, tuple) and len(x2_grid) == 3: x2_grid = np.linspace(x2_grid[0], x2_grid[1], x2_grid[2]) x1_grid = np.asarray(x1_grid).flatten() x2_grid = np.asarray(x2_grid).flatten() c_levels = np.linspace(0.0, 1.0, c_num_levels) # Get regular grid of G x H points, where each point is an (x1, x2) location G = x1_grid.size H = x2_grid.size x1_GH, x2_GH = np.meshgrid(x1_grid, x2_grid) # Combine the x1 and x2 values into one array # Flattened into M = G x H rows # Each row of x_M2 is a 2D vector [x_m1, x_m2] x_M2 = np.hstack([x1_GH.flatten()[:,np.newaxis], x2_GH.flatten()[:,np.newaxis]]) # Predict proba for each point in the flattened grid yproba1_M = clf.predict_proba(x_M2)[:,1] # Reshape the M probas into the GxH 2D field yproba1_GH = np.reshape(yproba1_M, x1_GH.shape) # Contour plot cmap = plt.cm.RdYlBu my_contourf_h = plt.contourf( x1_GH, x2_GH, yproba1_GH, levels=c_levels, vmin=0, vmax=1.0, cmap=cmap, alpha=0.5) # Edit the ticks observed if x1_ticks is not None: plt.xticks(x1_ticks, x1_ticks); if x2_ticks is not None: plt.yticks(x2_ticks, x2_ticks); if do_show_colorbar: left, bottom, width, height = plt.gca().get_position().bounds cax = plt.gcf().add_axes([left + 1.1*width, bottom, 0.03, height]) plt.colorbar(my_contourf_h, orientation='vertical', cax=cax, ticks=c_ticks); plt.sca(cur_ax); ``` ## Try an MLP with 2 hidden units, batch size of 25 This time, we'll use SGD as built in solver ```python mlp_2hidden_run5 = sklearn.neural_network.MLPClassifier( hidden_layer_sizes=[2], activation='relu', solver='sgd', learning_rate_init=0.1, random_state=5, batch_size=25, ) ``` ```python # Fit the model to training data mlp_2hidden_run5.fit(x_tr_N2, y_tr_N) ``` MLPClassifier(batch_size=25, hidden_layer_sizes=[2], learning_rate_init=0.1, random_state=5, solver='sgd') ### Visualize the results using our utility function ```python plt.figure(figsize=(4,4)) plot_pretty_probabilities_for_clf(mlp_2hidden_run5, do_show_colorbar=True, ax=plt.gca()); plt.plot(x_tr_N2[y_tr_N==0,0], x_tr_N2[y_tr_N==0,1], 'rx', label='y=0', mew=2); plt.plot(x_tr_N2[y_tr_N==1,0], x_tr_N2[y_tr_N==1,1], 'b+', label='y=1', mew=2); ``` ```python ### Visualize the trace of the loss plt.plot(mlp_2hidden_run5.loss_curve_, 'k.-') ``` # Try several trials with batch_size of 25 ```python for trial in [1, 2, 3, 4, 5]: mlp_2hidden_batchsize25 = sklearn.neural_network.MLPClassifier( hidden_layer_sizes=[2], activation='relu', solver='sgd', learning_rate_init=0.05, random_state=trial, batch_size=25, ) # Fit the model to training data mlp_2hidden_batchsize25.fit(x_tr_N2, y_tr_N) # Visualize the trace of the loss plt.plot(mlp_2hidden_batchsize25.loss_curve_, '.-', label='trial %d' % trial) plt.legend(); ``` ### Now try several trials with a batch_size of 1 ```python for trial in [1, 2, 3, 4, 5]: mlp_2hidden_batchsize1 = sklearn.neural_network.MLPClassifier( hidden_layer_sizes=[2], activation='relu', solver='sgd', learning_rate_init=0.05, random_state=trial, batch_size=1, ) # Fit the model to training data mlp_2hidden_batchsize1.fit(x_tr_N2, y_tr_N) # Visualize the trace of the loss plt.plot(mlp_2hidden_batchsize1.loss_curve_, '.-', label='trial %d' % trial) plt.legend(); ``` ### Discussion 4a: What is happening here? ```python ``` ```python ```
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module DFT.Plan ( module HM , DFTPlanID(..) , DFTType(..) , DFTPlan , FFTWLock , getFFTWLock , importFFTWWisdom , exportFFTWWisdom , getDFTPlan , emptyPlan , checkPlanID , dftExecuteWithPlan , dftExecuteBatch , dftExecuteBatchP , dftExecute , dft2dPlan , idft2dPlan , dft1dGPlan , idft1dGPlan ) where import Control.Concurrent.Async import Control.Concurrent.MVar import Control.Monad as M -- import Control.Monad.Parallel as MP import Data.Bits (Bits, complement, (.&.), (.|.)) import Data.Complex import Data.Hashable import Data.HashMap.Strict as HM import Data.List as L import Data.Vector.Storable as VS import Data.Vector.Storable.Mutable as VSM import DFT.FFI import Foreign.C import Foreign.Marshal.Array import GHC.Generics (Generic) -- The type definitions of Flag and Sign are borrowed from the fft package. -- This module allows shared plan execuation so that dft can run parallelly. newtype Flag = Flag { unFlag :: FFTWFlag } deriving (Eq, Show, Num, Bits) data Sign = DFTForward | DFTBackward deriving (Eq, Show) measure :: Flag measure = Flag c_measure unSign :: Sign -> FFTWSign unSign DFTForward = c_forward unSign DFTBackward = c_backward data DFTType = DFT1DG | IDFT1DG | DFT2D | IDFT2D deriving (Show, Eq, Generic) instance Hashable DFTType data DFTPlanID = DFTPlanID { dftType :: DFTType , dftDims :: [Int] , dftIdx :: [Int] } deriving (Show, Eq, Generic) instance Hashable DFTPlanID type DFTPlan = HashMap DFTPlanID Plan type FFTWLock = MVar () {-# INLINE getFFTWLock #-} getFFTWLock :: IO FFTWLock getFFTWLock = newMVar () {-# INLINE importFFTWWisdom #-} importFFTWWisdom :: FilePath -> IO () importFFTWWisdom filePath = newCString filePath >>= c_import_wisdom_filename >> return () {-# INLINE exportFFTWWisdom #-} exportFFTWWisdom :: FilePath -> IO () exportFFTWWisdom filePath = newCString filePath >>= c_export_wisdom_filename >> return () {-# INLINE emptyPlan #-} emptyPlan :: DFTPlan emptyPlan = HM.empty {-# INLINE checkPlanID #-} checkPlanID :: DFTPlan -> DFTPlanID -> Bool checkPlanID plan planID = case HM.lookup planID plan of Nothing -> False Just p -> True {-# INLINE getDFTPlan #-} getDFTPlan :: DFTPlan -> DFTPlanID -> Plan getDFTPlan plan planID = case HM.lookup planID plan of Nothing -> error $ "getDFTPlan: couldn't find plan for ID " L.++ show planID Just p -> p {-# INLINE dftExecuteWithPlan #-} dftExecuteWithPlan :: DFTPlanID -> Plan -> VS.Vector (Complex Double) -> IO (VS.Vector (Complex Double)) dftExecuteWithPlan planID@(DFTPlanID t d i) plan vec = do v <- VSM.new (L.product d) VS.unsafeWith vec $ \ip -> VSM.unsafeWith v $ \op -> c_execute_dft plan ip op u <- VS.freeze v if t == IDFT1DG || t == IDFT2D then if L.null i then return $ VS.map (/ (fromIntegral . L.product $ d)) u else if size == 0 then error $ "dftExecuteWithPlan: dimension error.\n" L.++ "dims: " L.++ show d L.++ "\nIdx: " L.++ show i else return $ VS.map (/ (fromIntegral size)) u else return u where size = L.product . L.take (L.last i - L.head i + 1) . L.drop (L.head i) $ d {-# INLINE dftExecuteBatch #-} dftExecuteBatch :: DFTPlan -> DFTPlanID -> [VS.Vector (Complex Double)] -> IO [VS.Vector (Complex Double)] dftExecuteBatch hashMap planID@(DFTPlanID t d i) vecs = case HM.lookup planID hashMap of Nothing -> error $ "dftExecuteBatch: couldn't find plan for ID " L.++ show planID L.++ "\nin\n" L.++ (show hashMap) Just plan -> M.mapM (dftExecuteWithPlan planID plan) vecs {-# INLINE dftExecuteBatchP #-} dftExecuteBatchP :: DFTPlan -> DFTPlanID -> [VS.Vector (Complex Double)] -> IO [VS.Vector (Complex Double)] dftExecuteBatchP hashMap planID@(DFTPlanID t d i) vecs = case HM.lookup planID hashMap of Nothing -> error $ "dftExecuteBatch: couldn't find plan for ID " L.++ show planID Just plan -> mapConcurrently (dftExecuteWithPlan planID plan) vecs {-# INLINE dftExecute #-} dftExecute :: DFTPlan -> DFTPlanID -> VS.Vector (Complex Double) -> IO (VS.Vector (Complex Double)) dftExecute hashMap planID@(DFTPlanID t d i) vec = case HM.lookup planID hashMap of Nothing -> error $ "dftExecute: couldn't find plan for ID " L.++ show planID L.++ "\n" L.++ show (keys hashMap) Just plan -> dftExecuteWithPlan planID plan vec {-# INLINE dft2dG #-} dft2dG :: MVar () -> Int -> Int -> VS.Vector (Complex Double) -> Sign -> Flag -> IO (Plan, VS.Vector (Complex Double)) dft2dG lock' rows cols vec sign flag = do v <- VSM.new (rows * cols) x <- takeMVar lock' p <- VS.unsafeWith vec $ \ip -> VSM.unsafeWith v $ \op -> do c_plan_dft_2d (fromIntegral cols) (fromIntegral rows) ip op (unSign sign) (unFlag flag) putMVar lock' x c_execute p u <- VS.freeze v return (p, u) {-# INLINE dft2dPlan #-} dft2dPlan :: FFTWLock -> DFTPlan -> Int -> Int -> VS.Vector (Complex Double) -> IO (DFTPlan, VS.Vector (Complex Double)) dft2dPlan lock' hashMap rows cols vec = case HM.lookup planID hashMap of Nothing -> do (p, v) <- dft2dG lock' rows cols vec DFTForward measure return (HM.insert planID p hashMap, v) Just p -> do v <- dftExecuteWithPlan planID p vec return (hashMap, v) where planID = DFTPlanID DFT2D [cols, rows] [] {-# INLINE idft2dPlan #-} idft2dPlan :: FFTWLock -> DFTPlan -> Int -> Int -> VS.Vector (Complex Double) -> IO (DFTPlan, VS.Vector (Complex Double)) idft2dPlan lock' hashMap rows cols vec = case HM.lookup planID hashMap of Nothing -> do (p, v) <- dft2dG lock' rows cols vec DFTBackward measure return (HM.insert planID p hashMap, VS.map (/ (fromIntegral $ rows * cols)) v) Just p -> do v <- dftExecuteWithPlan planID p vec return (hashMap, v) where planID = DFTPlanID IDFT2D [cols, rows] [] -- This is a generalied 1d dft, the 1 dimension can be many dimensions -- which are ascending ordered and continued. For example, given a N -- dimension array, the generalized 1d dft dimension is -- either [0,1..M] or [M,M+1.. N-1], where 0 <= M and M <= N-1 -- the dimension corresponding to the largest index spins the fastest. {-# INLINE dft1dGGeneric #-} dft1dGGeneric :: MVar () -> [Int] -> [Int] -> VS.Vector (Complex Double) -> Sign -> Flag -> IO (Plan, VS.Vector (Complex Double)) dft1dGGeneric lock' dims dftIndex vec sign flag | L.and (L.zipWith (\a b -> a + 1 == b) dftIndex . L.tail $ dftIndex) && (not . L.null $ dftIndex) && (L.head dftIndex == 0 || L.last dftIndex == rank - 1) = do v <- VSM.new . L.product $ dims x <- takeMVar lock' p <- VS.unsafeWith vec $ \ip -> VSM.unsafeWith v $ \op -> withArray (L.map fromIntegral dftDims) $ \n -> do let totalNum = L.product dims dftNum = L.product dftDims stride = if L.last dftIndex == rank - 1 then 1 else L.product . L.drop (1 + L.last dftIndex) $ dims dist = if L.last dftIndex == rank - 1 then dftNum else 1 c_plan_many_dft (fromIntegral dftRank) n (fromIntegral $ div totalNum dftNum) ip n (fromIntegral stride) (fromIntegral dist) op n (fromIntegral stride) (fromIntegral dist) (unSign sign) (unFlag flag) c_execute p putMVar lock' x u <- VS.freeze v return (p, u) | otherwise = error $ "dft1dG: dimension list doesn't satisify the restriction of generalized 1d dft.\n" L.++ "dims: " L.++ show dims L.++ "\ndftIndex: " L.++ show dftIndex where rank = L.length dims dftRank = L.length dftIndex dftDims = L.take (L.last dftIndex - L.head dftIndex + 1) . L.drop (L.head dftIndex) $ dims {-# INLINE dft1dGPlan #-} dft1dGPlan :: FFTWLock -> DFTPlan -> [Int] -> [Int] -> VS.Vector (Complex Double) -> IO (DFTPlan, VS.Vector (Complex Double)) dft1dGPlan lock' hashMap dims dftIndex vec = do when (L.product dims /= VS.length vec) (error "dft1dGPlan: input vector length and dims don't match.") case HM.lookup planID hashMap of Nothing -> do (p, v) <- dft1dGGeneric lock' dims dftIndex vec DFTForward measure return (HM.insert planID p hashMap, v) Just p -> do v <- dftExecuteWithPlan planID p vec return (hashMap, v) where planID = DFTPlanID DFT1DG dims dftIndex {-# INLINE idft1dGPlan #-} idft1dGPlan :: FFTWLock -> DFTPlan -> [Int] -> [Int] -> VS.Vector (Complex Double) -> IO (DFTPlan, VS.Vector (Complex Double)) idft1dGPlan lock' hashMap dims dftIndex vec = do when (L.product dims /= VS.length vec) (error "idft1dGPlan: input vector length and dims don't match.") case HM.lookup planID hashMap of Nothing -> do (p, v) <- dft1dGGeneric lock' dims dftIndex vec DFTBackward measure return (HM.insert planID p hashMap, VS.map (/ size) v) Just p -> do v <- dftExecuteWithPlan planID p vec return (hashMap, v) where planID = DFTPlanID IDFT1DG dims dftIndex size = fromIntegral . L.product . L.take (L.last dftIndex - L.head dftIndex + 1) . L.drop (L.head dftIndex) $ dims
module Halfer import Service import System import Numeric %default total -- Helpful type alias for even integers public export EvenNumber : Type EvenNumber = (n : WFInt ** Parity n 2) ||| Return a Just EvenNumber if the number is even, or Nothing otherwise. public export maybeEven : Integer -> Maybe EvenNumber ||| Round a number down to the nearest even number public export forceEven : Integer -> EvenNumber -- maybeEven a with (mod a 2) proof p -- maybeEven a | 0 = Just ((cast a) ** ModIsZero p) -- maybeEven a | _ = Nothing -- Run external service public export runHalfer : EvenNumber -> IO Integer runHalfer = do ?run public export halferContract : (a : EvenNumber) -> Contract (runHalfer a) Integer halferContract a = MkContract (runHalfer a) public export halferService : EvenNumber -> Service Integer halferService a = Promise (halferContract a)
// Copyright 2015 Cloudera, Inc. // // 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. // // Some portions copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. // // ------------------------------------------------------------ // This file implements a cache based on the NVML library (http://pmem.io), // specifically its "libvmem" component. This library makes it easy to program // against persistent memory hardware by exposing an API which parallels // malloc/free, but allocates from persistent memory instead of DRAM. // // We use this API to implement a cache which treats persistent memory or // non-volatile memory as if it were a larger cheaper bank of volatile memory. We // currently make no use of its persistence properties. // // Currently, we only store key/value in NVM. All other data structures such as the // ShardedLRUCache instances, hash table, etc are in DRAM. The assumption is that // the ratio of data stored vs overhead is quite high. #include "kudu/util/nvm_cache.h" #include <boost/foreach.hpp> #include <gflags/gflags.h> #include <glog/logging.h> #include <libvmem.h> #include <stdlib.h> #include <string> #include <iostream> #include <tr1/memory> #include <vector> #include "kudu/gutil/atomic_refcount.h" #include "kudu/gutil/hash/city.h" #include "kudu/gutil/stl_util.h" #include "kudu/gutil/strings/substitute.h" #include "kudu/util/atomic.h" #include "kudu/util/cache.h" #include "kudu/util/cache_metrics.h" #include "kudu/util/flags.h" #include "kudu/util/flag_tags.h" #include "kudu/util/locks.h" #include "kudu/util/metrics.h" DEFINE_string(nvm_cache_path, "/vmem", "The path at which the NVM cache will try to allocate its memory. " "This can be a tmpfs or ramfs for testing purposes."); TAG_FLAG(nvm_cache_path, experimental); DEFINE_int32(nvm_cache_allocation_retry_count, 10, "The number of times that the NVM cache will retry attempts to allocate " "memory for new entries. In between attempts, a cache entry will be " "evicted."); TAG_FLAG(nvm_cache_allocation_retry_count, advanced); TAG_FLAG(nvm_cache_allocation_retry_count, experimental); DEFINE_bool(nvm_cache_simulate_allocation_failure, false, "If true, the NVM cache will inject failures in calls to vmem_malloc " "for testing."); TAG_FLAG(nvm_cache_simulate_allocation_failure, unsafe); namespace kudu { class MetricEntity; namespace { using std::tr1::shared_ptr; using std::vector; typedef simple_spinlock MutexType; // LRU cache implementation // An entry is a variable length heap-allocated structure. Entries // are kept in a circular doubly linked list ordered by access time. struct LRUHandle { void* value; CacheDeleter* deleter; LRUHandle* next_hash; LRUHandle* next; LRUHandle* prev; size_t charge; // TODO(opt): Only allow uint32_t? size_t key_length; Atomic32 refs; uint32_t hash; // Hash of key(); used for fast sharding and comparisons uint8_t key_data[1]; // Beginning of key Slice key() const { // For cheaper lookups, we allow a temporary Handle object // to store a pointer to a key in "value". if (next == this) { return *(reinterpret_cast<Slice*>(value)); } else { return Slice(key_data, key_length); } } }; // We provide our own simple hash table since it removes a whole bunch // of porting hacks and is also faster than some of the built-in hash // table implementations in some of the compiler/runtime combinations // we have tested. E.g., readrandom speeds up by ~5% over the g++ // 4.4.3's builtin hashtable. class HandleTable { public: HandleTable() : length_(0), elems_(0), list_(NULL) { Resize(); } ~HandleTable() { delete[] list_; } LRUHandle* Lookup(const Slice& key, uint32_t hash) { return *FindPointer(key, hash); } LRUHandle* Insert(LRUHandle* h) { LRUHandle** ptr = FindPointer(h->key(), h->hash); LRUHandle* old = *ptr; h->next_hash = (old == NULL ? NULL : old->next_hash); *ptr = h; if (old == NULL) { ++elems_; if (elems_ > length_) { // Since each cache entry is fairly large, we aim for a small // average linked list length (<= 1). Resize(); } } return old; } LRUHandle* Remove(const Slice& key, uint32_t hash) { LRUHandle** ptr = FindPointer(key, hash); LRUHandle* result = *ptr; if (result != NULL) { *ptr = result->next_hash; --elems_; } return result; } private: // The table consists of an array of buckets where each bucket is // a linked list of cache entries that hash into the bucket. uint32_t length_; uint32_t elems_; LRUHandle** list_; // Return a pointer to slot that points to a cache entry that // matches key/hash. If there is no such cache entry, return a // pointer to the trailing slot in the corresponding linked list. LRUHandle** FindPointer(const Slice& key, uint32_t hash) { LRUHandle** ptr = &list_[hash & (length_ - 1)]; while (*ptr != NULL && ((*ptr)->hash != hash || key != (*ptr)->key())) { ptr = &(*ptr)->next_hash; } return ptr; } void Resize() { uint32_t new_length = 16; while (new_length < elems_ * 1.5) { new_length *= 2; } LRUHandle** new_list = new LRUHandle*[new_length]; memset(new_list, 0, sizeof(new_list[0]) * new_length); uint32_t count = 0; for (uint32_t i = 0; i < length_; i++) { LRUHandle* h = list_[i]; while (h != NULL) { LRUHandle* next = h->next_hash; uint32_t hash = h->hash; LRUHandle** ptr = &new_list[hash & (new_length - 1)]; h->next_hash = *ptr; *ptr = h; h = next; count++; } } DCHECK_EQ(elems_, count); delete[] list_; list_ = new_list; length_ = new_length; } }; // A single shard of sharded cache. class NvmLRUCache { public: explicit NvmLRUCache(VMEM *vmp); ~NvmLRUCache(); // Separate from constructor so caller can easily make an array of LRUCache void SetCapacity(size_t capacity) { capacity_ = capacity; } void SetMetrics(CacheMetrics* metrics) { metrics_ = metrics; } // Like Cache methods, but with an extra "hash" parameter. Cache::Handle* Insert(const Slice& key, uint32_t hash, void* value, size_t charge, CacheDeleter* deleter); Cache::Handle* Lookup(const Slice& key, uint32_t hash, bool caching); void Release(Cache::Handle* handle); void Erase(const Slice& key, uint32_t hash); void* AllocateAndRetry(size_t size); private: void NvmLRU_Remove(LRUHandle* e); void NvmLRU_Append(LRUHandle* e); // Just reduce the reference count by 1. // Return true if last reference bool Unref(LRUHandle* e); void FreeEntry(LRUHandle* e); // Evict the LRU item in the cache, adding it to the linked list // pointed to by 'to_remove_head'. void EvictOldestUnlocked(LRUHandle** to_remove_head); // Free all of the entries in the linked list that has to_free_head // as its head. void FreeLRUEntries(LRUHandle* to_free_head); // Wrapper around vmem_malloc which injects failures based on a flag. void* VmemMalloc(size_t size); // Initialized before use. size_t capacity_; // mutex_ protects the following state. MutexType mutex_; size_t usage_; // Dummy head of LRU list. // lru.prev is newest entry, lru.next is oldest entry. LRUHandle lru_; HandleTable table_; VMEM* vmp_; CacheMetrics* metrics_; }; NvmLRUCache::NvmLRUCache(VMEM* vmp) : usage_(0), vmp_(vmp), metrics_(NULL) { // Make empty circular linked list lru_.next = &lru_; lru_.prev = &lru_; } NvmLRUCache::~NvmLRUCache() { for (LRUHandle* e = lru_.next; e != &lru_; ) { LRUHandle* next = e->next; DCHECK_EQ(e->refs, 1); // Error if caller has an unreleased handle if (Unref(e)) { FreeEntry(e); } e = next; } } void* NvmLRUCache::VmemMalloc(size_t size) { if (PREDICT_FALSE(FLAGS_nvm_cache_simulate_allocation_failure)) { return NULL; } return vmem_malloc(vmp_, size); } bool NvmLRUCache::Unref(LRUHandle* e) { DCHECK_GT(ANNOTATE_UNPROTECTED_READ(e->refs), 0); return !base::RefCountDec(&e->refs); } void NvmLRUCache::FreeEntry(LRUHandle* e) { DCHECK_EQ(ANNOTATE_UNPROTECTED_READ(e->refs), 0); e->deleter->Delete(e->key(), e->value); if (PREDICT_TRUE(metrics_)) { metrics_->cache_usage->DecrementBy(e->charge); metrics_->evictions->Increment(); } vmem_free(vmp_, e); } // Allocate nvm memory. Try until successful or FLAGS_nvm_cache_allocation_retry_count // has been exceeded. void *NvmLRUCache::AllocateAndRetry(size_t size) { void *tmp; // There may be times that an allocation fails. With NVM we have // a fixed size to allocate from. If we cannot allocate the size // that was asked for, we will remove entries from the cache and // retry up to the configured number of retries. If this fails, we // return NULL, which will cause the caller to not insert anything // into the cache. LRUHandle *to_remove_head = NULL; tmp = VmemMalloc(size); if (tmp == NULL) { unique_lock<MutexType> l(&mutex_); int retries_remaining = FLAGS_nvm_cache_allocation_retry_count; while (tmp == NULL && retries_remaining-- > 0 && lru_.next != &lru_) { EvictOldestUnlocked(&to_remove_head); // Unlock while allocating memory. l.unlock(); tmp = VmemMalloc(size); l.lock(); } } // we free the entries here outside of mutex for // performance reasons FreeLRUEntries(to_remove_head); return tmp; } void NvmLRUCache::NvmLRU_Remove(LRUHandle* e) { e->next->prev = e->prev; e->prev->next = e->next; usage_ -= e->charge; } void NvmLRUCache::NvmLRU_Append(LRUHandle* e) { // Make "e" newest entry by inserting just before lru_ e->next = &lru_; e->prev = lru_.prev; e->prev->next = e; e->next->prev = e; usage_ += e->charge; } Cache::Handle* NvmLRUCache::Lookup(const Slice& key, uint32_t hash, bool caching) { LRUHandle* e; { lock_guard<MutexType> l(&mutex_); e = table_.Lookup(key, hash); if (e != NULL) { // If an entry exists, remove the old entry from the cache // and re-add to the end of the linked list. base::RefCountInc(&e->refs); NvmLRU_Remove(e); NvmLRU_Append(e); } } // Do the metrics outside of the lock. if (metrics_) { metrics_->lookups->Increment(); bool was_hit = (e != NULL); if (was_hit) { if (caching) { metrics_->cache_hits_caching->Increment(); } else { metrics_->cache_hits->Increment(); } } else { if (caching) { metrics_->cache_misses_caching->Increment(); } else { metrics_->cache_misses->Increment(); } } } return reinterpret_cast<Cache::Handle*>(e); } void NvmLRUCache::Release(Cache::Handle* handle) { LRUHandle* e = reinterpret_cast<LRUHandle*>(handle); bool last_reference = Unref(e); if (last_reference) { FreeEntry(e); } } void NvmLRUCache::EvictOldestUnlocked(LRUHandle** to_remove_head) { LRUHandle* old = lru_.next; NvmLRU_Remove(old); table_.Remove(old->key(), old->hash); if (Unref(old)) { old->next = *to_remove_head; *to_remove_head = old; } } void NvmLRUCache::FreeLRUEntries(LRUHandle* to_free_head) { while (to_free_head != NULL) { LRUHandle* next = to_free_head->next; FreeEntry(to_free_head); to_free_head = next; } } Cache::Handle* NvmLRUCache::Insert(const Slice& key, uint32_t hash, void* value, size_t charge, CacheDeleter* deleter) { // Account for nvm key memory. LRUHandle* e = reinterpret_cast<LRUHandle*>( AllocateAndRetry(sizeof(LRUHandle) - 1 /* sizeof(LRUHandle::key_data) */ + key.size())); LRUHandle* to_remove_head = NULL; if (!e) { return NULL; } e->value = value; memcpy(e->key_data, key.data(), key.size()); // Modify the charge to the nvm cache to account for all allocations // done from the nvm address space. In this case we allocated the value // slice object, the key slice and the key_data structure from nvm. e->charge = charge + key.size(); e->hash = hash; e->refs = 2; // One from LRUCache, one for the returned handle e->key_length = key.size(); e->deleter = deleter; if (PREDICT_TRUE(metrics_)) { metrics_->cache_usage->IncrementBy(e->charge); metrics_->inserts->Increment(); } { lock_guard<MutexType> l(&mutex_); NvmLRU_Append(e); LRUHandle* old = table_.Insert(e); if (old != NULL) { NvmLRU_Remove(old); if (Unref(old)) { old->next = to_remove_head; to_remove_head = old; } } while (usage_ > capacity_ && lru_.next != &lru_) { EvictOldestUnlocked(&to_remove_head); } } // we free the entries here outside of mutex for // performance reasons FreeLRUEntries(to_remove_head); return reinterpret_cast<Cache::Handle*>(e); } void NvmLRUCache::Erase(const Slice& key, uint32_t hash) { LRUHandle* e; bool last_reference = false; { lock_guard<MutexType> l(&mutex_); e = table_.Remove(key, hash); if (e != NULL) { NvmLRU_Remove(e); last_reference = Unref(e); } } // mutex not held here // last_reference will only be true if e != NULL if (last_reference) { FreeEntry(e); } } static const int kNumShardBits = 4; static const int kNumShards = 1 << kNumShardBits; class ShardedLRUCache : public Cache { private: gscoped_ptr<CacheMetrics> metrics_; vector<NvmLRUCache*> shards_; MutexType id_mutex_; uint64_t last_id_; VMEM* vmp_; static inline uint32_t HashSlice(const Slice& s) { return util_hash::CityHash64( reinterpret_cast<const char *>(s.data()), s.size()); } static uint32_t Shard(uint32_t hash) { return hash >> (32 - kNumShardBits); } public: explicit ShardedLRUCache(size_t capacity, const string& id, VMEM* vmp) : last_id_(0), vmp_(vmp) { const size_t per_shard = (capacity + (kNumShards - 1)) / kNumShards; for (int s = 0; s < kNumShards; s++) { gscoped_ptr<NvmLRUCache> shard(new NvmLRUCache(vmp_)); shard->SetCapacity(per_shard); shards_.push_back(shard.release()); } } virtual ~ShardedLRUCache() { STLDeleteElements(&shards_); // Per the note at the top of this file, our cache is entirely volatile. // Hence, when the cache is destructed, we delete the underlying // VMEM pool. vmem_delete(vmp_); } virtual Handle* Insert(const Slice& key, void* value, size_t charge, CacheDeleter* deleter) OVERRIDE { const uint32_t hash = HashSlice(key); return shards_[Shard(hash)]->Insert(key, hash, value, charge, deleter); } virtual Handle* Lookup(const Slice& key, CacheBehavior caching) OVERRIDE { const uint32_t hash = HashSlice(key); return shards_[Shard(hash)]->Lookup(key, hash, caching == EXPECT_IN_CACHE); } virtual void Release(Handle* handle) OVERRIDE { LRUHandle* h = reinterpret_cast<LRUHandle*>(handle); shards_[Shard(h->hash)]->Release(handle); } virtual void Erase(const Slice& key) OVERRIDE { const uint32_t hash = HashSlice(key); shards_[Shard(hash)]->Erase(key, hash); } virtual void* Value(Handle* handle) OVERRIDE { return reinterpret_cast<LRUHandle*>(handle)->value; } virtual uint64_t NewId() OVERRIDE { lock_guard<MutexType> l(&id_mutex_); return ++(last_id_); } virtual void SetMetrics(const scoped_refptr<MetricEntity>& entity) OVERRIDE { metrics_.reset(new CacheMetrics(entity)); BOOST_FOREACH(NvmLRUCache* cache, shards_) { cache->SetMetrics(metrics_.get()); } } virtual uint8_t* Allocate(int size) OVERRIDE { // Try allocating from each of the shards -- if vmem is tight, // this can cause eviction, so we might have better luck in different // shards. BOOST_FOREACH(NvmLRUCache* cache, shards_) { uint8_t* ptr = reinterpret_cast<uint8_t*>(cache->AllocateAndRetry(size)); if (ptr) return ptr; } // TODO: increment a metric here on allocation failure. return NULL; } virtual void Free(uint8_t *ptr) OVERRIDE { vmem_free(vmp_, ptr); } virtual uint8_t* MoveToHeap(uint8_t* ptr, int size) OVERRIDE { uint8_t* ret = new uint8_t[size]; memcpy(ret, ptr, size); vmem_free(vmp_, ptr); return ret; } }; } // end anonymous namespace Cache* NewLRUNvmCache(size_t capacity, const std::string& id) { // vmem_create() will fail if the capacity is too small, but with // an inscrutable error. So, we'll check ourselves. CHECK_GE(capacity, VMEM_MIN_POOL) << "configured capacity " << capacity << " bytes is less than " << "the minimum capacity for an NVM cache: " << VMEM_MIN_POOL; VMEM* vmp = vmem_create(FLAGS_nvm_cache_path.c_str(), capacity); // If we cannot create the cache pool we should not retry. PLOG_IF(FATAL, vmp == NULL) << "Could not initialize NVM cache library in path " << FLAGS_nvm_cache_path.c_str(); return new ShardedLRUCache(capacity, id, vmp); } } // namespace kudu
import catalan def balance (l : list (fin 2)) : ℤ := (l.count 1 : ℤ) - (l.count 0) @[simp] lemma balance_def {l} : balance l = (l.count 1 : ℤ) - (l.count 0) := rfl @[simp] lemma balance_nil : balance [] = 0 := by rw [balance, list.count_nil, list.count_nil, sub_self] structure dyck_word := (chars : list (fin 2)) (total_balance : balance chars = 0) (suffix_balance : ∀ t, t <:+ chars → balance t ≥ 0) lemma list.length_eq_count0_add_count1 (l : list (fin 2)) : l.length = l.count 0 + l.count 1 := begin induction l with head tail ih, { simp only [list.count_nil, list.length], }, { fin_cases head, all_goals {simp [ih, nat.succ_eq_add_one], abel, }, } end namespace dyck_word lemma even_length (d : dyck_word) : even d.chars.length := begin use [d.chars.count 0], have h₁ := d.total_balance, rw [balance] at h₁, rw [list.length_eq_count0_add_count1], linarith, end lemma list.is_suffix_of_append {α} {l a b : list α} (h : l <:+ (a ++ b)) : (∃ k, k <:+ a ∧ k ++ b = l) ∨ (l <:+ b) := begin simp [←list.mem_tails] at h, simp_rw [list.mem_tails] at h, cases h, {left, exact h}, right, replace h := list.tail_subset _ h, rwa list.mem_tails at h, end def append (a b : dyck_word) : dyck_word := { chars := a.chars ++ b.chars, total_balance := by { have h₁ := a.total_balance, have h₂ := b.total_balance, simp [balance, list.count_append] at *, linarith, }, suffix_balance := by { rintro t ht, rcases list.is_suffix_of_append ht with ⟨ta, hta, rfl⟩ | ht₂, { have h₁ := a.suffix_balance _ hta, have h₂ := b.total_balance, simp only [int.coe_nat_add, list.count_append, balance_def] at *, linarith, }, { linarith [b.suffix_balance _ ht₂], } }, } lemma list.suffix_singleton {α} {a : α} {l} (h : l <:+ [a]) : l = [] ∨ l = [a] := begin cases l, {left, refl}, right, have h₁ := list.length_le_of_sublist (list.sublist_of_suffix h), simp [list.length_eq_zero] at h₁, subst h₁, apply list.eq_of_sublist_of_length_eq (list.sublist_of_suffix h), simp, end def wrap (a : dyck_word) : dyck_word := { chars := [0] ++ a.chars ++ [1], total_balance := by { simpa using a.total_balance, }, suffix_balance := by { rintro t ht, simp at ht, rw list.suffix_cons_iff at ht, rcases ht with rfl | _, { apply ge_of_eq, simpa using a.total_balance, }, { rcases list.is_suffix_of_append ht with ⟨ta, hta, rfl⟩ | ht₂, { have h₁ := a.suffix_balance _ hta, simp at *, linarith, }, { rcases list.suffix_singleton ht₂ with ⟨rfl, rfl⟩, { simp }, { simp [h] }, } } }, } -- TODO: unique construction through nil, append, wrap -> induction principle on dyck_word def sized_dyck_word (n : ℕ) := {d : dyck_word // d.chars.length = n} instance {n} : fintype (sized_dyck_word n) := sorry theorem catalan_eq_dyck_words_card {n : ℕ} : catalan n = fintype.card (sized_dyck_word (2 * n)) := sorry end dyck_word
(* This file is generated by Why3's Coq driver *) (* Beware! Only edit allowed sections below *) Require Import BuiltIn. Require Reals.R_sqrt. Require BuiltIn. Require real.Real. Require real.Square. (* Why3 assumption *) Definition dot (x1:R) (x2:R) (y1:R) (y2:R): R := ((x1 * y1)%R + (x2 * y2)%R)%R. (* Why3 assumption *) Definition norm2 (x1:R) (x2:R): R := ((Reals.RIneq.Rsqr x1) + (Reals.RIneq.Rsqr x2))%R. Axiom norm2_pos : forall (x1:R) (x2:R), (0%R <= (norm2 x1 x2))%R. Axiom Lagrange : forall (a1:R) (a2:R) (b1:R) (b2:R), (((norm2 a1 a2) * (norm2 b1 b2))%R = ((Reals.RIneq.Rsqr (dot a1 a2 b1 b2)) + (Reals.RIneq.Rsqr ((a1 * b2)%R - (a2 * b1)%R)%R))%R). Axiom CauchySchwarz_aux : forall (x1:R) (x2:R) (y1:R) (y2:R), ((Reals.RIneq.Rsqr (dot x1 x2 y1 y2)) <= ((norm2 x1 x2) * (norm2 y1 y2))%R)%R. (* Why3 assumption *) Definition norm (x1:R) (x2:R): R := (Reals.R_sqrt.sqrt (norm2 x1 x2)). Axiom norm_pos : forall (x1:R) (x2:R), (0%R <= (norm x1 x2))%R. Axiom sqr_le_sqrt : forall (x:R) (y:R), ((Reals.RIneq.Rsqr x) <= y)%R -> (x <= (Reals.R_sqrt.sqrt y))%R. Require Import Why3. Ltac ae := why3 "Alt-Ergo,0.99.1," timelimit 3; admit. (* Why3 goal *) Theorem CauchySchwarz : forall (x1:R) (x2:R) (y1:R) (y2:R), ((dot x1 x2 y1 y2) <= ((norm x1 x2) * (norm y1 y2))%R)%R. (* Why3 intros x1 x2 y1 y2. *) intros x1 x2 y1 y2. unfold norm. rewrite <- R_sqrt.sqrt_mult. apply sqr_le_sqrt. ae. ae. ae. Admitted.
Giovanni Francesco Stoppani ( November 26 , 1753 ) – Cardinal @-@ Bishop of Palestrina
We would be grateful if you took the time in order for us to receive responses in either format. This will help us develop, improve and advance our website for the benefit of all the region 6 members. Please could you take the time to answer our short survey by clicking below.
------------------------------------------------------------------------ -- The Agda standard library -- -- Properties, related to products, that rely on the K rule ------------------------------------------------------------------------ {-# OPTIONS --with-K --safe #-} module Data.Product.Properties.WithK where open import Data.Product open import Data.Product.Properties open import Function open import Relation.Binary using (Decidable) open import Relation.Binary.PropositionalEquality open import Relation.Nullary using (yes; no) ------------------------------------------------------------------------ -- Equality module _ {a b} {A : Set a} {B : Set b} where ,-injective : ∀ {a c : A} {b d : B} → (a , b) ≡ (c , d) → a ≡ c × b ≡ d ,-injective refl = refl , refl module _ {a b} {A : Set a} {B : A → Set b} where ,-injectiveʳ : ∀ {a} {b c : B a} → (Σ A B ∋ (a , b)) ≡ (a , c) → b ≡ c ,-injectiveʳ refl = refl ≡-dec : Decidable _≡_ → (∀ {a} → Decidable {A = B a} _≡_) → Decidable {A = Σ A B} _≡_ ≡-dec dec₁ dec₂ (a , x) (b , y) with dec₁ a b ... | no a≢b = no (a≢b ∘ ,-injectiveˡ) ... | yes refl with dec₂ x y ... | no x≢y = no (x≢y ∘ ,-injectiveʳ) ... | yes refl = yes refl
module Statistics where import Control.Monad import Control.Monad.Bayes.Class ( bernoulli , MonadSample , discrete ) import Numeric.Log import Statistics.Distribution ( logProbability ) import Statistics.Distribution.Poisson ( poisson ) import qualified Statistics.Distribution.Binomial as SB boolToInt :: Bool -> Int boolToInt True = 1 boolToInt False = 0 binomial :: MonadSample m => Int -> Double -> m Int --binomial n p = Prelude.sum <$> replicateM n (boolToInt <$> bernoulli p) binomial n p = discrete $ SB.binomial n p poissonPdf :: Double -> -- | lambda Int -> -- | x Log Double poissonPdf lambda x = Exp $ logProbability (poisson lambda) x
[STATEMENT] lemma oosn_rreq: "opaodv i \<Turnstile> (otherwith quality_increases {i} (orecvmsg msg_fresh), other quality_increases {i} \<rightarrow>) onl \<Gamma>\<^sub>A\<^sub>O\<^sub>D\<^sub>V (seql i (\<lambda>(\<xi>, l). l \<in> {PAodv-:4, PAodv-:5} \<union> {PRreq-:n |n. True} \<longrightarrow> 1 \<le> osn \<xi>))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. opaodv i \<Turnstile> (otherwith quality_increases {i} (orecvmsg msg_fresh), other quality_increases {i} \<rightarrow>) onl \<Gamma>\<^sub>A\<^sub>O\<^sub>D\<^sub>V (seql i (\<lambda>(\<xi>, l). l \<in> {PAodv-:4, PAodv-:5} \<union> {PRreq-:n |n. True} \<longrightarrow> 1 \<le> osn \<xi>)) [PROOF STEP] by (rule oinvariant_weakenE [OF open_seq_invariant [OF osn_rreq initiali_aodv]]) (auto simp: seql_onl_swap)
lemma of_real_eq_numeral_power_int_cancel_iff [simp]: "(of_real y :: 'a :: {real_div_algebra, division_ring}) = power_int (numeral x) n \<longleftrightarrow> y = power_int (numeral x) n"
[STATEMENT] lemma higher_deriv_id [simp]: "(deriv ^^ n) id z = (if n = 0 then z else if n = 1 then 1 else 0)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (deriv ^^ n) id z = (if n = 0 then z else if n = 1 then 1::'a else (0::'a)) [PROOF STEP] by (simp add: id_def)
[STATEMENT] lemma (in abelian_subgroup) a_inv_op_closed2: shows "\<lbrakk>x \<in> carrier G; h \<in> H\<rbrakk> \<Longrightarrow> x \<oplus> h \<oplus> (\<ominus> x) \<in> H" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>x \<in> carrier G; h \<in> H\<rbrakk> \<Longrightarrow> x \<oplus> h \<oplus> \<ominus> x \<in> H [PROOF STEP] by (rule normal.inv_op_closed2 [OF a_normal, folded a_inv_def, simplified monoid_record_simps])
Mi Kamocha Am Yisrael? It was exactly a week ago when the public learnt about the tragic murder of Rabbi Ari Fuld HY”D who died al Shem Kiddush Hashem when despite his mortal wounds, he heroically neutralized his own murderer before the terrorist could harm or kill anyone else. Less than a week later, Ari’s father and children were writing the final letters on the Sefer Torah that was donated (one of 23) in his memory by the Rennert family at an event that was held in the office of Rav Aharon Bina shlit”a at Yeshivat Netiv Aryeh. Ari was a talmid of Rav Bina, and every Thursday night for the past 15 years without fail Ari would come to the Yeshiva to learn, teach and sing. Secular mastery. The scroll for the many who have pitiful feelings about the holocaust. Its harsh I know, but leave the whole Torah to a sefer and a sefer only. Our feelings secularize when we have the wrong motion to write on a permanent scroll for rabbinical use when we are not sefer’s. It is astute a wrong of this era. Am I alone on my insight on why Jews who might be not even kosher might have a poke and even a child yet to be called to Torah is ready with a bet? Its funny, but I do not see a tradition but a fad. This is dangerous.
-- Andreas, 2016-07-19 revisiting issue #418 module Issue418private where open import Common.Equality abstract A : Set₁ A = Set private works : A ≡ A works = refl test : A ≡ _ test = refl -- Since test is private, abstract definitions are transparent in its type. -- The meta should be solved (by A or Set).
[GOAL] p : ℝ[X] ⊢ Tendsto (fun x => eval x p / exp x) atTop (𝓝 0) [PROOFSTEP] induction p using Polynomial.induction_on' with | h_monomial n c => simpa [exp_neg, div_eq_mul_inv, mul_assoc] using tendsto_const_nhds.mul (tendsto_pow_mul_exp_neg_atTop_nhds_0 n) | h_add p q hp hq => simpa [add_div] using hp.add hq [GOAL] p : ℝ[X] ⊢ Tendsto (fun x => eval x p / exp x) atTop (𝓝 0) [PROOFSTEP] induction p using Polynomial.induction_on' with | h_monomial n c => simpa [exp_neg, div_eq_mul_inv, mul_assoc] using tendsto_const_nhds.mul (tendsto_pow_mul_exp_neg_atTop_nhds_0 n) | h_add p q hp hq => simpa [add_div] using hp.add hq [GOAL] case h_monomial n : ℕ c : ℝ ⊢ Tendsto (fun x => eval x (↑(monomial n) c) / exp x) atTop (𝓝 0) [PROOFSTEP] | h_monomial n c => simpa [exp_neg, div_eq_mul_inv, mul_assoc] using tendsto_const_nhds.mul (tendsto_pow_mul_exp_neg_atTop_nhds_0 n) [GOAL] case h_monomial n : ℕ c : ℝ ⊢ Tendsto (fun x => eval x (↑(monomial n) c) / exp x) atTop (𝓝 0) [PROOFSTEP] simpa [exp_neg, div_eq_mul_inv, mul_assoc] using tendsto_const_nhds.mul (tendsto_pow_mul_exp_neg_atTop_nhds_0 n) [GOAL] case h_add p q : ℝ[X] hp : Tendsto (fun x => eval x p / exp x) atTop (𝓝 0) hq : Tendsto (fun x => eval x q / exp x) atTop (𝓝 0) ⊢ Tendsto (fun x => eval x (p + q) / exp x) atTop (𝓝 0) [PROOFSTEP] | h_add p q hp hq => simpa [add_div] using hp.add hq [GOAL] case h_add p q : ℝ[X] hp : Tendsto (fun x => eval x p / exp x) atTop (𝓝 0) hq : Tendsto (fun x => eval x q / exp x) atTop (𝓝 0) ⊢ Tendsto (fun x => eval x (p + q) / exp x) atTop (𝓝 0) [PROOFSTEP] simpa [add_div] using hp.add hq
REBOL [ Title: "Red command-line front-end" Author: "Nenad Rakocevic, Andreas Bolka" File: %red.r Tabs: 4 Rights: "Copyright (C) 2011-2018 Red Foundation, Andreas Bolka. All rights reserved." License: "BSD-3 - https://github.com/red/red/blob/master/BSD-3-License.txt" Usage: { do/args %red.r "path/source.red" } Encap: [quiet secure none cgi title "Red" no-window] ] unless value? 'encap-fs [do %system/utils/encap-fs.r] unless all [value? 'red object? :red][ do-cache %compiler.r ] redc: context [ crush-lib: none ;-- points to compiled crush library crush-compress: none ;-- compression function win-version: none ;-- Windows version extracted from "ver" command SSE3?: yes Windows?: system/version/4 = 3 macOS?: system/version/4 = 2 load-lib?: any [encap? find system/components 'Library] if encap? [ temp-dir: switch/default system/version/4 [ 2 [ ;-- MacOS X libc: load/library %libc.dylib sys-call: make routine! [cmd [string!]] libc "system" join any [attempt [to-rebol-file get-env "HOME"] %/tmp] %/.red/ ] 3 [ ;-- Windows either lib?: find system/components 'Library [ sys-path: to-rebol-file get-env "SystemRoot" shell32: load/library sys-path/System32/shell32.dll kernel32: load/library sys-path/System32/kernel32.dll libc: load/library sys-path/System32/msvcrt.dll CSIDL_COMMON_APPDATA: to integer! #{00000023} SHGetFolderPath: make routine! [ hwndOwner [integer!] nFolder [integer!] hToken [integer!] dwFlags [integer!] pszPath [string!] return: [integer!] ] shell32 "SHGetFolderPathA" ShellExecuteW: make routine! [ hwnd [integer!] lpOperation [string!] lpFile [string!] lpParameters [string!] lpDirectory [integer!] nShowCmd [integer!] return: [integer!] ] shell32 "ShellExecuteW" GetCommandLineW: make routine! compose/deep [ return: [integer!] ] kernel32 "GetCommandLineW" WideCharToMultiByte: make routine! [ CodePage [integer!] dwFlags [integer!] lpWideCharStr [integer!] cchWideChar [integer!] lpMultiByteStr [string!] cbMultiByte [integer!] lpDefaultChar [integer!] lpUsedDefaultChar [integer!] return: [integer!] ] kernel32 "WideCharToMultiByte" _wsystem: make routine! [cmd [string!] return: [integer!]] libc "_wsystem" IsProcessorFeaturePresent: make routine! [feat [integer!] return: [integer!]] kernel32 "IsProcessorFeaturePresent" gui-sys-call: func [cmd [string!] args [string!]][ ShellExecuteW 0 utf8-to-utf16 "open" utf8-to-utf16 cmd utf8-to-utf16 args 0 1 ] sys-call: func [cmd [string!]][_wsystem utf8-to-utf16 cmd] SSE3?: to logic! IsProcessorFeaturePresent 13 path: head insert/dup make string! 255 null 255 unless zero? SHGetFolderPath 0 CSIDL_COMMON_APPDATA 0 0 path [ fail "SHGetFolderPath failed: can't determine temp folder path" ] append dirize to-rebol-file trim path %Red/ ][ sys-call: func [cmd][call/wait cmd] append to-rebol-file get-env "ALLUSERSPROFILE" %/Red/ ] ] ][ ;-- Linux (default) cpuinfo: attempt [read %/proc/cpuinfo] either cpuinfo [ SSE3?: parse cpuinfo [thru "flags" to "sse3" to end] ][ fail "Can't read /proc/cpuinfo" ] any [ exists? libc: %libc.so.6 exists? libc: %/lib32/libc.so.6 exists? libc: %/lib/i386-linux-gnu/libc.so.6 ; post 11.04 Ubuntu exists? libc: %/usr/lib32/libc.so.6 ; e.g. 64-bit Arch Linux exists? libc: %/lib/libc.so.6 exists? libc: %/System/Index/lib/libc.so.6 ; GoboLinux package exists? libc: %/system/index/framework/libraries/libc.so.6 ; Syllable exists? libc: %/lib/libc.so.5 ] libc: load/library libc sys-call: make routine! [cmd [string!]] libc "system" join any [attempt [to-rebol-file get-env "HOME"] %/tmp] %/.red/ ] ] if Windows? [ use [buf cmd][ cmd: "cmd /c ver" buf: make string! 128 either load-lib? [ do-cache %utils/call.r ;@@ put `call.r` in proper place when we encap win-call/output cmd buf ][ set 'win-call :call ;-- Rebol/Core compatible mode win-call/output/show cmd buf ;-- not using /show would freeze CALL ] parse/all buf [[thru "[" | thru "Version" | thru "ver" | thru "v" | thru "indows"] to #"." pos:] win-version: any [ attempt [load copy/part back back remove pos 3] 0 ] ] ] ;; Select a default target based on the REBOL version. default-target: does [ any [ switch/default system/version/4 [ 2 ["Darwin"] 3 ["MSDOS"] 4 [either system/version/5 = 8 ["RPI"]["Linux"]] 7 ["FreeBSD"] ]["MSDOS"] ] ] get-OS-name: does [ switch/default system/version/4 [ 2 ['macOS] 3 ['Windows] 4 ['Linux] ]['Linux] ;-- usage related to lib suffixes ] fail: func [value] [ print value if system/options/args [quit/return 1] halt ] fail-try: func [component body /local err] [ if error? set/any 'err try body [ err: disarm err foreach w [arg1 arg2 arg3][ set w either unset? get/any in err w [none][ get/any in err w ] ] fail [ "***" component "Internal Error:" system/error/(err/type)/type #":" reduce system/error/(err/type)/(err/id) newline "*** Where:" mold/flat err/where newline "*** Near: " mold/flat err/near newline ] ] ] format-time: func [time [time!]][ round (time/second * 1000) + (time/minute * 60000) ] decorate-name: func [name [file!]][ rejoin [ ;-- filename: <name>-year-month-day(ISO format)-time name #"-" build-date/year "-" build-date/month "-" build-date/day "-" to-integer build-date/time ] ] get-lib-suffix: does [ case [ Windows? [%.dll] system/version/4 = 2 [%.dylib] 'else [%.so] ] ] load-filename: func [filename /local result] [ unless any [ all [ #"%" = first filename attempt [result: load filename] file? result ] attempt [result: to-rebol-file filename] ][ fail ["Invalid filename:" filename] ] result ] load-targets: func [/local targets] [ targets: load-cache %system/config.r if exists? %system/custom-targets.r [ insert targets load %system/custom-targets.r ] targets ] get-output-path: func [opts [object!] /local path][ case [ opts/build-basename [ path: first split-path opts/build-basename either opts/build-prefix [join opts/build-prefix path][path] ] opts/build-prefix [opts/build-prefix] 'else [%""] ] ] red-system?: func [file [file!] /local ws rs?][ ws: charset " ^-^/^M" parse/all/case read file [ some [ thru "Red" opt ["/System" (rs?: yes)] any ws #"[" (return to logic! rs?) to end ] ] no ] split-tokens: has [args unescape len s e][ args: system/script/args unescape: to-paren [ if odd? len: offset? s e [len: len - 1] e: skip e negate len / 2 e: remove/part s e ] parse/all args: copy args [ ;-- preprocess escape chars any [ s: {'"} thru {"'} e: (s/1: #"{" e/-1: #"}") | s: #"'" [to #"'" e: (s/1: #"{" e/1: #"}") | to end] | s: some #"\" e: {"} unescape :e thru #"\" s: any #"\" e: {"} unescape :e | skip ] ] remove system/options/args: collect [ ;-- remove first entry parse/all args [ ;-- tokenize and collect some [[ some #"^"" s: to #"^"" e: (keep copy/part s e) some #"^"" | #"{" s: to #"}" e: (keep copy/part s e) skip | s: [ to #" " e: (keep copy/part s e) | to end e: (if s <> e [keep copy/part s e]) skip] ] any #" " ] ] ] ] fetch-cmdline: has [cmd buffer size][ either Windows? [ cmd: GetCommandLineW size: WideCharToMultiByte 65001 0 cmd -1 "" 0 0 0 ;-- CP_UTF8 buffer: make string! size + 1 insert/dup buffer null size + 1 WideCharToMultiByte 65001 0 cmd -1 buffer size 0 0 ;-- CP_UTF8 while [find " ^@" last buffer][remove back tail buffer] system/script/args: buffer split-tokens ][ ] ] safe-to-local-file: func [file [file! string!]][ if all [ find file: to-local-file file #" " Windows? ][ file: rejoin [{"} file {"}] ;-- avoid issues with blanks in path ] file ] form-args: func [file /local args delim pos pos2 flag][ args: make string! 32 foreach arg pos: find system/options/args file [ case [ find arg #" " [ delim: pick {'"} to logic! find arg #"^"" repend args [delim arg delim] ] find arg #"^"" [ repend args [#"'" arg #"'"] ] 'else [ append args arg ] ] append args #" " ] remove back tail args all [ pos2: find system/options/args flag: "--catch" positive? offset? pos2 pos insert insert args flag #" " ] args ] add-legacy-flags: func [opts [object!] /local out ver][ if all [Windows? win-version <= 60][ either opts/legacy [ ;-- do not compile gesture support code for XP, Vista, Windows Server 2003/2008(R1) append opts/legacy 'no-touch ][ opts/legacy: copy [no-touch] ] ] all [ not SSE3? any [ all [Windows? opts/OS = 'Windows] all [system/version/4 = 4 opts/OS = 'Linux] ] opts/cpu-version: 1.0 ] if system/version/4 = 2 [ ;-- macOS version extraction out: make string! 128 call/output "sw_vers -productVersion" out attempt [ ver: load out opts/OS-version: load rejoin [ver/1 #"." ver/2] ] ] ] build-compress-lib: has [script basename filename text opts ext src][ src: %runtime/crush.reds basename: either encap? [ unless exists? temp-dir [make-dir temp-dir] script: temp-dir/crush.reds decorate-name %crush ][ temp-dir: %./ script: %crush.reds copy %crush ] filename: append temp-dir/:basename get-lib-suffix if any [ not exists? filename all [ not encap? (modified? filename) < modified? src ] ][ if crush-lib [ free crush-lib crush-lib: none ] text: copy read-cache src append text " #export [crush/compress]" write script text unless encap? [basename: head insert basename %../] opts: make system-dialect/options-class [ ;-- minimal set of compilation options link?: yes config-name: to word! default-target build-basename: basename build-prefix: temp-dir dev-mode?: no ] opts: make opts select load-targets opts/config-name opts/type: 'dll if opts/OS <> 'Windows [opts/PIC?: yes] add-legacy-flags opts print "Compiling compression library..." unless encap? [ change-dir %system/ script: head insert script %../ ] system-dialect/compile/options script opts delete script unless encap? [change-dir %../] ] unless crush-lib [ crush-lib: load/library filename crush-compress: make routine! [ in [binary!] size [integer!] ;-- size in bytes out [binary!] ;-- output buffer (pre-allocated) return: [integer!] ;-- compressed data size ] crush-lib "crush/compress" ] ] run-console: func [ gui? [logic!] /with file [string!] /local opts result script filename exe console console-root files files2 source con-ui gui-target td ][ script: rejoin [temp-dir pick [%GUI/ %CLI/] gui? %gui-console.red] filename: decorate-name pick [%gui-console %console] gui? exe: temp-dir/:filename if Windows? [append exe %.exe] unless exists? temp-dir [make-dir temp-dir] unless exists? exe [ console-root: %environment/console/ console: join console-root pick [%GUI/ %CLI/] gui? con-ui: pick [%gui-console.red %console.red] gui? if gui? [ gui-target: select [ "Darwin" macOS "MSDOS" Windows ;"Linux" Linux-GTK ] default-target ] source: copy read-cache console/:con-ui if all [any [Windows? macOS?] not gui?][insert find/tail source #"[" "Needs: 'View^/"] files: [%auto-complete.red %engine.red %help.red] foreach f files [write temp-dir/:f read-cache console-root/:f] make-dir td: join temp-dir pick [%GUI/ %CLI/] gui? files2: pick [ [%core.red %highlight.red %settings.red %tips.red] [%input.red %wcwidth.reds %win32.reds %POSIX.reds] ] gui? if gui? [write/binary td/app.ico read-binary-cache console/app.ico] foreach f files2 [write td/:f read-cache console/:f] write script source opts: make system-dialect/options-class [ ;-- minimal set of compilation options link?: yes unicode?: yes config-name: any [gui-target to word! default-target] build-basename: filename build-prefix: temp-dir red-help?: yes ;-- include doc-strings gui-console?: gui? dev-mode?: no ] opts: make opts select load-targets opts/config-name add-legacy-flags opts print replace "Compiling Red $console..." "$" pick ["GUI " ""] gui? result: red/compile script opts system-dialect/compile/options/loaded script opts result delete script foreach f files [delete temp-dir/:f] foreach f files2 [delete td/:f] if gui? [delete td/app.ico] delete-dir td if all [Windows? not lib?][ print "Please run red.exe again to access the console." quit/return 1 ] ] exe: safe-to-local-file exe either gui? [ gui-sys-call exe any [all [file form-args file] ""] ][ if with [repend exe [" " form-args file]] sys-call exe ;-- replace the buggy CALL native ] quit/return 0 ] build-libRedRT: func [opts [object!] /local script result file path][ print "Compiling libRedRT..." file: libRedRT/lib-file path: get-output-path opts opts: make opts [ build-prefix: path build-basename: file type: 'dll libRedRT?: yes link?: yes unicode?: yes ] if opts/OS <> 'Windows [opts/PIC?: yes] all [ not empty? path: opts/build-prefix slash <> first path not encap? opts/build-prefix: head insert copy path %../ ] script: switch/default opts/OS [ ;-- empty script for the lib Windows macOS [ [[Needs: View]] ] ][ [[]] ] result: red/compile script opts print [ "...compilation time :" format-time result/2 "ms^/" "^/Compiling to native code..." ] unless encap? [change-dir %system/] result: system-dialect/compile/options/loaded file opts result unless encap? [change-dir %../] show-stats result ] needs-libRedRT?: func [opts [object!] /local file path lib lib? get-date ts date current?][ unless opts/dev-mode? [return no] path: get-output-path opts file: join path %libRedRT libRedRT/root-dir: path lib?: exists? lib: join file switch/default opts/OS [ Windows [%.dll] macOS [%.dylib] ][%.so] if lib? [ date: modified? lib current?: any [not encap? date > build-date] either all [load-lib? opts/OS = get-OS-name][ lib: load/library lib get-date: make routine! [return: [string!]] lib "red/get-build-date" ts: get-date free lib ][ ts: date ] if current? [print ["...using libRedRT built on" ts]] ] not all [ lib? current? exists? join path libRedRT/include-file exists? join path libRedRT/defs-file ] ] show-stats: func [result][ print ["...compilation time :" format-time result/1 "ms"] if result/2 [ print [ "...linking time :" format-time result/2 "ms^/" "...output file size :" result/3 "bytes^/" "...output file :" to-local-file result/4 lf ] ] ] do-clear: func [args [block!] /local path file][ either empty? args [path: %""][ path: either args/1/1 = #"%" [ attempt [load args/1] ][ attempt [to-rebol-file args/1] ] unless all [path exists? path][ fail "`red clear` command error: invalid path" ] ] foreach ext [%.dll %.dylib %.so][ if exists? file: rejoin [path libRedRT/lib-file ext][delete file] ] foreach file [include-file defs-file extras-file][ if exists? file: join path libRedRT/:file [delete file] ] reduce [none none] ] do-build: func [args [block!] /local cmd src][ switch/default args/1 [ "libRed" [ if all [encap? not exists? %libRed/][ make-dir path: %libRed/ foreach file [ %libRed.def %libRed.red %red.h ][ write path/:file read-cache path/:file ] write/binary path/libRed.lib read-cache path/libRed.lib ] cmd: copy "-r libRed/libRed.red" if all [not tail? next args args/2 = "stdcall"][ insert at cmd 3 " --config [export-ABI: 'stdcall]" ] parse-options cmd ] ][ fail reform ["command error: unknown command" args/1] ] ] parse-tokens: func [cmds [string!] /local ws list s e token store][ ws: charset " ^/^M^-" list: make block! 10 store: [ unless empty? token: trim copy/part s e [append list token] s: e ] parse/all cmds [ s: any [ e: some ws (do store) | {"} thru {"} e: (do store) | "[" thru "]" e: (do store) | skip ] e: (do store) ] list ] parse-options: func [ args [string! none!] /local src opts output target verbose filename config config-name base-path type mode target? gui? cmd spec cmds ws ssp ][ unless args [ if encap? [fetch-cmdline] ;-- Fetch real command-line in UTF8 format args: any [system/options/args system/script/args ""] ;-- ssa for quick-test.r ] unless block? args [args: parse-tokens args] target: default-target opts: make system-dialect/options-class [ link?: yes libRedRT-update?: no ] gui?: Windows? ;-- use GUI console by default on Windows unless empty? args [ if cmd: select [ "clear" do-clear "build" do-build "halt" 'halt ] first args [ return do reduce [cmd next args] ] ] parse/case args [ any [ ["-c" | "--compile"] (type: 'exe) | ["-r" | "--release"] (type: 'exe opts/dev-mode?: no) | ["-e" | "--encap"] (opts/encap?: yes) | ["-d" | "--debug-stabs" | "--debug"] (opts/debug?: yes) | ["-o" | "--output"] [set output skip | (fail "Missing output filename")] | ["-t" | "--target"] [set target skip | (fail "Missing target")] (target?: yes) | ["-v" | "--verbose"] [set verbose skip | (fail "Missing verbosity")] ;-- 1-3: Red, >3: Red/System | ["-h" | "--help"] (mode: 'help) | ["-V" | "--version"] (mode: 'version) | ["-u" | "--update-libRedRT"] (opts/libRedRT-update?: yes) | ["-s" | "--show-expanded"] (opts/show: 'expanded) | ["-dlib" | "--dynamic-lib"] (type: 'dll) ;| ["-slib" | "--static-lib"] (type 'lib) | "--config" set spec skip (attempt [spec: load spec]) | "--red-only" (opts/red-only?: yes) | "--dev" (opts/dev-mode?: yes) | "--no-runtime" (opts/runtime?: no) ;@@ overridable by config! | "--cli" (gui?: no) | "--catch" ;-- just pass-thru ] set filename skip (src: load-filename filename) ] if mode [ switch mode [ help [print read-cache %usage.txt] version [print load-cache %version.r] ] quit/return 0 ] ;; Process -t/--target first, so that all other command-line options ;; can potentially override the target config settings. unless config: select load-targets config-name: to word! trim target [ fail ["Unknown target:" target] ] if target? [unless type [type: 'exe]] ;-- implies compilation base-path: either encap? [ system/options/path ][ ssp: system/script/parent any [ all [ssp ssp/path] system/script/path ] ] opts: make opts config opts/config-name: config-name opts/build-prefix: base-path if all [target? none? opts/dev-mode?][ opts/dev-mode?: opts/OS = get-OS-name ;-- forces release mode if other OS ] ;; Process -o/--output (if any). if output [ either slash = last output [ attempt [opts/build-prefix: to-rebol-file output] ][ opts/build-basename: load-filename output if slash = first opts/build-basename [ opts/build-prefix: %"" ] ] ] ;; Process -v/--verbose (if any). if verbose [ unless attempt [opts/verbosity: to integer! trim verbose] [ fail ["Invalid verbosity:" verbose] ] ] ;; Process -dlib/--dynamic-lib (if any). if any [type = 'dll opts/type = 'dll][ if type = 'dll [opts/type: type] if opts/OS <> 'Windows [opts/PIC?: yes] ] ;; Check common syntax mistakes if all [ any [type output verbose target?] ;-- -c | -o | -dlib | -t | -v none? src ][ fail "Source file is missing" ] if all [output output/1 = #"-"][ ;-- -o (not followed by option) fail "Missing output file or path" ] ;; Process input sources. unless src [ either encap? [ if load-lib? [build-compress-lib] run-console gui? ][ return reduce [none none] ] ] if all [encap? none? output none? type][ if load-lib? [build-compress-lib] run-console/with gui? filename ] if slash <> first src [ ;-- if relative path src: clean-path join base-path src ;-- add working dir path ] unless exists? src [ fail ["Cannot access source file:" to-local-file src] ] add-legacy-flags opts if spec [ opts: make opts spec opts/command-line: spec ] if none? opts/dev-mode? [opts/dev-mode?: yes] ;-- fallback to dev mode if undefined reduce [src opts] ] compile: func [src opts /local result saved rs?][ print [ "Compiling" to-local-file src "..."] unless rs?: red-system? src [ ;--- 1st pass: Red compiler --- if load-lib? [build-compress-lib] if needs-libRedRT? opts [build-libRedRT opts] fail-try "Red Compiler" [ result: red/compile src opts ] print ["...compilation time :" format-time result/2 "ms"] if opts/red-only? [probe result/1 return none] ] ;--- 2nd pass: Red/System compiler --- print [ newline "Target:" opts/config-name lf lf "Compiling to native code..." ] fail-try "Red/System Compiler" [ unless encap? [change-dir %system/] result: either rs? [ system-dialect/compile/options src opts ][ opts/unicode?: yes ;-- force Red/System to use Red's Unicode API opts/verbosity: max 0 opts/verbosity - 3 ;-- Red/System verbosity levels upped by 3 system-dialect/compile/options/loaded src opts result ] unless encap? [change-dir %../] ] result ] main: func [/with cmd [string!] /local src opts build-dir prefix result file][ set [src opts] parse-options cmd unless src [do opts exit] ;-- run named command and terminates rs?: red-system? src ;-- If we use a build directory, ensure it exists. if all [prefix: opts/build-prefix find prefix %/] [ build-dir: copy/part prefix find/last prefix %/ unless attempt [make-dir/deep build-dir] [ fail ["Cannot access build dir:" to-local-file build-dir] ] ] print [lf "-=== Red Compiler" read-cache %version.r "===-" lf] ;-- libRedRT updating mode if opts/libRedRT-update? [ if exists? file: rejoin [get-output-path opts %libRedRT get-lib-suffix][ delete file ] opts/dev-mode?: opts/link?: no compile src opts print ["libRedRT-extras.r file generated, recompiling..." lf] opts/dev-mode?: opts/link?: yes opts/libRedRT-update?: no ] if result: compile src opts [ show-stats result if all [word: in opts 'packager get word][ file: join %system/formats/ [opts/packager %.r] unless exists?-cache file [fail ["Packager:" opts/packager "not found!"]] do bind load-cache file 'self packager/process opts src result/4 ] unless Windows? [print ""] ;-- extra LF for more readable output ] ] set 'rc func [cmd [file! string! block!]][ fail-try "Driver" [redc/main/with reform cmd] () ;-- return unset value ] ] redc/fail-try "Driver" [redc/main] if encap? [quit/return 0]
import defs.syntax import defs.fv import util.list.append theorem var_fv (x: var): fv (exp.var x) = [x] := by simp [fv] theorem if_fv (e1 e2 e3: exp): fv (exp.if_ e1 e2 e3) = fv e1 ++ (fv e2 ++ fv e3) := by simp [fv] theorem app_fv (e1 e2: exp): fv (exp.app e1 e2) = fv e1 ++ fv e2 := by simp [fv] theorem fn_fv (x: var) (τ: typ) (e: exp): fv (exp.fn x τ e) = list.filter (ne x) (fv e) := by simp [fv] theorem pair_fv (e1 e2: exp): fv (exp.pair e1 e2) = fv e1 ++ fv e2 := by simp [fv] theorem pair_left_fv (e: exp): fv (exp.pair_left e) = fv e := by simp [fv] theorem pair_right_fv (e: exp): fv (exp.pair_right e) = fv e := by simp [fv] theorem either_left_fv {τ: typ} (e: exp): fv (exp.either_left τ e) = fv e := by simp [fv] theorem either_right_fv {τ: typ} (e: exp): fv (exp.either_right τ e) = fv e := by simp [fv] theorem case_never_fv {τ: typ} (e: exp): fv (exp.case_never τ e) = fv e := by simp [fv] theorem case_fv (eh e1 e2: exp) (x1 x2: var): fv (exp.case eh x1 e1 x2 e2) = fv eh ++ list.filter (ne x1) (fv e1) ++ list.filter (ne x2) (fv e2) := by simp [fv] theorem if_fv_empty (e1 e2 e3: exp) : fv (exp.if_ e1 e2 e3) = [] ↔ (fv e1 = [] ∧ fv e2 = [] ∧ fv e3 = []) := begin split, intro h, rw if_fv e1 e2 e3 at h, let ap := iff.elim_left append_nil_both h, split, exact ap.left, exact iff.elim_left append_nil_both ap.right, intro h, cases h, cases h_right, rw if_fv e1 e2 e3 at *, rw h_left, rw h_right_left, rw h_right_right, simp [list.append], end theorem app_fv_empty (e1 e2: exp) : fv (exp.app e1 e2) = [] ↔ (fv e1 = [] ∧ fv e2 = []) := begin split, intro h, rw app_fv e1 e2 at h, exact iff.elim_left append_nil_both h, intro h, cases h, rw app_fv e1 e2 at *, rw h_left, rw h_right, simp [list.append], end theorem pair_fv_empty (e1 e2: exp) : fv (exp.pair e1 e2) = [] ↔ (fv e1 = [] ∧ fv e2 = []) := begin split, intro h, rw pair_fv e1 e2 at h, exact iff.elim_left append_nil_both h, intro h, cases h, rw pair_fv e1 e2 at *, rw h_left, rw h_right, simp [list.append], end
{-# OPTIONS --exact-split #-} module ExactSplitBerry where data Bool : Set where true false : Bool maj : Bool → Bool → Bool → Bool maj true true true = true maj x true false = x maj false y true = y maj true false z = z maj false false false = false
[STATEMENT] lemma LTL_nxt_2_means_vend: "alw (nxt (state_eq (Some 2)) impl (state_eq (Some 1))) (watch drinks i)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. alw (\<lambda>xs. nxt (state_eq (Some 2)) xs \<longrightarrow> state_eq (Some 1) xs) (watch drinks i) [PROOF STEP] proof(coinduction) [PROOF STATE] proof (state) goal (1 subgoal): 1. \<exists>xs. watch drinks i = xs \<and> (nxt (state_eq (Some 2)) xs \<longrightarrow> state_eq (Some 1) xs) \<and> (stl xs = watch drinks i \<or> alw (\<lambda>xs. nxt (state_eq (Some 2)) xs \<longrightarrow> state_eq (Some 1) xs) (stl xs)) [PROOF STEP] case alw [PROOF STATE] proof (state) this: goal (1 subgoal): 1. \<exists>xs. watch drinks i = xs \<and> (nxt (state_eq (Some 2)) xs \<longrightarrow> state_eq (Some 1) xs) \<and> (stl xs = watch drinks i \<or> alw (\<lambda>xs. nxt (state_eq (Some 2)) xs \<longrightarrow> state_eq (Some 1) xs) (stl xs)) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: [PROOF STEP] show ?case [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>xs. watch drinks i = xs \<and> (nxt (state_eq (Some 2)) xs \<longrightarrow> state_eq (Some 1) xs) \<and> (stl xs = watch drinks i \<or> alw (\<lambda>xs. nxt (state_eq (Some 2)) xs \<longrightarrow> state_eq (Some 1) xs) (stl xs)) [PROOF STEP] apply (case_tac "shd i") [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>a b. shd i = (a, b) \<Longrightarrow> \<exists>xs. watch drinks i = xs \<and> (nxt (state_eq (Some 2)) xs \<longrightarrow> state_eq (Some 1) xs) \<and> (stl xs = watch drinks i \<or> alw (\<lambda>xs. nxt (state_eq (Some 2)) xs \<longrightarrow> state_eq (Some 1) xs) (stl xs)) [PROOF STEP] apply (simp del: ltl_step.simps) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>a b. shd i = (a, b) \<Longrightarrow> fst (ltl_step drinks (Some 0) <> (a, b)) \<noteq> Some 2 \<and> (make_full_observation drinks (fst (ltl_step drinks (Some 0) <> (a, b))) (snd (snd (ltl_step drinks (Some 0) <> (a, b)))) (fst (snd (ltl_step drinks (Some 0) <> (a, b)))) (stl i) = watch drinks i \<or> alw (\<lambda>xs. state_eq (Some 2) (stl xs) \<longrightarrow> state_eq (Some 1) xs) (make_full_observation drinks (fst (ltl_step drinks (Some 0) <> (a, b))) (snd (snd (ltl_step drinks (Some 0) <> (a, b)))) (fst (snd (ltl_step drinks (Some 0) <> (a, b)))) (stl i))) [PROOF STEP] apply (rule P_ltl_step_0) [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>a b. shd i = (a, b) \<Longrightarrow> fst (None, [], <>) \<noteq> Some 2 \<and> (make_full_observation drinks (fst (None, [], <>)) (snd (snd (None, [], <>))) (fst (snd (None, [], <>))) (stl i) = watch drinks i \<or> alw (\<lambda>xs. state_eq (Some 2) (stl xs) \<longrightarrow> state_eq (Some 1) xs) (make_full_observation drinks (fst (None, [], <>)) (snd (snd (None, [], <>))) (fst (snd (None, [], <>))) (stl i))) 2. \<And>a b. shd i = (a, b) \<Longrightarrow> a = STR ''select'' \<longrightarrow> fst (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>) \<noteq> Some 2 \<and> (make_full_observation drinks (fst (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>)) (snd (snd (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>))) (fst (snd (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>))) (stl i) = watch drinks i \<or> alw (\<lambda>xs. state_eq (Some 2) (stl xs) \<longrightarrow> state_eq (Some 1) xs) (make_full_observation drinks (fst (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>)) (snd (snd (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>))) (fst (snd (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>))) (stl i))) [PROOF STEP] apply simp [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>a b. shd i = (a, b) \<Longrightarrow> make_full_observation drinks None <> [] (stl i) = watch drinks i \<or> alw (\<lambda>xs. state_eq (Some 2) (stl xs) \<longrightarrow> state_eq (Some 1) xs) (make_full_observation drinks None <> [] (stl i)) 2. \<And>a b. shd i = (a, b) \<Longrightarrow> a = STR ''select'' \<longrightarrow> fst (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>) \<noteq> Some 2 \<and> (make_full_observation drinks (fst (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>)) (snd (snd (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>))) (fst (snd (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>))) (stl i) = watch drinks i \<or> alw (\<lambda>xs. state_eq (Some 2) (stl xs) \<longrightarrow> state_eq (Some 1) xs) (make_full_observation drinks (fst (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>)) (snd (snd (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>))) (fst (snd (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>))) (stl i))) [PROOF STEP] apply (rule disjI2) [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>a b. shd i = (a, b) \<Longrightarrow> alw (\<lambda>xs. state_eq (Some 2) (stl xs) \<longrightarrow> state_eq (Some 1) xs) (make_full_observation drinks None <> [] (stl i)) 2. \<And>a b. shd i = (a, b) \<Longrightarrow> a = STR ''select'' \<longrightarrow> fst (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>) \<noteq> Some 2 \<and> (make_full_observation drinks (fst (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>)) (snd (snd (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>))) (fst (snd (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>))) (stl i) = watch drinks i \<or> alw (\<lambda>xs. state_eq (Some 2) (stl xs) \<longrightarrow> state_eq (Some 1) xs) (make_full_observation drinks (fst (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>)) (snd (snd (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>))) (fst (snd (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>))) (stl i))) [PROOF STEP] apply (rule alw_mono[of "nxt (state_eq None)"]) [PROOF STATE] proof (prove) goal (3 subgoals): 1. \<And>a b. shd i = (a, b) \<Longrightarrow> alw (nxt (state_eq None)) (make_full_observation drinks None <> [] (stl i)) 2. \<And>a b xs. \<lbrakk>shd i = (a, b); nxt (state_eq None) xs\<rbrakk> \<Longrightarrow> state_eq (Some 2) (stl xs) \<longrightarrow> state_eq (Some 1) xs 3. \<And>a b. shd i = (a, b) \<Longrightarrow> a = STR ''select'' \<longrightarrow> fst (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>) \<noteq> Some 2 \<and> (make_full_observation drinks (fst (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>)) (snd (snd (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>))) (fst (snd (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>))) (stl i) = watch drinks i \<or> alw (\<lambda>xs. state_eq (Some 2) (stl xs) \<longrightarrow> state_eq (Some 1) xs) (make_full_observation drinks (fst (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>)) (snd (snd (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>))) (fst (snd (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>))) (stl i))) [PROOF STEP] apply (simp add: once_none_nxt_always_none) [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>a b xs. \<lbrakk>shd i = (a, b); nxt (state_eq None) xs\<rbrakk> \<Longrightarrow> state_eq (Some 2) (stl xs) \<longrightarrow> state_eq (Some 1) xs 2. \<And>a b. shd i = (a, b) \<Longrightarrow> a = STR ''select'' \<longrightarrow> fst (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>) \<noteq> Some 2 \<and> (make_full_observation drinks (fst (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>)) (snd (snd (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>))) (fst (snd (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>))) (stl i) = watch drinks i \<or> alw (\<lambda>xs. state_eq (Some 2) (stl xs) \<longrightarrow> state_eq (Some 1) xs) (make_full_observation drinks (fst (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>)) (snd (snd (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>))) (fst (snd (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>))) (stl i))) [PROOF STEP] using one_before_two_aux [PROOF STATE] proof (prove) using this: \<exists>p r i. ?j = nxt (make_full_observation drinks (Some 1) r p) i \<Longrightarrow> alw (\<lambda>x. nxt (state_eq (Some 2)) x \<longrightarrow> state_eq (Some 1) x) ?j goal (2 subgoals): 1. \<And>a b xs. \<lbrakk>shd i = (a, b); nxt (state_eq None) xs\<rbrakk> \<Longrightarrow> state_eq (Some 2) (stl xs) \<longrightarrow> state_eq (Some 1) xs 2. \<And>a b. shd i = (a, b) \<Longrightarrow> a = STR ''select'' \<longrightarrow> fst (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>) \<noteq> Some 2 \<and> (make_full_observation drinks (fst (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>)) (snd (snd (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>))) (fst (snd (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>))) (stl i) = watch drinks i \<or> alw (\<lambda>xs. state_eq (Some 2) (stl xs) \<longrightarrow> state_eq (Some 1) xs) (make_full_observation drinks (fst (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>)) (snd (snd (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>))) (fst (snd (Some 1, [], <1 $:= Some (hd b), 2 $:= Some (Num 0)>))) (stl i))) [PROOF STEP] by auto [PROOF STATE] proof (state) this: \<exists>xs. watch drinks i = xs \<and> (nxt (state_eq (Some 2)) xs \<longrightarrow> state_eq (Some 1) xs) \<and> (stl xs = watch drinks i \<or> alw (\<lambda>xs. nxt (state_eq (Some 2)) xs \<longrightarrow> state_eq (Some 1) xs) (stl xs)) goal: No subgoals! [PROOF STEP] qed
------------------------------------------------------------------------ -- The Agda standard library -- -- Results concerning uniqueness of identity proofs ------------------------------------------------------------------------ {-# OPTIONS --without-K --safe #-} module Axiom.UniquenessOfIdentityProofs where open import Data.Empty open import Relation.Nullary open import Relation.Binary.Core open import Relation.Binary.PropositionalEquality.Core ------------------------------------------------------------------------ -- Definition -- -- Uniqueness of Identity Proofs (UIP) states that all proofs of -- equality are themselves equal. In other words, the equality relation -- is irrelevant. Here we define UIP relative to a given type. UIP : ∀ {a} (A : Set a) → Set a UIP A = Irrelevant {A = A} _≡_ ------------------------------------------------------------------------ -- Properties -- UIP always holds when using axiom K -- (see `Axiom.UniquenessOfIdentityProofs.WithK`). -- The existence of a constant function over proofs of equality for -- elements in A is enough to prove UIP for A. Indeed, we can relate any -- proof to its image via this function which we then know is equal to -- the image of any other proof. module Constant⇒UIP {a} {A : Set a} (f : _≡_ {A = A} ⇒ _≡_) (f-constant : ∀ {a b} (p q : a ≡ b) → f p ≡ f q) where ≡-canonical : ∀ {a b} (p : a ≡ b) → trans (sym (f refl)) (f p) ≡ p ≡-canonical refl = trans-symˡ (f refl) ≡-irrelevant : UIP A ≡-irrelevant p q = begin p ≡⟨ sym (≡-canonical p) ⟩ trans (sym (f refl)) (f p) ≡⟨ cong (trans _) (f-constant p q) ⟩ trans (sym (f refl)) (f q) ≡⟨ ≡-canonical q ⟩ q ∎ where open ≡-Reasoning -- If equality is decidable for a given type, then we can prove UIP for -- that type. Indeed, the decision procedure allows us to define a -- function over proofs of equality which is constant: it returns the -- proof produced by the decision procedure. module Decidable⇒UIP {a} {A : Set a} (_≟_ : Decidable (_≡_ {A = A})) where ≡-normalise : _≡_ {A = A} ⇒ _≡_ ≡-normalise {a} {b} a≡b with a ≟ b ... | yes p = p ... | no ¬p = ⊥-elim (¬p a≡b) ≡-normalise-constant : ∀ {a b} (p q : a ≡ b) → ≡-normalise p ≡ ≡-normalise q ≡-normalise-constant {a} {b} p q with a ≟ b ... | yes _ = refl ... | no ¬p = ⊥-elim (¬p p) ≡-irrelevant : UIP A ≡-irrelevant = Constant⇒UIP.≡-irrelevant ≡-normalise ≡-normalise-constant
import algebra.order.field.basic tactic.by_contra /-! # IMO 2009 A5 -/ namespace IMOSL namespace IMO2009A5 theorem final_solution {F : Type*} [linear_ordered_field F] (f : F → F) : ∃ x y : F, y * f x + x < f (x - f y) := begin ---- Assume contradiction, and start with `f(t) ≤ t + f(0)` for all `t : F` by_contra' h, have h0 : ∀ t : F, f t ≤ t + f 0 := λ t, by replace h := h (t + f 0) 0; rwa [add_sub_cancel, zero_mul, zero_add] at h, by_cases h1 : ∀ x : F, f x ≤ 0, ---- Case 1: `f(x) ≤ 0` for all `x : F` { replace h0 : ∀ t : F, f t ≤ t := λ t, le_trans (h0 t) (add_le_of_nonpos_right $ h1 0), cases exists_gt (max 0 (- 1 - f (-1))) with t h2, rw max_lt_iff at h2; cases h2 with h2 h3, revert h3; rw [imp_false, not_lt, le_sub_iff_add_le, ← le_sub_iff_add_le', ← neg_add'], replace h := h (f t - 1) t, rw sub_sub_cancel_left at h, refine le_trans h _; clear h, rw ← le_sub_iff_add_le, refine le_trans ((mul_le_mul_left h2).mpr $ h0 _) _, rw [le_sub_iff_add_le, ← add_one_mul, add_comm, le_neg_iff_add_nonpos_right, ← mul_add_one, sub_add_cancel], exact mul_nonpos_of_nonneg_of_nonpos (le_of_lt $ add_pos one_pos h2) (h1 t) }, ---- Case 2: `f(c) > 0` for some `c : F` { rw not_forall at h1, cases h1 with c h1; rw not_le at h1, cases exists_lt (min (c - f 0) ((- 1 - c - f 0) / f c)) with t h2, rw lt_min_iff at h2; cases h2 with h2 h3, rw [lt_div_iff h1, sub_right_comm, lt_sub_iff_add_lt] at h3, revert h3; clear h1; rw [imp_false, not_lt], refine le_trans _ (h c t), rw sub_le_iff_le_add; refine le_trans _ (h0 _), rw lt_sub_iff_add_lt at h2, replace h2 := lt_of_le_of_lt (h0 t) h2, rw ← sub_pos at h2, generalize_hyp : c - f t = y at h2 ⊢, -- Remains to prove `f(f(y)) ≥ -1` for all `y > 0` replace h := le_trans (h (f y) y) (add_le_add_left (h0 y) _), rw [sub_self, ← add_assoc, le_add_iff_nonneg_left, ← mul_add_one] at h, rwa [neg_le_iff_add_nonneg, ← zero_le_mul_left h2] } end end IMO2009A5 end IMOSL
{-# OPTIONS --without-K --rewriting #-} open import lib.Basics open import lib.types.Pi open import lib.types.Pointed open import lib.types.Sigma open import lib.types.Span open import lib.types.Paths import lib.types.Generic1HIT as Generic1HIT module lib.types.Pushout where module _ {i j k} where postulate -- HIT Pushout : (d : Span {i} {j} {k}) → Type (lmax (lmax i j) k) module _ {d : Span} where postulate -- HIT left : Span.A d → Pushout d right : Span.B d → Pushout d glue : (c : Span.C d) → left (Span.f d c) == right (Span.g d c) module PushoutElim {d : Span} {l} {P : Pushout d → Type l} (left* : (a : Span.A d) → P (left a)) (right* : (b : Span.B d) → P (right b)) (glue* : (c : Span.C d) → left* (Span.f d c) == right* (Span.g d c) [ P ↓ glue c ]) where postulate -- HIT f : Π (Pushout d) P left-β : ∀ a → f (left a) ↦ left* a right-β : ∀ b → f (right b) ↦ right* b {-# REWRITE left-β #-} {-# REWRITE right-β #-} postulate -- HIT glue-β : (c : Span.C d) → apd f (glue c) == glue* c Pushout-elim = PushoutElim.f module PushoutRec {i j k} {d : Span {i} {j} {k}} {l} {D : Type l} (left* : Span.A d → D) (right* : Span.B d → D) (glue* : (c : Span.C d) → left* (Span.f d c) == right* (Span.g d c)) where private module M = PushoutElim left* right* (λ c → ↓-cst-in (glue* c)) f : Pushout d → D f = M.f glue-β : (c : Span.C d) → ap f (glue c) == glue* c glue-β c = apd=cst-in {f = f} (M.glue-β c) Pushout-rec = PushoutRec.f Pushout-rec-η : ∀ {i j k} {d : Span {i} {j} {k}} {l} {D : Type l} (f : Pushout d → D) → Pushout-rec (f ∘ left) (f ∘ right) (ap f ∘ glue) ∼ f Pushout-rec-η f = Pushout-elim (λ _ → idp) (λ _ → idp) (λ c → ↓-='-in' $ ! $ PushoutRec.glue-β (f ∘ left) (f ∘ right) (ap f ∘ glue) c) module PushoutGeneric {i j k} {d : Span {i} {j} {k}} where open Span d renaming (f to g; g to h) open Generic1HIT (Coprod A B) C (inl ∘ g) (inr ∘ h) public module _ where module To = PushoutRec (cc ∘ inl) (cc ∘ inr) pp to : Pushout d → T to = To.f from-cc : Coprod A B → Pushout d from-cc (inl a) = left a from-cc (inr b) = right b module From = Rec from-cc glue from : T → Pushout d from = From.f abstract to-from : (x : T) → to (from x) == x to-from = elim to-from-cc to-from-pp where to-from-cc : (x : Coprod A B) → to (from (cc x)) == cc x to-from-cc (inl a) = idp to-from-cc (inr b) = idp to-from-pp : (c : C) → idp == idp [ (λ z → to (from z) == z) ↓ pp c ] to-from-pp c = ↓-∘=idf-in' to from (ap to (ap from (pp c)) =⟨ From.pp-β c |in-ctx ap to ⟩ ap to (glue c) =⟨ To.glue-β c ⟩ pp c =∎) from-to : (x : Pushout d) → from (to x) == x from-to = Pushout-elim (λ a → idp) (λ b → idp) (λ c → ↓-∘=idf-in' from to (ap from (ap to (glue c)) =⟨ To.glue-β c |in-ctx ap from ⟩ ap from (pp c) =⟨ From.pp-β c ⟩ glue c =∎)) generic-pushout : Pushout d ≃ T generic-pushout = equiv to from to-from from-to _⊔^[_]_/_ : ∀ {i j k} (A : Type i) (C : Type k) (B : Type j) (fg : (C → A) × (C → B)) → Type (lmax (lmax i j) k) A ⊔^[ C ] B / (f , g) = Pushout (span A B C f g) ⊙Pushout : ∀ {i j k} (d : ⊙Span {i} {j} {k}) → Ptd _ ⊙Pushout d = ⊙[ Pushout (⊙Span-to-Span d) , left (pt (⊙Span.X d)) ] module _ {i j k} (d : ⊙Span {i} {j} {k}) where open ⊙Span d ⊙left : X ⊙→ ⊙Pushout d ⊙left = (left , idp) ⊙right : Y ⊙→ ⊙Pushout d ⊙right = (right , ap right (! (snd g)) ∙ ! (glue (pt Z)) ∙' ap left (snd f)) ⊙glue : (⊙left ⊙∘ f) == (⊙right ⊙∘ g) ⊙glue = pair= (λ= glue) (↓-app=cst-in $ ap left (snd f) ∙ idp =⟨ ∙-unit-r _ ⟩ ap left (snd f) =⟨ lemma (glue (pt Z)) (ap right (snd g)) (ap left (snd f)) ⟩ glue (pt Z) ∙ ap right (snd g) ∙ ! (ap right (snd g)) ∙ ! (glue (pt Z)) ∙' ap left (snd f) =⟨ !-ap right (snd g) |in-ctx (λ w → glue (pt Z) ∙ ap right (snd g) ∙ w ∙ ! (glue (pt Z)) ∙' ap left (snd f)) ⟩ glue (pt Z) ∙ ap right (snd g) ∙ ap right (! (snd g)) ∙ ! (glue (pt Z)) ∙' ap left (snd f) =⟨ ! (app=-β glue (pt Z)) |in-ctx (λ w → w ∙ ap right (snd g) ∙ ap right (! (snd g)) ∙ ! (glue (pt Z)) ∙' ap left (snd f)) ⟩ app= (λ= glue) (pt Z) ∙ ap right (snd g) ∙ ap right (! (snd g)) ∙ ! (glue (pt Z)) ∙' ap left (snd f) =∎) where lemma : ∀ {i} {A : Type i} {x y z w : A} (p : x == y) (q : y == z) (r : x == w) → r == p ∙ q ∙ ! q ∙ ! p ∙' r lemma idp idp idp = idp ⊙pushout-J : ∀ {i j k l} (P : ⊙Span → Type l) → ({A : Type i} {B : Type j} (Z : Ptd k) (f : de⊙ Z → A) (g : de⊙ Z → B) → P (⊙span ⊙[ A , f (pt Z) ] ⊙[ B , g (pt Z) ] Z (f , idp) (g , idp))) → ((ps : ⊙Span) → P ps) ⊙pushout-J P t (⊙span ⊙[ _ , ._ ] ⊙[ _ , ._ ] Z (f , idp) (g , idp)) = t Z f g
lemma convex_on: assumes "convex S" shows "convex_on S f \<longleftrightarrow> (\<forall>k u x. (\<forall>i\<in>{1..k::nat}. 0 \<le> u i \<and> x i \<in> S) \<and> sum u {1..k} = 1 \<longrightarrow> f (sum (\<lambda>i. u i *\<^sub>R x i) {1..k}) \<le> sum (\<lambda>i. u i * f(x i)) {1..k})" (is "?lhs = (\<forall>k u x. ?rhs k u x)")
(* Title: Native_Cast.thy Author: Andreas Lochbihler, ETH Zurich *) header {* Conversions between unsigned words and between char *} theory Native_Cast imports "~~/src/HOL/Library/Code_Char" Uint8 Uint16 Uint32 begin text {* Auxiliary stuff *} context begin interpretation lifting_syntax . lemma char_of_integer_transfer [transfer_rule]: "(pcr_integer ===> op =) (\<lambda>n. char_of_nat (nat n)) char_of_integer" by(simp add: integer.pcr_cr_eq cr_integer_def rel_fun_def char_of_integer_def nat_of_integer_def) lemma integer_of_char_transfer [transfer_rule]: "(op = ===> pcr_integer) (\<lambda>n. int (nat_of_char n)) integer_of_char" by(simp add: integer.pcr_cr_eq cr_integer_def rel_fun_def integer_of_char_def) end lemma integer_of_char_char_of_integer [simp]: "0 \<le> x \<Longrightarrow> integer_of_char (char_of_integer x) = x mod 256" unfolding integer_of_char_def char_of_integer_def o_apply nat_of_char_of_nat including integer.lifting by transfer(auto dest: nat_mod_distrib[of _ 256, symmetric]) lemma char_of_integer_integer_of_char [simp]: "char_of_integer (integer_of_char x) = x" by(simp add: integer_of_char_def char_of_integer_def) lemma int_lt_numeral [simp]: "int x < numeral n \<longleftrightarrow> x < numeral n" by (metis nat_numeral zless_nat_eq_int_zless) lemma int_of_integer_ge_0: "0 \<le> int_of_integer x \<longleftrightarrow> 0 \<le> x" including integer.lifting by transfer simp lemma integer_of_char_ge_0 [simp]: "0 \<le> integer_of_char x" including integer.lifting by transfer simp section {* Conversions between @{typ uint8} and @{typ char} *} definition uint8_of_char :: "char \<Rightarrow> uint8" where "uint8_of_char = Uint8 \<circ> integer_of_char" definition char_of_uint8 :: "uint8 \<Rightarrow> char" where "char_of_uint8 = char_of_integer \<circ> integer_of_int \<circ> uint \<circ> Rep_uint8'" lemma uint8_of_char_char_of_uint8 [simp]: "uint8_of_char (char_of_uint8 x) = x" apply(simp add: uint8_of_char_def char_of_uint8_def) including integer.lifting apply transfer apply(simp add: mod_pos_pos_trivial uint_bounded[where ?'a=8, simplified]) done lemma char_of_uint8_uint8_of_char [simp]: "char_of_uint8 (uint8_of_char x) = x" proof - have "char_of_uint8 (uint8_of_char x) = char_of_integer (of_int (int_of_integer (integer_of_char x) mod 256))" by(simp add: uint8_of_char_def char_of_uint8_def Uint8.rep_eq uint_word_of_int) also { have "int_of_integer (integer_of_char x) < 256" including integer.lifting by transfer(simp add: nat_of_char_less_256) } hence "\<dots> = x" by(simp add: semiring_numeral_div_class.mod_less int_of_integer_ge_0) finally show ?thesis . qed code_printing code_module Native_Casts \<rightharpoonup> (Haskell) {*import qualified Data.Char; ord :: Char -> Int; ord = Data.Char.ord; chr :: Int -> Char; chr = Data.Char.chr; *} code_reserved Haskell Native_Casts code_printing constant uint8_of_char \<rightharpoonup> (SML) "Word8.fromInt (Char.ord _)" and (Haskell) "(Prelude.fromIntegral (Native'_Casts.ord _) :: Uint8.Word8)" and (Scala) "_.toByte" | constant char_of_uint8 \<rightharpoonup> (SML) "Char.chr (Word8.toInt _)" and (Haskell) "Native'_Casts.chr (Prelude.fromIntegral _)" and (Scala) "((_).toInt & 0xFF).toChar" section {* Conversion between native words *} lift_definition uint8_of_uint32 :: "uint32 \<Rightarrow> uint8" is ucast . lift_definition uint8_of_uint16 :: "uint16 \<Rightarrow> uint8" is ucast . lift_definition uint16_of_uint8 :: "uint8 \<Rightarrow> uint16" is ucast . lift_definition uint16_of_uint32 :: "uint32 \<Rightarrow> uint16" is ucast . lift_definition uint32_of_uint8 :: "uint8 \<Rightarrow> uint32" is ucast . lift_definition uint32_of_uint16 :: "uint16 \<Rightarrow> uint32" is ucast . code_printing constant uint8_of_uint16 \<rightharpoonup> (SML_word) "Word8.fromLarge (Word16.toLarge _)" and (Haskell) "(Prelude.fromIntegral _ :: Uint8.Word8)" and (Scala) "_.toByte" | constant uint8_of_uint32 \<rightharpoonup> (SML) "Word8.fromLarge (Word32.toLarge _)" and (Haskell) "(Prelude.fromIntegral _ :: Uint8.Word8)" and (Scala) "_.toByte" | constant uint16_of_uint8 \<rightharpoonup> (SML_word) "Word16.fromLarge (Word8.toLarge _)" and (Haskell) "(Prelude.fromIntegral _ :: Uint16.Word16)" and (Scala) "((_).toInt & 0xFF).toChar" | constant uint16_of_uint32 \<rightharpoonup> (SML_word) "Word16.fromLarge (Word32.toLarge _)" and (Haskell) "(Prelude.fromIntegral _ :: Uint16.Word16)" and (Scala) "_.toChar" | constant uint32_of_uint8 \<rightharpoonup> (SML) "Word32.fromLarge (Word8.toLarge _)" and (Haskell) "(Prelude.fromIntegral _ :: Uint32.Word32)" and (Scala) "((_).toInt & 0xFF)" | constant uint32_of_uint16 \<rightharpoonup> (SML_word) "Word32.fromLarge (Word16.toLarge _)" and (Haskell) "(Prelude.fromIntegral _ :: Uint32.Word32)" and (Scala) "(_).toInt" text {* Use @{const Abs_uint8'} etc. instead of @{const Rep_uint8} in code equations for conversion functions to avoid exceptions during code generation when the target language provides only some of the uint types. *} lemma uint8_of_uint16_code [code]: "uint8_of_uint16 x = Abs_uint8' (ucast (Rep_uint16' x))" by transfer simp lemma uint8_of_uint32_code [code]: "uint8_of_uint32 x = Abs_uint8' (ucast (Rep_uint32' x))" by transfer simp lemma uint16_of_uint8_code [code]: "uint16_of_uint8 x = Abs_uint16' (ucast (Rep_uint8' x))" by transfer simp lemma uint16_of_uint32_code [code]: "uint16_of_uint32 x = Abs_uint16' (ucast (Rep_uint32' x))" by transfer simp lemma uint32_of_uint8_code [code]: "uint32_of_uint8 x = Abs_uint32' (ucast (Rep_uint8' x))" by transfer simp lemma uint32_of_uint16_code [code]: "uint32_of_uint16 x = Abs_uint32' (ucast (Rep_uint16' x))" by transfer simp end
[STATEMENT] lemma reach3: assumes k_y: "\<not> s\<turnstile> k reachable_from y" assumes k_x: "\<not> s\<turnstile> k reachable_from x" shows "\<not> s\<langle>l:=y\<rangle>\<turnstile> k reachable_from x" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<not> s\<langle>l := y\<rangle>\<turnstile> k reachable_from x [PROOF STEP] proof [PROOF STATE] proof (state) goal (1 subgoal): 1. s\<langle>l := y\<rangle>\<turnstile> k reachable_from x \<Longrightarrow> False [PROOF STEP] assume "s\<langle>l:=y\<rangle>\<turnstile> k reachable_from x" [PROOF STATE] proof (state) this: s\<langle>l := y\<rangle>\<turnstile> k reachable_from x goal (1 subgoal): 1. s\<langle>l := y\<rangle>\<turnstile> k reachable_from x \<Longrightarrow> False [PROOF STEP] from this k_y k_x [PROOF STATE] proof (chain) picking this: s\<langle>l := y\<rangle>\<turnstile> k reachable_from x \<not> s\<turnstile> k reachable_from y \<not> s\<turnstile> k reachable_from x [PROOF STEP] show False [PROOF STATE] proof (prove) using this: s\<langle>l := y\<rangle>\<turnstile> k reachable_from x \<not> s\<turnstile> k reachable_from y \<not> s\<turnstile> k reachable_from x goal (1 subgoal): 1. False [PROOF STEP] proof (induct) [PROOF STATE] proof (state) goal (2 subgoals): 1. \<And>l. \<lbrakk>ref l \<noteq> nullV; \<not> s\<turnstile> l reachable_from y; \<not> s\<turnstile> l reachable_from ref l\<rbrakk> \<Longrightarrow> False 2. \<And>la k. \<lbrakk>s\<langle>l := y\<rangle>\<turnstile> la reachable_from (s\<langle>l := y\<rangle>@@k); \<lbrakk>\<not> s\<turnstile> la reachable_from y; \<not> s\<turnstile> la reachable_from (s\<langle>l := y\<rangle>@@k)\<rbrakk> \<Longrightarrow> False; ref k \<noteq> nullV; \<not> s\<turnstile> la reachable_from y; \<not> s\<turnstile> la reachable_from ref k\<rbrakk> \<Longrightarrow> False [PROOF STEP] case (Immediate l) [PROOF STATE] proof (state) this: ref l \<noteq> nullV \<not> s\<turnstile> l reachable_from y \<not> s\<turnstile> l reachable_from ref l goal (2 subgoals): 1. \<And>l. \<lbrakk>ref l \<noteq> nullV; \<not> s\<turnstile> l reachable_from y; \<not> s\<turnstile> l reachable_from ref l\<rbrakk> \<Longrightarrow> False 2. \<And>la k. \<lbrakk>s\<langle>l := y\<rangle>\<turnstile> la reachable_from (s\<langle>l := y\<rangle>@@k); \<lbrakk>\<not> s\<turnstile> la reachable_from y; \<not> s\<turnstile> la reachable_from (s\<langle>l := y\<rangle>@@k)\<rbrakk> \<Longrightarrow> False; ref k \<noteq> nullV; \<not> s\<turnstile> la reachable_from y; \<not> s\<turnstile> la reachable_from ref k\<rbrakk> \<Longrightarrow> False [PROOF STEP] have "\<not> s\<turnstile> l reachable_from ref l" and "ref l \<noteq> nullV" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<not> s\<turnstile> l reachable_from ref l &&& ref l \<noteq> nullV [PROOF STEP] by fact+ [PROOF STATE] proof (state) this: \<not> s\<turnstile> l reachable_from ref l ref l \<noteq> nullV goal (2 subgoals): 1. \<And>l. \<lbrakk>ref l \<noteq> nullV; \<not> s\<turnstile> l reachable_from y; \<not> s\<turnstile> l reachable_from ref l\<rbrakk> \<Longrightarrow> False 2. \<And>la k. \<lbrakk>s\<langle>l := y\<rangle>\<turnstile> la reachable_from (s\<langle>l := y\<rangle>@@k); \<lbrakk>\<not> s\<turnstile> la reachable_from y; \<not> s\<turnstile> la reachable_from (s\<langle>l := y\<rangle>@@k)\<rbrakk> \<Longrightarrow> False; ref k \<noteq> nullV; \<not> s\<turnstile> la reachable_from y; \<not> s\<turnstile> la reachable_from ref k\<rbrakk> \<Longrightarrow> False [PROOF STEP] thus False [PROOF STATE] proof (prove) using this: \<not> s\<turnstile> l reachable_from ref l ref l \<noteq> nullV goal (1 subgoal): 1. False [PROOF STEP] by (iprover intro: reach.intros) [PROOF STATE] proof (state) this: False goal (1 subgoal): 1. \<And>la k. \<lbrakk>s\<langle>l := y\<rangle>\<turnstile> la reachable_from (s\<langle>l := y\<rangle>@@k); \<lbrakk>\<not> s\<turnstile> la reachable_from y; \<not> s\<turnstile> la reachable_from (s\<langle>l := y\<rangle>@@k)\<rbrakk> \<Longrightarrow> False; ref k \<noteq> nullV; \<not> s\<turnstile> la reachable_from y; \<not> s\<turnstile> la reachable_from ref k\<rbrakk> \<Longrightarrow> False [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>la k. \<lbrakk>s\<langle>l := y\<rangle>\<turnstile> la reachable_from (s\<langle>l := y\<rangle>@@k); \<lbrakk>\<not> s\<turnstile> la reachable_from y; \<not> s\<turnstile> la reachable_from (s\<langle>l := y\<rangle>@@k)\<rbrakk> \<Longrightarrow> False; ref k \<noteq> nullV; \<not> s\<turnstile> la reachable_from y; \<not> s\<turnstile> la reachable_from ref k\<rbrakk> \<Longrightarrow> False [PROOF STEP] case (Indirect m k) [PROOF STATE] proof (state) this: s\<langle>l := y\<rangle>\<turnstile> m reachable_from (s\<langle>l := y\<rangle>@@k) \<lbrakk>\<not> s\<turnstile> m reachable_from y; \<not> s\<turnstile> m reachable_from (s\<langle>l := y\<rangle>@@k)\<rbrakk> \<Longrightarrow> False ref k \<noteq> nullV \<not> s\<turnstile> m reachable_from y \<not> s\<turnstile> m reachable_from ref k goal (1 subgoal): 1. \<And>la k. \<lbrakk>s\<langle>l := y\<rangle>\<turnstile> la reachable_from (s\<langle>l := y\<rangle>@@k); \<lbrakk>\<not> s\<turnstile> la reachable_from y; \<not> s\<turnstile> la reachable_from (s\<langle>l := y\<rangle>@@k)\<rbrakk> \<Longrightarrow> False; ref k \<noteq> nullV; \<not> s\<turnstile> la reachable_from y; \<not> s\<turnstile> la reachable_from ref k\<rbrakk> \<Longrightarrow> False [PROOF STEP] have k_not_Null: "ref k \<noteq> nullV" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ref k \<noteq> nullV [PROOF STEP] by fact [PROOF STATE] proof (state) this: ref k \<noteq> nullV goal (1 subgoal): 1. \<And>la k. \<lbrakk>s\<langle>l := y\<rangle>\<turnstile> la reachable_from (s\<langle>l := y\<rangle>@@k); \<lbrakk>\<not> s\<turnstile> la reachable_from y; \<not> s\<turnstile> la reachable_from (s\<langle>l := y\<rangle>@@k)\<rbrakk> \<Longrightarrow> False; ref k \<noteq> nullV; \<not> s\<turnstile> la reachable_from y; \<not> s\<turnstile> la reachable_from ref k\<rbrakk> \<Longrightarrow> False [PROOF STEP] have not_m_y: "\<not> s\<turnstile> m reachable_from y" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<not> s\<turnstile> m reachable_from y [PROOF STEP] by fact [PROOF STATE] proof (state) this: \<not> s\<turnstile> m reachable_from y goal (1 subgoal): 1. \<And>la k. \<lbrakk>s\<langle>l := y\<rangle>\<turnstile> la reachable_from (s\<langle>l := y\<rangle>@@k); \<lbrakk>\<not> s\<turnstile> la reachable_from y; \<not> s\<turnstile> la reachable_from (s\<langle>l := y\<rangle>@@k)\<rbrakk> \<Longrightarrow> False; ref k \<noteq> nullV; \<not> s\<turnstile> la reachable_from y; \<not> s\<turnstile> la reachable_from ref k\<rbrakk> \<Longrightarrow> False [PROOF STEP] have not_m_k: "\<not> s\<turnstile> m reachable_from ref k" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<not> s\<turnstile> m reachable_from ref k [PROOF STEP] by fact [PROOF STATE] proof (state) this: \<not> s\<turnstile> m reachable_from ref k goal (1 subgoal): 1. \<And>la k. \<lbrakk>s\<langle>l := y\<rangle>\<turnstile> la reachable_from (s\<langle>l := y\<rangle>@@k); \<lbrakk>\<not> s\<turnstile> la reachable_from y; \<not> s\<turnstile> la reachable_from (s\<langle>l := y\<rangle>@@k)\<rbrakk> \<Longrightarrow> False; ref k \<noteq> nullV; \<not> s\<turnstile> la reachable_from y; \<not> s\<turnstile> la reachable_from ref k\<rbrakk> \<Longrightarrow> False [PROOF STEP] have hyp: "\<lbrakk>\<not> s\<turnstile> m reachable_from y; \<not> s\<turnstile> m reachable_from (s\<langle>l := y\<rangle>@@k)\<rbrakk> \<Longrightarrow> False" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>\<not> s\<turnstile> m reachable_from y; \<not> s\<turnstile> m reachable_from (s\<langle>l := y\<rangle>@@k)\<rbrakk> \<Longrightarrow> False [PROOF STEP] by fact [PROOF STATE] proof (state) this: \<lbrakk>\<not> s\<turnstile> m reachable_from y; \<not> s\<turnstile> m reachable_from (s\<langle>l := y\<rangle>@@k)\<rbrakk> \<Longrightarrow> False goal (1 subgoal): 1. \<And>la k. \<lbrakk>s\<langle>l := y\<rangle>\<turnstile> la reachable_from (s\<langle>l := y\<rangle>@@k); \<lbrakk>\<not> s\<turnstile> la reachable_from y; \<not> s\<turnstile> la reachable_from (s\<langle>l := y\<rangle>@@k)\<rbrakk> \<Longrightarrow> False; ref k \<noteq> nullV; \<not> s\<turnstile> la reachable_from y; \<not> s\<turnstile> la reachable_from ref k\<rbrakk> \<Longrightarrow> False [PROOF STEP] have m_upd_k: "s\<langle>l := y\<rangle>\<turnstile> m reachable_from (s\<langle>l := y\<rangle>@@k)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. s\<langle>l := y\<rangle>\<turnstile> m reachable_from (s\<langle>l := y\<rangle>@@k) [PROOF STEP] by fact [PROOF STATE] proof (state) this: s\<langle>l := y\<rangle>\<turnstile> m reachable_from (s\<langle>l := y\<rangle>@@k) goal (1 subgoal): 1. \<And>la k. \<lbrakk>s\<langle>l := y\<rangle>\<turnstile> la reachable_from (s\<langle>l := y\<rangle>@@k); \<lbrakk>\<not> s\<turnstile> la reachable_from y; \<not> s\<turnstile> la reachable_from (s\<langle>l := y\<rangle>@@k)\<rbrakk> \<Longrightarrow> False; ref k \<noteq> nullV; \<not> s\<turnstile> la reachable_from y; \<not> s\<turnstile> la reachable_from ref k\<rbrakk> \<Longrightarrow> False [PROOF STEP] show False [PROOF STATE] proof (prove) goal (1 subgoal): 1. False [PROOF STEP] proof (cases "l=k") [PROOF STATE] proof (state) goal (2 subgoals): 1. l = k \<Longrightarrow> False 2. l \<noteq> k \<Longrightarrow> False [PROOF STEP] case False [PROOF STATE] proof (state) this: l \<noteq> k goal (2 subgoals): 1. l = k \<Longrightarrow> False 2. l \<noteq> k \<Longrightarrow> False [PROOF STEP] then [PROOF STATE] proof (chain) picking this: l \<noteq> k [PROOF STEP] have "s\<langle>l := y\<rangle>@@k = s@@k" [PROOF STATE] proof (prove) using this: l \<noteq> k goal (1 subgoal): 1. s\<langle>l := y\<rangle>@@k = s@@k [PROOF STEP] by simp [PROOF STATE] proof (state) this: s\<langle>l := y\<rangle>@@k = s@@k goal (2 subgoals): 1. l = k \<Longrightarrow> False 2. l \<noteq> k \<Longrightarrow> False [PROOF STEP] moreover [PROOF STATE] proof (state) this: s\<langle>l := y\<rangle>@@k = s@@k goal (2 subgoals): 1. l = k \<Longrightarrow> False 2. l \<noteq> k \<Longrightarrow> False [PROOF STEP] from not_m_k k_not_Null [PROOF STATE] proof (chain) picking this: \<not> s\<turnstile> m reachable_from ref k ref k \<noteq> nullV [PROOF STEP] have "\<not> s\<turnstile> m reachable_from (s@@k)" [PROOF STATE] proof (prove) using this: \<not> s\<turnstile> m reachable_from ref k ref k \<noteq> nullV goal (1 subgoal): 1. \<not> s\<turnstile> m reachable_from (s@@k) [PROOF STEP] by (iprover intro: reach.intros) [PROOF STATE] proof (state) this: \<not> s\<turnstile> m reachable_from (s@@k) goal (2 subgoals): 1. l = k \<Longrightarrow> False 2. l \<noteq> k \<Longrightarrow> False [PROOF STEP] ultimately [PROOF STATE] proof (chain) picking this: s\<langle>l := y\<rangle>@@k = s@@k \<not> s\<turnstile> m reachable_from (s@@k) [PROOF STEP] show False [PROOF STATE] proof (prove) using this: s\<langle>l := y\<rangle>@@k = s@@k \<not> s\<turnstile> m reachable_from (s@@k) goal (1 subgoal): 1. False [PROOF STEP] using not_m_y hyp [PROOF STATE] proof (prove) using this: s\<langle>l := y\<rangle>@@k = s@@k \<not> s\<turnstile> m reachable_from (s@@k) \<not> s\<turnstile> m reachable_from y \<lbrakk>\<not> s\<turnstile> m reachable_from y; \<not> s\<turnstile> m reachable_from (s\<langle>l := y\<rangle>@@k)\<rbrakk> \<Longrightarrow> False goal (1 subgoal): 1. False [PROOF STEP] by simp [PROOF STATE] proof (state) this: False goal (1 subgoal): 1. l = k \<Longrightarrow> False [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. l = k \<Longrightarrow> False [PROOF STEP] case True [PROOF STATE] proof (state) this: l = k goal (1 subgoal): 1. l = k \<Longrightarrow> False [PROOF STEP] note eq_l_k = this [PROOF STATE] proof (state) this: l = k goal (1 subgoal): 1. l = k \<Longrightarrow> False [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) goal (1 subgoal): 1. False [PROOF STEP] proof (cases "alive (ref l) s \<and> alive y s \<and> typeof y \<le> ltype l") [PROOF STATE] proof (state) goal (2 subgoals): 1. alive (ref l) s \<and> alive y s \<and> \<tau> y \<le> ltype l \<Longrightarrow> False 2. \<not> (alive (ref l) s \<and> alive y s \<and> \<tau> y \<le> ltype l) \<Longrightarrow> False [PROOF STEP] case True [PROOF STATE] proof (state) this: alive (ref l) s \<and> alive y s \<and> \<tau> y \<le> ltype l goal (2 subgoals): 1. alive (ref l) s \<and> alive y s \<and> \<tau> y \<le> ltype l \<Longrightarrow> False 2. \<not> (alive (ref l) s \<and> alive y s \<and> \<tau> y \<le> ltype l) \<Longrightarrow> False [PROOF STEP] with eq_l_k [PROOF STATE] proof (chain) picking this: l = k alive (ref l) s \<and> alive y s \<and> \<tau> y \<le> ltype l [PROOF STEP] have "s\<langle>l := y\<rangle>@@k = y" [PROOF STATE] proof (prove) using this: l = k alive (ref l) s \<and> alive y s \<and> \<tau> y \<le> ltype l goal (1 subgoal): 1. s\<langle>l := y\<rangle>@@k = y [PROOF STEP] by simp [PROOF STATE] proof (state) this: s\<langle>l := y\<rangle>@@k = y goal (2 subgoals): 1. alive (ref l) s \<and> alive y s \<and> \<tau> y \<le> ltype l \<Longrightarrow> False 2. \<not> (alive (ref l) s \<and> alive y s \<and> \<tau> y \<le> ltype l) \<Longrightarrow> False [PROOF STEP] with not_m_y hyp [PROOF STATE] proof (chain) picking this: \<not> s\<turnstile> m reachable_from y \<lbrakk>\<not> s\<turnstile> m reachable_from y; \<not> s\<turnstile> m reachable_from (s\<langle>l := y\<rangle>@@k)\<rbrakk> \<Longrightarrow> False s\<langle>l := y\<rangle>@@k = y [PROOF STEP] show False [PROOF STATE] proof (prove) using this: \<not> s\<turnstile> m reachable_from y \<lbrakk>\<not> s\<turnstile> m reachable_from y; \<not> s\<turnstile> m reachable_from (s\<langle>l := y\<rangle>@@k)\<rbrakk> \<Longrightarrow> False s\<langle>l := y\<rangle>@@k = y goal (1 subgoal): 1. False [PROOF STEP] by simp [PROOF STATE] proof (state) this: False goal (1 subgoal): 1. \<not> (alive (ref l) s \<and> alive y s \<and> \<tau> y \<le> ltype l) \<Longrightarrow> False [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<not> (alive (ref l) s \<and> alive y s \<and> \<tau> y \<le> ltype l) \<Longrightarrow> False [PROOF STEP] case False [PROOF STATE] proof (state) this: \<not> (alive (ref l) s \<and> alive y s \<and> \<tau> y \<le> ltype l) goal (1 subgoal): 1. \<not> (alive (ref l) s \<and> alive y s \<and> \<tau> y \<le> ltype l) \<Longrightarrow> False [PROOF STEP] hence "s\<langle>l := y\<rangle> = s" [PROOF STATE] proof (prove) using this: \<not> (alive (ref l) s \<and> alive y s \<and> \<tau> y \<le> ltype l) goal (1 subgoal): 1. s\<langle>l := y\<rangle> = s [PROOF STEP] by auto [PROOF STATE] proof (state) this: s\<langle>l := y\<rangle> = s goal (1 subgoal): 1. \<not> (alive (ref l) s \<and> alive y s \<and> \<tau> y \<le> ltype l) \<Longrightarrow> False [PROOF STEP] moreover [PROOF STATE] proof (state) this: s\<langle>l := y\<rangle> = s goal (1 subgoal): 1. \<not> (alive (ref l) s \<and> alive y s \<and> \<tau> y \<le> ltype l) \<Longrightarrow> False [PROOF STEP] from not_m_k k_not_Null [PROOF STATE] proof (chain) picking this: \<not> s\<turnstile> m reachable_from ref k ref k \<noteq> nullV [PROOF STEP] have "\<not> s\<turnstile> m reachable_from (s@@k)" [PROOF STATE] proof (prove) using this: \<not> s\<turnstile> m reachable_from ref k ref k \<noteq> nullV goal (1 subgoal): 1. \<not> s\<turnstile> m reachable_from (s@@k) [PROOF STEP] by (iprover intro: reach.intros) [PROOF STATE] proof (state) this: \<not> s\<turnstile> m reachable_from (s@@k) goal (1 subgoal): 1. \<not> (alive (ref l) s \<and> alive y s \<and> \<tau> y \<le> ltype l) \<Longrightarrow> False [PROOF STEP] ultimately [PROOF STATE] proof (chain) picking this: s\<langle>l := y\<rangle> = s \<not> s\<turnstile> m reachable_from (s@@k) [PROOF STEP] show False [PROOF STATE] proof (prove) using this: s\<langle>l := y\<rangle> = s \<not> s\<turnstile> m reachable_from (s@@k) goal (1 subgoal): 1. False [PROOF STEP] using not_m_y hyp [PROOF STATE] proof (prove) using this: s\<langle>l := y\<rangle> = s \<not> s\<turnstile> m reachable_from (s@@k) \<not> s\<turnstile> m reachable_from y \<lbrakk>\<not> s\<turnstile> m reachable_from y; \<not> s\<turnstile> m reachable_from (s\<langle>l := y\<rangle>@@k)\<rbrakk> \<Longrightarrow> False goal (1 subgoal): 1. False [PROOF STEP] by simp [PROOF STATE] proof (state) this: False goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: False goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: False goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: False goal: No subgoals! [PROOF STEP] qed
[STATEMENT] lemma dual_sup_eq [simp]: "dual (sup x y) = inf (dual x) (dual y)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. dual (sup x y) = inf (dual x) (dual y) [PROOF STEP] by transfer rule
lemma emeasure_lfp2[consumes 1, case_names cont f measurable]: assumes "P M" assumes cont: "sup_continuous F" assumes f: "\<And>M. P M \<Longrightarrow> f \<in> measurable M' M" assumes *: "\<And>M A. P M \<Longrightarrow> (\<And>N. P N \<Longrightarrow> Measurable.pred N A) \<Longrightarrow> Measurable.pred M (F A)" shows "emeasure M' {x\<in>space M'. lfp F (f x)} = (SUP i. emeasure M' {x\<in>space M'. (F ^^ i) (\<lambda>x. False) (f x)})"
-- DontCares shouldn't end up in the generated with functions. module Issue337 where data ℕ : Set where zero : ℕ suc : (n : ℕ) → ℕ {-# BUILTIN NATURAL ℕ #-} {-# BUILTIN ZERO zero #-} {-# BUILTIN SUC suc #-} data _≡_ {A : Set}(x : A) : A → Set where refl : x ≡ x postulate _≤_ : ℕ → ℕ → Set p₁ : 0 ≤ 1 p₂ : 0 ≤ 1 data SList (bound : ℕ) : Set where [] : SList bound scons : (head : ℕ) → .(head ≤ bound) → (tail : SList head) → SList bound l₁ : SList 1 l₁ = scons 0 p₁ [] l₂ : SList 1 l₂ = scons 0 p₂ [] l₁≡l₂ : l₁ ≡ l₂ l₁≡l₂ with Set ... | _ = refl
lemma offset_poly_0: "offset_poly 0 h = 0"
[STATEMENT] lemma log_twice [simp]: "n \<noteq> 0 \<Longrightarrow> log (2 * n) = Suc (log n)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. n \<noteq> 0 \<Longrightarrow> local.log (2 * n) = Suc (local.log n) [PROOF STEP] by (simp add: log_rec)
Formal statement is: lemma snd_quot_of_fract_nonzero [simp]: "snd (quot_of_fract x) \<noteq> 0" Informal statement is: The denominator of a fraction is never zero.
```python import sys, os sys.path.insert(0, os.path.join(os.pardir, 'src')) from approx1D import interpolation, comparison_plot from Lagrange import Lagrange_polynomials import sympy as sym x = sym.Symbol('x') Omega = [0,1] N_values = 3, 7, 11, 15 for s in 5, 20: f = -sym.tanh(s*(x-0.5)) # sympy expression for distribution in 'uniform', 'Chebyshev': for N in N_values: phi, points = Lagrange_polynomials( x, N, Omega, point_distribution=distribution) u, c = interpolation(f, phi, points) filename = 'tmp_tanh_%d_%d_%s' % (N, s, distribution) comparison_plot(f, u, Omega, filename, plot_title='s=%g, N=%d, %s points' % (s, N, distribution)) # Combine plot files (2x2) for ext in 'png', 'pdf': cmd = 'doconce combine_images ' + ext + ' ' cmd += ' '.join([ 'tmp_tanh_%d_%d_%s' % (N, s, distribution) for N in N_values]) cmd += ' tanh_Lagrange_%s_s%s' % (distribution, s) os.system(cmd) ``` ```python ```
(*** This file is part of Lem. eth-isabelle project just uses it. See lem-license. ***) chapter {* Generated by Lem from list.lem. *} theory "Lem_list" imports Main "Lem_bool" "Lem_maybe" "Lem_basic_classes" "Lem_function" "Lem_tuple" "Lem_num" "Lem" begin (*open import Bool Maybe Basic_classes Function Tuple Num*) (*open import {coq} `Coq.Lists.List`*) (*open import {isabelle} `$LIB_DIR/Lem`*) (*open import {hol} `lemTheory` `listTheory` `rich_listTheory` `sortingTheory`*) (* ========================================================================== *) (* Basic list functions *) (* ========================================================================== *) (* The type of lists as well as list literals like [], [1;2], ... are hardcoded. Thus, we can directly dive into derived definitions. *) (* ----------------------- *) (* cons *) (* ----------------------- *) (*val :: : forall 'a. 'a -> list 'a -> list 'a*) (* ----------------------- *) (* Emptyness check *) (* ----------------------- *) (*val null : forall 'a. list 'a -> bool*) (*let null l= match l with [] -> true | _ -> false end*) (* ----------------------- *) (* Length *) (* ----------------------- *) (*val length : forall 'a. list 'a -> nat*) (*let rec length l= match l with | [] -> 0 | x :: xs -> (Instance_Num_NumAdd_nat.+) (length xs) 1 end*) (* ----------------------- *) (* Equality *) (* ----------------------- *) (*val listEqual : forall 'a. Eq 'a => list 'a -> list 'a -> bool*) (*val listEqualBy : forall 'a. ('a -> 'a -> bool) -> list 'a -> list 'a -> bool*) fun listEqualBy :: "('a \<Rightarrow> 'a \<Rightarrow> bool)\<Rightarrow> 'a list \<Rightarrow> 'a list \<Rightarrow> bool " where " listEqualBy eq ([]) ([]) = ( True )" |" listEqualBy eq ([]) (_ # _) = ( False )" |" listEqualBy eq (_ # _) ([]) = ( False )" |" listEqualBy eq (x # xs) (y # ys) = ( (eq x y \<and> listEqualBy eq xs ys))" declare listEqualBy.simps [simp del] (* ----------------------- *) (* compare *) (* ----------------------- *) (*val lexicographicCompare : forall 'a. Ord 'a => list 'a -> list 'a -> ordering*) (*val lexicographicCompareBy : forall 'a. ('a -> 'a -> ordering) -> list 'a -> list 'a -> ordering*) fun lexicographicCompareBy :: "('a \<Rightarrow> 'a \<Rightarrow> ordering)\<Rightarrow> 'a list \<Rightarrow> 'a list \<Rightarrow> ordering " where " lexicographicCompareBy cmp ([]) ([]) = ( EQ )" |" lexicographicCompareBy cmp ([]) (_ # _) = ( LT )" |" lexicographicCompareBy cmp (_ # _) ([]) = ( GT )" |" lexicographicCompareBy cmp (x # xs) (y # ys) = ( ( (case cmp x y of LT => LT | GT => GT | EQ => lexicographicCompareBy cmp xs ys ) ))" declare lexicographicCompareBy.simps [simp del] (*val lexicographicLess : forall 'a. Ord 'a => list 'a -> list 'a -> bool*) (*val lexicographicLessBy : forall 'a. ('a -> 'a -> bool) -> ('a -> 'a -> bool) -> list 'a -> list 'a -> bool*) fun lexicographicLessBy :: "('a \<Rightarrow> 'a \<Rightarrow> bool)\<Rightarrow>('a \<Rightarrow> 'a \<Rightarrow> bool)\<Rightarrow> 'a list \<Rightarrow> 'a list \<Rightarrow> bool " where " lexicographicLessBy less1 less_eq1 ([]) ([]) = ( False )" |" lexicographicLessBy less1 less_eq1 ([]) (_ # _) = ( True )" |" lexicographicLessBy less1 less_eq1 (_ # _) ([]) = ( False )" |" lexicographicLessBy less1 less_eq1 (x # xs) (y # ys) = ( ((less1 x y) \<or> ((less_eq1 x y) \<and> (lexicographicLessBy less1 less_eq1 xs ys))))" declare lexicographicLessBy.simps [simp del] (*val lexicographicLessEq : forall 'a. Ord 'a => list 'a -> list 'a -> bool*) (*val lexicographicLessEqBy : forall 'a. ('a -> 'a -> bool) -> ('a -> 'a -> bool) -> list 'a -> list 'a -> bool*) fun lexicographicLessEqBy :: "('a \<Rightarrow> 'a \<Rightarrow> bool)\<Rightarrow>('a \<Rightarrow> 'a \<Rightarrow> bool)\<Rightarrow> 'a list \<Rightarrow> 'a list \<Rightarrow> bool " where " lexicographicLessEqBy less1 less_eq1 ([]) ([]) = ( True )" |" lexicographicLessEqBy less1 less_eq1 ([]) (_ # _) = ( True )" |" lexicographicLessEqBy less1 less_eq1 (_ # _) ([]) = ( False )" |" lexicographicLessEqBy less1 less_eq1 (x # xs) (y # ys) = ( (less1 x y \<or> (less_eq1 x y \<and> lexicographicLessEqBy less1 less_eq1 xs ys)))" declare lexicographicLessEqBy.simps [simp del] definition instance_Basic_classes_Ord_list_dict :: " 'a Ord_class \<Rightarrow>('a list)Ord_class " where " instance_Basic_classes_Ord_list_dict dict_Basic_classes_Ord_a = ((| compare_method = (lexicographicCompareBy (compare_method dict_Basic_classes_Ord_a)), isLess_method = (lexicographicLessBy (isLess_method dict_Basic_classes_Ord_a) (isLessEqual_method dict_Basic_classes_Ord_a)), isLessEqual_method = (lexicographicLessEqBy (isLess_method dict_Basic_classes_Ord_a) (isLessEqual_method dict_Basic_classes_Ord_a)), isGreater_method = (\<lambda> x y. (lexicographicLessBy (isLess_method dict_Basic_classes_Ord_a) (isLessEqual_method dict_Basic_classes_Ord_a) y x)), isGreaterEqual_method = (\<lambda> x y. (lexicographicLessEqBy (isLess_method dict_Basic_classes_Ord_a) (isLessEqual_method dict_Basic_classes_Ord_a) y x))|) )" (* ----------------------- *) (* Append *) (* ----------------------- *) (*val ++ : forall 'a. list 'a -> list 'a -> list 'a*) (* originally append *) (*let rec ++ xs ys= match xs with | [] -> ys | x :: xs' -> x :: (xs' ++ ys) end*) (* ----------------------- *) (* snoc *) (* ----------------------- *) (*val snoc : forall 'a. 'a -> list 'a -> list 'a*) (*let snoc e l= l ++ [e]*) (* ----------------------- *) (* Reverse *) (* ----------------------- *) (* First lets define the function [reverse_append], which is closely related to reverse. [reverse_append l1 l2] appends the list [l2] to the reverse of [l1]. This can be implemented more efficienctly than appending and is used to implement reverse. *) (*val reverseAppend : forall 'a. list 'a -> list 'a -> list 'a*) (* originally named rev_append *) (*let rec reverseAppend l1 l2= match l1 with | [] -> l2 | x :: xs -> reverseAppend xs (x :: l2) end*) (* Reversing a list *) (*val reverse : forall 'a. list 'a -> list 'a*) (* originally named rev *) (*let reverse l= reverseAppend l []*) (* ----------------------- *) (* Map *) (* ----------------------- *) (*val map_tr : forall 'a 'b. list 'b -> ('a -> 'b) -> list 'a -> list 'b*) function (sequential,domintros) map_tr :: " 'b list \<Rightarrow>('a \<Rightarrow> 'b)\<Rightarrow> 'a list \<Rightarrow> 'b list " where " map_tr rev_acc f ([]) = ( List.rev rev_acc )" |" map_tr rev_acc f (x # xs) = ( map_tr ((f x) # rev_acc) f xs )" by pat_completeness auto (* taken from: https://blogs.janestreet.com/optimizing-list-map/ *) (*val count_map : forall 'a 'b. ('a -> 'b) -> list 'a -> nat -> list 'b*) function (sequential,domintros) count_map :: "('a \<Rightarrow> 'b)\<Rightarrow> 'a list \<Rightarrow> nat \<Rightarrow> 'b list " where " count_map f ([]) ctr = ( [])" |" count_map f (hd1 # tl1) ctr = ( f hd1 # (if ctr <( 5000 :: nat) then count_map f tl1 (ctr +( 1 :: nat)) else map_tr [] f tl1))" by pat_completeness auto (*val map : forall 'a 'b. ('a -> 'b) -> list 'a -> list 'b*) (*let map f l= count_map f l 0*) (* ----------------------- *) (* Reverse Map *) (* ----------------------- *) (*val reverseMap : forall 'a 'b. ('a -> 'b) -> list 'a -> list 'b*) (* ========================================================================== *) (* Folding *) (* ========================================================================== *) (* ----------------------- *) (* fold left *) (* ----------------------- *) (*val foldl : forall 'a 'b. ('a -> 'b -> 'a) -> 'a -> list 'b -> 'a*) (* originally foldl *) (*let rec foldl f b l= match l with | [] -> b | x :: xs -> foldl f (f b x) xs end*) (* ----------------------- *) (* fold right *) (* ----------------------- *) (*val foldr : forall 'a 'b. ('a -> 'b -> 'b) -> 'b -> list 'a -> 'b*) (* originally foldr with different argument order *) (*let rec foldr f b l= match l with | [] -> b | x :: xs -> f x (foldr f b xs) end*) (* ----------------------- *) (* concatenating lists *) (* ----------------------- *) (*val concat : forall 'a. list (list 'a) -> list 'a*) (* before also called flatten *) (*let concat= foldr (++) []*) (* -------------------------- *) (* concatenating with mapping *) (* -------------------------- *) (*val concatMap : forall 'a 'b. ('a -> list 'b) -> list 'a -> list 'b*) (* ------------------------- *) (* universal qualification *) (* ------------------------- *) (*val all : forall 'a. ('a -> bool) -> list 'a -> bool*) (* originally for_all *) (*let all P l= foldl (fun r e -> P e && r) true l*) (* ------------------------- *) (* existential qualification *) (* ------------------------- *) (*val any : forall 'a. ('a -> bool) -> list 'a -> bool*) (* originally exist *) (*let any P l= foldl (fun r e -> P e || r) false l*) (* ------------------------- *) (* dest_init *) (* ------------------------- *) (* get the initial part and the last element of the list in a safe way *) (*val dest_init : forall 'a. list 'a -> maybe (list 'a * 'a)*) fun dest_init_aux :: " 'a list \<Rightarrow> 'a \<Rightarrow> 'a list \<Rightarrow> 'a list*'a " where " dest_init_aux rev_init last_elem_seen ([]) = ( (List.rev rev_init, last_elem_seen))" |" dest_init_aux rev_init last_elem_seen (x # xs) = ( dest_init_aux (last_elem_seen # rev_init) x xs )" declare dest_init_aux.simps [simp del] fun dest_init :: " 'a list \<Rightarrow>('a list*'a)option " where " dest_init ([]) = ( None )" |" dest_init (x # xs) = ( Some (dest_init_aux [] x xs))" declare dest_init.simps [simp del] (* ========================================================================== *) (* Indexing lists *) (* ========================================================================== *) (* ------------------------- *) (* index / nth with maybe *) (* ------------------------- *) (*val index : forall 'a. list 'a -> nat -> maybe 'a*) (*let rec index l n= match l with | [] -> Nothing | x :: xs -> if (Instance_Basic_classes_Eq_nat.=) n 0 then Just x else index xs ((Instance_Num_NumMinus_nat.-)n 1) end*) (* ------------------------- *) (* findIndices *) (* ------------------------- *) (* [findIndices P l] returns the indices of all elements of list [l] that satisfy predicate [P]. Counting starts with 0, the result list is sorted ascendingly *) (*val findIndices : forall 'a. ('a -> bool) -> list 'a -> list nat*) fun findIndices_aux :: " nat \<Rightarrow>('a \<Rightarrow> bool)\<Rightarrow> 'a list \<Rightarrow>(nat)list " where " findIndices_aux (i::nat) P ([]) = ( [])" |" findIndices_aux (i::nat) P (x # xs) = ( if P x then i # findIndices_aux (i +( 1 :: nat)) P xs else findIndices_aux (i +( 1 :: nat)) P xs )" declare findIndices_aux.simps [simp del] (*let findIndices P l= findIndices_aux 0 P l*) (* ------------------------- *) (* findIndex *) (* ------------------------- *) (* findIndex returns the first index of a list that satisfies a given predicate. *) (*val findIndex : forall 'a. ('a -> bool) -> list 'a -> maybe nat*) (*let findIndex P l= match findIndices P l with | [] -> Nothing | x :: _ -> Just x end*) (* ------------------------- *) (* elemIndices *) (* ------------------------- *) (*val elemIndices : forall 'a. Eq 'a => 'a -> list 'a -> list nat*) (* ------------------------- *) (* elemIndex *) (* ------------------------- *) (*val elemIndex : forall 'a. Eq 'a => 'a -> list 'a -> maybe nat*) (* ========================================================================== *) (* Creating lists *) (* ========================================================================== *) (* ------------------------- *) (* genlist *) (* ------------------------- *) (* [genlist f n] generates the list [f 0; f 1; ... (f (n-1))] *) (*val genlist : forall 'a. (nat -> 'a) -> nat -> list 'a*) (*let rec genlist f n= match n with | 0 -> [] | n' + 1 -> snoc (f n') (genlist f n') end*) (* ------------------------- *) (* replicate *) (* ------------------------- *) (*val replicate : forall 'a. nat -> 'a -> list 'a*) (*let rec replicate n x= match n with | 0 -> [] | n' + 1 -> x :: replicate n' x end*) (* ========================================================================== *) (* Sublists *) (* ========================================================================== *) (* ------------------------- *) (* splitAt *) (* ------------------------- *) (* [splitAt n xs] returns a tuple (xs1, xs2), with append xs1 xs2 = xs and length xs1 = n. If there are not enough elements in [xs], the original list and the empty one are returned. *) (*val splitAtAcc : forall 'a. list 'a -> nat -> list 'a -> (list 'a * list 'a)*) function (sequential,domintros) splitAtAcc :: " 'a list \<Rightarrow> nat \<Rightarrow> 'a list \<Rightarrow> 'a list*'a list " where " splitAtAcc revAcc n l = ( (case l of [] => (List.rev revAcc, []) | x # xs => if n \<le>( 0 :: nat) then (List.rev revAcc, l) else splitAtAcc (x # revAcc) (n-( 1 :: nat)) xs ))" by pat_completeness auto (*val splitAt : forall 'a. nat -> list 'a -> (list 'a * list 'a)*) (*let rec splitAt n l= splitAtAcc [] n l*) (* ------------------------- *) (* take *) (* ------------------------- *) (* take n xs returns the prefix of xs of length n, or xs itself if n > length xs *) (*val take : forall 'a. nat -> list 'a -> list 'a*) (*let take n l= fst (splitAt n l)*) (* ------------------------- *) (* drop *) (* ------------------------- *) (* [drop n xs] drops the first [n] elements of [xs]. It returns the empty list, if [n] > [length xs]. *) (*val drop : forall 'a. nat -> list 'a -> list 'a*) (*let drop n l= snd (splitAt n l)*) (* ------------------------- *) (* dropWhile *) (* ------------------------- *) (* [dropWhile p xs] drops the first elements of [xs] that satisfy [p]. *) (*val dropWhile : forall 'a. ('a -> bool) -> list 'a -> list 'a*) fun dropWhile :: "('a \<Rightarrow> bool)\<Rightarrow> 'a list \<Rightarrow> 'a list " where " dropWhile p l = ( (case l of [] => [] | x # xs => if p x then dropWhile p xs else l ))" declare dropWhile.simps [simp del] (* ------------------------- *) (* takeWhile *) (* ------------------------- *) (* [takeWhile p xs] takes the first elements of [xs] that satisfy [p]. *) (*val takeWhile : forall 'a. ('a -> bool) -> list 'a -> list 'a*) fun takeWhile :: "('a \<Rightarrow> bool)\<Rightarrow> 'a list \<Rightarrow> 'a list " where " takeWhile p ([]) = ( [])" |" takeWhile p (x # xs) = ( if p x then x # takeWhile p xs else [])" declare takeWhile.simps [simp del] (* ------------------------- *) (* splitWhile *) (* ------------------------- *) (*val splitWhile : forall 'a. ('a -> bool) -> list 'a -> (list 'a * list 'a)*) definition splitWhile :: "('a \<Rightarrow> bool)\<Rightarrow> 'a list \<Rightarrow> 'a list*'a list " where " splitWhile p xs = ( (takeWhile p xs, dropWhile p xs))" (* ------------------------- *) (* isPrefixOf *) (* ------------------------- *) (*val isPrefixOf : forall 'a. Eq 'a => list 'a -> list 'a -> bool*) fun isPrefixOf :: " 'a list \<Rightarrow> 'a list \<Rightarrow> bool " where " isPrefixOf ([]) _ = ( True )" |" isPrefixOf (_ # _) ([]) = ( False )" |" isPrefixOf (x # xs) (y # ys) = ( (x = y) \<and> isPrefixOf xs ys )" declare isPrefixOf.simps [simp del] (* ------------------------- *) (* update *) (* ------------------------- *) (*val update : forall 'a. list 'a -> nat -> 'a -> list 'a*) (*let rec update l n e= match l with | [] -> [] | x :: xs -> if (Instance_Basic_classes_Eq_nat.=) n 0 then e :: xs else x :: (update xs ((Instance_Num_NumMinus_nat.-) n 1) e) end*) (* ========================================================================== *) (* Searching lists *) (* ========================================================================== *) (* ------------------------- *) (* Membership test *) (* ------------------------- *) (* The membership test, one of the basic list functions, is actually tricky for Lem, because it is tricky, which equality to use. From Lem`s point of perspective, we want to use the equality provided by the equality type - class. This allows for example to check whether a set is in a list of sets. However, in order to use the equality type class, elem essentially becomes existential quantification over lists. For types, which implement semantic equality (=) with syntactic equality, this is overly complicated. In our theorem prover backend, we would end up with overly complicated, harder to read definitions and some of the automation would be harder to apply. Moreover, nearly all the old Lem generated code would change and require (hopefully minor) adaptions of proofs. For now, we ignore this problem and just demand, that all instances of the equality type class do the right thing for the theorem prover backends. *) (*val elem : forall 'a. Eq 'a => 'a -> list 'a -> bool*) (*val elemBy : forall 'a. ('a -> 'a -> bool) -> 'a -> list 'a -> bool*) definition elemBy :: "('a \<Rightarrow> 'a \<Rightarrow> bool)\<Rightarrow> 'a \<Rightarrow> 'a list \<Rightarrow> bool " where " elemBy eq e l = ( ((\<exists> x \<in> (set l). (eq e) x)))" (*let elem= elemBy (=)*) (* ------------------------- *) (* Find *) (* ------------------------- *) (*val find : forall 'a. ('a -> bool) -> list 'a -> maybe 'a*) (* previously not of maybe type *) (*let rec find P l= match l with | [] -> Nothing | x :: xs -> if P x then Just x else find P xs end*) (* ----------------------------- *) (* Lookup in an associative list *) (* ----------------------------- *) (*val lookup : forall 'a 'b. Eq 'a => 'a -> list ('a * 'b) -> maybe 'b*) (*val lookupBy : forall 'a 'b. ('a -> 'a -> bool) -> 'a -> list ('a * 'b) -> maybe 'b*) (* DPM: eta-expansion for Coq backend type-inference. *) definition lookupBy :: "('a \<Rightarrow> 'a \<Rightarrow> bool)\<Rightarrow> 'a \<Rightarrow>('a*'b)list \<Rightarrow> 'b option " where " lookupBy eq k m = ( map_option (\<lambda> x . snd x) (List.find (\<lambda> (k', _) . eq k k') m))" (* ------------------------- *) (* filter *) (* ------------------------- *) (*val filter : forall 'a. ('a -> bool) -> list 'a -> list 'a*) (*let rec filter P l= match l with | [] -> [] | x :: xs -> if (P x) then x :: (filter P xs) else filter P xs end*) (* ------------------------- *) (* partition *) (* ------------------------- *) (*val partition : forall 'a. ('a -> bool) -> list 'a -> list 'a * list 'a*) (*let partition P l= (filter P l, filter (fun x -> not (P x)) l)*) (*val reversePartition : forall 'a. ('a -> bool) -> list 'a -> list 'a * list 'a*) definition reversePartition :: "('a \<Rightarrow> bool)\<Rightarrow> 'a list \<Rightarrow> 'a list*'a list " where " reversePartition P l = ( List.partition P (List.rev l))" (* ------------------------- *) (* delete first element *) (* with certain property *) (* ------------------------- *) (*val deleteFirst : forall 'a. ('a -> bool) -> list 'a -> maybe (list 'a)*) (*let rec deleteFirst P l= match l with | [] -> Nothing | x :: xs -> if (P x) then Just xs else Maybe.map (fun xs' -> x :: xs') (deleteFirst P xs) end*) (*val delete : forall 'a. Eq 'a => 'a -> list 'a -> list 'a*) (*val deleteBy : forall 'a. ('a -> 'a -> bool) -> 'a -> list 'a -> list 'a*) definition deleteBy :: "('a \<Rightarrow> 'a \<Rightarrow> bool)\<Rightarrow> 'a \<Rightarrow> 'a list \<Rightarrow> 'a list " where " deleteBy eq x l = ( case_option l id (delete_first (eq x) l))" (* ========================================================================== *) (* Zipping and unzipping lists *) (* ========================================================================== *) (* ------------------------- *) (* zip *) (* ------------------------- *) (* zip takes two lists and returns a list of corresponding pairs. If one input list is short, excess elements of the longer list are discarded. *) (*val zip : forall 'a 'b. list 'a -> list 'b -> list ('a * 'b)*) (* before combine *) (*let rec zip l1 l2= match (l1, l2) with | (x :: xs, y :: ys) -> (x, y) :: zip xs ys | _ -> [] end*) (* ------------------------- *) (* unzip *) (* ------------------------- *) (*val unzip: forall 'a 'b. list ('a * 'b) -> (list 'a * list 'b)*) (*let rec unzip l= match l with | [] -> ([], []) | (x, y) :: xys -> let (xs, ys) = unzip xys in (x :: xs, y :: ys) end*) (* ------------------------- *) (* distinct elements *) (* ------------------------- *) (*val allDistinct : forall 'a. Eq 'a => list 'a -> bool*) fun allDistinct :: " 'a list \<Rightarrow> bool " where " allDistinct ([]) = ( True )" |" allDistinct (x # l') = ( \<not> (Set.member x (set l')) \<and> allDistinct l' )" declare allDistinct.simps [simp del] (* some more useful functions *) (*val mapMaybe : forall 'a 'b. ('a -> maybe 'b) -> list 'a -> list 'b*) function (sequential,domintros) mapMaybe :: "('a \<Rightarrow> 'b option)\<Rightarrow> 'a list \<Rightarrow> 'b list " where " mapMaybe f ([]) = ( [])" |" mapMaybe f (x # xs) = ( (case f x of None => mapMaybe f xs | Some y => y # (mapMaybe f xs) ))" by pat_completeness auto (*val mapi : forall 'a 'b. (nat -> 'a -> 'b) -> list 'a -> list 'b*) function (sequential,domintros) mapiAux :: "(nat \<Rightarrow> 'b \<Rightarrow> 'a)\<Rightarrow> nat \<Rightarrow> 'b list \<Rightarrow> 'a list " where " mapiAux f (n :: nat) ([]) = ( [])" |" mapiAux f (n :: nat) (x # xs) = ( (f n x) # mapiAux f (n +( 1 :: nat)) xs )" by pat_completeness auto definition mapi :: "(nat \<Rightarrow> 'a \<Rightarrow> 'b)\<Rightarrow> 'a list \<Rightarrow> 'b list " where " mapi f l = ( mapiAux f(( 0 :: nat)) l )" (*val deletes: forall 'a. Eq 'a => list 'a -> list 'a -> list 'a*) definition deletes :: " 'a list \<Rightarrow> 'a list \<Rightarrow> 'a list " where " deletes xs ys = ( List.foldl ((\<lambda> x y. remove1 y x)) xs ys )" (* ========================================================================== *) (* Comments (not clean yet, please ignore the rest of the file) *) (* ========================================================================== *) (* ----------------------- *) (* skipped from Haskell Lib*) (* ----------------------- intersperse :: a -> [a] -> [a] intercalate :: [a] -> [[a]] -> [a] transpose :: [[a]] -> [[a]] subsequences :: [a] -> [[a]] permutations :: [a] -> [[a]] foldl` :: (a -> b -> a) -> a -> [b] -> aSource foldl1` :: (a -> a -> a) -> [a] -> aSource and or sum product maximum minimum scanl scanr scanl1 scanr1 Accumulating maps mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])Source mapAccumR :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])Source iterate :: (a -> a) -> a -> [a] repeat :: a -> [a] cycle :: [a] -> [a] unfoldr takeWhile :: (a -> Bool) -> [a] -> [a]Source dropWhile :: (a -> Bool) -> [a] -> [a]Source dropWhileEnd :: (a -> Bool) -> [a] -> [a]Source span :: (a -> Bool) -> [a] -> ([a], [a])Source break :: (a -> Bool) -> [a] -> ([a], [a])Source break p is equivalent to span (not . p). stripPrefix :: Eq a => [a] -> [a] -> Maybe [a]Source group :: Eq a => [a] -> [[a]]Source inits :: [a] -> [[a]]Source tails :: [a] -> [[a]]Source isPrefixOf :: Eq a => [a] -> [a] -> BoolSource isSuffixOf :: Eq a => [a] -> [a] -> BoolSource isInfixOf :: Eq a => [a] -> [a] -> BoolSource notElem :: Eq a => a -> [a] -> BoolSource zip3 :: [a] -> [b] -> [c] -> [(a, b, c)]Source zip4 :: [a] -> [b] -> [c] -> [d] -> [(a, b, c, d)]Source zip5 :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a, b, c, d, e)]Source zip6 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [(a, b, c, d, e, f)]Source zip7 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [(a, b, c, d, e, f, g)]Source zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]Source zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]Source zipWith4 :: (a -> b -> c -> d -> e) -> [a] -> [b] -> [c] -> [d] -> [e]Source zipWith5 :: (a -> b -> c -> d -> e -> f) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f]Source zipWith6 :: (a -> b -> c -> d -> e -> f -> g) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g]Source zipWith7 :: (a -> b -> c -> d -> e -> f -> g -> h) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [h]Source unzip3 :: [(a, b, c)] -> ([a], [b], [c])Source unzip4 :: [(a, b, c, d)] -> ([a], [b], [c], [d])Source unzip5 :: [(a, b, c, d, e)] -> ([a], [b], [c], [d], [e])Source unzip6 :: [(a, b, c, d, e, f)] -> ([a], [b], [c], [d], [e], [f])Source unzip7 :: [(a, b, c, d, e, f, g)] -> ([a], [b], [c], [d], [e], [f], [g])Source lines :: String -> [String]Source words :: String -> [String]Source unlines :: [String] -> StringSource unwords :: [String] -> StringSource nub :: Eq a => [a] -> [a]Source delete :: Eq a => a -> [a] -> [a]Source () :: Eq a => [a] -> [a] -> [a]Source union :: Eq a => [a] -> [a] -> [a]Source intersect :: Eq a => [a] -> [a] -> [a]Source sort :: Ord a => [a] -> [a]Source insert :: Ord a => a -> [a] -> [a]Source nubBy :: (a -> a -> Bool) -> [a] -> [a]Source deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a]Source deleteFirstsBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]Source unionBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]Source intersectBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]Source groupBy :: (a -> a -> Bool) -> [a] -> [[a]]Source sortBy :: (a -> a -> Ordering) -> [a] -> [a]Source insertBy :: (a -> a -> Ordering) -> a -> [a] -> [a]Source maximumBy :: (a -> a -> Ordering) -> [a] -> aSource minimumBy :: (a -> a -> Ordering) -> [a] -> aSource genericLength :: Num i => [b] -> iSource genericTake :: Integral i => i -> [a] -> [a]Source genericDrop :: Integral i => i -> [a] -> [a]Source genericSplitAt :: Integral i => i -> [b] -> ([b], [b])Source genericIndex :: Integral a => [b] -> a -> bSource genericReplicate :: Integral i => i -> a -> [a]Source *) (* ----------------------- *) (* skipped from Lem Lib *) (* ----------------------- val for_all2 : forall 'a 'b. ('a -> 'b -> bool) -> list 'a -> list 'b -> bool val exists2 : forall 'a 'b. ('a -> 'b -> bool) -> list 'a -> list 'b -> bool val map2 : forall 'a 'b 'c. ('a -> 'b -> 'c) -> list 'a -> list 'b -> list 'c val rev_map2 : forall 'a 'b 'c. ('a -> 'b -> 'c) -> list 'a -> list 'b -> list 'c val fold_left2 : forall 'a 'b 'c. ('a -> 'b -> 'c -> 'a) -> 'a -> list 'b -> list 'c -> 'a val fold_right2 : forall 'a 'b 'c. ('a -> 'b -> 'c -> 'c) -> list 'a -> list 'b -> 'c -> 'c (* now maybe result and called lookup *) val assoc : forall 'a 'b. 'a -> list ('a * 'b) -> 'b let inline {ocaml} assoc = Ocaml.List.assoc val mem_assoc : forall 'a 'b. 'a -> list ('a * 'b) -> bool val remove_assoc : forall 'a 'b. 'a -> list ('a * 'b) -> list ('a * 'b) val stable_sort : forall 'a. ('a -> 'a -> num) -> list 'a -> list 'a val fast_sort : forall 'a. ('a -> 'a -> num) -> list 'a -> list 'a val merge : forall 'a. ('a -> 'a -> num) -> list 'a -> list 'a -> list 'a val intersect : forall 'a. list 'a -> list 'a -> list 'a *) (*val catMaybes : forall 'a. list (maybe 'a) -> list 'a*) function (sequential,domintros) catMaybes :: "('a option)list \<Rightarrow> 'a list " where " catMaybes ([]) = ( [])" |" catMaybes (None # xs') = ( catMaybes xs' )" |" catMaybes (Some x # xs') = ( x # catMaybes xs' )" by pat_completeness auto end
MODULE mod_crc IMPLICIT NONE PRIVATE PUBLIC :: crc16, crc16dim INTEGER, PARAMETER :: igenerator = 32773 ! Z'8005' !B'1000000000000101' ! x^16+x^15+x^2+1 CONTAINS !-------------------------------------------------------------------------- SUBROUTINE crc16(n, in, icrc) ! ISO 2.4.3.1, Table A.9, Table B.5 IMPLICIT NONE INTEGER, INTENT(IN ) :: n, in INTEGER, INTENT(IN OUT) :: icrc INTEGER :: j, ibit1, ibit2 DO j = n - 1, 0, -1 ibit1 = IBITS(in , j, 1) ! jth bit bit[31......0] ibit2 = IBITS(icrc, 15, 1) ! sign bit of 16bit crc icrc = ISHFT(IBITS(icrc, 0, 15), 1) ! shift up 1bit 16bit crc IF (IEOR(ibit1, ibit2) == 1) icrc = IEOR(icrc, igenerator) END DO RETURN END SUBROUTINE crc16 !-------------------------------------------------------------------------- SUBROUTINE crc16dim(n, in, icrc) IMPLICIT NONE INTEGER, INTENT(IN ) :: n, in(:) INTEGER, INTENT(IN OUT) :: icrc INTEGER :: i DO i = 1, SIZE(in) CALL crc16(n, in(i), icrc) END DO RETURN END SUBROUTINE crc16dim !-------------------------------------------------------------------------- END MODULE mod_crc
# Plotting ```python from IPython.display import Latex from matplotlib.pyplot import * from numpy import * from sympy import latex, simplify, solve, symbols ``` ```python x = symbols("x") X = linspace(-4, 4.05, 128) F = [x**2, x + 4] s = r'$$\begin{align}' + '\n' for i, f in enumerate(F): s += f"f_{i+1}={latex(F[i])}." + '\n' + (r'\\' if len(F) > i+1 else r'\end{align}$$') Latex(s) ``` $$\begin{align} f_1=x^{2}. \\f_2=x + 4. \end{align}$$ ```python xlabel("$x$") ylabel("$y$") grid(True) axis('equal') axis([-5, 5, 0, 16]) axis(False) labels = list() for f in F: Y = [f.evalf(subs={x:x0}) for x0 in X] labels.append(f"${latex(f)}$") plot(X,Y) legend(labels=labels) S = solve(F[0]-F[1]) for i in range(len(S)): annotate(rf"$\left({latex(S[i])}, {latex(F[i].subs({x:S[i]}))}\right)$", xy=(S[i].evalf(), F[i].evalf(subs={x:S[i]}))) Latex(f'$$S={latex(S)}.$$') ``` $$S=\left[ \frac{1}{2} - \frac{\sqrt{17}}{2}, \ \frac{1}{2} + \frac{\sqrt{17}}{2}\right].$$ ```python show() ``` ```python public(plt) ``` ```python ```
[STATEMENT] lemma one_strongly_connected_iff: "one_strongly_connected x \<longleftrightarrow> connected x \<and> many_strongly_connected x" [PROOF STATE] proof (prove) goal (1 subgoal): 1. one_strongly_connected x = (connected x \<and> many_strongly_connected x) [PROOF STEP] apply (rule iffI) [PROOF STATE] proof (prove) goal (2 subgoals): 1. one_strongly_connected x \<Longrightarrow> connected x \<and> many_strongly_connected x 2. connected x \<and> many_strongly_connected x \<Longrightarrow> one_strongly_connected x [PROOF STEP] apply (metis top_greatest x_leq_triple_x mult_double_iso top_greatest dual_order.trans many_strongly_connected_iff_1 comp_assoc conv_contrav conv_invol conv_iso le_supI2 star_conv) [PROOF STATE] proof (prove) goal (1 subgoal): 1. connected x \<and> many_strongly_connected x \<Longrightarrow> one_strongly_connected x [PROOF STEP] by (metis comp_assoc conv_contrav conv_iso conv_one conway.dagger_denest star_conv star_invol star_sum_unfold star_trans_eq)
import number_theory.padics.padic_integers --OUTPUT 1 theorem p_adic_units (p : ℕ) (x : ℕ) (h : coprime p x) : is_unit (x : ℤ/p) := begin -- Prove the contrapositive, that is, is $x$ is not a unit of $\mathbb{Z}_p$, then $x$ is not coprime to $p$ have h1 : ¬ is_unit (x : ℤ/p) → ¬ coprime p x, from by auto [nat.coprime.symm, nat.coprime.def, nat.coprime.def, nat.coprime.symm, nat.coprime.def, nat.coprime.def], -- We know that any element of $\mathbb{Z}_p$ is a unit if and only if it has norm 1 have h2 : is_unit (x : ℤ/p) ↔ (norm_num (x : ℤ/p)) = 1, from by auto [norm_num_eq_one_iff_is_unit], -- Also, since every element of $\mathbb{Z}_p$ must have norm less than or equal to 1 have h3 : (norm_num (x : ℤ/p)) ≤ 1, from by auto [norm_num_le_one], -- But this must imply that $p | x$ have h4 : ¬ is_unit (x : ℤ/p) → p ∣ x, from by auto [norm_num_eq_one_iff_is_unit, norm_num_le_one, nat.dvd_iff_norm_num_eq_zero], -- This completes our proof show is_unit (x : ℤ/p), from by auto [h1, h2, h3, h4, h] end --OUTPUT 2 theorem p_adic_units (p : ℕ) (x : ℕ) (h : nat.coprime x p) : nat.units (padic_int.mk_val_rat p x) := begin -- Let us prove the contrapositive, that is, is $x$ is not a unit of $\mathbb{Z}_p$, then $x$ is not coprime to $p$. have h1 : ¬ (nat.units (padic_int.mk_val_rat p x)) → ¬ (nat.coprime x p), from by auto, -- We know that any element of $\mathbb{Z}_p$ is a unit if and only if it has norm 1, thus $\Vert x \Vert \neq 1$. have h2 : nat.units (padic_int.mk_val_rat p x) ↔ (padic_int.norm (padic_int.mk_val_rat p x) = 1), from by auto [padic_int.norm_unit], have h3 : ¬ (nat.units (padic_int.mk_val_rat p x)) ↔ ¬ (padic_int.norm (padic_int.mk_val_rat p x) = 1), from by auto [not_iff_not_of_iff], have h4 : ¬ (nat.units (padic_int.mk_val_rat p x)) ↔ (padic_int.norm (padic_int.mk_val_rat p x) ≠ 1), from by auto [h2, h3], -- Also, since every element of $\mathbb{Z}_p$ must have norm less than or equal to 1, we conclude that $\Vert x \Vert < 1$. have h5 : ∀ x : ℚ, padic_int.norm x ≤ 1, from by auto [padic_int.norm_le_one], have h6 : ∀ x : ℚ, padic_int.norm x < 1 ↔ padic_int.norm x ≠ 1, from by auto [lt_iff_le_not_le], have h7 : ¬ (nat.units (padic_int.mk_val_rat p x)) ↔ padic_int.norm (padic_int.mk_val_rat p x) < 1, from by auto [h4, h6], -- But this must imply that $p | x$. have h8 : padic_int.norm (padic_int.mk_val_rat p x) < 1 → p ∣ x, from by auto [padic_int.norm_eq_pow_val], have h9 : ¬ (nat.units (padic_int.mk_val_rat p x)) → p ∣ x, from by auto [h7, h8], -- This completes our proof. show nat.units (padic_int.mk_val_rat p x), from by auto [h1, h9, h], end --OUTPUT 3 theorem padic_units (p : ℕ) (x : ℕ) : coprime p x → is_unit (padic_int.mk p x) := begin -- Let us prove the contrapositive, that is, is $x$ is not a unit of $\mathbb{Z}_p$, then $x$ is not coprime to $p$. assume h1 : ¬ is_unit (padic_int.mk p x), assume h2 : coprime p x, -- We know that any element of $\mathbb{Z}_p$ is a unit if and only if it has norm 1, thus $\Vert x \Vert \neq 1$. have h3 : ¬ padic_int.norm p (padic_int.mk p x) = 1, from by auto [h1, padic_int.norm_eq_one_iff_is_unit], -- Also, since every element of $\mathbb{Z}_p$ must have norm less than or equal to 1, we conclude that $\Vert x \Vert < 1$. have h4 : padic_int.norm p (padic_int.mk p x) < 1, from by auto [padic_int.norm_le_one, h3], -- But this must imply that $p | x$. have h5 : p ∣ x, from by auto [padic_int.norm_eq_one_iff_is_unit, h4, h1, padic_int.norm_eq_one_iff_is_unit], -- This completes our proof. show false, from by auto [h2, h5, coprime.def, not_and_distrib, not_not] end --OUTPUT 4 theorem padic_units (p : ℕ) (x : ℕ) : coprime p x → is_unit (x : ℤ_[p]) := begin -- Let us prove the contrapositive, that is, is $x$ is not a unit of $\mathbb{Z}_p$, then $x$ is not coprime to $p$. assume h1 : ¬(is_unit (x : ℤ_[p])), -- We know that any element of $\mathbb{Z}_p$ is a unit if and only if it has norm 1, thus $\Vert x \Vert \neq 1$. have h2 : ¬(∥x∥ = 1), from by auto [is_unit_iff_norm_eq_one], -- Also, since every element of $\mathbb{Z}_p$ must have norm less than or equal to 1, we conclude that $\Vert x \Vert < 1$. have h3 : ∥x∥ < 1, from by auto [h2, norm_nonneg], -- But this must imply that $p | x$. show ¬(coprime p x), from by auto [h3, lt_of_le_of_ne, norm_le_one, dvd_iff_norm_le_one], end --OUTPUT 5 theorem p_adic_units (p : ℕ) (x : ℕ) (h : nat.coprime p x) : nat.units (p_adic_int.padic_int p x) := begin --Let us prove the contrapositive, that is, is $x$ is not a unit of $\mathbb{Z}_p$, then $x$ is not coprime to $p$. have h1 : ¬ (nat.units (p_adic_int.padic_int p x)) → ¬ nat.coprime p x, from by auto [nat.coprime_iff_gcd_eq_one], -- We know that any element of $\mathbb{Z}_p$ is a unit if and only if it has norm 1, thus $\Vert x \Vert \neq 1$. have h2 : (nat.units (p_adic_int.padic_int p x)) ↔ (p_adic_int.norm p x = 1), from by auto using [p_adic_int.norm_unit_iff], -- Also, since every element of $\mathbb{Z}_p$ must have norm less than or equal to 1, we conclude that $\Vert x \Vert < 1$. have h3 : p_adic_int.norm p x ≤ 1, from by auto using [p_adic_int.norm_nonneg, p_adic_int.norm_le_one], -- But this must imply that $p | x$. have h4 : p_adic_int.norm p x = 1 → nat.coprime p x, from by auto [p_adic_int.norm_eq_one_iff_coprime], -- This completes our proof. show nat.units (p_adic_int.padic_int p x), from by auto [h1, h2, h3, h4, h] end --OUTPUT 6 theorem p_adic_units (p : ℕ) (x : ℕ) (h₁ : p.prime) (h₂ : x.coprime p) : x.units_of_padic_integers p := begin -- We know that any element of $\mathbb{Z}_p$ is a unit if and only if it has norm 1, thus $\Vert x \Vert \neq 1$. have h1 : (x.padic_norm p) ≠ 1, from by auto [h₂, padic_norm_eq_one_iff_units_of_padic_integers], -- Also, since every element of $\mathbb{Z}_p$ must have norm less than or equal to 1, we conclude that $\Vert x \Vert < 1$. have h2 : (x.padic_norm p) < 1, from by auto [padic_norm_le_one], -- But this must imply that $p | x$. have h3 : p ∣ x, from by auto [h₁, h2, padic_norm_lt_one_iff_dvd_p], -- This completes our proof. show x.units_of_padic_integers p, from by auto [h₁, h₂, h3, units_of_padic_integers_iff_coprime_p], end /- FEW SHOT PROMPTS TO CODEX(START) /--`theorem` Power Set is Closed under Intersection Let $S$ be a set. Let $\powerset S$ be the power set of $S$. Then: :$\forall A, B \in \powerset S: A \cap B \in \powerset S$ `proof` Let $A, B \in \powerset S$. Then by the definition of power set, $A \subseteq S$ and $B \subseteq S$. From Intersection is Subset we have that $A \cap B \subseteq A$. It follows from Subset Relation is Transitive that $A \cap B \subseteq S$. Thus $A \cap B \in \powerset S$ and closure is proved. {{qed}} -/ theorem power_set_intersection_closed {α : Type*} (S : set α) : ∀ A B ∈ 𝒫 S, (A ∩ B) ∈ 𝒫 S := begin -- $A$ and $B$ are sets. $A$ and $B$ belong to power set of $S$ assume (A : set α) (hA : A ∈ 𝒫 S) (B : set α) (hB : B ∈ 𝒫 S), -- Then $A ⊆ S$ and $B ⊆ S$, by power set definition have h1 : (A ⊆ S) ∧ (B ⊆ S), from by auto [set.subset_of_mem_powerset, set.subset_of_mem_powerset], -- Then $(A ∩ B) ⊆ A$, by intersection of set is a subset have h2 : (A ∩ B) ⊆ A, from by auto [set.inter_subset_left], -- Then $(A ∩ B) ⊆ S$, by subset relation is transitive have h3 : (A ∩ B) ⊆ S, from by auto [set.subset.trans], -- Hence $(A ∩ B) ∈ 𝒫 S$, by power set definition show (A ∩ B) ∈ 𝒫 S, from by auto [set.mem_powerset], end /--`theorem` Square of Sum :$\forall x, y \in \R: \paren {x + y}^2 = x^2 + 2 x y + y^2$ `proof` Follows from the distribution of multiplication over addition: {{begin-eqn}} {{eqn | l = \left({x + y}\right)^2 | r = \left({x + y}\right) \cdot \left({x + y}\right) }} {{eqn | r = x \cdot \left({x + y}\right) + y \cdot \left({x + y}\right) | c = Real Multiplication Distributes over Addition }} {{eqn | r = x \cdot x + x \cdot y + y \cdot x + y \cdot y | c = Real Multiplication Distributes over Addition }} {{eqn | r = x^2 + 2xy + y^2 | c = }} {{end-eqn}} {{qed}} -/ theorem square_of_sum (x y : ℝ) : (x + y)^2 = (x^2 + 2*x*y + y^2) := begin -- expand the power calc (x + y)^2 = (x+y)*(x+y) : by auto [sq] -- distributive property of multiplication over addition gives: ... = x*(x+y) + y*(x+y) : by auto [add_mul] -- applying the above property further gives: ... = x*x + x*y + y*x + y*y : by auto [mul_comm, add_mul] using [ring] -- rearranging the terms using commutativity and adding gives: ... = x^2 + 2*x*y + y^2 : by auto [sq, mul_comm] using [ring] end /--`theorem` Identity of Group is Unique Let $\struct {G, \circ}$ be a group. Then there is a unique identity element $e \in G$. `proof` From Group has Latin Square Property, there exists a unique $x \in G$ such that: :$a x = b$ and there exists a unique $y \in G$ such that: :$y a = b$ Setting $b = a$, this becomes: There exists a unique $x \in G$ such that: :$a x = a$ and there exists a unique $y \in G$ such that: :$y a = a$ These $x$ and $y$ are both $e$, by definition of identity element. {{qed}} -/ theorem group_identity_unique {G : Type*} [group G] : ∃! e : G, ∀ a : G, e * a = a ∧ a * e = a := begin -- Group has Latin Square Property have h1 : ∀ a b : G, ∃! x : G, a * x = b, from by auto using [use (a⁻¹ * b)], have h2 : ∀ a b : G, ∃! y : G, y * a = b, from by auto using [use b * a⁻¹], -- Setting $b = a$, this becomes: have h3 : ∀ a : G, ∃! x : G, a * x = a, from by auto [h1], have h4 : ∀ a : G, ∃! y : G, y * a = a, from by auto [h2], -- These $x$ and $y$ are both $(1 : G)$, by definition of identity element have h5 : ∀ a : G, classical.some (h3 a).exists = (1 : G), from by auto [exists_unique.unique, h3, classical.some_spec, exists_unique.exists, mul_one], have h6 : ∀ a : G, classical.some (h4 a).exists = (1 : G), from by auto [exists_unique.unique, h4, classical.some_spec, exists_unique.exists, one_mul], show ∃! e : G, ∀ a : G, e * a = a ∧ a * e = a, from by auto [h3, h4, exists_unique.unique, classical.some_spec, exists_unique.exists] using [use (1 : G)], end /--`theorem` p-adic units Given a prime number $p$ and a natural number $x$, if $x$ is coprime to $p$, then $x$ is a unit in the $p$-adic integers. `proof` Let us prove the contrapositive, that is, is $x$ is not a unit of $\mathbb{Z}_p$, then $x$ is not coprime to $p$. We know that any element of $\mathbb{Z}_p$ is a unit if and only if it has norm 1, thus $\Vert x \Vert \neq 1$. Also, since every element of $\mathbb{Z}_p$ must have norm less than or equal to 1, we conclude that $\Vert x \Vert < 1$. But this must imply that $p | x$. This completes our proof. QED -/ theorem FEW SHOT PROMPTS TO CODEX(END)-/
theory prop_05 imports Main "$HIPSTER_HOME/IsaHipster" begin datatype 'a list = Nil2 | Cons2 "'a" "'a list" datatype Nat = Z | S "Nat" fun equal2 :: "Nat => Nat => bool" where "equal2 (Z) (Z) = True" | "equal2 (Z) (S z) = False" | "equal2 (S x2) (Z) = False" | "equal2 (S x2) (S y2) = equal2 x2 y2" fun count :: "Nat => Nat list => Nat" where "count x (Nil2) = Z" | "count x (Cons2 z ys) = (if equal2 x z then S (count x ys) else count x ys)" (*hipster equal2 count *) hipster equal2 lemma lemma_a [thy_expl]: "equal2 x x = True" apply (induction x) apply simp by simp lemma lemma_aa [thy_expl]: "equal2 Z x = equal2 x Z" apply (induction x) apply simp by simp lemma lemma_ab [thy_expl]: "equal2 (S x) y = equal2 y (S x)" apply (induction y) (*apply (metis equal2.elims(2) equal2.simps(1))*) sledgehammer apply simp apply simp sledgehammer oops lemma lemma_ac [thy_expl]: "equal2 x (S x) = False" apply (induction x) apply simp by simp (* lemma lemma_ad [thy_expl]: "equal2 (S x) (S y) = equal2 y x" apply (induction x) apply (metis equal2.elims(2) equal2.simps(1) equal2.simps(3)) apply (metis Nat.distinct(1) Nat.inject equal2.elims(2) equal2.elims(3) equal2.simps(2) equal2.simps(3) equal2.simps(4)) apply simp by simp lemma lemma_a [thy_expl]: "equal2 x4 y4 = equal2 y4 x4" by (hipster_induct_schemes prop_05.equal2.simps) lemma lemma_aa [thy_expl]: "equal2 x2 x2 = True" by (hipster_induct_schemes prop_05.equal2.simps) lemma lemma_ab [thy_expl]: "equal2 x2 (S x2) = False" by (hipster_induct_schemes prop_05.equal2.simps) theorem x0 : "(n = x) ==> ((S (count n xs)) = (count n (Cons2 x xs)))" by (tactic {* Subgoal.FOCUS_PARAMS (K (Tactic_Data.hard_tac @{context})) @{context} 1 *}) end
//================================================================================================== /*! @file @copyright 2016 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #ifndef BOOST_SIMD_FUNCTION_IF_ELSE_ZERO_HPP_INCLUDED #define BOOST_SIMD_FUNCTION_IF_ELSE_ZERO_HPP_INCLUDED #if defined(DOXYGEN_ONLY) namespace boost { namespace simd { /*! @ingroup group-boolean This function object conditionally returns @c x (respectively @ref Zero) if @c c is @ref True (respectively @ref False) @par Header <boost/simd/function/if_else_zero.hpp> @par Example: @snippet if_else_zero.cpp if_else_zero @par Possible output: @snippet if_else_zero.txt if_else_zero **/ Value1 if_else_zero(Value0 const& c, Value1 const& t); } } #endif #include <boost/simd/function/scalar/if_else_zero.hpp> #include <boost/simd/function/simd/if_else_zero.hpp> #endif
#ifndef BENCH_GENERATE_RANGE #define BENCH_GENERATE_RANGE #include <boost/lexical_cast.hpp> #include <iostream> #include "range.hpp" template <typename T> int generate_range(int argc, char** argv) { if (argc != 3) { std::cerr << "Usage: " << argv[0] << " <count> <size>\n"; return EXIT_FAILURE; } std::random_device device; auto seed = device(); auto count = boost::lexical_cast<std::size_t>(argv[1]); auto size = boost::lexical_cast<std::size_t>(argv[2]); auto data = make_insertion_data_range<T>(count, size, seed); std::vector<T> container; insert_range(container, data); std::cout << seed << " " << make_checksum_unsigned(container) << "\n"; return EXIT_SUCCESS; } #endif // #ifndef BENCH_GENERATE_RANGE
function[]=makefigs_morlfreq %MAKEFIGS_MORLFREQ Makes a sample figure for MORLFREQ. fm=linspace(0,4,1000); [fn,fmin]=morlfreq(fm); figure plot([fn' fn'],[fm' fmin']),axis equal, dlines(1,'k--') axis([0 4 -1 4]),%vlines(1,'k:'), hlines(0,'k:') xlabel('Carrier Frequency (Radian)') ylabel('Frequency of Max and Min (Radian)') title('Frequencies of Morlet Maximum and Minimum')
//================================================================================================== /*! @file @copyright 2017 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #ifndef BOOST_SIMD_FUNCTION_FMASUBADD_HPP_INCLUDED #define BOOST_SIMD_FUNCTION_FMASUBADD_HPP_INCLUDED namespace boost { namespace simd { /*! @ingroup group-swar @ingroup swar-fmasubadd Computes the interleaved sum/difference of two the product of two values with a third one @par Header <boost/simd/function/fmasubadd.hpp> @par Example: @snippet fmasubadd.cpp fmasubadd @par Possible output: @snippet fmasubadd.txt fmasubadd **/ } } #include <boost/simd/function/scalar/fmasubadd.hpp> #include <boost/simd/function/simd/fmasubadd.hpp> #endif
install.packages("keras") library(keras) use_python("/usr/bin/python", required = TRUE) install_keras(method="virtualenv")
= = Works = =
!** Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. !** See https://llvm.org/LICENSE.txt for license information. !** SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception program mmul integer, parameter :: n = 4 real(kind = 8), dimension(1:n, 1:n) :: a, b, c real(kind = 8), dimension(n * n) :: expected data expected / -256.0, -256.0, -256.0, -256.0, & -256.0, -256.0, -256.0, -256.0, & -256.0, -256.0, -256.0, -256.0, & -256.0, -256.0, -256.0, -256.0 / a = 1.0 b = -1.0 c = 2.0 call do_matmul(a, b, c, n) call checkd(reshape(c, (/ n * n /)), expected, n * n) contains subroutine do_matmul(a, b, c, n) integer, intent(in) :: n real(kind = 8), dimension(:, :), intent(in) :: a, b real(kind = 8), dimension(:, :), intent(inout) :: c c(1:n, 1:n) = matmul(matmul(matmul(a(1:n, 1:n), b(1:n, 1:n)), matmul(a(1:n, 1:n), b(1:n, 1:n))), b(1:n, 1:n)) end subroutine end program mmul
module BTA5 where open import Data.Nat hiding (_<_) open import Data.Bool open import Data.List open import Data.Nat.Properties open import Relation.Nullary ----------------- -- CLEANUP (∈) : this is surely in the standard library ----------------- -- More general purpose definitions (should also be in standard library) -- list membership infix 4 _∈_ data _∈_ {A : Set} : A → List A → Set where hd : ∀ {x xs} → x ∈ (x ∷ xs) tl : ∀ {x y xs} → x ∈ xs → x ∈ (y ∷ xs) data Type : Set where Int : Type Fun : Type → Type → Type data AType : Set where AInt : AType AFun : AType → AType → AType D : Type → AType -- typed annotated expressions ACtx = List AType Ctx = List Type ----------------------- -- CLEANUP (≤) : these properties are surely in the standard library ----------------------- ≤-refl : ∀ {n} → n ≤ n ≤-refl {zero} = z≤n ≤-refl {suc n} = s≤s ≤-refl ----------------------- -- CLEANUP (≤) : these properties are surely in the standard library ----------------------- ≤-trans : ∀ {a b c} → a ≤ b → b ≤ c → a ≤ c ≤-trans z≤n q = z≤n ≤-trans (s≤s p) (s≤s q) = s≤s (≤-trans p q) ----------------------- -- CLEANUP (≤) : these properties are surely in the standard library ----------------------- ≤-suc-right : ∀ {m n} → m ≤ n → m ≤ suc n ≤-suc-right z≤n = z≤n ≤-suc-right (s≤s p) = s≤s (≤-suc-right p) ----------------------- -- CLEANUP (≤) : these properties are surely in the standard library ----------------------- ≤-suc-left : ∀ {m n} → suc m ≤ n → m ≤ n ≤-suc-left (s≤s p) = ≤-suc-right p data _↝_ : Ctx → Ctx → Set where ↝-refl : ∀ {Γ} → Γ ↝ Γ ↝-extend : ∀ {Γ Γ' τ} → Γ ↝ Γ' → Γ ↝ (τ ∷ Γ') ↝-≤ : ∀ Γ Γ' → Γ ↝ Γ' → length Γ ≤ length Γ' ↝-≤ .Γ' Γ' ↝-refl = ≤-refl ↝-≤ Γ .(τ ∷ Γ') (↝-extend {.Γ} {Γ'} {τ} Γ↝Γ') = ≤-suc-right (↝-≤ Γ Γ' Γ↝Γ') ↝-no-left : ∀ Γ τ → ¬ (τ ∷ Γ) ↝ Γ ↝-no-left Γ τ p = 1+n≰n (↝-≤ (τ ∷ Γ) Γ p) ↝-trans : ∀ {Γ Γ' Γ''} → Γ ↝ Γ' → Γ' ↝ Γ'' → Γ ↝ Γ'' ↝-trans Γ↝Γ' ↝-refl = Γ↝Γ' ↝-trans Γ↝Γ' (↝-extend Γ'↝Γ'') = ↝-extend (↝-trans Γ↝Γ' Γ'↝Γ'') lem : ∀ x y xs xs' → (x ∷ xs) ↝ xs' → xs ↝ (y ∷ xs') lem x y xs .(x ∷ xs) ↝-refl = ↝-extend (↝-extend ↝-refl) lem x y xs .(x' ∷ xs') (↝-extend {.(x ∷ xs)} {xs'} {x'} p) = ↝-extend (lem x x' xs xs' p) data _↝_↝_ : Ctx → Ctx → Ctx → Set where ↝↝-base : ∀ {Γ Γ''} → Γ ↝ Γ'' → Γ ↝ [] ↝ Γ'' ↝↝-extend : ∀ {Γ Γ' Γ'' τ} → Γ ↝ Γ' ↝ Γ'' → (τ ∷ Γ) ↝ (τ ∷ Γ') ↝ (τ ∷ Γ'') -- Typed residula expressions data Exp'' (Γ : Ctx) : Type → Set where EVar : ∀ {τ} → τ ∈ Γ → Exp'' Γ τ EInt : ℕ → Exp'' Γ Int EAdd : Exp'' Γ Int → Exp'' Γ Int -> Exp'' Γ Int ELam : ∀ {τ τ'} → Exp'' (τ ∷ Γ) τ' → Exp'' Γ (Fun τ τ') EApp : ∀ {τ τ'} → Exp'' Γ (Fun τ τ') → Exp'' Γ τ → Exp'' Γ τ' data AExp (Δ : ACtx) : AType → Set where AVar : ∀ {α} → α ∈ Δ → AExp Δ α AInt : ℕ → AExp Δ AInt AAdd : AExp Δ AInt → AExp Δ AInt → AExp Δ AInt ALam : ∀ {α₁ α₂} → AExp (α₂ ∷ Δ) α₁ → AExp Δ (AFun α₂ α₁) AApp : ∀ {α₁ α₂} → AExp Δ (AFun α₂ α₁) → AExp Δ α₂ → AExp Δ α₁ DInt : ℕ → AExp Δ (D Int) DAdd : AExp Δ (D Int) → AExp Δ (D Int) → AExp Δ (D Int) DLam : ∀ {α₁ α₂} → AExp ((D α₂) ∷ Δ) (D α₁) → AExp Δ (D (Fun α₂ α₁)) DApp : ∀ {α₁ α₂} → AExp Δ (D (Fun α₂ α₁)) → AExp Δ (D α₂) → AExp Δ (D α₁) -- -- index Γ = nesting level of dynamic definitions / dynamic environment Imp'' : Ctx → AType → Set Imp'' Γ (AInt) = ℕ Imp'' Γ (AFun α₁ α₂) = ∀ {Γ'} → Γ ↝ Γ' → (Imp'' Γ' α₁ → Imp'' Γ' α₂) Imp'' Γ (D σ) = Exp'' Γ σ -- -- index = nesting level of dynamic definitions data AEnv2 : Ctx → ACtx → Set where [] : AEnv2 [] [] consS : ∀ {Γ Δ Γ'} → Γ ↝ Γ' → (α : AType) → Imp'' Γ' α → AEnv2 Γ Δ → AEnv2 Γ' (α ∷ Δ) consD : ∀ {Γ Δ} → (σ : Type) → Exp'' (σ ∷ Γ) σ → AEnv2 Γ Δ → AEnv2 (σ ∷ Γ) (D σ ∷ Δ) elevate-var : ∀ {Γ Γ' τ} → Γ ↝ Γ' → τ ∈ Γ → τ ∈ Γ' elevate-var ↝-refl x = x elevate-var (↝-extend Γ↝Γ') x = tl (elevate-var Γ↝Γ' x) elevate-var2 : ∀ {Γ Γ' Γ'' τ} → Γ ↝ Γ' ↝ Γ'' → τ ∈ Γ → τ ∈ Γ'' elevate-var2 (↝↝-base x) x₁ = elevate-var x x₁ elevate-var2 (↝↝-extend Γ↝Γ'↝Γ'') hd = hd elevate-var2 (↝↝-extend Γ↝Γ'↝Γ'') (tl x) = tl (elevate-var2 Γ↝Γ'↝Γ'' x) elevate : ∀ {Γ Γ' Γ'' τ} → Γ ↝ Γ' ↝ Γ'' → Exp'' Γ τ → Exp'' Γ'' τ elevate Γ↝Γ'↝Γ'' (EVar x) = EVar (elevate-var2 Γ↝Γ'↝Γ'' x) elevate Γ↝Γ'↝Γ'' (EInt x) = EInt x elevate Γ↝Γ'↝Γ'' (EAdd e e₁) = EAdd (elevate Γ↝Γ'↝Γ'' e) (elevate Γ↝Γ'↝Γ'' e₁) elevate Γ↝Γ'↝Γ'' (ELam e) = ELam (elevate (↝↝-extend Γ↝Γ'↝Γ'') e) elevate Γ↝Γ'↝Γ'' (EApp e e₁) = EApp (elevate Γ↝Γ'↝Γ'' e) (elevate Γ↝Γ'↝Γ'' e₁) lift2 : ∀ {Γ Γ'} α → Γ ↝ Γ' → Imp'' Γ α → Imp'' Γ' α lift2 AInt p v = v lift2 (AFun x x₁) Γ↝Γ' v = λ Γ'↝Γ'' → v (↝-trans Γ↝Γ' Γ'↝Γ'') lift2 (D x₁) Γ↝Γ' v = elevate (↝↝-base Γ↝Γ') v lookup2 : ∀ {α Δ Γ Γ'} → Γ ↝ Γ' → AEnv2 Γ Δ → α ∈ Δ → Imp'' Γ' α lookup2 Γ↝Γ' (consS p α v env) hd = lift2 α Γ↝Γ' v lookup2 Γ↝Γ' (consS p α₁ v env) (tl x) = lookup2 (↝-trans p Γ↝Γ') env x lookup2 Γ↝Γ' (consD α v env) hd = lift2 (D α) Γ↝Γ' v lookup2 ↝-refl (consD α₁ v env) (tl x) = lookup2 (↝-extend ↝-refl) env x lookup2 (↝-extend Γ↝Γ') (consD α₁ v env) (tl x) = lookup2 (lem α₁ _ _ _ Γ↝Γ') env x pe2 : ∀ {α Δ Γ} → AExp Δ α → AEnv2 Γ Δ → Imp'' Γ α pe2 (AVar x) env = lookup2 ↝-refl env x pe2 (AInt x) env = x pe2 (AAdd e₁ e₂) env = pe2 e₁ env + pe2 e₂ env pe2 {AFun α₂ α₁} (ALam e) env = λ Γ↝Γ' → λ y → pe2 e (consS Γ↝Γ' α₂ y env) pe2 (AApp e₁ e₂) env = ((pe2 e₁ env) ↝-refl) (pe2 e₂ env) pe2 (DInt x) env = EInt x pe2 (DAdd e e₁) env = EAdd (pe2 e env) (pe2 e₁ env) pe2 {D (Fun σ₁ σ₂)} (DLam e) env = ELam (pe2 e (consD σ₁ (EVar hd) env)) -- ELam (pe2 (consS (↝-extend {τ = σ₁} ↝-refl) (D σ₁) (EVar hd) env)) works too; -- it is probably a canonical solution, but I (Lu) do not see why... pe2 (DApp e e₁) env = EApp (pe2 e env) (pe2 e₁ env) module Examples where open import Relation.Binary.PropositionalEquality x : ∀ {α Δ} → AExp (α ∷ Δ) α x = AVar hd y : ∀ {α₁ α Δ} → AExp (α₁ ∷ α ∷ Δ) α y = AVar (tl hd) z : ∀ {α₁ α₂ α Δ} → AExp (α₁ ∷ α₂ ∷ α ∷ Δ) α z = AVar (tl (tl hd)) -- Dλ y → let f = λ x → x D+ y in Dλ z → f z term1 : AExp [] (D (Fun Int (Fun Int Int))) term1 = DLam (AApp (ALam (DLam (AApp (ALam y) x))) ((ALam (DAdd x y)))) -- Dλ y → let f = λ x → (Dλ w → x D+ y) in Dλ z → f z -- Dλ y → (λ f → Dλ z → f z) (λ x → (Dλ w → x D+ y)) term2 : AExp [] (D (Fun Int (Fun Int Int))) term2 = DLam (AApp (ALam (DLam (AApp (ALam y) x))) ((ALam (DLam {α₂ = Int} (DAdd y z))))) ex-pe-term1 : pe2 term1 [] ≡ ELam (ELam (EVar hd)) ex-pe-term1 = refl ex-pe-term2 : pe2 term2 [] ≡ ELam (ELam (EVar hd)) ex-pe-term2 = refl -- end of file
= ImpParser: Lexing and Parsing in Idris > module ImpParser > The development of the Imp language in `Imp.lidr` completely ignores issues of concrete syntax -- how an ASCII string that a programmer might write gets translated into abstract syntax trees defined by the datatypes \idr{AExp}, \idr{BExp}, and \idr{Com}. In this chapter, we illustrate how the rest of the story can be filled in by building a simple lexical analyzer and parser using Idris's functional programming facilities. It is not important to understand all the details here (and accordingly, the explanations are fairly terse and there are no exercises). The main point is simply to demonstrate that it can be done. You are invited to look through the code -- most of it is not very complicated, though the parser relies on some "monadic" programming idioms that may require a little work to make out -- but most readers will probably want to just skim down to the `Examples` section at the very end to get the punchline. > import Maps > import Imp > == Internals === Lexical Analysis > data Chartype = White | Alpha | Digit | Other > > classifyChar : (c : Char) -> Chartype > classifyChar c = > if isSpace c then > White > else if isAlpha c then > Alpha > else if isDigit c then > Digit > else > Other > > Token : Type > Token = String > > tokenizeHelper : (cls : Chartype) -> (acc, xs : List Char) -> List (List Char) > tokenizeHelper cls acc xs = > case xs of > [] => tk > (x::xs') => > case (cls, classifyChar x, x) of > (_, _, '(') => > tk ++ ['('] :: (tokenizeHelper Other [] xs') > (_, _, ')') => > tk ++ [')'] :: (tokenizeHelper Other [] xs') > (_, White, _) => > tk ++ (tokenizeHelper White [] xs') > (Alpha, Alpha, x) => > tokenizeHelper Alpha (x::acc) xs' > (Digit, Digit, x) => > tokenizeHelper Digit (x::acc) xs' > (Other, Other, x) => > tokenizeHelper Other (x::acc) xs' > (_, tp, x) => > tk ++ (tokenizeHelper tp [x] xs') > where > tk : List (List Char) > tk = case acc of > [] => [] > (_::_) => [reverse acc] > > tokenize : (s : String) -> List String > tokenize s = map pack (tokenizeHelper White [] (unpack s)) > > tokenizeEx1 : tokenize "abc12==3 223*(3+(a+c))" = ["abc","12","==","3","223","*","(","3","+","(","a","+","c",")",")"] > tokenizeEx1 = Refl > === Parsing ==== Options With Errors An \idr{Option} type with error messages: > data OptionE : (x : Type) -> Type where > SomeE : x -> OptionE x > NoneE : String -> OptionE x > Some interface instances to make writing nested match-expressions on \idr{OptionE} more convenient. \todo[inline]{Explain these/link to Haskell etc?} > Functor OptionE where > map f (SomeE x) = SomeE (f x) > map _ (NoneE err) = NoneE err > > Applicative OptionE where > pure = SomeE > (SomeE f) <*> (SomeE x) = SomeE (f x) > (SomeE _) <*> (NoneE e) = NoneE e > (NoneE e) <*> _ = NoneE e > > Alternative OptionE where > empty = NoneE "" > (SomeE x) <|> _ = SomeE x > (NoneE _) <|> v = v > > Monad OptionE where > (NoneE e) >>= _ = NoneE e > (SomeE x) >>= k = k x > ==== Generic Combinators for Building Parsers > Parser : (t : Type) -> Type > Parser t = List Token -> OptionE (t, List Token) > > manyHelper : (p : Parser t) -> (acc : List t) -> (steps : Nat) -> Parser (List t) > manyHelper p acc Z _ = NoneE "Too many recursive calls" > manyHelper p acc (S steps') xs with (p xs) > | NoneE _ = SomeE (reverse acc, xs) > | SomeE (t', xs') = manyHelper p (t'::acc) steps' xs' > A (step-indexed) parser that expects zero or more \idr{p}s: > many : (p : Parser t) -> (steps : Nat) -> Parser (List t) > many p steps = manyHelper p [] steps > A parser that expects a given token, followed by \idr{p}: > firstExpect : (a : Token) -> (p : Parser t) -> Parser t > firstExpect a p (x::xs) = if x == a then p xs else NoneE ("Expected '" ++ a ++ "'") > firstExpect a _ [] = NoneE ("Expected '" ++ a ++ "'") > A parser that expects a particular token: > expect : (t : Token) -> Parser () > expect t = firstExpect t (\xs => SomeE ((), xs)) > ==== A Recursive-Descent Parser for Imp Identifiers: > parseIdentifier : Parser Id > parseIdentifier [] = NoneE "Expected identifier" > parseIdentifier (x::xs) = > if all isLower (unpack x) > then SomeE (MkId x, xs) > else NoneE ("Illegal identifier:'" ++ x ++ "'") > Numbers: > parseNumber : Parser Nat > parseNumber [] = NoneE "Expected number" > parseNumber (x::xs) = > if all isDigit (unpack x) > then SomeE (foldl (\n, d => 10 * n + (cast (ord d - ord '0'))) 0 (unpack x), xs) > else NoneE "Expected number" > Parse arithmetic expressions > mutual > parsePrimaryExp : (steps : Nat) -> Parser AExp > parsePrimaryExp Z _ = NoneE "Too many recursive calls" > parsePrimaryExp (S steps') xs = > (do (i, rest) <- parseIdentifier xs > pure (AId i, rest)) > <|> > (do (n, rest) <- parseNumber xs > pure (ANum n, rest)) > <|> > (do (e, rest) <- firstExpect "(" (parseSumExp steps') xs > (u, rest') <- expect ")" rest > pure (e, rest')) > > parseProductExp : (steps : Nat) -> Parser AExp > parseProductExp Z _ = NoneE "Too many recursive calls" > parseProductExp (S steps') xs = > do (e, rest) <- parsePrimaryExp steps' xs > (es, rest') <- many (firstExpect "*" (parsePrimaryExp steps')) steps' rest > pure (foldl AMult e es, rest') > > parseSumExp : (steps : Nat) -> Parser AExp > parseSumExp Z _ = NoneE "Too many recursive calls" > parseSumExp (S steps') xs = > do (e, rest) <- parseProductExp steps' xs > (es, rest') <- many psum steps' rest > pure (foldl (\e0, term => > case term of > (True, e) => APlus e0 e > (False, e) => AMinus e0 e > ) e es, rest') > where > psum : Parser (Bool, AExp) > psum xs = > let p = parseProductExp steps' in > (do (e, r) <- firstExpect "+" p xs > pure ((True, e), r)) > <|> > (do (e, r) <- firstExpect "-" p xs > pure ((False, e), r)) > > parseAExp : (steps : Nat) -> Parser AExp > parseAExp = parseSumExp > Parsing boolean expressions: > mutual > parseAtomicExp : (steps : Nat) -> Parser BExp > parseAtomicExp Z _ = NoneE "Too many recursive calls" > parseAtomicExp (S steps') xs = > (do (_, rest) <- expect "true" xs > pure (BTrue, rest)) > <|> > (do (_, rest) <- expect "false" xs > pure (BFalse, rest)) > <|> > (do (e, rest) <- firstExpect "not" (parseAtomicExp steps') xs > pure (BNot e, rest)) > <|> > (do (e, rest) <- firstExpect "(" (parseConjunctionExp steps') xs > (_, rest') <- expect ")" rest > pure (e, rest')) > <|> > (do (e, rest) <- parseProductExp steps' xs > ((do (e', rest') <- firstExpect "==" (parseAExp steps') rest > pure (BEq e e', rest')) > <|> > (do (e', rest') <- firstExpect "<=" (parseAExp steps') rest > pure (BLe e e', rest')) > <|> > (NoneE "Expected '==' or '<=' after arithmetic expression"))) > > parseConjunctionExp : (steps : Nat) -> Parser BExp > parseConjunctionExp Z _ = NoneE "Too many recursive calls" > parseConjunctionExp (S steps') xs = > do (e, rest) <- parseAtomicExp steps' xs > (es, rest') <- many (firstExpect "&&" (parseAtomicExp steps')) steps' rest > pure (foldl BAnd e es, rest') > > parseBExp : (steps : Nat) -> Parser BExp > parseBExp = parseConjunctionExp > > testParsing : (p : Nat -> Parser t) -> (s : String) -> OptionE (t, List Token) > testParsing p s = p 100 (tokenize s) > \todo[inline]{The second one seems designed to fail} ```idris λΠ> testParsing parseProductExp "x*y*(x*x)*x" λΠ> testParsing parseConjunctionExp "not((x==x||x*x<=(x*x)*x)&&x==x" ``` Parsing commands: > mutual > parseSimpleCommand : (steps : Nat) -> Parser Com > parseSimpleCommand Z _ = NoneE "Too many recursive calls" > parseSimpleCommand (S steps') xs = > (do (_, rest) <- expect "SKIP" xs > pure (SKIP, rest)) > <|> > (do (e, rest) <- firstExpect "IF" (parseBExp steps') xs > (c, rest') <- firstExpect "THEN" (parseSequencedCommand steps') rest > (c', rest'') <- firstExpect "ELSE" (parseSequencedCommand steps') rest' > (_, rest''') <- expect "END" rest'' > pure (IFB e THEN c ELSE c' FI, rest''')) > <|> > (do (e, rest) <- firstExpect "WHILE" (parseBExp steps') xs > (c, rest') <- firstExpect "DO" (parseSequencedCommand steps') rest > (_, rest'') <- expect "END" rest' > pure (WHILE e c, rest'')) > <|> > (do (i, rest) <- parseIdentifier xs; > (e, rest') <- firstExpect ":=" (parseAExp steps') rest > pure (i ::= e, rest')) > > parseSequencedCommand : (steps : Nat) -> Parser Com > parseSequencedCommand Z _ = NoneE "Too many recursive calls" > parseSequencedCommand (S steps') xs = > do (c, rest) <- parseSimpleCommand steps' xs > ((do (c', rest') <- firstExpect ";;" (parseSequencedCommand steps') rest > pure ((do c; c'), rest')) > <|> > (pure (c, rest))) > > bignumber : Nat > bignumber = 1000 > > parse : (str : String) -> OptionE (Com, List Token) > parse str = parseSequencedCommand bignumber (tokenize str) > == Examples ```idris λΠ> parse "IF x == y + 1 + 2 - y * 6 + 3 THEN x := x * 1;; y := 0 ELSE SKIP END" SomeE (CIf (BEq (AId (MkId "x")) (APlus (AMinus (APlus (APlus (AId (MkId "y")) (ANum 1)) (ANum 2)) (AMult (AId (MkId "y")) (ANum 6))) (ANum 3))) (CSeq (CAss (MkId "x") (AMult (AId (MkId "x")) (ANum 1))) (CAss (MkId "y") (ANum 0))) CSkip, []) : OptionE (Com, List String) λΠ> parse "SKIP;; z:=x*y*(x*x);; WHILE x==x DO IF z <= z*z && not x == 2 THEN x := z;; y := z ELSE SKIP END;; SKIP END;; x:=z" ``` \todo[inline]{This one is repeated twice in the book for some reason} ```idris λΠ> parse "SKIP;; z:=x*y*(x*x);; WHILE x==x DO IF z <= z*z && not x == 2 THEN x := z;; y := z ELSE SKIP END;; SKIP END;; x:=z" SomeE (CSeq CSkip (CSeq (CAss (MkId "z") (AMult (AMult (AId (MkId "x")) (AId (MkId "y"))) (AMult (AId (MkId "x")) (AId (MkId "x"))))) (CSeq (CWhile (BEq (AId (MkId "x")) (AId (MkId "x"))) (CSeq (CIf (BAnd (BLe (AId (MkId "z")) (AMult (AId (MkId "z")) (AId (MkId "z")))) (BNot (BEq (AId (MkId "x")) (ANum 2)))) (CSeq (CAss (MkId "x") (AId (MkId "z"))) (CAss (MkId "y") (AId (MkId "z")))) CSkip) CSkip)) (CAss (MkId "x") (AId (MkId "z"))))), []) : OptionE (Com, List String) ```
[GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : FiniteDimensional k V p : ι → P hi : AffineIndependent k p ⊢ _root_.Finite ι [PROOFSTEP] nontriviality ι [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : FiniteDimensional k V p : ι → P hi : AffineIndependent k p ✝ : Nontrivial ι ⊢ _root_.Finite ι [PROOFSTEP] inhabit ι [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : FiniteDimensional k V p : ι → P hi : AffineIndependent k p ✝ : Nontrivial ι inhabited_h : Inhabited ι ⊢ _root_.Finite ι [PROOFSTEP] rw [affineIndependent_iff_linearIndependent_vsub k p default] at hi [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : FiniteDimensional k V p : ι → P ✝ : Nontrivial ι inhabited_h : Inhabited ι hi : LinearIndependent k fun i => p ↑i -ᵥ p default ⊢ _root_.Finite ι [PROOFSTEP] letI : IsNoetherian k V := IsNoetherian.iff_fg.2 inferInstance [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : FiniteDimensional k V p : ι → P ✝ : Nontrivial ι inhabited_h : Inhabited ι hi : LinearIndependent k fun i => p ↑i -ᵥ p default this : IsNoetherian k V := Iff.mpr IsNoetherian.iff_fg inferInstance ⊢ _root_.Finite ι [PROOFSTEP] exact (Set.finite_singleton default).finite_of_compl (Set.finite_coe_iff.1 hi.finite_of_isNoetherian) [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : DecidableEq P p : ι → P hi : AffineIndependent k p s : Finset ι n : ℕ hc : Finset.card s = n + 1 ⊢ finrank k { x // x ∈ vectorSpan k ↑(Finset.image p s) } = n [PROOFSTEP] classical have hi' := hi.range.mono (Set.image_subset_range p ↑s) have hc' : (s.image p).card = n + 1 := by rwa [s.card_image_of_injective hi.injective] have hn : (s.image p).Nonempty := by simp [hc', ← Finset.card_pos] rcases hn with ⟨p₁, hp₁⟩ have hp₁' : p₁ ∈ p '' s := by simpa using hp₁ rw [affineIndependent_set_iff_linearIndependent_vsub k hp₁', ← Finset.coe_singleton, ← Finset.coe_image, ← Finset.coe_sdiff, Finset.sdiff_singleton_eq_erase, ← Finset.coe_image] at hi' have hc : (Finset.image (fun p : P => p -ᵥ p₁) ((Finset.image p s).erase p₁)).card = n := by rw [Finset.card_image_of_injective _ (vsub_left_injective _), Finset.card_erase_of_mem hp₁] exact Nat.pred_eq_of_eq_succ hc' rwa [vectorSpan_eq_span_vsub_finset_right_ne k hp₁, finrank_span_finset_eq_card, hc] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : DecidableEq P p : ι → P hi : AffineIndependent k p s : Finset ι n : ℕ hc : Finset.card s = n + 1 ⊢ finrank k { x // x ∈ vectorSpan k ↑(Finset.image p s) } = n [PROOFSTEP] have hi' := hi.range.mono (Set.image_subset_range p ↑s) [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : DecidableEq P p : ι → P hi : AffineIndependent k p s : Finset ι n : ℕ hc : Finset.card s = n + 1 hi' : AffineIndependent k fun x => ↑x ⊢ finrank k { x // x ∈ vectorSpan k ↑(Finset.image p s) } = n [PROOFSTEP] have hc' : (s.image p).card = n + 1 := by rwa [s.card_image_of_injective hi.injective] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : DecidableEq P p : ι → P hi : AffineIndependent k p s : Finset ι n : ℕ hc : Finset.card s = n + 1 hi' : AffineIndependent k fun x => ↑x ⊢ Finset.card (Finset.image p s) = n + 1 [PROOFSTEP] rwa [s.card_image_of_injective hi.injective] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : DecidableEq P p : ι → P hi : AffineIndependent k p s : Finset ι n : ℕ hc : Finset.card s = n + 1 hi' : AffineIndependent k fun x => ↑x hc' : Finset.card (Finset.image p s) = n + 1 ⊢ finrank k { x // x ∈ vectorSpan k ↑(Finset.image p s) } = n [PROOFSTEP] have hn : (s.image p).Nonempty := by simp [hc', ← Finset.card_pos] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : DecidableEq P p : ι → P hi : AffineIndependent k p s : Finset ι n : ℕ hc : Finset.card s = n + 1 hi' : AffineIndependent k fun x => ↑x hc' : Finset.card (Finset.image p s) = n + 1 ⊢ Finset.Nonempty (Finset.image p s) [PROOFSTEP] simp [hc', ← Finset.card_pos] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : DecidableEq P p : ι → P hi : AffineIndependent k p s : Finset ι n : ℕ hc : Finset.card s = n + 1 hi' : AffineIndependent k fun x => ↑x hc' : Finset.card (Finset.image p s) = n + 1 hn : Finset.Nonempty (Finset.image p s) ⊢ finrank k { x // x ∈ vectorSpan k ↑(Finset.image p s) } = n [PROOFSTEP] rcases hn with ⟨p₁, hp₁⟩ [GOAL] case intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : DecidableEq P p : ι → P hi : AffineIndependent k p s : Finset ι n : ℕ hc : Finset.card s = n + 1 hi' : AffineIndependent k fun x => ↑x hc' : Finset.card (Finset.image p s) = n + 1 p₁ : P hp₁ : p₁ ∈ Finset.image p s ⊢ finrank k { x // x ∈ vectorSpan k ↑(Finset.image p s) } = n [PROOFSTEP] have hp₁' : p₁ ∈ p '' s := by simpa using hp₁ [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : DecidableEq P p : ι → P hi : AffineIndependent k p s : Finset ι n : ℕ hc : Finset.card s = n + 1 hi' : AffineIndependent k fun x => ↑x hc' : Finset.card (Finset.image p s) = n + 1 p₁ : P hp₁ : p₁ ∈ Finset.image p s ⊢ p₁ ∈ p '' ↑s [PROOFSTEP] simpa using hp₁ [GOAL] case intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : DecidableEq P p : ι → P hi : AffineIndependent k p s : Finset ι n : ℕ hc : Finset.card s = n + 1 hi' : AffineIndependent k fun x => ↑x hc' : Finset.card (Finset.image p s) = n + 1 p₁ : P hp₁ : p₁ ∈ Finset.image p s hp₁' : p₁ ∈ p '' ↑s ⊢ finrank k { x // x ∈ vectorSpan k ↑(Finset.image p s) } = n [PROOFSTEP] rw [affineIndependent_set_iff_linearIndependent_vsub k hp₁', ← Finset.coe_singleton, ← Finset.coe_image, ← Finset.coe_sdiff, Finset.sdiff_singleton_eq_erase, ← Finset.coe_image] at hi' [GOAL] case intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : DecidableEq P p : ι → P hi : AffineIndependent k p s : Finset ι n : ℕ hc : Finset.card s = n + 1 hc' : Finset.card (Finset.image p s) = n + 1 p₁ : P hi'✝² : LinearIndependent k fun v => ↑v hi'✝¹ : LinearIndependent k fun v => ↑v hi'✝ : LinearIndependent k fun v => ↑v hi' : LinearIndependent k fun v => ↑v hp₁ : p₁ ∈ Finset.image p s hp₁' : p₁ ∈ p '' ↑s ⊢ finrank k { x // x ∈ vectorSpan k ↑(Finset.image p s) } = n [PROOFSTEP] have hc : (Finset.image (fun p : P => p -ᵥ p₁) ((Finset.image p s).erase p₁)).card = n := by rw [Finset.card_image_of_injective _ (vsub_left_injective _), Finset.card_erase_of_mem hp₁] exact Nat.pred_eq_of_eq_succ hc' [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : DecidableEq P p : ι → P hi : AffineIndependent k p s : Finset ι n : ℕ hc : Finset.card s = n + 1 hc' : Finset.card (Finset.image p s) = n + 1 p₁ : P hi'✝² : LinearIndependent k fun v => ↑v hi'✝¹ : LinearIndependent k fun v => ↑v hi'✝ : LinearIndependent k fun v => ↑v hi' : LinearIndependent k fun v => ↑v hp₁ : p₁ ∈ Finset.image p s hp₁' : p₁ ∈ p '' ↑s ⊢ Finset.card (Finset.image (fun p => p -ᵥ p₁) (Finset.erase (Finset.image p s) p₁)) = n [PROOFSTEP] rw [Finset.card_image_of_injective _ (vsub_left_injective _), Finset.card_erase_of_mem hp₁] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : DecidableEq P p : ι → P hi : AffineIndependent k p s : Finset ι n : ℕ hc : Finset.card s = n + 1 hc' : Finset.card (Finset.image p s) = n + 1 p₁ : P hi'✝² : LinearIndependent k fun v => ↑v hi'✝¹ : LinearIndependent k fun v => ↑v hi'✝ : LinearIndependent k fun v => ↑v hi' : LinearIndependent k fun v => ↑v hp₁ : p₁ ∈ Finset.image p s hp₁' : p₁ ∈ p '' ↑s ⊢ Finset.card (Finset.image p s) - 1 = n [PROOFSTEP] exact Nat.pred_eq_of_eq_succ hc' [GOAL] case intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : DecidableEq P p : ι → P hi : AffineIndependent k p s : Finset ι n : ℕ hc✝ : Finset.card s = n + 1 hc' : Finset.card (Finset.image p s) = n + 1 p₁ : P hi'✝² : LinearIndependent k fun v => ↑v hi'✝¹ : LinearIndependent k fun v => ↑v hi'✝ : LinearIndependent k fun v => ↑v hi' : LinearIndependent k fun v => ↑v hp₁ : p₁ ∈ Finset.image p s hp₁' : p₁ ∈ p '' ↑s hc : Finset.card (Finset.image (fun p => p -ᵥ p₁) (Finset.erase (Finset.image p s) p₁)) = n ⊢ finrank k { x // x ∈ vectorSpan k ↑(Finset.image p s) } = n [PROOFSTEP] rwa [vectorSpan_eq_span_vsub_finset_right_ne k hp₁, finrank_span_finset_eq_card, hc] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : Fintype ι p : ι → P hi : AffineIndependent k p n : ℕ hc : Fintype.card ι = n + 1 ⊢ finrank k { x // x ∈ vectorSpan k (Set.range p) } = n [PROOFSTEP] classical rw [← Finset.card_univ] at hc rw [← Set.image_univ, ← Finset.coe_univ, ← Finset.coe_image] exact hi.finrank_vectorSpan_image_finset hc [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : Fintype ι p : ι → P hi : AffineIndependent k p n : ℕ hc : Fintype.card ι = n + 1 ⊢ finrank k { x // x ∈ vectorSpan k (Set.range p) } = n [PROOFSTEP] rw [← Finset.card_univ] at hc [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : Fintype ι p : ι → P hi : AffineIndependent k p n : ℕ hc : Finset.card Finset.univ = n + 1 ⊢ finrank k { x // x ∈ vectorSpan k (Set.range p) } = n [PROOFSTEP] rw [← Set.image_univ, ← Finset.coe_univ, ← Finset.coe_image] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : Fintype ι p : ι → P hi : AffineIndependent k p n : ℕ hc : Finset.card Finset.univ = n + 1 ⊢ finrank k { x // x ∈ vectorSpan k ↑(Finset.image p Finset.univ) } = n [PROOFSTEP] exact hi.finrank_vectorSpan_image_finset hc [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : DecidableEq P p : ι → P s : Finset ι n : ℕ hc : Finset.card s = n + 1 ⊢ finrank k { x // x ∈ vectorSpan k ↑(Finset.image p s) } ≤ n [PROOFSTEP] classical have hn : (s.image p).Nonempty := by rw [Finset.Nonempty.image_iff, ← Finset.card_pos, hc] apply Nat.succ_pos rcases hn with ⟨p₁, hp₁⟩ rw [vectorSpan_eq_span_vsub_finset_right_ne k hp₁] refine' le_trans (finrank_span_finset_le_card (((s.image p).erase p₁).image fun p => p -ᵥ p₁)) _ rw [Finset.card_image_of_injective _ (vsub_left_injective p₁), Finset.card_erase_of_mem hp₁, tsub_le_iff_right, ← hc] apply Finset.card_image_le [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : DecidableEq P p : ι → P s : Finset ι n : ℕ hc : Finset.card s = n + 1 ⊢ finrank k { x // x ∈ vectorSpan k ↑(Finset.image p s) } ≤ n [PROOFSTEP] have hn : (s.image p).Nonempty := by rw [Finset.Nonempty.image_iff, ← Finset.card_pos, hc] apply Nat.succ_pos [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : DecidableEq P p : ι → P s : Finset ι n : ℕ hc : Finset.card s = n + 1 ⊢ Finset.Nonempty (Finset.image p s) [PROOFSTEP] rw [Finset.Nonempty.image_iff, ← Finset.card_pos, hc] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : DecidableEq P p : ι → P s : Finset ι n : ℕ hc : Finset.card s = n + 1 ⊢ 0 < n + 1 [PROOFSTEP] apply Nat.succ_pos [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : DecidableEq P p : ι → P s : Finset ι n : ℕ hc : Finset.card s = n + 1 hn : Finset.Nonempty (Finset.image p s) ⊢ finrank k { x // x ∈ vectorSpan k ↑(Finset.image p s) } ≤ n [PROOFSTEP] rcases hn with ⟨p₁, hp₁⟩ [GOAL] case intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : DecidableEq P p : ι → P s : Finset ι n : ℕ hc : Finset.card s = n + 1 p₁ : P hp₁ : p₁ ∈ Finset.image p s ⊢ finrank k { x // x ∈ vectorSpan k ↑(Finset.image p s) } ≤ n [PROOFSTEP] rw [vectorSpan_eq_span_vsub_finset_right_ne k hp₁] [GOAL] case intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : DecidableEq P p : ι → P s : Finset ι n : ℕ hc : Finset.card s = n + 1 p₁ : P hp₁ : p₁ ∈ Finset.image p s ⊢ finrank k { x // x ∈ Submodule.span k ↑(Finset.image (fun x => x -ᵥ p₁) (Finset.erase (Finset.image p s) p₁)) } ≤ n [PROOFSTEP] refine' le_trans (finrank_span_finset_le_card (((s.image p).erase p₁).image fun p => p -ᵥ p₁)) _ [GOAL] case intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : DecidableEq P p : ι → P s : Finset ι n : ℕ hc : Finset.card s = n + 1 p₁ : P hp₁ : p₁ ∈ Finset.image p s ⊢ Finset.card (Finset.image (fun p => p -ᵥ p₁) (Finset.erase (Finset.image p s) p₁)) ≤ n [PROOFSTEP] rw [Finset.card_image_of_injective _ (vsub_left_injective p₁), Finset.card_erase_of_mem hp₁, tsub_le_iff_right, ← hc] [GOAL] case intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : DecidableEq P p : ι → P s : Finset ι n : ℕ hc : Finset.card s = n + 1 p₁ : P hp₁ : p₁ ∈ Finset.image p s ⊢ Finset.card (Finset.image p s) ≤ Finset.card s [PROOFSTEP] apply Finset.card_image_le [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : Fintype ι p : ι → P n : ℕ hc : Fintype.card ι = n + 1 ⊢ finrank k { x // x ∈ vectorSpan k (Set.range p) } ≤ n [PROOFSTEP] classical rw [← Set.image_univ, ← Finset.coe_univ, ← Finset.coe_image] rw [← Finset.card_univ] at hc exact finrank_vectorSpan_image_finset_le _ _ _ hc [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : Fintype ι p : ι → P n : ℕ hc : Fintype.card ι = n + 1 ⊢ finrank k { x // x ∈ vectorSpan k (Set.range p) } ≤ n [PROOFSTEP] rw [← Set.image_univ, ← Finset.coe_univ, ← Finset.coe_image] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : Fintype ι p : ι → P n : ℕ hc : Fintype.card ι = n + 1 ⊢ finrank k { x // x ∈ vectorSpan k ↑(Finset.image p Finset.univ) } ≤ n [PROOFSTEP] rw [← Finset.card_univ] at hc [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : Fintype ι p : ι → P n : ℕ hc : Finset.card Finset.univ = n + 1 ⊢ finrank k { x // x ∈ vectorSpan k ↑(Finset.image p Finset.univ) } ≤ n [PROOFSTEP] exact finrank_vectorSpan_image_finset_le _ _ _ hc [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : Fintype ι p : ι → P n : ℕ hc : Fintype.card ι = n + 1 ⊢ AffineIndependent k p ↔ finrank k { x // x ∈ vectorSpan k (Set.range p) } = n [PROOFSTEP] classical have hn : Nonempty ι := by simp [← Fintype.card_pos_iff, hc] cases' hn with i₁ rw [affineIndependent_iff_linearIndependent_vsub _ _ i₁, linearIndependent_iff_card_eq_finrank_span, eq_comm, vectorSpan_range_eq_span_range_vsub_right_ne k p i₁, Set.finrank] congr rw [← Finset.card_univ] at hc rw [Fintype.subtype_card] simp [Finset.filter_ne', Finset.card_erase_of_mem, hc] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : Fintype ι p : ι → P n : ℕ hc : Fintype.card ι = n + 1 ⊢ AffineIndependent k p ↔ finrank k { x // x ∈ vectorSpan k (Set.range p) } = n [PROOFSTEP] have hn : Nonempty ι := by simp [← Fintype.card_pos_iff, hc] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : Fintype ι p : ι → P n : ℕ hc : Fintype.card ι = n + 1 ⊢ Nonempty ι [PROOFSTEP] simp [← Fintype.card_pos_iff, hc] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : Fintype ι p : ι → P n : ℕ hc : Fintype.card ι = n + 1 hn : Nonempty ι ⊢ AffineIndependent k p ↔ finrank k { x // x ∈ vectorSpan k (Set.range p) } = n [PROOFSTEP] cases' hn with i₁ [GOAL] case intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : Fintype ι p : ι → P n : ℕ hc : Fintype.card ι = n + 1 i₁ : ι ⊢ AffineIndependent k p ↔ finrank k { x // x ∈ vectorSpan k (Set.range p) } = n [PROOFSTEP] rw [affineIndependent_iff_linearIndependent_vsub _ _ i₁, linearIndependent_iff_card_eq_finrank_span, eq_comm, vectorSpan_range_eq_span_range_vsub_right_ne k p i₁, Set.finrank] [GOAL] case intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : Fintype ι p : ι → P n : ℕ hc : Fintype.card ι = n + 1 i₁ : ι ⊢ finrank k { x // x ∈ Submodule.span k (Set.range fun i => p ↑i -ᵥ p i₁) } = Fintype.card { x // x ≠ i₁ } ↔ finrank k { x // x ∈ Submodule.span k (Set.range fun i => p ↑i -ᵥ p i₁) } = n [PROOFSTEP] congr [GOAL] case intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : Fintype ι p : ι → P n : ℕ hc : Fintype.card ι = n + 1 i₁ : ι ⊢ finrank k { x // x ∈ Submodule.span k (Set.range fun i => p ↑i -ᵥ p i₁) } = Fintype.card { x // x ≠ i₁ } ↔ finrank k { x // x ∈ Submodule.span k (Set.range fun i => p ↑i -ᵥ p i₁) } = n [PROOFSTEP] rw [← Finset.card_univ] at hc [GOAL] case intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : Fintype ι p : ι → P n : ℕ hc : Finset.card Finset.univ = n + 1 i₁ : ι ⊢ finrank k { x // x ∈ Submodule.span k (Set.range fun i => p ↑i -ᵥ p i₁) } = Fintype.card { x // x ≠ i₁ } ↔ finrank k { x // x ∈ Submodule.span k (Set.range fun i => p ↑i -ᵥ p i₁) } = n [PROOFSTEP] rw [Fintype.subtype_card] [GOAL] case intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : Fintype ι p : ι → P n : ℕ hc : Finset.card Finset.univ = n + 1 i₁ : ι ⊢ finrank k { x // x ∈ Submodule.span k (Set.range fun i => p ↑i -ᵥ p i₁) } = Finset.card (Finset.filter (fun x => x ≠ i₁) Finset.univ) ↔ finrank k { x // x ∈ Submodule.span k (Set.range fun i => p ↑i -ᵥ p i₁) } = n [PROOFSTEP] simp [Finset.filter_ne', Finset.card_erase_of_mem, hc] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : Fintype ι p : ι → P n : ℕ hc : Fintype.card ι = n + 1 ⊢ AffineIndependent k p ↔ n ≤ finrank k { x // x ∈ vectorSpan k (Set.range p) } [PROOFSTEP] rw [affineIndependent_iff_finrank_vectorSpan_eq k p hc] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : Fintype ι p : ι → P n : ℕ hc : Fintype.card ι = n + 1 ⊢ finrank k { x // x ∈ vectorSpan k (Set.range p) } = n ↔ n ≤ finrank k { x // x ∈ vectorSpan k (Set.range p) } [PROOFSTEP] constructor [GOAL] case mp k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : Fintype ι p : ι → P n : ℕ hc : Fintype.card ι = n + 1 ⊢ finrank k { x // x ∈ vectorSpan k (Set.range p) } = n → n ≤ finrank k { x // x ∈ vectorSpan k (Set.range p) } [PROOFSTEP] rintro rfl [GOAL] case mp k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : Fintype ι p : ι → P hc : Fintype.card ι = finrank k { x // x ∈ vectorSpan k (Set.range p) } + 1 ⊢ finrank k { x // x ∈ vectorSpan k (Set.range p) } ≤ finrank k { x // x ∈ vectorSpan k (Set.range p) } [PROOFSTEP] rfl [GOAL] case mpr k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : Fintype ι p : ι → P n : ℕ hc : Fintype.card ι = n + 1 ⊢ n ≤ finrank k { x // x ∈ vectorSpan k (Set.range p) } → finrank k { x // x ∈ vectorSpan k (Set.range p) } = n [PROOFSTEP] exact fun hle => le_antisymm (finrank_vectorSpan_range_le k p hc) hle [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : Fintype ι p : ι → P n : ℕ hc : Fintype.card ι = n + 2 ⊢ AffineIndependent k p ↔ ¬finrank k { x // x ∈ vectorSpan k (Set.range p) } ≤ n [PROOFSTEP] rw [affineIndependent_iff_le_finrank_vectorSpan k p hc, ← Nat.lt_iff_add_one_le, lt_iff_not_ge] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁵ : DivisionRing k inst✝⁴ : AddCommGroup V inst✝³ : Module k V inst✝² : AffineSpace V P inst✝¹ : DecidableEq P p : ι → P hi : AffineIndependent k p s : Finset ι sp : AffineSubspace k P inst✝ : FiniteDimensional k { x // x ∈ direction sp } hle : affineSpan k ↑(Finset.image p s) ≤ sp hc : Finset.card s = finrank k { x // x ∈ direction sp } + 1 ⊢ affineSpan k ↑(Finset.image p s) = sp [PROOFSTEP] have hn : s.Nonempty := by rw [← Finset.card_pos, hc] apply Nat.succ_pos [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁵ : DivisionRing k inst✝⁴ : AddCommGroup V inst✝³ : Module k V inst✝² : AffineSpace V P inst✝¹ : DecidableEq P p : ι → P hi : AffineIndependent k p s : Finset ι sp : AffineSubspace k P inst✝ : FiniteDimensional k { x // x ∈ direction sp } hle : affineSpan k ↑(Finset.image p s) ≤ sp hc : Finset.card s = finrank k { x // x ∈ direction sp } + 1 ⊢ Finset.Nonempty s [PROOFSTEP] rw [← Finset.card_pos, hc] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁵ : DivisionRing k inst✝⁴ : AddCommGroup V inst✝³ : Module k V inst✝² : AffineSpace V P inst✝¹ : DecidableEq P p : ι → P hi : AffineIndependent k p s : Finset ι sp : AffineSubspace k P inst✝ : FiniteDimensional k { x // x ∈ direction sp } hle : affineSpan k ↑(Finset.image p s) ≤ sp hc : Finset.card s = finrank k { x // x ∈ direction sp } + 1 ⊢ 0 < finrank k { x // x ∈ direction sp } + 1 [PROOFSTEP] apply Nat.succ_pos [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁵ : DivisionRing k inst✝⁴ : AddCommGroup V inst✝³ : Module k V inst✝² : AffineSpace V P inst✝¹ : DecidableEq P p : ι → P hi : AffineIndependent k p s : Finset ι sp : AffineSubspace k P inst✝ : FiniteDimensional k { x // x ∈ direction sp } hle : affineSpan k ↑(Finset.image p s) ≤ sp hc : Finset.card s = finrank k { x // x ∈ direction sp } + 1 hn : Finset.Nonempty s ⊢ affineSpan k ↑(Finset.image p s) = sp [PROOFSTEP] refine' eq_of_direction_eq_of_nonempty_of_le _ ((hn.image p).to_set.affineSpan k) hle [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁵ : DivisionRing k inst✝⁴ : AddCommGroup V inst✝³ : Module k V inst✝² : AffineSpace V P inst✝¹ : DecidableEq P p : ι → P hi : AffineIndependent k p s : Finset ι sp : AffineSubspace k P inst✝ : FiniteDimensional k { x // x ∈ direction sp } hle : affineSpan k ↑(Finset.image p s) ≤ sp hc : Finset.card s = finrank k { x // x ∈ direction sp } + 1 hn : Finset.Nonempty s ⊢ direction (affineSpan k ↑(Finset.image p s)) = direction sp [PROOFSTEP] have hd := direction_le hle [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁵ : DivisionRing k inst✝⁴ : AddCommGroup V inst✝³ : Module k V inst✝² : AffineSpace V P inst✝¹ : DecidableEq P p : ι → P hi : AffineIndependent k p s : Finset ι sp : AffineSubspace k P inst✝ : FiniteDimensional k { x // x ∈ direction sp } hle : affineSpan k ↑(Finset.image p s) ≤ sp hc : Finset.card s = finrank k { x // x ∈ direction sp } + 1 hn : Finset.Nonempty s hd : direction (affineSpan k ↑(Finset.image p s)) ≤ direction sp ⊢ direction (affineSpan k ↑(Finset.image p s)) = direction sp [PROOFSTEP] rw [direction_affineSpan] at hd ⊢ [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁵ : DivisionRing k inst✝⁴ : AddCommGroup V inst✝³ : Module k V inst✝² : AffineSpace V P inst✝¹ : DecidableEq P p : ι → P hi : AffineIndependent k p s : Finset ι sp : AffineSubspace k P inst✝ : FiniteDimensional k { x // x ∈ direction sp } hle : affineSpan k ↑(Finset.image p s) ≤ sp hc : Finset.card s = finrank k { x // x ∈ direction sp } + 1 hn : Finset.Nonempty s hd : vectorSpan k ↑(Finset.image p s) ≤ direction sp ⊢ vectorSpan k ↑(Finset.image p s) = direction sp [PROOFSTEP] exact hi.vectorSpan_image_finset_eq_of_le_of_card_eq_finrank_add_one hd hc [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁵ : DivisionRing k inst✝⁴ : AddCommGroup V inst✝³ : Module k V inst✝² : AffineSpace V P inst✝¹ : Fintype ι p : ι → P hi : AffineIndependent k p sp : AffineSubspace k P inst✝ : FiniteDimensional k { x // x ∈ direction sp } hle : affineSpan k (Set.range p) ≤ sp hc : Fintype.card ι = finrank k { x // x ∈ direction sp } + 1 ⊢ affineSpan k (Set.range p) = sp [PROOFSTEP] classical rw [← Finset.card_univ] at hc rw [← Set.image_univ, ← Finset.coe_univ, ← Finset.coe_image] at hle ⊢ exact hi.affineSpan_image_finset_eq_of_le_of_card_eq_finrank_add_one hle hc [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁵ : DivisionRing k inst✝⁴ : AddCommGroup V inst✝³ : Module k V inst✝² : AffineSpace V P inst✝¹ : Fintype ι p : ι → P hi : AffineIndependent k p sp : AffineSubspace k P inst✝ : FiniteDimensional k { x // x ∈ direction sp } hle : affineSpan k (Set.range p) ≤ sp hc : Fintype.card ι = finrank k { x // x ∈ direction sp } + 1 ⊢ affineSpan k (Set.range p) = sp [PROOFSTEP] rw [← Finset.card_univ] at hc [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁵ : DivisionRing k inst✝⁴ : AddCommGroup V inst✝³ : Module k V inst✝² : AffineSpace V P inst✝¹ : Fintype ι p : ι → P hi : AffineIndependent k p sp : AffineSubspace k P inst✝ : FiniteDimensional k { x // x ∈ direction sp } hle : affineSpan k (Set.range p) ≤ sp hc : Finset.card Finset.univ = finrank k { x // x ∈ direction sp } + 1 ⊢ affineSpan k (Set.range p) = sp [PROOFSTEP] rw [← Set.image_univ, ← Finset.coe_univ, ← Finset.coe_image] at hle ⊢ [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁵ : DivisionRing k inst✝⁴ : AddCommGroup V inst✝³ : Module k V inst✝² : AffineSpace V P inst✝¹ : Fintype ι p : ι → P hi : AffineIndependent k p sp : AffineSubspace k P inst✝ : FiniteDimensional k { x // x ∈ direction sp } hle✝¹ : affineSpan k (p '' Set.univ) ≤ sp hle✝ : affineSpan k (p '' ↑Finset.univ) ≤ sp hle : affineSpan k ↑(Finset.image p Finset.univ) ≤ sp hc : Finset.card Finset.univ = finrank k { x // x ∈ direction sp } + 1 ⊢ affineSpan k ↑(Finset.image p Finset.univ) = sp [PROOFSTEP] exact hi.affineSpan_image_finset_eq_of_le_of_card_eq_finrank_add_one hle hc [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁵ : DivisionRing k inst✝⁴ : AddCommGroup V inst✝³ : Module k V inst✝² : AffineSpace V P inst✝¹ : FiniteDimensional k V inst✝ : Fintype ι p : ι → P hi : AffineIndependent k p ⊢ affineSpan k (Set.range p) = ⊤ ↔ Fintype.card ι = finrank k V + 1 [PROOFSTEP] constructor [GOAL] case mp k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁵ : DivisionRing k inst✝⁴ : AddCommGroup V inst✝³ : Module k V inst✝² : AffineSpace V P inst✝¹ : FiniteDimensional k V inst✝ : Fintype ι p : ι → P hi : AffineIndependent k p ⊢ affineSpan k (Set.range p) = ⊤ → Fintype.card ι = finrank k V + 1 [PROOFSTEP] intro h_tot [GOAL] case mp k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁵ : DivisionRing k inst✝⁴ : AddCommGroup V inst✝³ : Module k V inst✝² : AffineSpace V P inst✝¹ : FiniteDimensional k V inst✝ : Fintype ι p : ι → P hi : AffineIndependent k p h_tot : affineSpan k (Set.range p) = ⊤ ⊢ Fintype.card ι = finrank k V + 1 [PROOFSTEP] let n := Fintype.card ι - 1 [GOAL] case mp k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁵ : DivisionRing k inst✝⁴ : AddCommGroup V inst✝³ : Module k V inst✝² : AffineSpace V P inst✝¹ : FiniteDimensional k V inst✝ : Fintype ι p : ι → P hi : AffineIndependent k p h_tot : affineSpan k (Set.range p) = ⊤ n : ℕ := Fintype.card ι - 1 ⊢ Fintype.card ι = finrank k V + 1 [PROOFSTEP] have hn : Fintype.card ι = n + 1 := (Nat.succ_pred_eq_of_pos (card_pos_of_affineSpan_eq_top k V P h_tot)).symm [GOAL] case mp k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁵ : DivisionRing k inst✝⁴ : AddCommGroup V inst✝³ : Module k V inst✝² : AffineSpace V P inst✝¹ : FiniteDimensional k V inst✝ : Fintype ι p : ι → P hi : AffineIndependent k p h_tot : affineSpan k (Set.range p) = ⊤ n : ℕ := Fintype.card ι - 1 hn : Fintype.card ι = n + 1 ⊢ Fintype.card ι = finrank k V + 1 [PROOFSTEP] rw [hn, ← finrank_top, ← (vectorSpan_eq_top_of_affineSpan_eq_top k V P) h_tot, ← hi.finrank_vectorSpan hn] [GOAL] case mpr k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁵ : DivisionRing k inst✝⁴ : AddCommGroup V inst✝³ : Module k V inst✝² : AffineSpace V P inst✝¹ : FiniteDimensional k V inst✝ : Fintype ι p : ι → P hi : AffineIndependent k p ⊢ Fintype.card ι = finrank k V + 1 → affineSpan k (Set.range p) = ⊤ [PROOFSTEP] intro hc [GOAL] case mpr k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁵ : DivisionRing k inst✝⁴ : AddCommGroup V inst✝³ : Module k V inst✝² : AffineSpace V P inst✝¹ : FiniteDimensional k V inst✝ : Fintype ι p : ι → P hi : AffineIndependent k p hc : Fintype.card ι = finrank k V + 1 ⊢ affineSpan k (Set.range p) = ⊤ [PROOFSTEP] rw [← finrank_top, ← direction_top k V P] at hc [GOAL] case mpr k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁵ : DivisionRing k inst✝⁴ : AddCommGroup V inst✝³ : Module k V inst✝² : AffineSpace V P inst✝¹ : FiniteDimensional k V inst✝ : Fintype ι p : ι → P hi : AffineIndependent k p hc : Fintype.card ι = finrank k { x // x ∈ direction ⊤ } + 1 ⊢ affineSpan k (Set.range p) = ⊤ [PROOFSTEP] exact hi.affineSpan_eq_of_le_of_card_eq_finrank_add_one le_top hc [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P inst✝ : FiniteDimensional k V n : ℕ T : Simplex k V n hrank : finrank k V = n ⊢ affineSpan k (Set.range T.points) = ⊤ [PROOFSTEP] rw [AffineIndependent.affineSpan_eq_top_iff_card_eq_finrank_add_one T.Independent, Fintype.card_fin, hrank] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P s : AffineSubspace k P inst✝ : FiniteDimensional k { x // x ∈ direction s } p : P ⊢ FiniteDimensional k { x // x ∈ vectorSpan k (insert p ↑s) } [PROOFSTEP] rw [← direction_affineSpan, ← affineSpan_insert_affineSpan] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P s : AffineSubspace k P inst✝ : FiniteDimensional k { x // x ∈ direction s } p : P ⊢ FiniteDimensional k { x // x ∈ direction (affineSpan k (insert p ↑(affineSpan k ↑s))) } [PROOFSTEP] rcases(s : Set P).eq_empty_or_nonempty with (hs | ⟨p₀, hp₀⟩) [GOAL] case inl k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P s : AffineSubspace k P inst✝ : FiniteDimensional k { x // x ∈ direction s } p : P hs : ↑s = ∅ ⊢ FiniteDimensional k { x // x ∈ direction (affineSpan k (insert p ↑(affineSpan k ↑s))) } [PROOFSTEP] rw [coe_eq_bot_iff] at hs [GOAL] case inl k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P s : AffineSubspace k P inst✝ : FiniteDimensional k { x // x ∈ direction s } p : P hs : s = ⊥ ⊢ FiniteDimensional k { x // x ∈ direction (affineSpan k (insert p ↑(affineSpan k ↑s))) } [PROOFSTEP] rw [hs, bot_coe, span_empty, bot_coe, direction_affineSpan] [GOAL] case inl k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P s : AffineSubspace k P inst✝ : FiniteDimensional k { x // x ∈ direction s } p : P hs : s = ⊥ ⊢ FiniteDimensional k { x // x ∈ vectorSpan k (insert p ∅) } [PROOFSTEP] convert finiteDimensional_bot _ _ [GOAL] case h.e'_2.h.e'_2.h.h.e'_5 k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P s : AffineSubspace k P inst✝ : FiniteDimensional k { x // x ∈ direction s } p : P hs : s = ⊥ x✝ : V ⊢ vectorSpan k (insert p ∅) = ⊥ [PROOFSTEP] simp [GOAL] case h.e'_4.e'_6 k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P s : AffineSubspace k P inst✝ : FiniteDimensional k { x // x ∈ direction s } p : P hs : s = ⊥ e_2✝ : { x // x ∈ vectorSpan k (insert p ∅) } = { x // x ∈ ⊥ } ⊢ vectorSpan k (insert p ∅) = ⊥ [PROOFSTEP] simp [GOAL] case h.e'_5.e'_6.h.h k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P s : AffineSubspace k P inst✝ : FiniteDimensional k { x // x ∈ direction s } p : P hs : s = ⊥ e_2✝ : { x // x ∈ vectorSpan k (insert p ∅) } = { x // x ∈ ⊥ } e_4✝ : HEq (Submodule.addCommGroup (vectorSpan k (insert p ∅))) (Submodule.addCommGroup ⊥) e_3✝ : Ring.toSemiring = DivisionSemiring.toSemiring ⊢ vectorSpan k (insert p ∅) = ⊥ [PROOFSTEP] simp [GOAL] case inr.intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P s : AffineSubspace k P inst✝ : FiniteDimensional k { x // x ∈ direction s } p p₀ : P hp₀ : p₀ ∈ ↑s ⊢ FiniteDimensional k { x // x ∈ direction (affineSpan k (insert p ↑(affineSpan k ↑s))) } [PROOFSTEP] rw [affineSpan_coe, direction_affineSpan_insert hp₀] [GOAL] case inr.intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P s : AffineSubspace k P inst✝ : FiniteDimensional k { x // x ∈ direction s } p p₀ : P hp₀ : p₀ ∈ ↑s ⊢ FiniteDimensional k { x // x ∈ Submodule.span k {p -ᵥ p₀} ⊔ direction s } [PROOFSTEP] infer_instance [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P s : Set P inst✝ : FiniteDimensional k { x // x ∈ vectorSpan k s } p : P ⊢ FiniteDimensional k { x // x ∈ vectorSpan k (insert p s) } [PROOFSTEP] haveI : FiniteDimensional k (affineSpan k s).direction := (direction_affineSpan k s).symm ▸ inferInstance [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P s : Set P inst✝ : FiniteDimensional k { x // x ∈ vectorSpan k s } p : P this : FiniteDimensional k { x // x ∈ direction (affineSpan k s) } ⊢ FiniteDimensional k { x // x ∈ vectorSpan k (insert p s) } [PROOFSTEP] rw [← direction_affineSpan, ← affineSpan_insert_affineSpan, direction_affineSpan] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P s : Set P inst✝ : FiniteDimensional k { x // x ∈ vectorSpan k s } p : P this : FiniteDimensional k { x // x ∈ direction (affineSpan k s) } ⊢ FiniteDimensional k { x // x ∈ vectorSpan k (insert p ↑(affineSpan k s)) } [PROOFSTEP] exact finiteDimensional_vectorSpan_insert (affineSpan k s) p [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P s : Set P inst✝ : FiniteDimensional k { x // x ∈ vectorSpan k s } ⊢ Collinear k s ↔ finrank k { x // x ∈ vectorSpan k s } ≤ 1 [PROOFSTEP] have h := collinear_iff_rank_le_one k s [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P s : Set P inst✝ : FiniteDimensional k { x // x ∈ vectorSpan k s } h : Collinear k s ↔ Module.rank k { x // x ∈ vectorSpan k s } ≤ 1 ⊢ Collinear k s ↔ finrank k { x // x ∈ vectorSpan k s } ≤ 1 [PROOFSTEP] rw [← finrank_eq_rank] at h [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P s : Set P inst✝ : FiniteDimensional k { x // x ∈ vectorSpan k s } h : Collinear k s ↔ ↑(finrank k { x // x ∈ vectorSpan k s }) ≤ 1 ⊢ Collinear k s ↔ finrank k { x // x ∈ vectorSpan k s } ≤ 1 [PROOFSTEP] exact_mod_cast h [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P ⊢ Collinear k ∅ [PROOFSTEP] rw [collinear_iff_rank_le_one, vectorSpan_empty] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P ⊢ Module.rank k { x // x ∈ ⊥ } ≤ 1 [PROOFSTEP] simp [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : P ⊢ Collinear k {p} [PROOFSTEP] rw [collinear_iff_rank_le_one, vectorSpan_singleton] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : P ⊢ Module.rank k { x // x ∈ ⊥ } ≤ 1 [PROOFSTEP] simp [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₀ : P h : p₀ ∈ s ⊢ Collinear k s ↔ ∃ v, ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₀ [PROOFSTEP] simp_rw [collinear_iff_rank_le_one, rank_submodule_le_one_iff', Submodule.le_span_singleton_iff] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₀ : P h : p₀ ∈ s ⊢ (∃ v₀, ∀ (v : V), v ∈ vectorSpan k s → ∃ r, r • v₀ = v) ↔ ∃ v, ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₀ [PROOFSTEP] constructor [GOAL] case mp k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₀ : P h : p₀ ∈ s ⊢ (∃ v₀, ∀ (v : V), v ∈ vectorSpan k s → ∃ r, r • v₀ = v) → ∃ v, ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₀ [PROOFSTEP] rintro ⟨v₀, hv⟩ [GOAL] case mp.intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₀ : P h : p₀ ∈ s v₀ : V hv : ∀ (v : V), v ∈ vectorSpan k s → ∃ r, r • v₀ = v ⊢ ∃ v, ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₀ [PROOFSTEP] use v₀ [GOAL] case h k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₀ : P h : p₀ ∈ s v₀ : V hv : ∀ (v : V), v ∈ vectorSpan k s → ∃ r, r • v₀ = v ⊢ ∀ (p : P), p ∈ s → ∃ r, p = r • v₀ +ᵥ p₀ [PROOFSTEP] intro p hp [GOAL] case h k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₀ : P h : p₀ ∈ s v₀ : V hv : ∀ (v : V), v ∈ vectorSpan k s → ∃ r, r • v₀ = v p : P hp : p ∈ s ⊢ ∃ r, p = r • v₀ +ᵥ p₀ [PROOFSTEP] obtain ⟨r, hr⟩ := hv (p -ᵥ p₀) (vsub_mem_vectorSpan k hp h) [GOAL] case h.intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₀ : P h : p₀ ∈ s v₀ : V hv : ∀ (v : V), v ∈ vectorSpan k s → ∃ r, r • v₀ = v p : P hp : p ∈ s r : k hr : r • v₀ = p -ᵥ p₀ ⊢ ∃ r, p = r • v₀ +ᵥ p₀ [PROOFSTEP] use r [GOAL] case h k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₀ : P h : p₀ ∈ s v₀ : V hv : ∀ (v : V), v ∈ vectorSpan k s → ∃ r, r • v₀ = v p : P hp : p ∈ s r : k hr : r • v₀ = p -ᵥ p₀ ⊢ p = r • v₀ +ᵥ p₀ [PROOFSTEP] rw [eq_vadd_iff_vsub_eq] [GOAL] case h k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₀ : P h : p₀ ∈ s v₀ : V hv : ∀ (v : V), v ∈ vectorSpan k s → ∃ r, r • v₀ = v p : P hp : p ∈ s r : k hr : r • v₀ = p -ᵥ p₀ ⊢ p -ᵥ p₀ = r • v₀ [PROOFSTEP] exact hr.symm [GOAL] case mpr k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₀ : P h : p₀ ∈ s ⊢ (∃ v, ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₀) → ∃ v₀, ∀ (v : V), v ∈ vectorSpan k s → ∃ r, r • v₀ = v [PROOFSTEP] rintro ⟨v, hp₀v⟩ [GOAL] case mpr.intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₀ : P h : p₀ ∈ s v : V hp₀v : ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₀ ⊢ ∃ v₀, ∀ (v : V), v ∈ vectorSpan k s → ∃ r, r • v₀ = v [PROOFSTEP] use v [GOAL] case h k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₀ : P h : p₀ ∈ s v : V hp₀v : ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₀ ⊢ ∀ (v_1 : V), v_1 ∈ vectorSpan k s → ∃ r, r • v = v_1 [PROOFSTEP] intro w hw [GOAL] case h k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₀ : P h : p₀ ∈ s v : V hp₀v : ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₀ w : V hw : w ∈ vectorSpan k s ⊢ ∃ r, r • v = w [PROOFSTEP] have hs : vectorSpan k s ≤ k ∙ v := by rw [vectorSpan_eq_span_vsub_set_right k h, Submodule.span_le, Set.subset_def] intro x hx rw [SetLike.mem_coe, Submodule.mem_span_singleton] rw [Set.mem_image] at hx rcases hx with ⟨p, hp, rfl⟩ rcases hp₀v p hp with ⟨r, rfl⟩ use r simp [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₀ : P h : p₀ ∈ s v : V hp₀v : ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₀ w : V hw : w ∈ vectorSpan k s ⊢ vectorSpan k s ≤ Submodule.span k {v} [PROOFSTEP] rw [vectorSpan_eq_span_vsub_set_right k h, Submodule.span_le, Set.subset_def] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₀ : P h : p₀ ∈ s v : V hp₀v : ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₀ w : V hw : w ∈ vectorSpan k s ⊢ ∀ (x : V), x ∈ (fun x => x -ᵥ p₀) '' s → x ∈ ↑(Submodule.span k {v}) [PROOFSTEP] intro x hx [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₀ : P h : p₀ ∈ s v : V hp₀v : ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₀ w : V hw : w ∈ vectorSpan k s x : V hx : x ∈ (fun x => x -ᵥ p₀) '' s ⊢ x ∈ ↑(Submodule.span k {v}) [PROOFSTEP] rw [SetLike.mem_coe, Submodule.mem_span_singleton] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₀ : P h : p₀ ∈ s v : V hp₀v : ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₀ w : V hw : w ∈ vectorSpan k s x : V hx : x ∈ (fun x => x -ᵥ p₀) '' s ⊢ ∃ a, a • v = x [PROOFSTEP] rw [Set.mem_image] at hx [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₀ : P h : p₀ ∈ s v : V hp₀v : ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₀ w : V hw : w ∈ vectorSpan k s x : V hx : ∃ x_1, x_1 ∈ s ∧ x_1 -ᵥ p₀ = x ⊢ ∃ a, a • v = x [PROOFSTEP] rcases hx with ⟨p, hp, rfl⟩ [GOAL] case intro.intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₀ : P h : p₀ ∈ s v : V hp₀v : ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₀ w : V hw : w ∈ vectorSpan k s p : P hp : p ∈ s ⊢ ∃ a, a • v = p -ᵥ p₀ [PROOFSTEP] rcases hp₀v p hp with ⟨r, rfl⟩ [GOAL] case intro.intro.intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₀ : P h : p₀ ∈ s v : V hp₀v : ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₀ w : V hw : w ∈ vectorSpan k s r : k hp : r • v +ᵥ p₀ ∈ s ⊢ ∃ a, a • v = r • v +ᵥ p₀ -ᵥ p₀ [PROOFSTEP] use r [GOAL] case h k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₀ : P h : p₀ ∈ s v : V hp₀v : ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₀ w : V hw : w ∈ vectorSpan k s r : k hp : r • v +ᵥ p₀ ∈ s ⊢ r • v = r • v +ᵥ p₀ -ᵥ p₀ [PROOFSTEP] simp [GOAL] case h k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₀ : P h : p₀ ∈ s v : V hp₀v : ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₀ w : V hw : w ∈ vectorSpan k s hs : vectorSpan k s ≤ Submodule.span k {v} ⊢ ∃ r, r • v = w [PROOFSTEP] have hw' := SetLike.le_def.1 hs hw [GOAL] case h k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₀ : P h : p₀ ∈ s v : V hp₀v : ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₀ w : V hw : w ∈ vectorSpan k s hs : vectorSpan k s ≤ Submodule.span k {v} hw' : w ∈ Submodule.span k {v} ⊢ ∃ r, r • v = w [PROOFSTEP] rwa [Submodule.mem_span_singleton] at hw' [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P ⊢ Collinear k s ↔ ∃ p₀ v, ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₀ [PROOFSTEP] rcases Set.eq_empty_or_nonempty s with (rfl | ⟨⟨p₁, hp₁⟩⟩) [GOAL] case inl k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P ⊢ Collinear k ∅ ↔ ∃ p₀ v, ∀ (p : P), p ∈ ∅ → ∃ r, p = r • v +ᵥ p₀ [PROOFSTEP] simp [collinear_empty] [GOAL] case inr.intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₁ : P hp₁ : p₁ ∈ s ⊢ Collinear k s ↔ ∃ p₀ v, ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₀ [PROOFSTEP] rw [collinear_iff_of_mem hp₁] [GOAL] case inr.intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₁ : P hp₁ : p₁ ∈ s ⊢ (∃ v, ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₁) ↔ ∃ p₀ v, ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₀ [PROOFSTEP] constructor [GOAL] case inr.intro.mp k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₁ : P hp₁ : p₁ ∈ s ⊢ (∃ v, ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₁) → ∃ p₀ v, ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₀ [PROOFSTEP] exact fun h => ⟨p₁, h⟩ [GOAL] case inr.intro.mpr k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₁ : P hp₁ : p₁ ∈ s ⊢ (∃ p₀ v, ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₀) → ∃ v, ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₁ [PROOFSTEP] rintro ⟨p, v, hv⟩ [GOAL] case inr.intro.mpr.intro.intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₁ : P hp₁ : p₁ ∈ s p : P v : V hv : ∀ (p_1 : P), p_1 ∈ s → ∃ r, p_1 = r • v +ᵥ p ⊢ ∃ v, ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₁ [PROOFSTEP] use v [GOAL] case h k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₁ : P hp₁ : p₁ ∈ s p : P v : V hv : ∀ (p_1 : P), p_1 ∈ s → ∃ r, p_1 = r • v +ᵥ p ⊢ ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₁ [PROOFSTEP] intro p₂ hp₂ [GOAL] case h k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₁ : P hp₁ : p₁ ∈ s p : P v : V hv : ∀ (p_1 : P), p_1 ∈ s → ∃ r, p_1 = r • v +ᵥ p p₂ : P hp₂ : p₂ ∈ s ⊢ ∃ r, p₂ = r • v +ᵥ p₁ [PROOFSTEP] rcases hv p₂ hp₂ with ⟨r, rfl⟩ [GOAL] case h.intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₁ : P hp₁ : p₁ ∈ s p : P v : V hv : ∀ (p_1 : P), p_1 ∈ s → ∃ r, p_1 = r • v +ᵥ p r : k hp₂ : r • v +ᵥ p ∈ s ⊢ ∃ r_1, r • v +ᵥ p = r_1 • v +ᵥ p₁ [PROOFSTEP] rcases hv p₁ hp₁ with ⟨r₁, rfl⟩ [GOAL] case h.intro.intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p : P v : V hv : ∀ (p_1 : P), p_1 ∈ s → ∃ r, p_1 = r • v +ᵥ p r : k hp₂ : r • v +ᵥ p ∈ s r₁ : k hp₁ : r₁ • v +ᵥ p ∈ s ⊢ ∃ r_1, r • v +ᵥ p = r_1 • v +ᵥ (r₁ • v +ᵥ p) [PROOFSTEP] use r - r₁ [GOAL] case h k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p : P v : V hv : ∀ (p_1 : P), p_1 ∈ s → ∃ r, p_1 = r • v +ᵥ p r : k hp₂ : r • v +ᵥ p ∈ s r₁ : k hp₁ : r₁ • v +ᵥ p ∈ s ⊢ r • v +ᵥ p = (r - r₁) • v +ᵥ (r₁ • v +ᵥ p) [PROOFSTEP] simp [vadd_vadd, ← add_smul] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ : P ⊢ Collinear k {p₁, p₂} [PROOFSTEP] rw [collinear_iff_exists_forall_eq_smul_vadd] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ : P ⊢ ∃ p₀ v, ∀ (p : P), p ∈ {p₁, p₂} → ∃ r, p = r • v +ᵥ p₀ [PROOFSTEP] use p₁, p₂ -ᵥ p₁ [GOAL] case h k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ : P ⊢ ∀ (p : P), p ∈ {p₁, p₂} → ∃ r, p = r • (p₂ -ᵥ p₁) +ᵥ p₁ [PROOFSTEP] intro p hp [GOAL] case h k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ p : P hp : p ∈ {p₁, p₂} ⊢ ∃ r, p = r • (p₂ -ᵥ p₁) +ᵥ p₁ [PROOFSTEP] rw [Set.mem_insert_iff, Set.mem_singleton_iff] at hp [GOAL] case h k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ p : P hp : p = p₁ ∨ p = p₂ ⊢ ∃ r, p = r • (p₂ -ᵥ p₁) +ᵥ p₁ [PROOFSTEP] cases' hp with hp hp [GOAL] case h.inl k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ p : P hp : p = p₁ ⊢ ∃ r, p = r • (p₂ -ᵥ p₁) +ᵥ p₁ [PROOFSTEP] use 0 [GOAL] case h k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ p : P hp : p = p₁ ⊢ p = 0 • (p₂ -ᵥ p₁) +ᵥ p₁ [PROOFSTEP] simp [hp] [GOAL] case h.inr k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ p : P hp : p = p₂ ⊢ ∃ r, p = r • (p₂ -ᵥ p₁) +ᵥ p₁ [PROOFSTEP] use 1 [GOAL] case h k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ p : P hp : p = p₂ ⊢ p = 1 • (p₂ -ᵥ p₁) +ᵥ p₁ [PROOFSTEP] simp [hp] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P ⊢ AffineIndependent k p ↔ ¬Collinear k (Set.range p) [PROOFSTEP] rw [collinear_iff_finrank_le_one, affineIndependent_iff_not_finrank_vectorSpan_le k p (Fintype.card_fin 3)] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P ⊢ Collinear k (Set.range p) ↔ ¬AffineIndependent k p [PROOFSTEP] rw [collinear_iff_finrank_le_one, finrank_vectorSpan_le_iff_not_affineIndependent k p (Fintype.card_fin 3)] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ p₃ : P ⊢ AffineIndependent k ![p₁, p₂, p₃] ↔ ¬Collinear k {p₁, p₂, p₃} [PROOFSTEP] rw [affineIndependent_iff_not_collinear] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ p₃ : P ⊢ ¬Collinear k (Set.range ![p₁, p₂, p₃]) ↔ ¬Collinear k {p₁, p₂, p₃} [PROOFSTEP] simp_rw [Matrix.range_cons, Matrix.range_empty, Set.singleton_union, insert_emptyc_eq] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P i₁ i₂ i₃ : Fin 3 h₁₂ : i₁ ≠ i₂ h₁₃ : i₁ ≠ i₃ h₂₃ : i₂ ≠ i₃ ⊢ AffineIndependent k p ↔ ¬Collinear k {p i₁, p i₂, p i₃} [PROOFSTEP] have hu : (Finset.univ : Finset (Fin 3)) = { i₁, i₂, i₃ } := by -- Porting note: Originally `by decide!`fin_cases i₁ <;> fin_cases i₂ <;> fin_cases i₃ <;> simp only at h₁₂ h₁₃ h₂₃ ⊢ [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P i₁ i₂ i₃ : Fin 3 h₁₂ : i₁ ≠ i₂ h₁₃ : i₁ ≠ i₃ h₂₃ : i₂ ≠ i₃ ⊢ Finset.univ = {i₁, i₂, i₃} [PROOFSTEP] fin_cases i₁ [GOAL] case head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P i₂ i₃ : Fin 3 h₂₃ : i₂ ≠ i₃ h₁₂ : { val := 0, isLt := (_ : 0 < 3) } ≠ i₂ h₁₃ : { val := 0, isLt := (_ : 0 < 3) } ≠ i₃ ⊢ Finset.univ = {{ val := 0, isLt := (_ : 0 < 3) }, i₂, i₃} [PROOFSTEP] fin_cases i₂ [GOAL] case tail.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P i₂ i₃ : Fin 3 h₂₃ : i₂ ≠ i₃ h₁₂ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ i₂ h₁₃ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ i₃ ⊢ Finset.univ = {{ val := 1, isLt := (_ : (fun a => a < 3) 1) }, i₂, i₃} [PROOFSTEP] fin_cases i₂ [GOAL] case tail.tail.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P i₂ i₃ : Fin 3 h₂₃ : i₂ ≠ i₃ h₁₂ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ i₂ h₁₃ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ i₃ ⊢ Finset.univ = {{ val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }, i₂, i₃} [PROOFSTEP] fin_cases i₂ [GOAL] case head.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P i₃ : Fin 3 h₁₃ h₂₃ : { val := 0, isLt := (_ : 0 < 3) } ≠ i₃ h₁₂ : { val := 0, isLt := (_ : 0 < 3) } ≠ { val := 0, isLt := (_ : 0 < 3) } ⊢ Finset.univ = {{ val := 0, isLt := (_ : 0 < 3) }, { val := 0, isLt := (_ : 0 < 3) }, i₃} [PROOFSTEP] fin_cases i₃ [GOAL] case head.tail.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P i₃ : Fin 3 h₁₃ : { val := 0, isLt := (_ : 0 < 3) } ≠ i₃ h₂₃ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ i₃ h₁₂ : { val := 0, isLt := (_ : 0 < 3) } ≠ { val := 1, isLt := (_ : (fun a => a < 3) 1) } ⊢ Finset.univ = {{ val := 0, isLt := (_ : 0 < 3) }, { val := 1, isLt := (_ : (fun a => a < 3) 1) }, i₃} [PROOFSTEP] fin_cases i₃ [GOAL] case head.tail.tail.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P i₃ : Fin 3 h₁₃ : { val := 0, isLt := (_ : 0 < 3) } ≠ i₃ h₂₃ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ i₃ h₁₂ : { val := 0, isLt := (_ : 0 < 3) } ≠ { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ⊢ Finset.univ = {{ val := 0, isLt := (_ : 0 < 3) }, { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }, i₃} [PROOFSTEP] fin_cases i₃ [GOAL] case tail.head.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P i₃ : Fin 3 h₁₃ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ i₃ h₂₃ : { val := 0, isLt := (_ : 0 < 3) } ≠ i₃ h₁₂ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ { val := 0, isLt := (_ : 0 < 3) } ⊢ Finset.univ = {{ val := 1, isLt := (_ : (fun a => a < 3) 1) }, { val := 0, isLt := (_ : 0 < 3) }, i₃} [PROOFSTEP] fin_cases i₃ [GOAL] case tail.head.tail.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P i₃ : Fin 3 h₁₃ h₂₃ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ i₃ h₁₂ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ { val := 1, isLt := (_ : (fun a => a < 3) 1) } ⊢ Finset.univ = {{ val := 1, isLt := (_ : (fun a => a < 3) 1) }, { val := 1, isLt := (_ : (fun a => a < 3) 1) }, i₃} [PROOFSTEP] fin_cases i₃ [GOAL] case tail.head.tail.tail.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P i₃ : Fin 3 h₁₃ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ i₃ h₂₃ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ i₃ h₁₂ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ⊢ Finset.univ = {{ val := 1, isLt := (_ : (fun a => a < 3) 1) }, { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }, i₃} [PROOFSTEP] fin_cases i₃ [GOAL] case tail.tail.head.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P i₃ : Fin 3 h₁₃ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ i₃ h₂₃ : { val := 0, isLt := (_ : 0 < 3) } ≠ i₃ h₁₂ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ { val := 0, isLt := (_ : 0 < 3) } ⊢ Finset.univ = {{ val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }, { val := 0, isLt := (_ : 0 < 3) }, i₃} [PROOFSTEP] fin_cases i₃ [GOAL] case tail.tail.head.tail.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P i₃ : Fin 3 h₁₃ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ i₃ h₂₃ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ i₃ h₁₂ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ { val := 1, isLt := (_ : (fun a => a < 3) 1) } ⊢ Finset.univ = {{ val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }, { val := 1, isLt := (_ : (fun a => a < 3) 1) }, i₃} [PROOFSTEP] fin_cases i₃ [GOAL] case tail.tail.head.tail.tail.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P i₃ : Fin 3 h₁₃ h₂₃ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ i₃ h₁₂ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ⊢ Finset.univ = {{ val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }, { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }, i₃} [PROOFSTEP] fin_cases i₃ [GOAL] case head.head.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P h₁₂ h₁₃ h₂₃ : { val := 0, isLt := (_ : 0 < 3) } ≠ { val := 0, isLt := (_ : 0 < 3) } ⊢ Finset.univ = {{ val := 0, isLt := (_ : 0 < 3) }, { val := 0, isLt := (_ : 0 < 3) }, { val := 0, isLt := (_ : 0 < 3) }} [PROOFSTEP] simp only at h₁₂ h₁₃ h₂₃ ⊢ [GOAL] case head.head.tail.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P h₁₂ : { val := 0, isLt := (_ : 0 < 3) } ≠ { val := 0, isLt := (_ : 0 < 3) } h₁₃ h₂₃ : { val := 0, isLt := (_ : 0 < 3) } ≠ { val := 1, isLt := (_ : (fun a => a < 3) 1) } ⊢ Finset.univ = {{ val := 0, isLt := (_ : 0 < 3) }, { val := 0, isLt := (_ : 0 < 3) }, { val := 1, isLt := (_ : (fun a => a < 3) 1) }} [PROOFSTEP] simp only at h₁₂ h₁₃ h₂₃ ⊢ [GOAL] case head.head.tail.tail.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P h₁₂ : { val := 0, isLt := (_ : 0 < 3) } ≠ { val := 0, isLt := (_ : 0 < 3) } h₁₃ h₂₃ : { val := 0, isLt := (_ : 0 < 3) } ≠ { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ⊢ Finset.univ = {{ val := 0, isLt := (_ : 0 < 3) }, { val := 0, isLt := (_ : 0 < 3) }, { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }} [PROOFSTEP] simp only at h₁₂ h₁₃ h₂₃ ⊢ [GOAL] case head.tail.head.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P h₁₂ : { val := 0, isLt := (_ : 0 < 3) } ≠ { val := 1, isLt := (_ : (fun a => a < 3) 1) } h₁₃ : { val := 0, isLt := (_ : 0 < 3) } ≠ { val := 0, isLt := (_ : 0 < 3) } h₂₃ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ { val := 0, isLt := (_ : 0 < 3) } ⊢ Finset.univ = {{ val := 0, isLt := (_ : 0 < 3) }, { val := 1, isLt := (_ : (fun a => a < 3) 1) }, { val := 0, isLt := (_ : 0 < 3) }} [PROOFSTEP] simp only at h₁₂ h₁₃ h₂₃ ⊢ [GOAL] case head.tail.head.tail.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P h₁₂ h₁₃ : { val := 0, isLt := (_ : 0 < 3) } ≠ { val := 1, isLt := (_ : (fun a => a < 3) 1) } h₂₃ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ { val := 1, isLt := (_ : (fun a => a < 3) 1) } ⊢ Finset.univ = {{ val := 0, isLt := (_ : 0 < 3) }, { val := 1, isLt := (_ : (fun a => a < 3) 1) }, { val := 1, isLt := (_ : (fun a => a < 3) 1) }} [PROOFSTEP] simp only at h₁₂ h₁₃ h₂₃ ⊢ [GOAL] case head.tail.head.tail.tail.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P h₁₂ : { val := 0, isLt := (_ : 0 < 3) } ≠ { val := 1, isLt := (_ : (fun a => a < 3) 1) } h₁₃ : { val := 0, isLt := (_ : 0 < 3) } ≠ { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } h₂₃ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ⊢ Finset.univ = {{ val := 0, isLt := (_ : 0 < 3) }, { val := 1, isLt := (_ : (fun a => a < 3) 1) }, { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }} [PROOFSTEP] simp only at h₁₂ h₁₃ h₂₃ ⊢ [GOAL] case head.tail.tail.head.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P h₁₂ : { val := 0, isLt := (_ : 0 < 3) } ≠ { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } h₁₃ : { val := 0, isLt := (_ : 0 < 3) } ≠ { val := 0, isLt := (_ : 0 < 3) } h₂₃ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ { val := 0, isLt := (_ : 0 < 3) } ⊢ Finset.univ = {{ val := 0, isLt := (_ : 0 < 3) }, { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }, { val := 0, isLt := (_ : 0 < 3) }} [PROOFSTEP] simp only at h₁₂ h₁₃ h₂₃ ⊢ [GOAL] case head.tail.tail.head.tail.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P h₁₂ : { val := 0, isLt := (_ : 0 < 3) } ≠ { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } h₁₃ : { val := 0, isLt := (_ : 0 < 3) } ≠ { val := 1, isLt := (_ : (fun a => a < 3) 1) } h₂₃ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ { val := 1, isLt := (_ : (fun a => a < 3) 1) } ⊢ Finset.univ = {{ val := 0, isLt := (_ : 0 < 3) }, { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }, { val := 1, isLt := (_ : (fun a => a < 3) 1) }} [PROOFSTEP] simp only at h₁₂ h₁₃ h₂₃ ⊢ [GOAL] case head.tail.tail.head.tail.tail.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P h₁₂ h₁₃ : { val := 0, isLt := (_ : 0 < 3) } ≠ { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } h₂₃ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ⊢ Finset.univ = {{ val := 0, isLt := (_ : 0 < 3) }, { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }, { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }} [PROOFSTEP] simp only at h₁₂ h₁₃ h₂₃ ⊢ [GOAL] case tail.head.head.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P h₁₂ h₁₃ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ { val := 0, isLt := (_ : 0 < 3) } h₂₃ : { val := 0, isLt := (_ : 0 < 3) } ≠ { val := 0, isLt := (_ : 0 < 3) } ⊢ Finset.univ = {{ val := 1, isLt := (_ : (fun a => a < 3) 1) }, { val := 0, isLt := (_ : 0 < 3) }, { val := 0, isLt := (_ : 0 < 3) }} [PROOFSTEP] simp only at h₁₂ h₁₃ h₂₃ ⊢ [GOAL] case tail.head.head.tail.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P h₁₂ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ { val := 0, isLt := (_ : 0 < 3) } h₁₃ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ { val := 1, isLt := (_ : (fun a => a < 3) 1) } h₂₃ : { val := 0, isLt := (_ : 0 < 3) } ≠ { val := 1, isLt := (_ : (fun a => a < 3) 1) } ⊢ Finset.univ = {{ val := 1, isLt := (_ : (fun a => a < 3) 1) }, { val := 0, isLt := (_ : 0 < 3) }, { val := 1, isLt := (_ : (fun a => a < 3) 1) }} [PROOFSTEP] simp only at h₁₂ h₁₃ h₂₃ ⊢ [GOAL] case tail.head.head.tail.tail.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P h₁₂ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ { val := 0, isLt := (_ : 0 < 3) } h₁₃ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } h₂₃ : { val := 0, isLt := (_ : 0 < 3) } ≠ { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ⊢ Finset.univ = {{ val := 1, isLt := (_ : (fun a => a < 3) 1) }, { val := 0, isLt := (_ : 0 < 3) }, { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }} [PROOFSTEP] simp only at h₁₂ h₁₃ h₂₃ ⊢ [GOAL] case tail.head.tail.head.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P h₁₂ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ { val := 1, isLt := (_ : (fun a => a < 3) 1) } h₁₃ h₂₃ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ { val := 0, isLt := (_ : 0 < 3) } ⊢ Finset.univ = {{ val := 1, isLt := (_ : (fun a => a < 3) 1) }, { val := 1, isLt := (_ : (fun a => a < 3) 1) }, { val := 0, isLt := (_ : 0 < 3) }} [PROOFSTEP] simp only at h₁₂ h₁₃ h₂₃ ⊢ [GOAL] case tail.head.tail.head.tail.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P h₁₂ h₁₃ h₂₃ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ { val := 1, isLt := (_ : (fun a => a < 3) 1) } ⊢ Finset.univ = {{ val := 1, isLt := (_ : (fun a => a < 3) 1) }, { val := 1, isLt := (_ : (fun a => a < 3) 1) }, { val := 1, isLt := (_ : (fun a => a < 3) 1) }} [PROOFSTEP] simp only at h₁₂ h₁₃ h₂₃ ⊢ [GOAL] case tail.head.tail.head.tail.tail.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P h₁₂ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ { val := 1, isLt := (_ : (fun a => a < 3) 1) } h₁₃ h₂₃ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ⊢ Finset.univ = {{ val := 1, isLt := (_ : (fun a => a < 3) 1) }, { val := 1, isLt := (_ : (fun a => a < 3) 1) }, { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }} [PROOFSTEP] simp only at h₁₂ h₁₃ h₂₃ ⊢ [GOAL] case tail.head.tail.tail.head.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P h₁₂ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } h₁₃ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ { val := 0, isLt := (_ : 0 < 3) } h₂₃ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ { val := 0, isLt := (_ : 0 < 3) } ⊢ Finset.univ = {{ val := 1, isLt := (_ : (fun a => a < 3) 1) }, { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }, { val := 0, isLt := (_ : 0 < 3) }} [PROOFSTEP] simp only at h₁₂ h₁₃ h₂₃ ⊢ [GOAL] case tail.head.tail.tail.head.tail.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P h₁₂ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } h₁₃ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ { val := 1, isLt := (_ : (fun a => a < 3) 1) } h₂₃ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ { val := 1, isLt := (_ : (fun a => a < 3) 1) } ⊢ Finset.univ = {{ val := 1, isLt := (_ : (fun a => a < 3) 1) }, { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }, { val := 1, isLt := (_ : (fun a => a < 3) 1) }} [PROOFSTEP] simp only at h₁₂ h₁₃ h₂₃ ⊢ [GOAL] case tail.head.tail.tail.head.tail.tail.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P h₁₂ h₁₃ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } h₂₃ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ⊢ Finset.univ = {{ val := 1, isLt := (_ : (fun a => a < 3) 1) }, { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }, { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }} [PROOFSTEP] simp only at h₁₂ h₁₃ h₂₃ ⊢ [GOAL] case tail.tail.head.head.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P h₁₂ h₁₃ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ { val := 0, isLt := (_ : 0 < 3) } h₂₃ : { val := 0, isLt := (_ : 0 < 3) } ≠ { val := 0, isLt := (_ : 0 < 3) } ⊢ Finset.univ = {{ val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }, { val := 0, isLt := (_ : 0 < 3) }, { val := 0, isLt := (_ : 0 < 3) }} [PROOFSTEP] simp only at h₁₂ h₁₃ h₂₃ ⊢ [GOAL] case tail.tail.head.head.tail.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P h₁₂ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ { val := 0, isLt := (_ : 0 < 3) } h₁₃ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ { val := 1, isLt := (_ : (fun a => a < 3) 1) } h₂₃ : { val := 0, isLt := (_ : 0 < 3) } ≠ { val := 1, isLt := (_ : (fun a => a < 3) 1) } ⊢ Finset.univ = {{ val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }, { val := 0, isLt := (_ : 0 < 3) }, { val := 1, isLt := (_ : (fun a => a < 3) 1) }} [PROOFSTEP] simp only at h₁₂ h₁₃ h₂₃ ⊢ [GOAL] case tail.tail.head.head.tail.tail.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P h₁₂ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ { val := 0, isLt := (_ : 0 < 3) } h₁₃ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } h₂₃ : { val := 0, isLt := (_ : 0 < 3) } ≠ { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ⊢ Finset.univ = {{ val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }, { val := 0, isLt := (_ : 0 < 3) }, { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }} [PROOFSTEP] simp only at h₁₂ h₁₃ h₂₃ ⊢ [GOAL] case tail.tail.head.tail.head.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P h₁₂ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ { val := 1, isLt := (_ : (fun a => a < 3) 1) } h₁₃ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ { val := 0, isLt := (_ : 0 < 3) } h₂₃ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ { val := 0, isLt := (_ : 0 < 3) } ⊢ Finset.univ = {{ val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }, { val := 1, isLt := (_ : (fun a => a < 3) 1) }, { val := 0, isLt := (_ : 0 < 3) }} [PROOFSTEP] simp only at h₁₂ h₁₃ h₂₃ ⊢ [GOAL] case tail.tail.head.tail.head.tail.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P h₁₂ h₁₃ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ { val := 1, isLt := (_ : (fun a => a < 3) 1) } h₂₃ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ { val := 1, isLt := (_ : (fun a => a < 3) 1) } ⊢ Finset.univ = {{ val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }, { val := 1, isLt := (_ : (fun a => a < 3) 1) }, { val := 1, isLt := (_ : (fun a => a < 3) 1) }} [PROOFSTEP] simp only at h₁₂ h₁₃ h₂₃ ⊢ [GOAL] case tail.tail.head.tail.head.tail.tail.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P h₁₂ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ { val := 1, isLt := (_ : (fun a => a < 3) 1) } h₁₃ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } h₂₃ : { val := 1, isLt := (_ : (fun a => a < 3) 1) } ≠ { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ⊢ Finset.univ = {{ val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }, { val := 1, isLt := (_ : (fun a => a < 3) 1) }, { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }} [PROOFSTEP] simp only at h₁₂ h₁₃ h₂₃ ⊢ [GOAL] case tail.tail.head.tail.tail.head.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P h₁₂ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } h₁₃ h₂₃ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ { val := 0, isLt := (_ : 0 < 3) } ⊢ Finset.univ = {{ val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }, { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }, { val := 0, isLt := (_ : 0 < 3) }} [PROOFSTEP] simp only at h₁₂ h₁₃ h₂₃ ⊢ [GOAL] case tail.tail.head.tail.tail.head.tail.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P h₁₂ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } h₁₃ h₂₃ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ { val := 1, isLt := (_ : (fun a => a < 3) 1) } ⊢ Finset.univ = {{ val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }, { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }, { val := 1, isLt := (_ : (fun a => a < 3) 1) }} [PROOFSTEP] simp only at h₁₂ h₁₃ h₂₃ ⊢ [GOAL] case tail.tail.head.tail.tail.head.tail.tail.head k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P h₁₂ h₁₃ h₂₃ : { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ≠ { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) } ⊢ Finset.univ = {{ val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }, { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }, { val := 2, isLt := (_ : (fun a => (fun a => a < 3) a) 2) }} [PROOFSTEP] simp only at h₁₂ h₁₃ h₂₃ ⊢ [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p : Fin 3 → P i₁ i₂ i₃ : Fin 3 h₁₂ : i₁ ≠ i₂ h₁₃ : i₁ ≠ i₃ h₂₃ : i₂ ≠ i₃ hu : Finset.univ = {i₁, i₂, i₃} ⊢ AffineIndependent k p ↔ ¬Collinear k {p i₁, p i₂, p i₃} [PROOFSTEP] rw [affineIndependent_iff_not_collinear, ← Set.image_univ, ← Finset.coe_univ, hu, Finset.coe_insert, Finset.coe_insert, Finset.coe_singleton, Set.image_insert_eq, Set.image_pair] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ p₃ : P h : ¬Collinear k {p₁, p₂, p₃} ⊢ p₁ ≠ p₂ [PROOFSTEP] rintro rfl [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₃ : P h : ¬Collinear k {p₁, p₁, p₃} ⊢ False [PROOFSTEP] simp [collinear_pair] at h [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ p₃ : P h : ¬Collinear k {p₁, p₂, p₃} ⊢ p₁ ≠ p₃ [PROOFSTEP] rintro rfl [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ : P h : ¬Collinear k {p₁, p₂, p₁} ⊢ False [PROOFSTEP] simp [collinear_pair] at h [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ p₃ : P h : ¬Collinear k {p₁, p₂, p₃} ⊢ p₂ ≠ p₃ [PROOFSTEP] rintro rfl [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ : P h : ¬Collinear k {p₁, p₂, p₂} ⊢ False [PROOFSTEP] simp [collinear_pair] at h [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P h : Collinear k s p₁ p₂ p₃ : P hp₁ : p₁ ∈ s hp₂ : p₂ ∈ s hp₃ : p₃ ∈ s hp₁p₂ : p₁ ≠ p₂ ⊢ p₃ ∈ affineSpan k {p₁, p₂} [PROOFSTEP] rw [collinear_iff_of_mem hp₁] at h [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₁ : P h : ∃ v, ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₁ p₂ p₃ : P hp₁ : p₁ ∈ s hp₂ : p₂ ∈ s hp₃ : p₃ ∈ s hp₁p₂ : p₁ ≠ p₂ ⊢ p₃ ∈ affineSpan k {p₁, p₂} [PROOFSTEP] rcases h with ⟨v, h⟩ [GOAL] case intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₁ p₂ p₃ : P hp₁ : p₁ ∈ s hp₂ : p₂ ∈ s hp₃ : p₃ ∈ s hp₁p₂ : p₁ ≠ p₂ v : V h : ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₁ ⊢ p₃ ∈ affineSpan k {p₁, p₂} [PROOFSTEP] rcases h p₂ hp₂ with ⟨r₂, rfl⟩ [GOAL] case intro.intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₁ p₃ : P hp₁ : p₁ ∈ s hp₃ : p₃ ∈ s v : V h : ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₁ r₂ : k hp₂ : r₂ • v +ᵥ p₁ ∈ s hp₁p₂ : p₁ ≠ r₂ • v +ᵥ p₁ ⊢ p₃ ∈ affineSpan k {p₁, r₂ • v +ᵥ p₁} [PROOFSTEP] rcases h p₃ hp₃ with ⟨r₃, rfl⟩ [GOAL] case intro.intro.intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₁ : P hp₁ : p₁ ∈ s v : V h : ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₁ r₂ : k hp₂ : r₂ • v +ᵥ p₁ ∈ s hp₁p₂ : p₁ ≠ r₂ • v +ᵥ p₁ r₃ : k hp₃ : r₃ • v +ᵥ p₁ ∈ s ⊢ r₃ • v +ᵥ p₁ ∈ affineSpan k {p₁, r₂ • v +ᵥ p₁} [PROOFSTEP] rw [vadd_left_mem_affineSpan_pair] [GOAL] case intro.intro.intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₁ : P hp₁ : p₁ ∈ s v : V h : ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₁ r₂ : k hp₂ : r₂ • v +ᵥ p₁ ∈ s hp₁p₂ : p₁ ≠ r₂ • v +ᵥ p₁ r₃ : k hp₃ : r₃ • v +ᵥ p₁ ∈ s ⊢ ∃ r, r • (r₂ • v +ᵥ p₁ -ᵥ p₁) = r₃ • v [PROOFSTEP] refine' ⟨r₃ / r₂, _⟩ [GOAL] case intro.intro.intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₁ : P hp₁ : p₁ ∈ s v : V h : ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₁ r₂ : k hp₂ : r₂ • v +ᵥ p₁ ∈ s hp₁p₂ : p₁ ≠ r₂ • v +ᵥ p₁ r₃ : k hp₃ : r₃ • v +ᵥ p₁ ∈ s ⊢ (r₃ / r₂) • (r₂ • v +ᵥ p₁ -ᵥ p₁) = r₃ • v [PROOFSTEP] have h₂ : r₂ ≠ 0 := by rintro rfl simp at hp₁p₂ [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₁ : P hp₁ : p₁ ∈ s v : V h : ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₁ r₂ : k hp₂ : r₂ • v +ᵥ p₁ ∈ s hp₁p₂ : p₁ ≠ r₂ • v +ᵥ p₁ r₃ : k hp₃ : r₃ • v +ᵥ p₁ ∈ s ⊢ r₂ ≠ 0 [PROOFSTEP] rintro rfl [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₁ : P hp₁ : p₁ ∈ s v : V h : ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₁ r₃ : k hp₃ : r₃ • v +ᵥ p₁ ∈ s hp₂ : 0 • v +ᵥ p₁ ∈ s hp₁p₂ : p₁ ≠ 0 • v +ᵥ p₁ ⊢ False [PROOFSTEP] simp at hp₁p₂ [GOAL] case intro.intro.intro k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p₁ : P hp₁ : p₁ ∈ s v : V h : ∀ (p : P), p ∈ s → ∃ r, p = r • v +ᵥ p₁ r₂ : k hp₂ : r₂ • v +ᵥ p₁ ∈ s hp₁p₂ : p₁ ≠ r₂ • v +ᵥ p₁ r₃ : k hp₃ : r₃ • v +ᵥ p₁ ∈ s h₂ : r₂ ≠ 0 ⊢ (r₃ / r₂) • (r₂ • v +ᵥ p₁ -ᵥ p₁) = r₃ • v [PROOFSTEP] simp [smul_smul, h₂] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P h : Collinear k s p₁ p₂ p₃ : P hp₂ : p₂ ∈ s hp₃ : p₃ ∈ s hp₂p₃ : p₂ ≠ p₃ ⊢ Collinear k (insert p₁ s) ↔ Collinear k {p₁, p₂, p₃} [PROOFSTEP] have hv : vectorSpan k (insert p₁ s) = vectorSpan k ({ p₁, p₂, p₃ } : Set P) := by -- Porting note: Original proof used `conv_lhs` and `conv_rhs`, but these tactics timed out. rw [← direction_affineSpan, ← affineSpan_insert_affineSpan] symm rw [← direction_affineSpan, ← affineSpan_insert_affineSpan, h.affineSpan_eq_of_ne hp₂ hp₃ hp₂p₃] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P h : Collinear k s p₁ p₂ p₃ : P hp₂ : p₂ ∈ s hp₃ : p₃ ∈ s hp₂p₃ : p₂ ≠ p₃ ⊢ vectorSpan k (insert p₁ s) = vectorSpan k {p₁, p₂, p₃} [PROOFSTEP] rw [← direction_affineSpan, ← affineSpan_insert_affineSpan] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P h : Collinear k s p₁ p₂ p₃ : P hp₂ : p₂ ∈ s hp₃ : p₃ ∈ s hp₂p₃ : p₂ ≠ p₃ ⊢ direction (affineSpan k (insert p₁ ↑(affineSpan k s))) = vectorSpan k {p₁, p₂, p₃} [PROOFSTEP] symm [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P h : Collinear k s p₁ p₂ p₃ : P hp₂ : p₂ ∈ s hp₃ : p₃ ∈ s hp₂p₃ : p₂ ≠ p₃ ⊢ vectorSpan k {p₁, p₂, p₃} = direction (affineSpan k (insert p₁ ↑(affineSpan k s))) [PROOFSTEP] rw [← direction_affineSpan, ← affineSpan_insert_affineSpan, h.affineSpan_eq_of_ne hp₂ hp₃ hp₂p₃] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P h : Collinear k s p₁ p₂ p₃ : P hp₂ : p₂ ∈ s hp₃ : p₃ ∈ s hp₂p₃ : p₂ ≠ p₃ hv : vectorSpan k (insert p₁ s) = vectorSpan k {p₁, p₂, p₃} ⊢ Collinear k (insert p₁ s) ↔ Collinear k {p₁, p₂, p₃} [PROOFSTEP] rw [Collinear, Collinear, hv] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p : P h : p ∈ affineSpan k s ⊢ Collinear k (insert p s) ↔ Collinear k s [PROOFSTEP] rw [Collinear, Collinear, vectorSpan_insert_eq_vectorSpan h] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ p₃ : P h : p₁ ∈ affineSpan k {p₂, p₃} ⊢ Collinear k {p₁, p₂, p₃} [PROOFSTEP] rw [collinear_insert_iff_of_mem_affineSpan h] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ p₃ : P h : p₁ ∈ affineSpan k {p₂, p₃} ⊢ Collinear k {p₂, p₃} [PROOFSTEP] exact collinear_pair _ _ _ [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ p₃ p₄ : P h₁ : p₁ ∈ affineSpan k {p₃, p₄} h₂ : p₂ ∈ affineSpan k {p₃, p₄} ⊢ Collinear k {p₁, p₂, p₃, p₄} [PROOFSTEP] rw [collinear_insert_iff_of_mem_affineSpan ((AffineSubspace.le_def' _ _).1 (affineSpan_mono k (Set.subset_insert _ _)) _ h₁), collinear_insert_iff_of_mem_affineSpan h₂] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ p₃ p₄ : P h₁ : p₁ ∈ affineSpan k {p₃, p₄} h₂ : p₂ ∈ affineSpan k {p₃, p₄} ⊢ Collinear k {p₃, p₄} [PROOFSTEP] exact collinear_pair _ _ _ [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ p₃ p₄ p₅ : P h₁ : p₁ ∈ affineSpan k {p₄, p₅} h₂ : p₂ ∈ affineSpan k {p₄, p₅} h₃ : p₃ ∈ affineSpan k {p₄, p₅} ⊢ Collinear k {p₁, p₂, p₃, p₄, p₅} [PROOFSTEP] rw [collinear_insert_iff_of_mem_affineSpan ((AffineSubspace.le_def' _ _).1 (affineSpan_mono k ((Set.subset_insert _ _).trans (Set.subset_insert _ _))) _ h₁), collinear_insert_iff_of_mem_affineSpan ((AffineSubspace.le_def' _ _).1 (affineSpan_mono k (Set.subset_insert _ _)) _ h₂), collinear_insert_iff_of_mem_affineSpan h₃] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ p₃ p₄ p₅ : P h₁ : p₁ ∈ affineSpan k {p₄, p₅} h₂ : p₂ ∈ affineSpan k {p₄, p₅} h₃ : p₃ ∈ affineSpan k {p₄, p₅} ⊢ Collinear k {p₄, p₅} [PROOFSTEP] exact collinear_pair _ _ _ [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ p₃ p₄ p₅ : P h₁ : p₁ ∈ affineSpan k {p₄, p₅} h₂ : p₂ ∈ affineSpan k {p₄, p₅} h₃ : p₃ ∈ affineSpan k {p₄, p₅} ⊢ Collinear k {p₁, p₂, p₃, p₄} [PROOFSTEP] refine' (collinear_insert_insert_insert_of_mem_affineSpan_pair h₁ h₂ h₃).subset _ [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ p₃ p₄ p₅ : P h₁ : p₁ ∈ affineSpan k {p₄, p₅} h₂ : p₂ ∈ affineSpan k {p₄, p₅} h₃ : p₃ ∈ affineSpan k {p₄, p₅} ⊢ {p₁, p₂, p₃, p₄} ⊆ {p₁, p₂, p₃, p₄, p₅} [PROOFSTEP] repeat apply Set.insert_subset_insert [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ p₃ p₄ p₅ : P h₁ : p₁ ∈ affineSpan k {p₄, p₅} h₂ : p₂ ∈ affineSpan k {p₄, p₅} h₃ : p₃ ∈ affineSpan k {p₄, p₅} ⊢ {p₁, p₂, p₃, p₄} ⊆ {p₁, p₂, p₃, p₄, p₅} [PROOFSTEP] apply Set.insert_subset_insert [GOAL] case h k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ p₃ p₄ p₅ : P h₁ : p₁ ∈ affineSpan k {p₄, p₅} h₂ : p₂ ∈ affineSpan k {p₄, p₅} h₃ : p₃ ∈ affineSpan k {p₄, p₅} ⊢ {p₂, p₃, p₄} ⊆ {p₂, p₃, p₄, p₅} [PROOFSTEP] apply Set.insert_subset_insert [GOAL] case h.h k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ p₃ p₄ p₅ : P h₁ : p₁ ∈ affineSpan k {p₄, p₅} h₂ : p₂ ∈ affineSpan k {p₄, p₅} h₃ : p₃ ∈ affineSpan k {p₄, p₅} ⊢ {p₃, p₄} ⊆ {p₃, p₄, p₅} [PROOFSTEP] apply Set.insert_subset_insert [GOAL] case h.h.h k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ p₃ p₄ p₅ : P h₁ : p₁ ∈ affineSpan k {p₄, p₅} h₂ : p₂ ∈ affineSpan k {p₄, p₅} h₃ : p₃ ∈ affineSpan k {p₄, p₅} ⊢ {p₄} ⊆ {p₄, p₅} [PROOFSTEP] apply Set.insert_subset_insert [GOAL] case h.h.h k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ p₃ p₄ p₅ : P h₁ : p₁ ∈ affineSpan k {p₄, p₅} h₂ : p₂ ∈ affineSpan k {p₄, p₅} h₃ : p₃ ∈ affineSpan k {p₄, p₅} ⊢ {p₄} ⊆ {p₄, p₅} [PROOFSTEP] simp [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ p₃ p₄ p₅ : P h₁ : p₁ ∈ affineSpan k {p₄, p₅} h₂ : p₂ ∈ affineSpan k {p₄, p₅} h₃ : p₃ ∈ affineSpan k {p₄, p₅} ⊢ Collinear k {p₁, p₂, p₃} [PROOFSTEP] refine' (collinear_insert_insert_insert_left_of_mem_affineSpan_pair h₁ h₂ h₃).subset _ [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P p₁ p₂ p₃ p₄ p₅ : P h₁ : p₁ ∈ affineSpan k {p₄, p₅} h₂ : p₂ ∈ affineSpan k {p₄, p₅} h₃ : p₃ ∈ affineSpan k {p₄, p₅} ⊢ {p₁, p₂, p₃} ⊆ {p₁, p₂, p₃, p₄} [PROOFSTEP] simp [Set.insert_subset_insert] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P h : Coplanar k s ⊢ FiniteDimensional k { x // x ∈ vectorSpan k s } [PROOFSTEP] refine' IsNoetherian.iff_fg.1 (IsNoetherian.iff_rank_lt_aleph0.2 (lt_of_le_of_lt h _)) [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P h : Coplanar k s ⊢ 2 < Cardinal.aleph0 [PROOFSTEP] exact Cardinal.lt_aleph0.2 ⟨2, rfl⟩ [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P s : Set P inst✝ : FiniteDimensional k { x // x ∈ vectorSpan k s } ⊢ Coplanar k s ↔ finrank k { x // x ∈ vectorSpan k s } ≤ 2 [PROOFSTEP] have h : Coplanar k s ↔ Module.rank k (vectorSpan k s) ≤ 2 := Iff.rfl [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P s : Set P inst✝ : FiniteDimensional k { x // x ∈ vectorSpan k s } h : Coplanar k s ↔ Module.rank k { x // x ∈ vectorSpan k s } ≤ 2 ⊢ Coplanar k s ↔ finrank k { x // x ∈ vectorSpan k s } ≤ 2 [PROOFSTEP] rw [← finrank_eq_rank] at h [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝⁴ : DivisionRing k inst✝³ : AddCommGroup V inst✝² : Module k V inst✝¹ : AffineSpace V P s : Set P inst✝ : FiniteDimensional k { x // x ∈ vectorSpan k s } h : Coplanar k s ↔ ↑(finrank k { x // x ∈ vectorSpan k s }) ≤ 2 ⊢ Coplanar k s ↔ finrank k { x // x ∈ vectorSpan k s } ≤ 2 [PROOFSTEP] exact_mod_cast h [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 ι : Type u_4 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p : P h : p ∈ affineSpan k s ⊢ Coplanar k (insert p s) ↔ Coplanar k s [PROOFSTEP] rw [Coplanar, Coplanar, vectorSpan_insert_eq_vectorSpan h] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P ⊢ finrank k { x // x ∈ vectorSpan k (insert p ↑s) } ≤ finrank k { x // x ∈ direction s } + 1 [PROOFSTEP] by_cases hf : FiniteDimensional k s.direction [GOAL] case pos k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf : FiniteDimensional k { x // x ∈ direction s } ⊢ finrank k { x // x ∈ vectorSpan k (insert p ↑s) } ≤ finrank k { x // x ∈ direction s } + 1 case neg k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf : ¬FiniteDimensional k { x // x ∈ direction s } ⊢ finrank k { x // x ∈ vectorSpan k (insert p ↑s) } ≤ finrank k { x // x ∈ direction s } + 1 [PROOFSTEP] swap [GOAL] case neg k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf : ¬FiniteDimensional k { x // x ∈ direction s } ⊢ finrank k { x // x ∈ vectorSpan k (insert p ↑s) } ≤ finrank k { x // x ∈ direction s } + 1 [PROOFSTEP] have hf' : ¬FiniteDimensional k (vectorSpan k (insert p (s : Set P))) := by intro h have h' : s.direction ≤ vectorSpan k (insert p (s : Set P)) := by conv_lhs => rw [← affineSpan_coe s, direction_affineSpan] exact vectorSpan_mono k (Set.subset_insert _ _) exact hf (Submodule.finiteDimensional_of_le h') [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf : ¬FiniteDimensional k { x // x ∈ direction s } ⊢ ¬FiniteDimensional k { x // x ∈ vectorSpan k (insert p ↑s) } [PROOFSTEP] intro h [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf : ¬FiniteDimensional k { x // x ∈ direction s } h : FiniteDimensional k { x // x ∈ vectorSpan k (insert p ↑s) } ⊢ False [PROOFSTEP] have h' : s.direction ≤ vectorSpan k (insert p (s : Set P)) := by conv_lhs => rw [← affineSpan_coe s, direction_affineSpan] exact vectorSpan_mono k (Set.subset_insert _ _) [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf : ¬FiniteDimensional k { x // x ∈ direction s } h : FiniteDimensional k { x // x ∈ vectorSpan k (insert p ↑s) } ⊢ direction s ≤ vectorSpan k (insert p ↑s) [PROOFSTEP] conv_lhs => rw [← affineSpan_coe s, direction_affineSpan] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf : ¬FiniteDimensional k { x // x ∈ direction s } h : FiniteDimensional k { x // x ∈ vectorSpan k (insert p ↑s) } | direction s [PROOFSTEP] rw [← affineSpan_coe s, direction_affineSpan] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf : ¬FiniteDimensional k { x // x ∈ direction s } h : FiniteDimensional k { x // x ∈ vectorSpan k (insert p ↑s) } | direction s [PROOFSTEP] rw [← affineSpan_coe s, direction_affineSpan] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf : ¬FiniteDimensional k { x // x ∈ direction s } h : FiniteDimensional k { x // x ∈ vectorSpan k (insert p ↑s) } | direction s [PROOFSTEP] rw [← affineSpan_coe s, direction_affineSpan] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf : ¬FiniteDimensional k { x // x ∈ direction s } h : FiniteDimensional k { x // x ∈ vectorSpan k (insert p ↑s) } ⊢ vectorSpan k ↑s ≤ vectorSpan k (insert p ↑s) [PROOFSTEP] exact vectorSpan_mono k (Set.subset_insert _ _) [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf : ¬FiniteDimensional k { x // x ∈ direction s } h : FiniteDimensional k { x // x ∈ vectorSpan k (insert p ↑s) } h' : direction s ≤ vectorSpan k (insert p ↑s) ⊢ False [PROOFSTEP] exact hf (Submodule.finiteDimensional_of_le h') [GOAL] case neg k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf : ¬FiniteDimensional k { x // x ∈ direction s } hf' : ¬FiniteDimensional k { x // x ∈ vectorSpan k (insert p ↑s) } ⊢ finrank k { x // x ∈ vectorSpan k (insert p ↑s) } ≤ finrank k { x // x ∈ direction s } + 1 [PROOFSTEP] rw [finrank_of_infinite_dimensional hf, finrank_of_infinite_dimensional hf', zero_add] [GOAL] case neg k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf : ¬FiniteDimensional k { x // x ∈ direction s } hf' : ¬FiniteDimensional k { x // x ∈ vectorSpan k (insert p ↑s) } ⊢ 0 ≤ 1 [PROOFSTEP] exact zero_le_one [GOAL] case pos k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf : FiniteDimensional k { x // x ∈ direction s } ⊢ finrank k { x // x ∈ vectorSpan k (insert p ↑s) } ≤ finrank k { x // x ∈ direction s } + 1 [PROOFSTEP] have : FiniteDimensional k s.direction := hf [GOAL] case pos k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf this : FiniteDimensional k { x // x ∈ direction s } ⊢ finrank k { x // x ∈ vectorSpan k (insert p ↑s) } ≤ finrank k { x // x ∈ direction s } + 1 [PROOFSTEP] rw [← direction_affineSpan, ← affineSpan_insert_affineSpan] [GOAL] case pos k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf this : FiniteDimensional k { x // x ∈ direction s } ⊢ finrank k { x // x ∈ direction (affineSpan k (insert p ↑(affineSpan k ↑s))) } ≤ finrank k { x // x ∈ direction s } + 1 [PROOFSTEP] rcases(s : Set P).eq_empty_or_nonempty with (hs | ⟨p₀, hp₀⟩) [GOAL] case pos.inl k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf this : FiniteDimensional k { x // x ∈ direction s } hs : ↑s = ∅ ⊢ finrank k { x // x ∈ direction (affineSpan k (insert p ↑(affineSpan k ↑s))) } ≤ finrank k { x // x ∈ direction s } + 1 [PROOFSTEP] rw [coe_eq_bot_iff] at hs [GOAL] case pos.inl k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf this : FiniteDimensional k { x // x ∈ direction s } hs : s = ⊥ ⊢ finrank k { x // x ∈ direction (affineSpan k (insert p ↑(affineSpan k ↑s))) } ≤ finrank k { x // x ∈ direction s } + 1 [PROOFSTEP] rw [hs, bot_coe, span_empty, bot_coe, direction_affineSpan, direction_bot, finrank_bot, zero_add] [GOAL] case pos.inl k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf this : FiniteDimensional k { x // x ∈ direction s } hs : s = ⊥ ⊢ finrank k { x // x ∈ vectorSpan k (insert p ∅) } ≤ 1 [PROOFSTEP] convert zero_le_one' ℕ [GOAL] case h.e'_3 k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf this : FiniteDimensional k { x // x ∈ direction s } hs : s = ⊥ ⊢ finrank k { x // x ∈ vectorSpan k (insert p ∅) } = 0 [PROOFSTEP] rw [← finrank_bot k V] [GOAL] case h.e'_3 k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf this : FiniteDimensional k { x // x ∈ direction s } hs : s = ⊥ ⊢ finrank k { x // x ∈ vectorSpan k (insert p ∅) } = finrank k { x // x ∈ ⊥ } [PROOFSTEP] convert rfl [GOAL] case h.e'_3.h.e'_2.h.e'_2.h.h.e'_5 k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf this : FiniteDimensional k { x // x ∈ direction s } hs : s = ⊥ x✝ : V ⊢ ⊥ = vectorSpan k (insert p ∅) [PROOFSTEP] simp [GOAL] case h.e'_3.h.e'_4.e'_6 k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf this : FiniteDimensional k { x // x ∈ direction s } hs : s = ⊥ e_2✝ : { x // x ∈ ⊥ } = { x // x ∈ vectorSpan k (insert p ∅) } ⊢ ⊥ = vectorSpan k (insert p ∅) [PROOFSTEP] simp [GOAL] case h.e'_3.h.e'_5.e'_6 k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf this : FiniteDimensional k { x // x ∈ direction s } hs : s = ⊥ e_2✝ : { x // x ∈ ⊥ } = { x // x ∈ vectorSpan k (insert p ∅) } e_3✝ : Ring.toSemiring = DivisionSemiring.toSemiring e_4✝ : HEq (Submodule.addCommGroup ⊥) (Submodule.addCommGroup (vectorSpan k (insert p ∅))) ⊢ ⊥ = vectorSpan k (insert p ∅) [PROOFSTEP] simp [GOAL] case pos.inr.intro k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf this : FiniteDimensional k { x // x ∈ direction s } p₀ : P hp₀ : p₀ ∈ ↑s ⊢ finrank k { x // x ∈ direction (affineSpan k (insert p ↑(affineSpan k ↑s))) } ≤ finrank k { x // x ∈ direction s } + 1 [PROOFSTEP] rw [affineSpan_coe, direction_affineSpan_insert hp₀, add_comm] [GOAL] case pos.inr.intro k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf this : FiniteDimensional k { x // x ∈ direction s } p₀ : P hp₀ : p₀ ∈ ↑s ⊢ finrank k { x // x ∈ Submodule.span k {p -ᵥ p₀} ⊔ direction s } ≤ 1 + finrank k { x // x ∈ direction s } [PROOFSTEP] refine' (Submodule.finrank_add_le_finrank_add_finrank _ _).trans (add_le_add_right _ _) [GOAL] case pos.inr.intro k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf this : FiniteDimensional k { x // x ∈ direction s } p₀ : P hp₀ : p₀ ∈ ↑s ⊢ finrank k { x // x ∈ Submodule.span k {p -ᵥ p₀} } ≤ 1 [PROOFSTEP] refine' finrank_le_one ⟨p -ᵥ p₀, Submodule.mem_span_singleton_self _⟩ fun v => _ [GOAL] case pos.inr.intro k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf this : FiniteDimensional k { x // x ∈ direction s } p₀ : P hp₀ : p₀ ∈ ↑s v : { x // x ∈ Submodule.span k {p -ᵥ p₀} } ⊢ ∃ c, c • { val := p -ᵥ p₀, property := (_ : p -ᵥ p₀ ∈ Submodule.span k {p -ᵥ p₀}) } = v [PROOFSTEP] have h := v.property [GOAL] case pos.inr.intro k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf this : FiniteDimensional k { x // x ∈ direction s } p₀ : P hp₀ : p₀ ∈ ↑s v : { x // x ∈ Submodule.span k {p -ᵥ p₀} } h : ↑v ∈ Submodule.span k {p -ᵥ p₀} ⊢ ∃ c, c • { val := p -ᵥ p₀, property := (_ : p -ᵥ p₀ ∈ Submodule.span k {p -ᵥ p₀}) } = v [PROOFSTEP] rw [Submodule.mem_span_singleton] at h [GOAL] case pos.inr.intro k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf this : FiniteDimensional k { x // x ∈ direction s } p₀ : P hp₀ : p₀ ∈ ↑s v : { x // x ∈ Submodule.span k {p -ᵥ p₀} } h : ∃ a, a • (p -ᵥ p₀) = ↑v ⊢ ∃ c, c • { val := p -ᵥ p₀, property := (_ : p -ᵥ p₀ ∈ Submodule.span k {p -ᵥ p₀}) } = v [PROOFSTEP] rcases h with ⟨c, hc⟩ [GOAL] case pos.inr.intro.intro k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf this : FiniteDimensional k { x // x ∈ direction s } p₀ : P hp₀ : p₀ ∈ ↑s v : { x // x ∈ Submodule.span k {p -ᵥ p₀} } c : k hc : c • (p -ᵥ p₀) = ↑v ⊢ ∃ c, c • { val := p -ᵥ p₀, property := (_ : p -ᵥ p₀ ∈ Submodule.span k {p -ᵥ p₀}) } = v [PROOFSTEP] refine' ⟨c, _⟩ [GOAL] case pos.inr.intro.intro k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf this : FiniteDimensional k { x // x ∈ direction s } p₀ : P hp₀ : p₀ ∈ ↑s v : { x // x ∈ Submodule.span k {p -ᵥ p₀} } c : k hc : c • (p -ᵥ p₀) = ↑v ⊢ c • { val := p -ᵥ p₀, property := (_ : p -ᵥ p₀ ∈ Submodule.span k {p -ᵥ p₀}) } = v [PROOFSTEP] ext [GOAL] case pos.inr.intro.intro.a k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : AffineSubspace k P p : P hf this : FiniteDimensional k { x // x ∈ direction s } p₀ : P hp₀ : p₀ ∈ ↑s v : { x // x ∈ Submodule.span k {p -ᵥ p₀} } c : k hc : c • (p -ᵥ p₀) = ↑v ⊢ ↑(c • { val := p -ᵥ p₀, property := (_ : p -ᵥ p₀ ∈ Submodule.span k {p -ᵥ p₀}) }) = ↑v [PROOFSTEP] exact hc [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p : P ⊢ finrank k { x // x ∈ vectorSpan k (insert p s) } ≤ finrank k { x // x ∈ vectorSpan k s } + 1 [PROOFSTEP] rw [← direction_affineSpan, ← affineSpan_insert_affineSpan, direction_affineSpan] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p : P ⊢ finrank k { x // x ∈ vectorSpan k (insert p ↑(affineSpan k s)) } ≤ finrank k { x // x ∈ vectorSpan k s } + 1 [PROOFSTEP] refine' (finrank_vectorSpan_insert_le _ _).trans (add_le_add_right _ _) [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P p : P ⊢ finrank k { x // x ∈ direction (affineSpan k s) } ≤ finrank k { x // x ∈ vectorSpan k s } [PROOFSTEP] rw [direction_affineSpan] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P h : Collinear k s p : P ⊢ Coplanar k (insert p s) [PROOFSTEP] have : FiniteDimensional k { x // x ∈ vectorSpan k s } := h.finiteDimensional_vectorSpan [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P h : Collinear k s p : P this : FiniteDimensional k { x // x ∈ vectorSpan k s } ⊢ Coplanar k (insert p s) [PROOFSTEP] rw [coplanar_iff_finrank_le_two] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P h : Collinear k s p : P this : FiniteDimensional k { x // x ∈ vectorSpan k s } ⊢ finrank k { x // x ∈ vectorSpan k (insert p s) } ≤ 2 [PROOFSTEP] exact (finrank_vectorSpan_insert_le_set k s p).trans (add_le_add_right h.finrank_le_one _) [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P h : finrank k V = 2 ⊢ Coplanar k s [PROOFSTEP] have : FiniteDimensional k V := finiteDimensional_of_finrank_eq_succ h [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P h : finrank k V = 2 this : FiniteDimensional k V ⊢ Coplanar k s [PROOFSTEP] rw [coplanar_iff_finrank_le_two, ← h] [GOAL] k : Type u_1 V : Type u_2 P : Type u_3 inst✝³ : DivisionRing k inst✝² : AddCommGroup V inst✝¹ : Module k V inst✝ : AffineSpace V P s : Set P h : finrank k V = 2 this : FiniteDimensional k V ⊢ finrank k { x // x ∈ vectorSpan k s } ≤ finrank k V [PROOFSTEP] exact Submodule.finrank_le _ [GOAL] ι : Type u₁ k : Type u₂ V : Type u₃ P : Type u₄ inst✝⁵ : AddCommGroup V inst✝⁴ : AffineSpace V P inst✝³ : DivisionRing k inst✝² : Module k V inst✝¹ : Fintype ι inst✝ : FiniteDimensional k V h : Fintype.card ι = FiniteDimensional.finrank k V + 1 ⊢ Nonempty (AffineBasis ι k P) [PROOFSTEP] obtain ⟨s, b, hb⟩ := AffineBasis.exists_affineBasis k V P [GOAL] case intro.intro ι : Type u₁ k : Type u₂ V : Type u₃ P : Type u₄ inst✝⁵ : AddCommGroup V inst✝⁴ : AffineSpace V P inst✝³ : DivisionRing k inst✝² : Module k V inst✝¹ : Fintype ι inst✝ : FiniteDimensional k V h : Fintype.card ι = FiniteDimensional.finrank k V + 1 s : Set P b : AffineBasis (↑s) k P hb : ↑b = Subtype.val ⊢ Nonempty (AffineBasis ι k P) [PROOFSTEP] lift s to Finset P using b.finite_set [GOAL] case intro.intro.intro ι : Type u₁ k : Type u₂ V : Type u₃ P : Type u₄ inst✝⁵ : AddCommGroup V inst✝⁴ : AffineSpace V P inst✝³ : DivisionRing k inst✝² : Module k V inst✝¹ : Fintype ι inst✝ : FiniteDimensional k V h : Fintype.card ι = FiniteDimensional.finrank k V + 1 s : Finset P b : AffineBasis (↑↑s) k P hb : ↑b = Subtype.val ⊢ Nonempty (AffineBasis ι k P) [PROOFSTEP] refine' ⟨b.reindex <| Fintype.equivOfCardEq _⟩ [GOAL] case intro.intro.intro ι : Type u₁ k : Type u₂ V : Type u₃ P : Type u₄ inst✝⁵ : AddCommGroup V inst✝⁴ : AffineSpace V P inst✝³ : DivisionRing k inst✝² : Module k V inst✝¹ : Fintype ι inst✝ : FiniteDimensional k V h : Fintype.card ι = FiniteDimensional.finrank k V + 1 s : Finset P b : AffineBasis (↑↑s) k P hb : ↑b = Subtype.val ⊢ Fintype.card ↑↑s = Fintype.card ι [PROOFSTEP] rw [h, ← b.card_eq_finrank_add_one]
% Test whether it is necessary to rotate VB PCA function nc2010_publish_datasets n = 200; m = 50; d = 10; ncomps = 30; randn('state', 1); rand('state', 1); % Generate multivariate normal data disp('Using weak subspace') eigs = (1 + [d:-1:1 zeros(1,m-d)]) .^ 2 datastring = 'weak'; plot_eigenvalues(eigs, datastring); disp('Using strong subspace') eigs = ([5*ones(1,d) 1*ones(1,m-d)]) .^ 2 datastring = 'strong'; plot_eigenvalues(eigs, datastring); disp('Using no subspace') eigs = (m:-1:1) .^ 2 datastring = 'no'; plot_eigenvalues(eigs, datastring); function plot_eigenvalues(eigs, datastring) filename = sprintf(['/home/jluttine/papers/neurocomputing2010/' ... 'fig_eigenvalues_dataset=%s'], datastring); figure plot(sqrt(eigs), 'k-'); set(gcf, 'units', 'centimeters', 'paperunits', 'centimeters'); pos = get(gcf, 'position'); set(gcf, 'position', [pos(1:2), 6,4]); pos = get(gcf, 'paperposition'); set(gcf, 'paperposition', [pos(1:2),6,4]) ylim([0, max(sqrt(eigs))+1]); xlim([1, length(eigs)]); %ylabel('standard deviation') print(gcf, '-depsc2', filename);
subroutine gather(n,a,b,indx) * * $Id$ * integer n, indx(n) double precision a(n),b(*) integer i do i=1,n a(i) = b(indx(i)) enddo return end
theory Extract_Certificate imports Worklist_Algorithms.Unified_PW_Impl Worklist_Algorithms.Next_Key DBM.DBM_Operations_Impl_Refine Worklist_Algorithms.Leadsto_Impl begin subsection \<open>Turning a map into a list\<close> definition list_of_map where "list_of_map m \<equiv> do { (xs, m) \<leftarrow> WHILEIT (\<lambda> (xs, m'). finite (dom m') \<and> m = m' ++ map_of xs \<and> dom m' \<inter> dom (map_of xs) = {}) (\<lambda> (_, m). Map.empty \<noteq> m) (\<lambda> (xs, m). do { k \<leftarrow> next_key m; let (x, m) = op_map_extract k m; ASSERT (x \<noteq> None); RETURN ((k, the x) # xs, m) } ) ([], m); RETURN xs } " context begin private definition "ran_of_map_var = (inv_image (measure (card o dom)) (\<lambda> (a, b). b))" private lemma wf_ran_of_map_var: "wf ran_of_map_var" unfolding ran_of_map_var_def by auto (* XXX Maybe move *) private lemma insert_restrict_ran: "insert v (ran (m |` (- {k}))) = ran m " if "m k = Some v" using that unfolding ran_def restrict_map_def by force private lemma 1: "(m |` (- {x}))(x \<mapsto> y) = m" if "m x = Some y" using that unfolding restrict_map_def by auto private lemma 2: "(m1 ++ m2)(x \<mapsto> y) = m1(x \<mapsto> y) ++ m2" if "x \<notin> dom m2" using that by auto lemma list_of_map_correct[refine]: "list_of_map m \<le> SPEC (\<lambda> r. map_of r = m)" if "finite (dom m)" using that unfolding list_of_map_def next_key_def apply (refine_vcg wf_ran_of_map_var) apply (clarsimp; fail)+ subgoal for s xs m' x v xs' xs1 xs'1 unfolding dom_def apply (clarsimp simp: map_upd_eq_restrict) apply (subst 2) apply auto apply (subst 1) apply auto done unfolding ran_of_map_var_def by (fastforce intro: card_Diff1_less split: if_split_asm)+ end \<comment> \<open>End of private context for auxiliary facts and definitions\<close> context fixes K :: "_ \<Rightarrow> _ :: {hashable, heap} \<Rightarrow> assn" assumes is_pure_K[safe_constraint_rules]: "is_pure K" and left_unique_K[safe_constraint_rules]: "IS_LEFT_UNIQUE (the_pure K)" and right_unique_K[safe_constraint_rules]: "IS_RIGHT_UNIQUE (the_pure K)" notes [sepref_fr_rules] = hm_it_next_key_next_key''[OF is_pure_K] begin sepref_definition list_of_map_impl is "list_of_map" :: "(hm.hms_assn' K A)\<^sup>d \<rightarrow>\<^sub>a (list_assn (K \<times>\<^sub>a A))" unfolding list_of_map_def hm.hms_assn'_id_hms_assn[symmetric] unfolding op_map_is_empty_def[symmetric] unfolding hm.hms_fold_custom_empty HOL_list.fold_custom_empty by sepref end (* Anonymous context for setup *) lemmas list_of_map_impl_code[code] = list_of_map_impl_def[of "pure Id", simplified, OF Sepref_Constraints.safe_constraint_rules(41)] context notes [sepref_fr_rules] = hm_it_next_key_next_key'[folded hm.hms_assn'_id_hms_assn] begin sepref_definition list_of_map_impl' is "list_of_map" :: "(hm.hms_assn A)\<^sup>d \<rightarrow>\<^sub>a (list_assn (id_assn \<times>\<^sub>a A))" unfolding list_of_map_def hm.hms_assn'_id_hms_assn[symmetric] unfolding op_map_is_empty_def[symmetric] unfolding hm.hms_fold_custom_empty HOL_list.fold_custom_empty by sepref end (* Anonymous context for setup *) context Worklist_Map2_Impl begin definition extract_certificate :: "_ nres" where "extract_certificate = do { (_, passed) \<leftarrow> pw_algo_map2; list_of_map passed }" context begin private definition "pw_algo_map2_copy = pw_algo_map2" sepref_register pw_algo_map2_copy lemma pw_algo_map2_copy_fold: "PR_CONST pw_algo_map2_copy = pw_algo_map2" unfolding pw_algo_map2_copy_def by simp lemmas [sepref_fr_rules] = pw_algo_map2_impl.refine_raw[folded pw_algo_map2_copy_fold] list_of_map_impl.refine[OF pure_K left_unique_K right_unique_K] sepref_thm extract_certificate_impl is "uncurry0 extract_certificate" :: "unit_assn\<^sup>k \<rightarrow>\<^sub>a (list_assn (K \<times>\<^sub>a lso_assn A))" unfolding extract_certificate_def pw_algo_map2_copy_def[symmetric] by sepref end end concrete_definition extract_certificate_impl uses Worklist_Map2_Impl.extract_certificate_impl.refine_raw print_theorems end