import vorspiel binary_recursion init.algebra.order tactic.omega.main

universes u v

attribute [simp] pi.smul_apply

namespace landau_notation

variables (α : Type u) [has_mul α] [linear_order α]

def eventually (p : ℕ → Prop) : Prop := ∃ n : ℕ, ∀ m ≥ n, p m

local notation `Eventually` binders `, ` r:(scoped p, eventually p) := r

def frequently (p : ℕ → Prop) : Prop := ∀ n : ℕ, ∃ m ≥ n, p m

local notation `Frequently` binders `, ` r:(scoped p, frequently p) := r

lemma eventually_def (p : ℕ → Prop) : (Eventually x, p x) ↔ (∃ n : ℕ, ∀ m ≥ n, p m) := by refl

@[simp] lemma eventually_true : Eventually x, true :=
⟨0, by simp⟩

lemma eventually_of_all (p : ℕ → Prop) (h : ∀ x, p x) : Eventually x, p x := ⟨0, λ m _, h m⟩

lemma eventually_and {p q : ℕ → Prop} : (Eventually x, p x ∧ q x) ↔ (Eventually x, p x) ∧ (Eventually x, q x) :=
⟨by { rintros ⟨M, h⟩, refine ⟨⟨M, λ m le, (h m le).left⟩, ⟨M, λ m le, (h m le).right⟩⟩ },
 by { rintros ⟨⟨M₁, h₁⟩, ⟨M₂, h₂⟩⟩, refine ⟨max M₁ M₂, _⟩, simp, intros m le₁ le₂, exact ⟨h₁ m le₁, h₂ m le₂⟩ }⟩

lemma eventually_imply {p q : ℕ → Prop} (I : ∀ x, p x → q x) : (Eventually x, p x) → (Eventually x, q x) :=
by rintros ⟨c, h⟩; refine ⟨c, λ m le, I _ (h m le)⟩

lemma frequently_def (p : ℕ → Prop) : (Frequently x, p x) ↔ (∀ n : ℕ, ∃ m ≥ n, p m) := by refl

def bigO (f g : ℕ → ℕ) : Prop := ∃ c, c ≠ 0 ∧ Eventually x, f x ≤ c * g x

infix ` ≤ᴼ `:50 := bigO

def littleo (f g : ℕ → ℕ) : Prop := ∀ e, e ≠ 0 ∧ Eventually x, f x ≤ g x / e

infix ` ≤ₒ `:50 := littleo

def bigΘ (f g : ℕ → ℕ) : Prop := f ≤ᴼ g ∧ g ≤ᴼ f

infix ` ≃Θ `:60 := bigΘ

namespace bigO
variables {f g h : ℕ → ℕ}

@[refl, simp] protected lemma refl : f ≤ᴼ f :=
⟨1, one_ne_zero, 0, λ m _, by simp⟩

@[trans] lemma trans : f ≤ᴼ g → g ≤ᴼ h → f ≤ᴼ h :=
begin
  rintros ⟨c₁, hc₁, h₁⟩ ⟨c₂, hc₂, h₂⟩,
  refine ⟨c₁ * c₂, by simp[hc₁, hc₂], _⟩,
  have : (Eventually x, f x ≤ c₁ * g x ∧ g x ≤ c₂ * h x), refine eventually_and.mpr ⟨h₁, h₂⟩,
  refine eventually_imply _ this,
  { rintros x ⟨le₁, le₂⟩,
    have : c₁ * g x ≤ c₁ * c₂ * h x, by simpa[mul_assoc] using mul_le_mul_left' le₂ c₁,
    exact le_trans le₁ this }
end

@[simp] lemma zero_le : 0 ≤ᴼ f := ⟨1, by simp, by simp⟩

lemma of_beq (n : ℕ) (h : ∀ m ≥ n, f m = g m) : f ≃Θ g :=
⟨⟨1, by simp, n, λ m hm, by simp[h m hm]⟩, ⟨1, by simp, n, λ m hm, by simp[h m hm]⟩⟩

end bigO

namespace bigΘ
variables {f g h : ℕ → ℕ}

@[refl, simp] protected lemma refl (f) : f ≃Θ f := ⟨by refl, by refl⟩

@[symm] protected lemma symm : f ≃Θ g → g ≃Θ f := λ ⟨h₁, h₂⟩, ⟨h₂, h₁⟩

@[trans] protected lemma trans : f ≃Θ g → g ≃Θ h → f ≃Θ h :=
λ ⟨hf₁, hf₂⟩ ⟨hg₁, hg₂⟩, ⟨hf₁.trans hg₁, hg₂.trans hf₂⟩

theorem equivalence : equivalence (≃Θ) :=
⟨landau_notation.bigΘ.refl, @landau_notation.bigΘ.symm, @landau_notation.bigΘ.trans⟩

def setoid : setoid (ℕ → ℕ) := ⟨_, equivalence⟩

def quo := quotient setoid

def bigO_class (f : ℕ → ℕ) : quo := quotient.mk' f

notation `O[` f `]` := bigO_class f

def log := O[Log]

def linear := O[id]

def exp := O[(^) 2]

@[elab_as_eliminator]
protected lemma ind_on {C : quo → Prop} (q : quo) (h : ∀ f, C O[f]) : C q := quotient.induction_on' q h

@[elab_as_eliminator, reducible]
protected def lift_on {φ : Sort*} (q : quo) (F : (ℕ → ℕ) → φ)
  (h : ∀ f g, f ≃Θ g → F f = F g) : φ := quotient.lift_on' q F h

@[elab_as_eliminator, reducible, simp]
protected def lift_on₂ {φ : Sort*} (q₁ q₂ : quo) (F : (ℕ → ℕ) → (ℕ → ℕ) → φ)
  (h : ∀ f₁ f₂ g₁ g₂, f₁ ≃Θ g₁ → f₂ ≃Θ g₂ → F f₁ f₂ = F g₁ g₂) : φ :=
quotient.lift_on₂' q₁ q₂ F h

@[simp] protected lemma lift_on₂_eq {φ : Sort*} (f g : ℕ → ℕ) (F : (ℕ → ℕ) → (ℕ → ℕ) → φ) (h) :
  bigΘ.lift_on₂ O[f] O[g] F h = F f g := rfl

lemma of_eq_of {f g : ℕ → ℕ} : O[f] = O[g] ↔ f ≃Θ g := quotient.eq'

lemma of_eq {f g : ℕ → ℕ} (h : f = g) : O[f] = O[g] := by rw h

lemma nat_fun_maximum (f : ℕ → ℕ) (n : ℕ) : ∃ m, ∀ n' < n, f n' ≤ m :=
by { induction n with n IH,
     { simp }, { rcases IH with ⟨m, IH⟩, refine ⟨max m (f n), _⟩,
     intros n' hn',
     have : n' < n ∨ n' = n, from nat.lt_succ_iff_lt_or_eq.mp hn',
     rcases this with (hn' | rfl),
     { simp[IH n' hn'] }, { simp } } }

section arith

instance : has_add quo :=
⟨λ q₁ q₂, bigΘ.lift_on₂ q₁ q₂ (λ f g, O[f + g])
  (by { rintros f₁ f₂ g₁ g₂ ⟨hfg₁, hgf₁⟩ ⟨hfg₂, hgf₂⟩,
        refine of_eq_of.mpr ⟨_, _⟩,
        { rcases hfg₁ with ⟨c₁, hc₁, n₁, h₁⟩, rcases hfg₂ with ⟨c₂, hc₂, n₂, h₂⟩,
          refine ⟨max c₁ c₂, by simp[hc₁, hc₂], max n₁ n₂, _⟩, simp[mul_add],
          intros m hm₁ hm₂,
          refine add_le_add
            ((h₁ m hm₁).trans (nat.mul_le_mul_right _ (by simp)))
            ((h₂ m hm₂).trans (nat.mul_le_mul_right _ (by simp))) },
        { rcases hgf₁ with ⟨c₁, hc₁, n₁, h₁⟩, rcases hgf₂ with ⟨c₂, hc₂, n₂, h₂⟩,
          refine ⟨max c₁ c₂, by simp[hc₁, hc₂], max n₁ n₂, _⟩, simp[mul_add],
          intros m hm₁ hm₂,
          refine add_le_add
            ((h₁ m hm₁).trans (nat.mul_le_mul_right _ (by simp)))
            ((h₂ m hm₂).trans (nat.mul_le_mul_right _ (by simp))) } })⟩

instance : has_mul quo :=
⟨λ q₁ q₂, bigΘ.lift_on₂ q₁ q₂ (λ f g, O[f * g])
  (by { rintros f₁ f₂ g₁ g₂ ⟨hfg₁, hgf₁⟩ ⟨hfg₂, hgf₂⟩,
        refine of_eq_of.mpr ⟨_, _⟩,
        { rcases hfg₁ with ⟨c₁, hc₁, n₁, h₁⟩, rcases hfg₂ with ⟨c₂, hc₂, n₂, h₂⟩,
          refine ⟨c₁ * c₂, by simp[hc₁, hc₂], max n₁ n₂, _⟩, simp[mul_add],
          intros m hm₁ hm₂,
          calc f₁ m * f₂ m ≤ (c₁ * g₁ m) * (c₂ * g₂ m) : nat.mul_le_mul (h₁ m hm₁) (h₂ m hm₂)
                       ... = c₁ * c₂ * (g₁ m * g₂ m)   : by ring },
        { rcases hgf₁ with ⟨c₁, hc₁, n₁, h₁⟩, rcases hgf₂ with ⟨c₂, hc₂, n₂, h₂⟩,
          refine ⟨c₁ * c₂, by simp[hc₁, hc₂], max n₁ n₂, _⟩, simp[mul_add],
          intros m hm₁ hm₂,
          calc g₁ m * g₂ m ≤ (c₁ * f₁ m) * (c₂ * f₂ m) : nat.mul_le_mul (h₁ m hm₁) (h₂ m hm₂)
                       ... = c₁ * c₂ * (f₁ m * f₂ m)   : by ring } })⟩

variables (f g)

lemma of_add_of : O[f + g] = O[f] + O[g] := by refl

lemma of_mul_of : O[f * g] = O[f] * O[g] := by refl

@[simp] lemma smul_eq {c} (h : c ≠ 0) : O[c • f] = O[f] :=
of_eq_of.mpr ⟨⟨c, h, 0, by simp⟩, by { refine ⟨1, by simp, 0, λ m _, by { simp; exact nat.le_mul_of_pos_left (pos_iff_ne_zero.mpr h) }⟩ }⟩

variables {f g}

instance : add_comm_monoid quo :=
{ add_assoc := λ q₁ q₂ q₃,
  by {
    induction q₁ using landau_notation.bigΘ.ind_on with f,
    induction q₂ using landau_notation.bigΘ.ind_on with g,
    induction q₃ using landau_notation.bigΘ.ind_on with h,
    simp[←of_add_of, add_assoc] },
  zero := O[0],
  zero_add := λ q, by {
    induction q using landau_notation.bigΘ.ind_on with f,
    simp[←of_add_of] },
  add_zero := λ q, by {
    induction q using landau_notation.bigΘ.ind_on with f,
    simp[←of_add_of] },
  add_comm := λ q₁ q₂, by {
    induction q₁ using landau_notation.bigΘ.ind_on with f,
    induction q₂ using landau_notation.bigΘ.ind_on with g,
    simp[←of_add_of, add_comm] },
  ..quo.has_add }

lemma zero_def : 0 = O[0] := rfl

instance : comm_monoid quo :=
{ mul_assoc := λ q₁ q₂ q₃,
  by {
    induction q₁ using landau_notation.bigΘ.ind_on with f,
    induction q₂ using landau_notation.bigΘ.ind_on with g,
    induction q₃ using landau_notation.bigΘ.ind_on with h,
    simp[←of_mul_of, mul_assoc] },
  one := O[1],
  one_mul := λ q, by {
    induction q using landau_notation.bigΘ.ind_on with f,
    simp[←of_mul_of] },
  mul_one := λ q, by {
    induction q using landau_notation.bigΘ.ind_on with f,
    simp[←of_mul_of] },
  mul_comm := λ q₁ q₂, by {
    induction q₁ using landau_notation.bigΘ.ind_on with f,
    induction q₂ using landau_notation.bigΘ.ind_on with g,
    simp[←of_mul_of, mul_comm] },
  ..quo.has_mul }

instance : monoid_with_zero quo :=
{ zero_mul := λ q, by {
    induction q using landau_notation.bigΘ.ind_on with f,
    simp[show add_comm_monoid.zero = O[0], by refl], unfold comm_monoid.mul,
    simp[←of_mul_of] },
  mul_zero := λ q, by {
    induction q using landau_notation.bigΘ.ind_on with f,
    simp[show add_comm_monoid.zero = O[0], by refl], unfold comm_monoid.mul,
    simp[←of_mul_of] },
  .. quo.add_comm_monoid, ..quo.comm_monoid }

lemma one_def : 1 = O[1] := rfl

instance : distrib quo :=
{ left_distrib := λ q₁ q₂ q₃, by {
    induction q₁ using landau_notation.bigΘ.ind_on with f,
    induction q₂ using landau_notation.bigΘ.ind_on with g,
    induction q₃ using landau_notation.bigΘ.ind_on with h,
    simp[←of_add_of, ←of_mul_of],
    refine of_eq (funext $ λ x, by simp[mul_add]) },
  right_distrib := λ q₁ q₂ q₃, by {
    induction q₁ using landau_notation.bigΘ.ind_on with f,
    induction q₂ using landau_notation.bigΘ.ind_on with g,
    induction q₃ using landau_notation.bigΘ.ind_on with h,
    simp[←of_add_of, ←of_mul_of],
    refine of_eq (funext $ λ x, by simp[add_mul]) },
  ..quo.has_add, ..quo.has_mul }

end arith

section order

instance : partial_order quo :=
{ le := λ q₁ q₂, bigΘ.lift_on₂ q₁ q₂ (λ f g, f ≤ᴼ g)
    (by { rintros f₁ f₂ g₁ g₂ ⟨hfg₁, hgf₁⟩ ⟨hfg₂, hgf₂⟩, simp,
          refine ⟨λ h, (hgf₁.trans h).trans hfg₂, λ h, (hfg₁.trans h).trans hgf₂⟩ }),
  le_refl := λ q, by { induction q using landau_notation.bigΘ.ind_on with f, simp },
  le_trans := λ q₁ q₂ q₃,
    by { induction q₁ using landau_notation.bigΘ.ind_on with f,
         induction q₂ using landau_notation.bigΘ.ind_on with g,
         induction q₃ using landau_notation.bigΘ.ind_on with h, simp, exact bigO.trans },
  le_antisymm := λ q₁ q₂,
    by { induction q₁ using landau_notation.bigΘ.ind_on with f,
         induction q₂ using landau_notation.bigΘ.ind_on with g, simp[has_le.le, preorder.le, of_eq_of],
         intros h₁ h₂, refine ⟨h₁, h₂⟩ } }

lemma of_le_of : O[f] ≤ O[g] ↔ f ≤ᴼ g := by simp[(≤), preorder.le, partial_order.le]

instance : semilattice_sup quo :=
{ sup := (+),
  le_sup_left := λ q₁ q₂,
    by{ induction q₁ using landau_notation.bigΘ.ind_on with f,
        induction q₂ using landau_notation.bigΘ.ind_on with g,
        simp[←of_add_of, of_eq_of, of_le_of],
        refine ⟨1, by simp, 0, λ m _, by simp⟩ },
  le_sup_right := λ q₁ q₂,
    by{ induction q₁ using landau_notation.bigΘ.ind_on with f,
        induction q₂ using landau_notation.bigΘ.ind_on with g,
        simp[←of_add_of, of_eq_of, of_le_of],
        refine ⟨1, by simp, 0, λ m _, by simp⟩ },
  sup_le := λ q₁ q₂ q₃,
    by{ induction q₁ using landau_notation.bigΘ.ind_on with f,
        induction q₂ using landau_notation.bigΘ.ind_on with g,
        induction q₃ using landau_notation.bigΘ.ind_on with h,
        simp[←of_add_of, of_le_of],
        rintros ⟨c₁, hc₁, m₁, h₁⟩ ⟨c₂, hc₂, m₂, h₂⟩,
        refine ⟨c₁ + c₂, by simp[hc₁, hc₂], max m₁ m₂,
          by{ simp, intros m le₁ le₂,
              calc f m + g m ≤ c₁ * h m + c₂ * h m : add_le_add (h₁ m le₁) (h₂ m le₂)
                         ... = (c₁ + c₂) * h m     : by simp[add_mul] }⟩ },
  .. quo.partial_order }

lemma sup_def {q₁ q₂ : quo} : q₁ ⊔ q₂ = q₁ + q₂ := rfl

instance : order_bot quo := ⟨0, λ q, by { induction q using landau_notation.bigΘ.ind_on with f, simp[zero_def, of_le_of] }⟩

lemma bot_def : (⊥ : quo) = 0 := rfl

@[simp] lemma smul_le {c : ℕ} (f) : O[c • f] ≤ O[f] :=
by { by_cases C : c = 0, { simp[C, ←zero_def, ←bot_def] }, { rw[smul_eq f C] } }

end order

section const
variables {f}

lemma eq_zero : O[f] = 0 ↔ Eventually n, f n = 0 :=
by { simp [zero_def, of_eq_of, (≃Θ)], split,
     { rintros ⟨c, hc, h⟩, simpa using h }, { intros h, refine ⟨1, by simp, by simpa using h⟩ } }

lemma le_one_iff : O[f] ≤ 1 ↔ ∃ M, ∀ n, f n ≤ M :=
begin
  simp[one_def, of_eq_of], split,
  { rintros ⟨c, hc, n, h⟩, simp at h,
    have :  ∃ m, ∀ n' < n, f n' ≤ m, from nat_fun_maximum f n,
    rcases this with ⟨m, hm⟩,
    refine ⟨max m c, λ n', _⟩,
    have : n' < n ∨ n ≤ n', from lt_or_ge n' n,
    rcases this with (hn' | hn'),
    { simp [hm n' hn'] }, { simp[h n' hn'] } },
  { rintros ⟨M, hM⟩,
    refine ⟨M + 1, by simp, 0, λ m _, _⟩, simp,
    exact le_add_right (hM m) }
end

lemma one_le_iff : 1 ≤ O[f] ↔ Eventually n, f n ≠ 0 :=
by { simp[one_def, of_le_of], split,
     { rintros ⟨c, hc, b, h⟩, simp at h, refine ⟨b, λ m hm A, _⟩, have : 1 ≤ c * f m, from h m hm, rw[A] at this, simpa using this },
     { rintros ⟨b, h⟩, refine ⟨1, by simp, b, _⟩, simpa[nat.one_le_iff_ne_zero] using h } }

lemma eq_one_of : O[f] = 1 ↔ (∃ M, ∀ n, f n ≤ M) ∧ (Eventually n, f n ≠ 0) :=
by rw[le_antisymm_iff, le_one_iff, one_le_iff]

@[simp] lemma const_eq_one {c : ℕ} (h : c ≠ 0) : O[λ _, c] = 1 := by simp[eq_one_of, h]; refine ⟨c, by refl⟩

end const

section pow

lemma pow_eq (n : ℕ) (f) : O[f]^n = O[f^n] :=
begin
  induction n with n IH,
  { simp[one_def] },
  { calc
      O[f] ^ n.succ = O[f] * O[f^n] : by simp[pow_succ, IH]
                ... = O[f ^ n.succ] : by simp[pow_succ, of_mul_of] }
end

lemma poly_mono {n m : ℕ} (h : n ≤ m) : linear^n ≤ linear^m :=
by{ simp[linear, pow_eq, of_le_of], refine ⟨1, by simp, 1, λ x hx, by { simp, refine pow_mono hx h}⟩ }

lemma log_mono {n m : ℕ} (h : n ≤ m) : log^n ≤ log^m :=
by{ simp[log, pow_eq, of_le_of],
    refine ⟨1, by simp, 1, λ x hx, by { simp, refine pow_mono (by simpa using Log_monotone hx) h}⟩ }

end pow

section Log
variables {f}

@[simp] lemma zero_le (q : quo) : 0 ≤ q := by simp[←bot_def]

@[simp] lemma one_le_Log : 1 ≤ log :=
by { simp[log, one_def, of_le_of], refine ⟨1, by simp, 1, λ m hm, by simpa using Log_monotone hm⟩ }

lemma log_le_of_le {n m : ℕ} (h : n ≤ m) : log^n ≤ log^m :=
by { simp[log, pow_eq, of_le_of], refine ⟨1, by simp, 1, λ x hx, by { simp, exact pow_mono (by simpa using Log_monotone hx) h}⟩ }

end Log

section linear
variables {f}

lemma linear_le_of_le {n m : ℕ} (h : n ≤ m) : linear^n ≤ linear^m :=
by { simp[linear, pow_eq, of_le_of], refine ⟨1, by simp, 1, λ x hx, by { simp, exact pow_mono hx h}⟩ }

@[simp] lemma log_le_linear : log ≤ linear :=
by { simp[linear, one_def, of_le_of], refine ⟨1, by simp, 1, by simp⟩ }

@[simp] lemma log_poly_le_linear (k : ℕ) : log^k ≤ linear :=
by { simp[log, pow_eq, linear, one_def, of_le_of],
     refine ⟨(k.pow_le_two_mul_pow_of_le_bound + 1)^k, by { simp,
     suffices : 1 ≤ (k.pow_le_two_mul_pow_of_le_bound + 1)^k, exact ne_zero.ne _,
     refine nat.one_le_pow' _ _ }, 2^k.pow_le_two_mul_pow_of_le_bound, _⟩,
     simpa using Log_pow_le_linear k }

end linear

section exp
variables {f}

@[simp] lemma linear_le_exp : linear ≤ exp :=
by { simp[linear, exp, of_le_of], refine ⟨1, by simp, 0, _⟩, simp, sorry }

end exp

section lambda

@[simp] lemma lambda_add : O[λ x, f x + g x] = O[f] + O[g] := (of_add_of f g).symm

@[simp] lemma lambda_add_const {c : ℕ} (h : c ≠ 0) : O[λ x, f x + c] = O[f] + 1 :=
by { show O[f + λ _, c] = O[f] + 1, rw [of_add_of, const_eq_one h] }

@[simp] lemma lambda_smul {c : ℕ} (h : c ≠ 0) : O[λ x, c * f x] = O[f] := smul_eq f h

@[simp] lemma lambda_le_smul {c : ℕ} : O[λ x, c * f x] ≤ O[f] := smul_le f

@[simp] lemma lambda_smul_poly1 {c : ℕ} (h : c ≠ 0) : O[(*) c] = linear :=
by simpa[show c • id = (*) c, from funext (by simp)] using smul_eq id h

@[simp] lemma lambda_smul_le_poly1 {c : ℕ} : O[(*) c] ≤ linear :=
by simpa[show c • id = (*) c, from funext (by simp)] using smul_le id

end lambda

end bigΘ

section
open nat
variables (f : ℕ → ℕ)

lemma le_poly1_of_binary_rec (c : ℕ) (h : ∀ b n, f (bit b n) ≤ 2 * f n + c) : O[f] ≤ bigΘ.linear :=
begin
  have : f ≤ᴼ (λ n, (f 1 + c)*n),
  { have : ∀ n, n ≠ 0 → f n ≤ (f 1 + c) * n - c,
    from binary_recursion_nonzero
      (by simp[add_mul]; rw [mul_one, mul_one, tsub_eq_of_eq_add]; refl)
      (λ b n hn IH, by {
        have : c ≤ 2 * (f 1 + c) * n - c,
          calc c = 2 * c - c
          : by rw[two_mul]; simp
             ... ≤ 2 * ((f 1 + c) * n) - c
          : tsub_le_tsub_right (by simp[hn]; refine le_mul_of_le_of_one_le (by simp) (one_le_iff_ne_zero.mpr hn)) c
             ... ≤ 2 * (f 1 + c) * n - c
          : by rw[mul_assoc],
        calc
          f (bit b n) ≤ 2 * f n + c                   : h b n
                  ... ≤ 2 * ((f 1 + c) * n - c) + c   : by simpa using IH
                  ... = 2 * (f 1 + c) * n - 2 * c + c : by simp[nat.mul_sub_left_distrib, mul_assoc]
                  ... = 2 * (f 1 + c) * n - c - c + c : by rw[two_mul c, tsub_add_eq_tsub_tsub]
                  ... = 2 * (f 1 + c) * n - c         : by rw nat.sub_add_cancel this
                  ... = (f 1 + c) * (2 * n) - c       : by rw[mul_comm 2 (f 1 + c), mul_assoc]
                  ... ≤ (f 1 + c) * bit b n - c       : tsub_le_tsub_right (mul_le_mul_left' (by simp[bit_val]) _) c }),
    refine ⟨1, by simp, 1,
      λ n hn, by simp; refine le_trans (this n (one_le_iff_ne_zero.mp hn)) (nat.sub_le _ _)⟩ },
  refine (bigΘ.of_le_of.mpr this).trans (by simp)
end

lemma le_Log_of_binary_rec (c : ℕ) (h : ∀ b n, f (bit b n) ≤ f n + c) : O[f] ≤ bigΘ.log :=
begin
  have : f ≤ᴼ (λ n, c * Log n + f 0),
  from ⟨1, by simp, 0, by { simp,
  refine nat.binary_rec (by simp)
    (λ b n IH, by {
      by_cases C : bit b n = 0, { simp[C] },
      calc
        f (bit b n) ≤ f n + c                 : h b n
                ... ≤ c * Log n + f 0 + c     : by simpa using IH
                ... = c * (Log n + 1) + f 0   : by ring
                ... = c * Log (bit b n) + f 0 : by simp[Log_bit C] }) }⟩,
  have := bigΘ.of_le_of.mpr this,
  simp at this,
  sorry
end

end

end landau_notation


/-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura

Unordered pairs
-/
import data.prod logic.identities
open prod prod.ops quot function

private definition eqv {A : Type} (p₁ p₂ : A × A) : Prop :=
p₁ = p₂ ∨ swap p₁ = p₂

infix `~` := eqv    -- this is "~"

private theorem eqv.refl [refl] {A : Type} : ∀ p : A × A, p ~ p :=
take p, or.inl rfl

private theorem eqv.symm [symm] {A : Type} : ∀ p₁ p₂ : A × A, p₁ ~ p₂ → p₂ ~ p₁ :=
take p₁ p₂ h, or.elim h
  (λ e, by rewrite e)
  (λ e, begin esimp [eqv], rewrite [-e, swap_swap], right, reflexivity end)

private theorem eqv.trans [trans] {A : Type} : ∀ p₁ p₂ p₃ : A × A, p₁ ~ p₂ → p₂ ~ p₃ → p₁ ~ p₃ :=
take p₁ p₂ p₃ h₁ h₂, or.elim h₁
  (λ e₁₂,  or.elim h₂
    (λ e₂₃,  by rewrite [e₁₂, e₂₃])
    (λ es₂₃, begin esimp [eqv], rewrite -es₂₃, right, congruence, assumption end))
  (λ es₁₂, or.elim h₂
    (λ e₂₃,  begin esimp [eqv], rewrite es₁₂, right, assumption end)
    (λ es₂₃, begin esimp [eqv], rewrite [-es₁₂ at es₂₃, swap_swap at es₂₃], left, assumption end))

private theorem is_equivalence (A : Type) : equivalence (@eqv A) :=
mk_equivalence (@eqv A) (@eqv.refl A) (@eqv.symm A) (@eqv.trans A)

definition uprod.setoid [instance] (A : Type) : setoid (A × A) :=
setoid.mk (@eqv A) (is_equivalence A)

definition uprod (A : Type) : Type :=
quot (uprod.setoid A)

namespace uprod
  definition mk {A : Type} (a b : A) : uprod A :=
  ⟦(a, b)⟧

  theorem mk_eq_mk {A : Type} (a b : A) : mk a b = mk b a :=
  quot.sound (or.inr rfl)

  private definition mem_fn {A : Type} (a : A) : A × A → Prop
  | (a₁, a₂) := a = a₁ ∨ a = a₂

  private lemma mem_swap {A : Type} {a : A} : ∀ {p : A × A}, mem_fn a p ↔ mem_fn a (swap p)
  | (a₁, a₂) := iff.intro
    (λ l : a = a₁ ∨ a = a₂, or.swap l)
    (λ r : a = a₂ ∨ a = a₁, or.swap r)

  private lemma mem_coherent {A : Type} : ∀ {p₁ p₂ : A × A} (a : A),  p₁ ~ p₂ → mem_fn a p₁ = mem_fn a p₂
  | (a₁, b₁) (a₂, b₂) a h :=
    or.elim h
     (λ e,  by rewrite e)
     (λ es, begin rewrite -es, apply propext, rewrite (propext mem_swap) end)

  definition mem {A : Type} (a : A) (u : uprod A) : Prop :=
  quot.lift_on u (λ p, mem_fn a p) (λ p₁ p₂ e, mem_coherent a e)

  infix `∈` := mem

  theorem mem_mk_left {A : Type} (a b : A) : a ∈ mk a b :=
  or.inl rfl

  theorem mem_mk_right {A : Type} (a b : A) : b ∈ mk a b :=
  or.inr rfl

  theorem mem_or_mem_of_mem_mk {A : Type} {a b c : A} : c ∈ mk a b → c = a ∨ c = b :=
  λ h, h

  private definition map_fn {A B : Type} (f : A → B) : A × A → uprod B
  | (a₁, a₂) := mk (f a₁) (f a₂)

  private lemma map_coherent {A B : Type} (f : A → B) : ∀ {p₁ p₂ : A × A}, p₁ ~ p₂ → map_fn f p₁ = map_fn f p₂
  | (a₁, b₁) (a₂, b₂) h :=
    or.elim h
      (λ e,  by rewrite e)
      (λ es, begin rewrite -es, apply quot.sound, right, reflexivity end)

  definition map {A B : Type} (f : A → B) (u : uprod A) : uprod B :=
  quot.lift_on u (λ p, map_fn f p) (λ p₁ p₂ c, map_coherent f c)

  theorem mem_map_mk_left {A B : Type} (f : A → B) (a₁ a₂ : A) : f a₁ ∈ map f (mk a₁ a₂) :=
  or.inl rfl

  theorem mem_map_mk_right {A B : Type} (f : A → B) (a₁ a₂ : A) : f a₂ ∈ map f (mk a₁ a₂) :=
  or.inr rfl

  theorem map_map {A B C : Type} (g : B → C) (f : A → B) (u : uprod A) : map g (map f u) = map (g ∘ f) u :=
  quot.induction_on u (λ p : A × A, begin cases p, reflexivity end)
end uprod


inductive Vec (α : Type u) : Nat → Type u
  | nil  : Vec α 0
  | cons : α → Vec α n → Vec α (n+1)

def Vec.map (xs : Vec α n) (f : α → β) : Vec β n :=
  match xs with
  | nil       => nil
  | cons a as => cons (f a) (map as f)

def Vec.map' (f : α → β) : Vec α n → Vec β n
  | nil       => nil
  | cons a as => cons (f a) (map' f as)

def Vec.map2 (f : α → α → β) : Vec α n → Vec α n → Vec β n
  | nil,       nil       => nil
  | cons a as, cons b bs => cons (f a b) (map2 f as bs)

def Vec.head (xs : Vec α (n+1)) : α :=
  match xs with
  | cons x _ => x

theorem ex1 (xs ys : Vec α (n+1)) (h : xs = ys) : xs.head = ys.head := by
  induction xs -- error, use cases

theorem ex2 (xs ys : Vec α (n+1)) (h : xs = ys) : xs.head = ys.head := by
  cases xs with
  | cons x xs =>
    traceState -- `h` has been refined
    repeat admit

inductive ExprType where
  | bool  : ExprType
  | nat   : ExprType

inductive Expr : ExprType → Type
  | natVal : Nat → Expr ExprType.nat
  | boolVal : Bool → Expr ExprType.bool
  | eq : Expr α → Expr α → Expr ExprType.bool
  | add : Expr ExprType.nat → Expr ExprType.nat → Expr ExprType.nat

def constProp : Expr α → Expr α
  | Expr.add a b =>
    match constProp a, constProp b with
   | Expr.natVal v, Expr.natVal w => Expr.natVal (v + w)
   | a, b => Expr.add a b
  | e => e

abbrev denoteType : ExprType → Type
  | ExprType.bool => Bool
  | ExprType.nat  => Nat

instance : BEq (denoteType α) where
  beq a b :=
    match α, a, b with
    | ExprType.bool, a, b => a == b
    | ExprType.nat,  a, b => a == b

def eval : Expr α → denoteType α
  | Expr.natVal v  => v
  | Expr.boolVal b => b
  | Expr.eq a b    => eval a == eval b
  | Expr.add a b   => eval a + eval b

theorem ex3 (a b : Expr α) (h : a = b) : eval (constProp a) = eval b := by
  set_option trace.Meta.debug true in
  induction a
  traceState -- b's type must have been refined, `h` too
  repeat admit


/-
Copyright (c) 2021 Paula Neeley. All rights reserved.
Author: Paula Neeley
Following the textbook "Dynamic Epistemic Logic" by
Hans van Ditmarsch, Wiebe van der Hoek, and Barteld Kooi
-/

import del.semantics.translationdefs tactic.linarith

variables {agents : Type}

---------------------- Generic helper lemmas ----------------------

lemma comp_gt_zero {φ : formPA agents} : complexity φ > 0 :=
begin
induction φ,
repeat { rw complexity }, repeat { linarith },
have h1 : 4 > 0, linarith,
exact (mul_pos (add_lt_add h1 φ_ih_φ) φ_ih_ψ)
end

lemma comp_ge_zero {φ : formPA agents} : complexity φ ≥ 0 := le_of_lt comp_gt_zero

lemma comp_ge_one {φ : formPA agents} : complexity φ ≥ 1 :=
begin
have h1 : complexity φ > 0, from comp_gt_zero,
linarith
end

lemma maxhelper {n1 n2 n3 n4 : nat} : n1 + n2 < n4 → n1 + n3 < n4 → n1 + max n2 n3 < n4 :=
begin
intros h1 h2,
exact nat.add_lt_of_lt_sub_left (max_lt (nat.lt_sub_left_of_add_lt h1) (nat.lt_sub_left_of_add_lt h2))
end

lemma le_maxhelper {n1 n2 n3 n4 : nat} : n1 + n2 ≤ n4 → n1 + n3 ≤ n4 → n1 + max n2 n3 ≤ n4 :=
begin
intros h1 h2,
have h3 := max_le (nat.le_sub_left_of_add_le h1) (nat.le_sub_left_of_add_le h2),
rw nat.le_sub_right_iff_add_le at h3,
have h4 : max n2 n3 + n1 = n1 + max n2 n3, linarith,
exact eq.subst h4 h3, linarith
end

-------------- Helper lemmas for translation function --------------

lemma tr1 : ∀ φ ψ : formPA agents, complexity φ < 1 + max (complexity φ) (complexity ψ) :=
begin
intros φ ψ,
have h1 := lt_add_one _,
have h2 := add_comm _ _,
exact (eq.subst h2 (lt_of_le_of_lt (le_max_left (complexity φ) (complexity ψ)) h1))
end

lemma tr2 : ∀ φ ψ : formPA agents, complexity ψ < 1 + max (complexity φ) (complexity ψ) :=
begin
intros φ ψ,
have h1 := lt_add_one _,
have h2 := add_comm _ _,
exact (eq.subst h2 (lt_of_le_of_lt (le_max_right (complexity φ) (complexity ψ)) h1))
end

lemma tr3 : ∀ φ : formPA agents, 1 + max (complexity φ) 1 < 4 + complexity φ :=
begin
intro φ,
have h1 : complexity φ < complexity φ + 1, from lt_add_one _,
have h2 := zero_lt_iff_ne_zero,
have h3 : 3 + (complexity φ + 1) = complexity φ + 4, from add_comm _ _,
have h4 := add_comm (complexity φ) 4,
have h5 := (rfl.congr h4).mp h3,
exact (eq.subst h5 (add_lt_add (lt_add_of_pos_right 1 (h2.mpr (nat.add_one_ne_zero 1)))
  (max_lt h1 (lt_add_of_pos_left 1 comp_gt_zero))))
end

lemma tr4helper {φ ψ : formPA agents} : (4 + complexity φ) * (1 + max (complexity ψ) 1) > 9 :=
begin
have h1 : complexity φ ≥ 1, from comp_ge_one,
have h2 : (4 + complexity φ) ≥ 5, linarith,
have h3 : complexity ψ ≥ 1, from comp_ge_one,
have h4 := max_eq_left h3,
have h5 : 1 + max (complexity ψ) 1 ≥ 1 + 1, linarith,
have h6 : 0 ≤ 2, linarith,
have h7 : 0 ≤ 4 + complexity φ, linarith,
exact (mul_le_mul h2 h5 h6 h7),
end

lemma tr4helper1 {n m : nat} : n ≥ 4 → m ≥ 1 → 2 + n * m < n * (1 + m) :=
begin
intros h1 h2,
have h3 := mul_add n 1 m,
linarith,
end

lemma tr4helper2 {φ ψ : formPA agents} : 1 + 1 + (4 + complexity φ) * complexity ψ <
  (4 + complexity φ) * (1 + complexity ψ) :=
begin
have h1 : 4 + complexity φ ≥ 4, linarith,
exact (tr4helper1 h1 (comp_ge_one))
end

lemma tr4helper3 {φ ψ : formPA agents} : 1 + 1 + ((4 + complexity φ) * complexity ψ) <
  (4 + complexity φ) * (1 + max (complexity ψ) 1) :=
begin
have h1 : complexity ψ ≥ 1, from comp_ge_one,
have h2 := max_eq_left h1,
have h3 := congr_arg (has_mul.mul (4 + complexity φ)) (congr_arg (has_add.add 1)
  (eq.symm (max_eq_left comp_ge_one))),
exact (eq.subst h3 tr4helper2)
end

lemma tr4 : ∀ φ ψ : formPA agents, 1 + max (complexity φ) (1 + max ((4 + complexity φ)
  * complexity ψ) 1) < (4 + complexity φ) * (1 + max (complexity ψ) 1) :=
begin
intros φ ψ,
have h1 : 1 ≤ 1 + max (complexity ψ) 1, linarith,
have h2 : 1 + complexity φ < (4 + complexity φ), linarith,
have h3 : 1 > 0, linarith,
have h4 : 4 ≥ 0, linarith,
have h5 : complexity ψ ≥ 1, from comp_ge_one,
have h6 : 1 ≥ 1, linarith,
have h7 := le_max_right (complexity ψ) 1,
have h8 : 3 < 9, linarith,
have h9 : 1 + 1 + max ((4 + complexity φ) * complexity ψ) 1 =
  1 + (1 + max ((4 + complexity φ) * complexity ψ) 1), linarith,
exact (maxhelper (eq.subst (mul_one (1 + complexity φ))
  (mul_lt_mul h2 h1 h3 (add_nonneg h4 comp_ge_zero)))
  (eq.subst h9 (maxhelper tr4helper3 (lt_trans h8 tr4helper))))
end

lemma tr5helper {φ ψ : formPA agents} : 1 + ((4 + complexity φ) * complexity ψ) <
  (4 + complexity φ) * (1 + (complexity ψ)) :=
begin
have h1 : 1 + 1 + (4 + complexity φ) * complexity ψ < (4 + complexity φ) * (1 + complexity ψ), from tr4helper2,
linarith,
end

lemma tr5helper1 {ψ χ : formPA agents} : complexity χ ≤ max (complexity χ) (complexity ψ) :=
begin
cases max_choice (complexity ψ) (complexity χ),
repeat {have h : complexity χ ≤ complexity χ, linarith, exact (le_max_left_of_le h)}
end

lemma tr5helper2 {ψ χ : formPA agents} : max (complexity ψ) (complexity χ) = complexity ψ →
  complexity χ ≤ complexity ψ :=
begin
intro h1,
have h2 : max (complexity χ) (complexity ψ) = complexity ψ,
  from eq.substr (max_comm (complexity χ) (complexity ψ)) h1,
exact (eq.subst h2 tr5helper1)
end

lemma tr5helper3 {φ ψ χ : formPA agents} : complexity χ ≤ complexity ψ →
  1 + ((4 + complexity φ) * complexity χ) < (4 + complexity φ) * (1 + (complexity ψ)) :=
begin
intro h1,
have h2 : 4 + complexity φ > 0, linarith,
have h3 : 4 + complexity φ ≤ 4 + complexity φ, linarith,
have h4 := nat.mul_le_mul_left (4 + complexity φ) h1,
have h5 : 1 + (4 + complexity φ) * complexity χ ≤ 1 + (4 + complexity φ) * complexity ψ, linarith,
exact (lt_of_le_of_lt h5 tr5helper)
end

lemma tr5 : ∀ φ ψ χ : formPA agents, 1 + max ((4 + complexity φ) * complexity ψ)
  ((4 + complexity φ) * complexity χ) < (4 + complexity φ) * (1 + max (complexity ψ) (complexity χ)) :=
begin
intros φ ψ χ,
cases max_choice (complexity ψ) (complexity χ),
cases max_choice ((4 + complexity φ) * complexity ψ) ((4 + complexity φ) * complexity χ),
exact (eq.substr h_1 (eq.substr h (tr5helper))),
exact (eq.substr h_1 (eq.substr h (tr5helper3 (tr5helper2 h)))),
cases max_choice ((4 + complexity φ) * complexity ψ) ((4 + complexity φ) * complexity χ),
exact (eq.substr h_1 (eq.substr h (tr5helper3 (tr5helper2 (eq.subst (max_comm (complexity ψ) (complexity χ)) h))))),
exact (eq.substr h_1 (eq.substr h tr5helper)),
end

lemma tr6 : ∀ φ ψ : formPA agents, 1 + max (complexity φ) (1 + (4 + complexity φ)
  * complexity ψ) < (4 + complexity φ) * (1 + complexity ψ) :=
begin
intros φ ψ,
have h1 : 1 + complexity φ < 4 + complexity φ, linarith,
have h2 : complexity ψ + 1 ≥ 1, linarith,
have h3 : 0 < 1, linarith,
have h4 : 0 ≤ 4 + complexity φ, linarith,
have h5 := mul_lt_mul h1 h2 h3 h4,
have h6 : 1 + complexity φ < (4 + complexity φ) * (1 + complexity ψ), linarith,
have h7 : 1 + 1 + (4 + complexity φ) * complexity ψ = 1 + (1 + (4 + complexity φ) * complexity ψ), linarith,
have h8 : 1 + complexity ψ = complexity ψ + 1, linarith,
exact (maxhelper h6 (eq.subst h8 (eq.subst h7 tr4helper2)))
end

lemma tr7helper1 {φ ψ : formPA agents} : (4 + complexity φ ) * (4 + complexity ψ)
  = (complexity φ) * (complexity ψ) + 4 * (complexity ψ) + 4 * (complexity φ) + 4 * 4 :=
begin
have h1 := mul_add (complexity φ + 4) (complexity ψ) 4,
have h2 := add_mul (complexity φ) 4 (complexity ψ),
have h3 := add_mul (complexity φ) 4 4,
linarith
end

lemma tr7helper2 {φ ψ : formPA agents} : 5 + (complexity φ) < (complexity φ) * (complexity ψ) + 4 * (complexity ψ) + 4 * (complexity φ) + 4 * 4 :=
begin
have h1 : complexity φ ≥ 1, from comp_ge_one,
have h2 : complexity ψ ≥ 1, from comp_ge_one,
have : complexity φ * complexity ψ ≥ 0, apply nat.zero_le,
linarith
end

lemma tr7helper3 {φ ψ : formPA agents} : 5 + (complexity φ) < (4 + complexity φ) * (4 + complexity ψ) :=
begin
have h1 := tr7helper1,
exact (eq.substr h1 tr7helper2)
end

lemma tr7helper4 {φ ψ : formPA agents} : 5 + (complexity φ) * (complexity ψ) + 4 * (complexity ψ) <
  (complexity φ) * (complexity ψ) + 4 * (complexity ψ) + 4 * (complexity φ) + 4 * 4 :=
begin
have h1 : 5 + (complexity φ) * (complexity ψ) + 4 * (complexity ψ) =
  (complexity φ) * (complexity ψ) + (5 + 4 * (complexity ψ)), linarith,
have h2 : 5 + 4 * (complexity ψ) < 4 * (complexity ψ) + 4 * (complexity φ) + 4 * 4, linarith,
have h3 := add_lt_add_left h2 ((complexity φ) * (complexity ψ)),
have h4 : 5 + (complexity φ) * (complexity ψ) + 4 * (complexity ψ) <
  (complexity φ) * (complexity ψ) + (4 * (complexity ψ) + 4 * (complexity φ) + 4 * 4), from eq.substr h1 h3,
have h5 : 5 + (complexity φ) * (complexity ψ) + 4 * (complexity ψ) <
  (complexity φ) * (complexity ψ) + 4 * (complexity ψ) + 4 * (complexity φ) + 4 * 4, linarith,
exact h5
end

lemma tr7helper5 {φ ψ : formPA agents} : 5 + (complexity φ) * (complexity ψ) + 4 * (complexity ψ) =
  (5 + ((4 + complexity φ) * complexity ψ)) :=
begin
have h1 := add_mul (complexity φ) 4 (complexity ψ),
have h2 : 5 + (complexity φ) * (complexity ψ) + 4 * (complexity ψ)
  = 5 + ((4 + complexity φ) * complexity ψ), linarith,
exact h2
end

lemma tr7helper6 {φ ψ : formPA agents} : (5 + ((4 + complexity φ) * complexity ψ))
  < (4 + complexity φ) * (4 + complexity ψ) :=
begin
have h1 := tr7helper5,
have h2 := tr7helper1,
exact (eq.substr h2 (eq.subst h1 tr7helper4))
end

lemma tr7 : ∀ φ ψ χ : formPA agents, (4 + (1 + max (complexity φ) ((4 + complexity φ)
  * complexity ψ))) * complexity χ < (4 + complexity φ) * ((4 + complexity ψ) * complexity χ) :=
begin
intros φ ψ χ,
have h1 := mul_assoc (4 + complexity φ) (4 + complexity ψ) (complexity χ),
have h2 : (5 + max (complexity φ) ((4 + complexity φ) * complexity ψ))
  = (4 + 1 + max (complexity φ) ((4 + complexity φ) * complexity ψ)), linarith,
have h3 : (4 + 1 + max (complexity φ) ((4 + complexity φ) * complexity ψ))
  = (4 + (1 + max (complexity φ) ((4 + complexity φ) * complexity ψ))), linarith,
exact eq.subst h1 (mul_lt_mul_of_pos_right (eq.subst h3 (maxhelper tr7helper3 tr7helper6)) comp_gt_zero),
end

-------------- Helper lemmas for equiv_translation_aux --------------

lemma compand1 {φ ψ : formPA agents} {n : nat} : complexity (φ & ψ) ≤ n + 1 → complexity φ ≤ n :=
begin
intro h,
rw complexity at *,
have h1 := le_max_left (complexity φ) (complexity ψ),
linarith
end

lemma compand2 {φ ψ : formPA agents} {n : nat} : complexity (φ & ψ) ≤ n + 1 → complexity ψ ≤ n :=
begin
intro h,
rw complexity at *,
have h1 := le_max_right (complexity φ) (complexity ψ),
linarith
end

lemma compimp1 {φ ψ : formPA agents} {n : nat} : complexity (φ ⊃ ψ) ≤ n + 1 → complexity φ ≤ n :=
begin
intro h,
rw complexity at *,
have h1 := le_max_left (complexity φ) (complexity ψ),
linarith
end

lemma compimp2 {φ ψ : formPA agents} {n : nat} : complexity (φ ⊃ ψ) ≤ n + 1 → complexity ψ ≤ n :=
begin
intro h,
rw complexity at *,
have h1 := le_max_right (complexity φ) (complexity ψ),
linarith
end

lemma updatecomphelper {φ ψ : formPA agents} :
  complexity (U φ ψ) = (complexity φ + 4) * complexity ψ :=
begin
have h1 := add_comm 4 (complexity φ),
have h2 : (4 + complexity φ) * complexity ψ = (4 + complexity φ) * complexity ψ, refl,
exact (eq.subst h1 h2),
end

lemma updatecompand1 {φ ψ χ : formPA agents} {n : nat} :
  complexity (U φ (ψ & χ)) ≤ n + 1 → complexity (U φ ψ) ≤ n :=
begin
intro h1,
simp only [complexity] at *,
have h2 := add_le_add_left (le_max_left (complexity ψ) (complexity χ)) 1,
have h3 := comp_ge_one,
have h4 : complexity φ + 4 ≥ 1, from le_add_right h3,
have h5 := le_trans (nat.mul_le_mul_left ((4 + complexity φ)) h2) h1,
have h6 := mul_add (4 + complexity φ) 1 (complexity ψ),
have h7 : (4 + complexity φ) * (complexity ψ) <
  (4 + complexity φ) + (4 + complexity φ) * (complexity ψ), linarith,
linarith
end

lemma updatecompand2 {φ ψ χ : formPA agents} {n : nat} :
  complexity (U φ (ψ & χ)) ≤ n + 1 → complexity (U φ χ) ≤ n :=
begin
intro h1,
simp only [complexity] at *,
have h2 := add_le_add_left (le_max_right (complexity ψ) (complexity χ)) 1,
have h3 := comp_ge_one,
have h4 : complexity φ + 4 ≥ 1, from le_add_right h3,
have h5 := le_trans (nat.mul_le_mul_left ((4 + complexity φ)) h2) h1,
have h6 := mul_add (4 + complexity φ) 1 (complexity χ),
have h7 : (4 + complexity φ) * (complexity ψ) <
  (4 + complexity φ) + (4 + complexity φ) * (complexity ψ), linarith,
linarith
end

lemma updatecompimp1 {φ ψ χ : formPA agents} {n : nat} :
  complexity (U φ (ψ ⊃ χ)) ≤ n + 1 → complexity (U φ ψ) ≤ n :=
begin
intro h1,
rw complexity at *,
have h2 := add_le_add_left (le_max_left (complexity ψ) (complexity χ)) 1,
have h3 := comp_ge_one,
have h4 : complexity φ + 4 ≥ 1, from le_add_right h3,
have h5 := le_trans (nat.mul_le_mul_left ((4 + complexity φ)) h2) h1,
have h6 := mul_add (4 + complexity φ) 1 (complexity ψ),
have h7 : (4 + complexity φ) * (complexity ψ) <
  (4 + complexity φ) + (4 + complexity φ) * (complexity ψ), linarith,
linarith
end

lemma updatecompimp2 {φ ψ χ : formPA agents} {n : nat} :
  complexity (U φ (ψ ⊃ χ)) ≤ n + 1 → complexity (U φ χ) ≤ n :=
begin
intro h1,
simp only [complexity] at *,
have h2 := add_le_add_left (le_max_right (complexity ψ) (complexity χ)) 1,
have h3 := comp_ge_one,
have h4 : complexity φ + 4 ≥ 1, from le_add_right h3,
have h5 := le_trans (nat.mul_le_mul_left ((4 + complexity φ)) h2) h1,
have h6 := mul_add (4 + complexity φ) 1 (complexity χ),
have h7 : (4 + complexity φ) * (complexity ψ) <
  (4 + complexity φ) + (4 + complexity φ) * (complexity ψ), linarith,
linarith
end

lemma updatecompknow1' (φ ψ : formPA agents) {n : nat} {a : agents} : complexity (U φ (K a ψ)) ≤ n + 1
  → 1 + complexity φ ≤ n :=
begin
intro h1,
simp only [complexity] at h1,
have h2 : complexity φ > 0, from comp_gt_zero,
have h3 : complexity ψ ≥ 1, from comp_ge_one,
have h4 := add_mul 4 (complexity φ) (1 + complexity ψ),
have h5 := mul_add (complexity φ) 1 (complexity ψ),
have h6 := mul_add 4 1 (complexity ψ),
have h7 : 4 * (1 + complexity ψ) + complexity φ * (1 + complexity ψ) =
  4 * (1 + complexity ψ) + complexity φ * 1 + complexity φ * complexity ψ, linarith,
have h8 : (4 + complexity φ) * (1 + complexity ψ) =
  4 * 1 + 4 * complexity ψ + complexity φ * 1 + complexity φ * complexity ψ, linarith,
have h9 : complexity φ * complexity ψ + complexity φ * 1 + 4 * complexity ψ + 4 * 1 ≤ n + 1, linarith,
have h10 : complexity φ * complexity ψ + complexity φ * 1 + 4 * complexity ψ ≤ n, linarith,
have : complexity φ * complexity ψ ≥ 0, apply nat.zero_le,
have h11 : 1 + complexity φ ≤
  complexity φ * complexity ψ + complexity φ * 1 + 4 * complexity ψ, linarith,
exact le_trans h11 h10
end

lemma updatecompknow2' {φ ψ : formPA agents} {n : nat} : (4 + complexity φ) * (1 + complexity ψ) ≤ n + 1
  → 1 + (1 + (4 + complexity φ) * complexity ψ) ≤ n :=
begin
intro h1,
have h2 : complexity φ ≥ 1, from comp_ge_one,
have h3 : complexity ψ ≥ 1, from comp_ge_one,
have h4 := add_mul 4 (complexity φ) (1 + complexity ψ),
have h5 := mul_add (complexity φ) 1 (complexity ψ),
have h6 := mul_add 4 (complexity ψ) 1,
have h7 : (4 + complexity φ) * (1 + complexity ψ) =
  4 * (1 + complexity ψ) + complexity φ * 1 + complexity φ * complexity ψ, linarith,
have h8 : (4 + complexity φ) * (1 + complexity ψ) =
  complexity φ * complexity ψ + complexity φ * 1 + 4 * complexity ψ + 4 * 1, linarith,
have h9 : complexity φ * complexity ψ + complexity φ * 1 + 4 * complexity ψ + 4 ≤ n + 1,
  from eq.subst h8 h1,
have h10 : complexity φ * complexity ψ + complexity φ * 1 + 4 * complexity ψ + 3 ≤ n, linarith,
have h11 : (4 + complexity φ) * complexity ψ = 4 * complexity ψ + complexity φ * complexity ψ,
  from add_mul 4 (complexity φ) (complexity ψ),
have h12 : 1 + (4 + complexity φ) * complexity ψ =
  1 + (4 * complexity ψ + complexity φ * complexity ψ), linarith,
have h13 : 1 + (1 + (4 + complexity φ) * complexity ψ) =
  1 + (1 + (4 * complexity ψ + complexity φ * complexity ψ)), linarith,
have h14 : 1 + (1 + (4 * complexity ψ + complexity φ * complexity ψ)) =
  2 + 4 * complexity ψ + complexity φ * complexity ψ, linarith,
have h15 : 2 + 4 * complexity ψ + complexity φ * complexity ψ ≤
  complexity φ * complexity ψ + complexity φ * 1 + 4 * complexity ψ + 3, linarith,
have h16 : 1 + (1 + (4 * complexity ψ + complexity φ * complexity ψ)) ≤
  complexity φ * complexity ψ + complexity φ * 1 + 4 * complexity ψ + 3, from eq.substr h14 h15,
have h17 : 1 + (1 + (4 + complexity φ) * complexity ψ) ≤
  complexity φ * complexity ψ + complexity φ * 1 + 4 * complexity ψ + 3, from eq.substr h12 h16,
exact le_trans h17 h10
end

lemma updatecompknow1 {a : agents} {φ ψ : formPA agents} {n : nat} :
  complexity (U φ (K a ψ)) ≤ n + 1 → complexity φ ≤ n :=
begin
intro h1,
have h2 := updatecompknow1' φ ψ h1,
linarith
end

lemma updatecompknow2 {a : agents} {φ ψ : formPA agents} {n : nat} :
  complexity (U φ (K a ψ)) ≤ n + 1 → complexity (φ ⊃ K a (U φ ψ)) ≤ n :=
begin
intro h1,
exact le_maxhelper (updatecompknow1' φ ψ h1) (updatecompknow2' h1)
end

lemma updatecompupdate {φ ψ χ : formPA agents} {n : nat} :
  complexity (U φ (U ψ χ)) ≤ n + 1 → complexity (U (φ & U φ ψ) χ) ≤ n :=
begin
intro h1, repeat {rw complexity at *},
have h2 := add_left_comm 1 4 (max (complexity φ) ((complexity φ + 4) * complexity ψ)),
have h3 : (1 + (4 + max (complexity φ) ((4 + complexity φ) * complexity ψ))) =
  (4 + (1 + max (complexity φ) ((4 + complexity φ) * complexity ψ))),
  from eq.subst (add_comm (complexity φ) 4) h2,
have h4 : (1 + (4 + max (complexity φ) ((4 + complexity φ) * complexity ψ))) * complexity χ =
  (1 + (4 + max (complexity φ) ((4 + complexity φ) * complexity ψ))) * complexity χ, refl,
have h5 := lt_of_lt_of_le (tr7 φ ψ χ) h1,
linarith
end


-- this only works with the nightly 2022-07-13, adding results as comments
import Aesop

theorem inv_inv
  {G: Type}
  (inv: G → G)
  (mul: G → G → G)
  (one: G)
  (assocMul: forall (a b c: G), mul a (mul b c) = (mul (mul a b) c))
  (invLeft: forall (a: G), mul (inv a) a = one)
  (mulOne: forall (a: G), mul a one = a)
  (oneMul: forall (a: G), mul one a = a)
  (invRight: forall (a: G), mul a (inv a) = one)
  (x: G)
  : (inv (inv x) = x) := by
  aesop -- aesop: failed to prove the goal after exhaustive search.

theorem inv_mul_cancel_left
  {G: Type}
  (inv: G → G)
  (mul: G → G → G)
  (one: G)
  (assocMul: forall (a b c: G), mul a (mul b c) = (mul (mul a b) c))
  (invLeft: forall (a: G), mul (inv a) a = one)
  (mulOne: forall (a: G), mul a one = a)
  (oneMul: forall (a: G), mul one a = a)
  (invRight: forall (a: G), mul a (inv a) = one)
  (x y : G)
  : (mul (inv x) (mul x y)) = y := by
  aesop -- goals accomplished

theorem mul_inv_cancel_left
  {G: Type}
  (inv: G → G)
  (mul: G → G → G)
  (one: G)
  (assocMul: forall (a b c: G), mul a (mul b c) = (mul (mul a b) c))
  (invLeft: forall (a: G), mul (inv a) a = one)
  (mulOne: forall (a: G), mul a one = a)
  (oneMul: forall (a: G), mul one a = a)
  (invRight: forall (a: G), mul a (inv a) = one)
  (x y : G)
  : (mul x (mul (inv x) y)) = y := by
  aesop -- goals accomplished

theorem inv_mul
  {G: Type}
  (inv: G → G)
  (mul: G → G → G)
  (one: G)
  (assocMul: forall (a b c: G), mul a (mul b c) = (mul (mul a b) c))
  (invLeft: forall (a: G), mul (inv a) a = one)
  (mulOne: forall (a: G), mul a one = a)
  (oneMul: forall (a: G), mul one a = a)
  (invRight: forall (a: G), mul a (inv a) = one)
  (x y : G)
  : (inv (mul x y)) = (mul (inv y) (inv x)) := by
  aesop -- aesop: failed to prove the goal after exhaustive search.

theorem one_inv
  {G: Type}
  (inv: G → G)
  (mul: G → G → G)
  (one: G)
  (assocMul: forall (a b c: G), mul a (mul b c) = (mul (mul a b) c))
  (invLeft: forall (a: G), mul (inv a) a = one)
  (mulOne: forall (a: G), mul a one = a)
  (oneMul: forall (a: G), mul one a = a)
  (invRight: forall (a: G), mul a (inv a) = one)
  (x y : G)
  : (inv one) = one := by
  aesop -- aesop: failed to prove the goal after exhaustive search.


import data.pnat.basic
import lib.num

lemma pnat.succ_pred (n : ℕ+) : nat.succ (nat.pred n) = n :=
begin
  cases n with n h,
  cases n,
  have := lt_irrefl _ h ; contradiction,
  simp
end

def fin.with_max' (n : ℕ) (m : ℕ+) : fin m :=
⟨ min n (m-1), begin
                 have p := min_le_right n (nat.pred m),
                 have q := nat.lt_succ_of_le p,
                 rw nat.succ_pred_eq_of_pos at q,
                 exact q,
                 exact m.property,
               end ⟩


-- Copyright 2022-2023 VMware, Inc.
-- SPDX-License-Identifier: BSD-2-Clause

import init.algebra.order

import algebra.big_operators.basic
import data.dfinsupp.basic
import data.finset
import data.multiset.sort
import data.prod.lex

import tactic.omega
import tactic.linarith

/-!

# Z-sets

The type `Z[A]` is called a Z-set over elements of type A, which we can think of
as a collection of rows of type A. However, Z-sets are more general in that they
allow *integer multiplicities*; multiplicities greater than 1 correspond to
duplicates, while negative multiplicities correspond to retractions or
deletions. Hence `Z[A]` can be used not only to represent a table with rows of
type A but also changes to such a table.

Formally `Z[A]` is modeled as a function `A → ℤ` with finite support; that is,
only finitely many elements have non-zero multiplicity. This is necessary to
support well-defined summations over Z-sets.

`Z[A]` has a group structure that is essentially inherited from ℤ (the
operations are all pointwise). Similarly, it has a partial ordering where `m1 ≤
m2 := ∀ x, m1 x ≤ m2 x`.

Note that `Z[A]` is isomorphic to the free abelian group over `A`, so it is in a
formal sense the minimum needed to give `A` a group structure.

-/

variables {A B C: Type}.
variables [decidable_eq A] [decidable_eq B] [decidable_eq C].

/--
A Z-set is a function from A to ℤ with finite support.

This is implemented using dfinsupp; we use dfinsupp rather than finsupp since
its implementation is computable.
-/
def zset (A: Type) := Π₀ (_:A), ℤ.

notation `Z[` T `]` := zset T.

namespace zset.

instance zset_group : add_comm_group Z[A] :=
  by { unfold zset, apply (@dfinsupp.add_comm_group A (λ _, ℤ) _), }.

instance zset_fun_like : fun_like Z[A] A (λ (_:A), ℤ) :=
  by { unfold zset, apply_instance }.

-- this next few definitions do some work to implement printing of Z-sets, which
-- is unused so far.

def graph (m: Z[A]) : multiset (A × ℤ) :=
  m.support.val.map (λ a, (a, m a)).

def graph_list [linear_order A] (m: Z[A]) : list (A ×ₗ ℤ) :=
  multiset.sort (≤) (graph m).

def elements [linear_order A] (m: Z[A]) : list A :=
  multiset.sort (≤) (m.sum (λ a _, {a})).

@[protected, instance]
meta def has_to_format [has_to_format A] [linear_order A] : has_to_format Z[A] :=
  {to_format := λ m, (graph_list m).to_format}.

@[protected]
instance has_to_string [has_to_string A] [linear_order A] : has_to_string Z[A] :=
  {to_string := λ m, (list.map (λ (xz: A × ℤ), xz) (graph_list m)).to_string}.

@[simp]
lemma add_apply (m1 m2: Z[A]) (a: A) : (m1 + m2) a = m1 a + m2 a := rfl.

@[simp]
lemma sub_apply (m1 m2: Z[A]) (a: A) : (m1 - m2) a = m1 a - m2 a := rfl.

@[simp]
lemma neg_apply (m: Z[A]) (a: A) : (-m) a = -(m a) := rfl.

lemma add_support (m1 m2: Z[A]) :
  (m1 + m2).support =
  (m1.support ∪ m2.support).filter (λ a, m1 a + m2 a ≠ 0) :=
begin
  ext a, simp,
  contrapose!,
  intros h, cases h with h1 h2, rw [h1, h2], simp,
end

-- now we do some work so that `{a, b, c}` can be used to construct a Z-set

protected def empty : Z[A] := dfinsupp.mk ∅ (λ _, 0).
instance : has_emptyc Z[A] := {emptyc := zset.empty}.

protected def single (a:A) : Z[A] :=
  dfinsupp.single a 1.
instance : has_singleton A Z[A] := {singleton := zset.single}.

protected def insert (a:A) (m: Z[A])  : Z[A] := m + {a}.
instance : has_insert A Z[A] := {insert := zset.insert}.

@[simp]
lemma emptyc_apply (a:A) : (∅ : Z[A]) a = 0 := rfl.

@[simp]
lemma single_apply (a:A) (a': A) :
  ({a} : Z[A]) a' = if a = a' then 1 else 0 :=
begin
  change ({a} : Z[A]) with (zset.single a),
  unfold zset.single, simp,
end

@[simp]
lemma insert_apply (a: A) (m: Z[A]) (a': A) :
  has_insert.insert a m a' = m a' + if a = a' then 1 else 0 :=
begin
  change (has_insert.insert a m) with (zset.insert a m),
  unfold zset.insert, simp,
end

instance : is_lawful_singleton A Z[A] :=
begin
  split,
  intros x, ext a, simp,
end

#eval graph ({"alice", "bob"} : Z[string]).
#eval graph ({"alice"} - {"bob"} : Z[string]).

-- TODO: data.dfinsupp.order does contain a partial_order, but it had some weird
-- behavior
@[protected]
instance po : partial_order Z[A] :=
  { le := λ m1 m2, ∀ a, m1 a ≤ m2 a,
    le_refl := by { intros m a, simp, },
    le_trans := begin
      intros m1 m2 m3 h12 h23, intros a,
      apply le_trans, apply h12, apply h23,
    end,
    le_antisymm := begin
      intros m1 m2 hle1 hle2,
      ext a,
      apply le_antisymm, apply hle1, apply hle2,
    end,
  }.

-- TODO: how do I define `ordered_add_comm_group Z[A]` by just extending the existing
-- instances?

@[ext]
lemma zset_le_ext (m1 m2: Z[A]) : m1 ≤ m2 = (∀ a, m1 a ≤ m2 a) := rfl.

instance zset_mem : has_mem A Z[A] := ⟨λ a m, a ∈ m.support⟩.
lemma elem_eq (a: A) (m: zset A) : (a ∈ m) = (a ∈ m.support) := rfl.

protected def from_set (s: finset A) : Z[A] := dfinsupp.mk s (λ a, 1).

@[simp]
lemma from_set_0 : zset.from_set (∅ : finset A) = dfinsupp.mk ∅ (λ a, 1)
  := rfl.

@[simp]
lemma from_set_apply (s: finset A) (a: A) :
  zset.from_set s a = if (a ∈ s) then 1 else 0
  := rfl.

@[simp]
lemma from_set_support (s: finset A) :
  (zset.from_set s).support = s := by { ext a, simp }.

protected def to_set (s: Z[A]) : finset A := s.support.

@[simp]
lemma elem_to_set (a: A) (m: Z[A]) : a ∈ m.to_set ↔ a ∈ m := by refl.

@[simp]
lemma elem_from_set (a: A) (s: finset A) : a ∈ zset.from_set s ↔ a ∈ s :=
begin
  rw elem_eq, simp,
end

lemma to_from_set (s: finset A) [∀ a, decidable (a ∈ s)] :
  (zset.from_set s).to_set = s :=
begin
  ext a, simp,
end

/-
  Unlike the paper, we use [is_bag] for the property on ℤ-sets, [fun_positive]
  for the property on functions, [positive] for streams, and [is_positive] for
  the property on operators.
-/
def is_set (m: Z[A]) := ∀ a, a ∈ m → m a = 1.
def is_bag (m: Z[A]) := 0 ≤ m.
def fun_positive (f: Z[A] → Z[B]) := ∀ m, is_bag m → is_bag (f m).
def fun_positive2 (f: Z[A] → Z[B] → Z[C]) :=
  ∀ m1 m2, is_bag m1 → is_bag m2 → is_bag (f m1 m2).

-- mp stands for multiplicity, the result of applying a zset to an element
lemma elem_mp (m: Z[A]) (a: A) : a ∈ m ↔ m a ≠ 0 :=
  by { rw elem_eq, simp }.
lemma not_elem_mp (a: A) (m: Z[A]) : a ∉ m ↔ m a = 0 :=
  by { rw elem_eq, simp }.

lemma is_set_or (s: Z[A]) :
  is_set s ↔ ∀ a, s a = 0 ∨ s a = 1 :=
begin
  unfold is_set,
  split; intros h a,
  { rw<- not_elem_mp,
    by_cases (a ∈ s); tauto, },
  { have h' := h a,
    rw elem_mp, tauto, }
end

@[simp]
lemma is_set_0 : is_set (0: Z[A]) :=
begin
  rw is_set_or, tauto,
end

lemma set_is_bag (s: Z[A]) :
  is_set s -> is_bag s :=
begin
  intros hset a,
  cases ((is_set_or _).mp hset a) with h_a h_a; rw h_a;
  simp,
end

@[simp]
lemma elem_single (a x:A) :
  x ∈ ({a} : Z[A]) ↔ a = x :=
begin
  rw elem_mp, simp,
end

@[simp]
lemma support_single (a: A) :
  ({a} : Z[A]).support = {a} :=
begin
  ext x, simp, tauto,
end

def distinct (m: Z[A]) : Z[A] :=
  dfinsupp.mk (m.support.filter (λ a, m a > 0)) (λ _, 1).

@[simp]
lemma distinct_apply (m: Z[A]) (a: A) :
  distinct m a = if m a > 0 then 1 else 0 :=
begin
  unfold distinct, simp,
  congr' 1, ext, simp,
  intros, linarith,
end

section sum_linear.

namespace finset.
  lemma union_disjoint_l (s1 s2: finset A) :
    s1 ∪ s2 = s1.disj_union (s2 \ s1) finset.disjoint_sdiff :=
  begin
    ext a, simp,
  end

  lemma filter_filter_comm (p q : A → Prop) [decidable_pred p] [decidable_pred q] (s: finset A) :
    finset.filter p (finset.filter q s) = finset.filter q (finset.filter p s) :=
  begin
    repeat { rw finset.filter_filter },
    congr' 1, finish,
  end
end finset.

lemma sum_union_zero_l {α: Type} [add_comm_monoid α] (f: A → α) (s s': finset A) :
  (∀ x, x ∈ s' → x ∉ s → f x = 0) →
  finset.sum (s ∪ s') f =
  finset.sum s f :=
begin
  intros hz,
  rw finset.union_disjoint_l,
  rw finset.sum_disj_union,
  repeat { rw finset.sum_ite <|> rw finset.sum_add_distrib },
  simp,
  rw (@finset.sum_eq_zero _ _ _ _ (s' \ s)), simp,
  introv hel, simp at hel, apply hz; finish,
end

variables {G: Type} [add_comm_group G] (f: A → ℤ → G).

theorem general_sum_linear (m1 m2: Z[A]) :
  (∀ a, f a 0 = 0) →
  (∀ a m1 m2, f a (m1 + m2) = f a m1 + f a m2) →
  (m1 + m2).support.sum (λ a, f a ((m1 + m2) a)) =
  m1.support.sum (λ a, f a (m1 a)) +
  m2.support.sum (λ a, f a (m2 a)) :=
begin
  intros hf0 hflin,
  rw add_support,
  simp only [ne.def],
  rw finset.sum_filter_of_ne, swap,
  { intros x, simp, intros h1, contrapose!,
    intro hz, rw hz,
    apply hf0,
  },
  conv_lhs {
    congr, skip,
    funext,
    simp, rw hflin, skip,
  },
  rw finset.sum_add_distrib,
  congr' 1,
  { rw sum_union_zero_l, simp,
    introv hnz hz,
    rw hz,
    apply hf0, },
  { rw finset.union_comm,
    rw sum_union_zero_l, simp,
    introv hnz hz,
    rw hz,
    apply hf0, }
end

end sum_linear.

-- map is sufficiently complex and specific to the zset representation that we
-- define it here and prove some basic properties, from which it is much easier
-- to reason about it as a relational operator
section flatmap.

variables (f: A → Z[B]).

-- the core of flatmap (without the finite support of a real `Z[B]`)
def flatmap_at (m: Z[A]) : B → ℤ :=
  λ b, (m.support.sum (λ a, f a b * m a)).

def flatmap (m: Z[A]) : Z[B] :=
  dfinsupp.mk (m.support.bUnion (λ a, (f a).support)) (λ b, flatmap_at f m b).

-- This is the function used in the definition of flatmap; the theorem shows that
-- the support chosen is correct; that is, it is an over-approximation (the
-- actual support excludes elements where the sum cancels out and
-- reaches 0)
lemma flatmap_apply (m: Z[A]) :
  ∀ b, m.flatmap f b = flatmap_at f m b :=
begin
  intros,
  unfold zset.flatmap flatmap_at,
  simp,
  intros h,
  rw finset.sum_eq_zero,
  intros x h'; simp at h',
  rw h, simp, assumption,
end

theorem flatmap_0 : zset.flatmap f 0 = 0 := rfl.

private lemma ite_cases {c: Prop} [decidable c] (x z: A) (p: A → Prop) :
  p z →
  p x →
  p (ite c x z) :=
begin
  intros, split_ifs; finish,
end

theorem flatmap_linear (m1 m2: Z[A]) :
  zset.flatmap f (m1 + m2) = zset.flatmap f m1 + zset.flatmap f m2 :=
begin
  ext b, simp,
  repeat { rw flatmap_apply }, unfold flatmap_at,
  apply general_sum_linear (λ a m, f a b * m),
  { intros, simp, },
  { intros, simp, rw mul_add, },
end

lemma flatmap_from_set_card (s: finset A) (b:B) :
  (∀ a, (f a).is_set) →
  zset.flatmap_at f (zset.from_set s) b =
  finset.card (s.filter (λ (x : A), b ∈ f x)) :=
begin
  intros hset,
  unfold flatmap_at, simp,
  have hsum_1 : s.sum (λ a, f a b) = s.sum (λ a, if b ∈ f a then 1 else 0) := by {
    apply finset.sum_congr, refl,
    intros, split_ifs,
    { apply hset, assumption, },
    { rw not_elem_mp at h, assumption, },
  },
  rw hsum_1, simp,
end

lemma map_from_set_card (f: A → B) (s: finset A) (b:B) :
  zset.flatmap_at (λ a, {f a}) (zset.from_set s) b =
  finset.card (s.filter (λ (x : A), f x = b)) :=
begin
  rw flatmap_from_set_card,
  { simp },
  intros a,
  unfold is_set, simp,
end
end flatmap.

section map.

variables (f: A → B).

protected def map (m: Z[A]) : Z[B] := flatmap (λ a, {f a}) m.

lemma flatmap_map_at (m: Z[A]) (b: B) :
  flatmap_at (λ a, {f a}) m b = m.support.sum (λ a, if f a = b then m a else 0) :=
begin
  unfold flatmap_at, simp,
end

lemma map_apply (m: Z[A]) (b: B) :
  zset.map f m b = m.support.sum (λ a, if f a = b then m a else 0) :=
begin
  unfold zset.map, rw flatmap_apply,
  rw flatmap_map_at,
end

theorem map_linear (f: A → B) (m1 m2: Z[A]) :
  zset.map f (m1 + m2) = zset.map f m1 + zset.map f m2 :=
begin
  apply flatmap_linear,
end

lemma map_is_card (s: finset A) :
  ∀ b, zset.map f (zset.from_set s) b =
       (s.val.map f).count b :=
begin
  intros, unfold zset.map,
  rw flatmap_apply,
  rw flatmap_from_set_card,
  unfold multiset.count,
  rw multiset.countp_map,
  simp,
  rw finset.card_def,
  simp,
  congr' 1,
  apply multiset.filter_congr,
  { finish, },
  { intros a, unfold is_set, simp, },
end

namespace finset.
lemma sum_nonneg (s: finset A) (f: A → ℤ) :
  (∀ x, x ∈ s → 0 ≤ f x) →
  0 ≤ s.sum f :=
begin
  intros hnn,
  apply finset.sum_induction,
  { intros, linarith, },
  { linarith, },
  { assumption, },
end

lemma sum_pos (s: finset A) (f: A → ℤ) :
  (∃ a, a ∈ s ∧ 0 < f a) →
  (∀ x, x ∈ s → 0 ≤ f x) →
  0 < s.sum f :=
begin
  intros hpos hnn,
    cases hpos with a hpos, cases hpos with hel hpos,
  rw<- (finset.add_sum_erase s _ hel),
  suffices h : 0 ≤ (s.erase a).sum f,
  linarith,
  apply sum_nonneg,
  safe,
end
end finset.

lemma map_at_nonneg (f: A → B) (m: Z[A]) (b: B) :
  is_bag m →
  0 ≤ flatmap_at (λ a, {f a}) m b :=
begin
  intros hpos,
  unfold flatmap_at,
  apply finset.sum_nonneg,
  intros x, simp, intros,
  apply ite_cases, omega,
  apply hpos,
end

lemma map_at_pos (f: A → B) (m: Z[A]) (b: B) :
  is_bag m →
  (0 < flatmap_at (λ a, {f a}) m b ↔ ∃ a, a ∈ m ∧ f a = b) :=
begin
  intros hpos,
  split,
  { unfold flatmap_at,
    intros hmap,
    by_contra,
    rw finset.sum_eq_zero at hmap,
    { linarith, },
    { intros x, simp, intros h1 h2,
      push_neg at h,
      rw<- not_elem_mp at h1,
      tauto,
    }
  },
  { intros hex,
    unfold flatmap_at,
    apply finset.sum_pos,
    { cases hex with a h, cases h with hel hf,
      use a, simp,
      rw (if_pos hf),
      have ha := hpos a, simp at ha,
      rw elem_mp at hel, simp at hel,
      split,
      { tauto },
      { omega, }
    },
    { simp, intros,
      apply ite_cases, omega,
      apply hpos, },
  }
end

end map.

end zset.


/-
Copyright (c) 2019 Seul Baek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Seul Baek
-/

/-
Linear integer arithmetic formulas in pre-normalized form.
-/

import tactic.omega.int.preterm

namespace omega
namespace int

/-- Intermediate shadow syntax for LNA formulas that includes unreified exprs -/
meta inductive exprform
| eq  : exprterm → exprterm → exprform
| le  : exprterm → exprterm → exprform
| not : exprform → exprform
| or  : exprform → exprform → exprform
| and : exprform → exprform → exprform

/-- Intermediate shadow syntax for LIA formulas that includes non-canonical terms -/
@[derive has_reflect, derive inhabited]
inductive preform
| eq  : preterm → preterm → preform
| le  : preterm → preterm → preform
| not : preform → preform
| or  : preform → preform → preform
| and : preform → preform → preform

localized "notation (name := preform.eq) x ` =* ` y := omega.int.preform.eq x y" in omega.int
localized "notation (name := preform.le) x ` ≤* ` y := omega.int.preform.le x y" in omega.int
localized "notation (name := preform.not) `¬* ` p   := omega.int.preform.not p" in omega.int
localized "notation (name := preform.or) p ` ∨* ` q := omega.int.preform.or p q" in omega.int
localized "notation (name := preform.and) p ` ∧* ` q := omega.int.preform.and p q" in omega.int

namespace preform

/-- Evaluate a preform into prop using the valuation v. -/
@[simp] def holds (v : nat → int) : preform → Prop
| (t =* s) := t.val v = s.val v
| (t ≤* s) := t.val v ≤ s.val v
| (¬* p)   := ¬ p.holds
| (p ∨* q) := p.holds ∨ q.holds
| (p ∧* q) := p.holds ∧ q.holds

end preform

/-- univ_close p n := p closed by prepending n universal quantifiers -/
@[simp] def univ_close (p : preform) : (nat → int) → nat → Prop
| v 0     := p.holds v
| v (k+1) := ∀ i : int, univ_close (update_zero i v) k

namespace preform

/-- Fresh de Brujin index not used by any variable in argument -/
def fresh_index : preform → nat
| (t =* s) := max t.fresh_index s.fresh_index
| (t ≤* s) := max t.fresh_index s.fresh_index
| (¬* p)   := p.fresh_index
| (p ∨* q) := max p.fresh_index q.fresh_index
| (p ∧* q) := max p.fresh_index q.fresh_index

/-- All valuations satisfy argument -/
def valid (p : preform) : Prop :=
∀ v, holds v p

/-- There exists some valuation that satisfies argument -/
def sat (p : preform) : Prop :=
∃ v, holds v p

/-- implies p q := under any valuation, q holds if p holds -/
def implies (p q : preform) : Prop :=
∀ v, (holds v p → holds v q)

/-- equiv p q := under any valuation, p holds iff q holds -/
def equiv (p q : preform) : Prop :=
∀ v, (holds v p ↔ holds v q)

lemma sat_of_implies_of_sat {p q : preform} :
  implies p q → sat p → sat q :=
begin intros h1 h2, apply exists_imp_exists h1 h2 end

lemma sat_or {p q : preform} :
  sat (p ∨* q) ↔ sat p ∨ sat q :=
begin
  constructor; intro h1,
  { cases h1 with v h1, cases h1 with h1 h1;
    [left,right]; refine ⟨v,_⟩; assumption },
  { cases h1 with h1 h1; cases h1 with v h1;
    refine ⟨v,_⟩; [left,right]; assumption }
end

/-- There does not exist any valuation that satisfies argument -/
def unsat (p : preform) : Prop := ¬ sat p

def repr : preform → string
| (t =* s) := "(" ++ t.repr ++ " = " ++ s.repr ++ ")"
| (t ≤* s) := "(" ++ t.repr ++ " ≤ " ++ s.repr ++ ")"
| (¬* p)   := "¬" ++ p.repr
| (p ∨* q) := "(" ++ p.repr ++ " ∨ " ++ q.repr ++ ")"
| (p ∧* q) := "(" ++ p.repr ++ " ∧ " ++ q.repr ++ ")"

instance has_repr : has_repr preform := ⟨repr⟩
meta instance has_to_format : has_to_format preform := ⟨λ x, x.repr⟩

end preform

lemma univ_close_of_valid {p : preform} :
  ∀ {m v}, p.valid → univ_close p v m
| 0 v h1     := h1 _
| (m+1) v h1 := λ i, univ_close_of_valid h1

lemma valid_of_unsat_not {p : preform} : (¬*p).unsat → p.valid :=
begin
  simp only [preform.sat, preform.unsat, preform.valid, preform.holds],
  rw not_exists_not, intro h, assumption
end

/-- Tactic for setting up proof by induction over preforms. -/
meta def preform.induce (t : tactic unit := tactic.skip) : tactic unit :=
`[ intro p, induction p with t s t s p ih p q ihp ihq p q ihp ihq; t]

end int

end omega


/-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import algebra.lie.subalgebra
import ring_theory.noetherian

/-!
# Lie submodules of a Lie algebra

In this file we define Lie submodules and Lie ideals, we construct the lattice structure on Lie
submodules and we use it to define various important operations, notably the Lie span of a subset
of a Lie module.

## Main definitions

  * `lie_submodule`
  * `lie_submodule.well_founded_of_noetherian`
  * `lie_submodule.lie_span`
  * `lie_submodule.map`
  * `lie_submodule.comap`
  * `lie_ideal`
  * `lie_ideal.map`
  * `lie_ideal.comap`

## Tags

lie algebra, lie submodule, lie ideal, lattice structure
-/

universes u v w w₁ w₂

section lie_submodule

variables (R : Type u) (L : Type v) (M : Type w)
variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M]
variables [lie_ring_module L M] [lie_module R L M]

set_option old_structure_cmd true
/-- A Lie submodule of a Lie module is a submodule that is closed under the Lie bracket.
This is a sufficient condition for the subset itself to form a Lie module. -/
structure lie_submodule extends submodule R M :=
(lie_mem : ∀ {x : L} {m : M}, m ∈ carrier → ⁅x, m⁆ ∈ carrier)

attribute [nolint doc_blame] lie_submodule.to_submodule

namespace lie_submodule

variables {R L M} (N N' : lie_submodule R L M)

instance : set_like (lie_submodule R L M) M :=
{ coe := carrier,
  coe_injective' := λ N O h, by cases N; cases O; congr' }

/-- The zero module is a Lie submodule of any Lie module. -/
instance : has_zero (lie_submodule R L M) :=
⟨{ lie_mem := λ x m h, by { rw ((submodule.mem_bot R).1 h), apply lie_zero, },
   ..(0 : submodule R M)}⟩

instance : inhabited (lie_submodule R L M) := ⟨0⟩

instance coe_submodule : has_coe (lie_submodule R L M) (submodule R M) := ⟨to_submodule⟩

@[simp] lemma to_submodule_eq_coe : N.to_submodule = N := rfl

@[norm_cast]
lemma coe_to_submodule : ((N : submodule R M) : set M) = N := rfl

@[simp] lemma mem_carrier {x : M} : x ∈ N.carrier ↔ x ∈ (N : set M) :=
iff.rfl

@[simp] lemma mem_mk_iff (S : set M) (h₁ h₂ h₃ h₄) {x : M} :
  x ∈ (⟨S, h₁, h₂, h₃, h₄⟩ : lie_submodule R L M) ↔ x ∈ S :=
iff.rfl

@[simp] lemma mem_coe_submodule {x : M} : x ∈ (N : submodule R M) ↔ x ∈ N := iff.rfl

lemma mem_coe {x : M} : x ∈ (N : set M) ↔ x ∈ N := iff.rfl

@[simp] lemma zero_mem : (0 : M) ∈ N := (N : submodule R M).zero_mem

@[simp] lemma mk_eq_zero {x} (h : x ∈ N) : (⟨x, h⟩ : N) = 0 ↔ x = 0 := subtype.ext_iff_val

@[simp] lemma coe_to_set_mk (S : set M) (h₁ h₂ h₃ h₄) :
  ((⟨S, h₁, h₂, h₃, h₄⟩ : lie_submodule R L M) : set M) = S := rfl

@[simp] lemma coe_to_submodule_mk (p : submodule R M) (h) :
  (({lie_mem := h, ..p} : lie_submodule R L M) : submodule R M) = p :=
by { cases p, refl, }

lemma coe_submodule_injective :
  function.injective (to_submodule : lie_submodule R L M → submodule R M) :=
λ x y h, by { cases x, cases y, congr, injection h }

@[ext] lemma ext (h : ∀ m, m ∈ N ↔ m ∈ N') : N = N' := set_like.ext h

@[simp] lemma coe_to_submodule_eq_iff : (N : submodule R M) = (N' : submodule R M) ↔ N = N' :=
coe_submodule_injective.eq_iff

/-- Copy of a lie_submodule with a new `carrier` equal to the old one. Useful to fix definitional
equalities. -/
protected def copy (s : set M) (hs : s = ↑N) : lie_submodule R L M :=
{ carrier := s,
  zero_mem' := hs.symm ▸ N.zero_mem',
  add_mem'  := hs.symm ▸ N.add_mem',
  smul_mem' := hs.symm ▸ N.smul_mem',
  lie_mem   := hs.symm ▸ N.lie_mem, }

@[simp] lemma coe_copy (S : lie_submodule R L M) (s : set M) (hs : s = ↑S) :
  (S.copy s hs : set M) = s := rfl

lemma copy_eq (S : lie_submodule R L M) (s : set M) (hs : s = ↑S) : S.copy s hs = S :=
coe_submodule_injective (set_like.coe_injective hs)

instance : lie_ring_module L N :=
{ bracket     := λ (x : L) (m : N), ⟨⁅x, m.val⁆, N.lie_mem m.property⟩,
  add_lie     := by { intros x y m, apply set_coe.ext, apply add_lie, },
  lie_add     := by { intros x m n, apply set_coe.ext, apply lie_add, },
  leibniz_lie := by { intros x y m, apply set_coe.ext, apply leibniz_lie, }, }

instance module' {S : Type*} [semiring S] [has_scalar S R] [module S M] [is_scalar_tower S R M] :
  module S N :=
N.to_submodule.module'

instance : module R N := N.to_submodule.module

instance {S : Type*} [semiring S] [has_scalar S R] [has_scalar Sᵐᵒᵖ R] [module S M] [module Sᵐᵒᵖ M]
  [is_scalar_tower S R M] [is_scalar_tower Sᵐᵒᵖ R M] [is_central_scalar S M] :
  is_central_scalar S N :=
N.to_submodule.is_central_scalar

instance : lie_module R L N :=
{ lie_smul := by { intros t x y, apply set_coe.ext, apply lie_smul, },
  smul_lie := by { intros t x y, apply set_coe.ext, apply smul_lie, }, }

@[simp, norm_cast] lemma coe_zero : ((0 : N) : M) = (0 : M) := rfl

@[simp, norm_cast] lemma coe_add (m m' : N) : (↑(m + m') : M) = (m : M) + (m' : M) := rfl

@[simp, norm_cast] lemma coe_neg (m : N) : (↑(-m) : M) = -(m : M) := rfl

@[simp, norm_cast] lemma coe_sub (m m' : N) : (↑(m - m') : M) = (m : M) - (m' : M) := rfl

@[simp, norm_cast] lemma coe_smul (t : R) (m : N) : (↑(t • m) : M) = t • (m : M) := rfl

@[simp, norm_cast] lemma coe_bracket (x : L) (m : N) : (↑⁅x, m⁆ : M) = ⁅x, ↑m⁆ := rfl

end lie_submodule

section lie_ideal

variables (L)

/-- An ideal of a Lie algebra is a Lie submodule of the Lie algebra as a Lie module over itself. -/
abbreviation lie_ideal := lie_submodule R L L

lemma lie_mem_right (I : lie_ideal R L) (x y : L) (h : y ∈ I) : ⁅x, y⁆ ∈ I := I.lie_mem h

lemma lie_mem_left (I : lie_ideal R L) (x y : L) (h : x ∈ I) : ⁅x, y⁆ ∈ I :=
 by { rw [←lie_skew, ←neg_lie], apply lie_mem_right, assumption, }

/-- An ideal of a Lie algebra is a Lie subalgebra. -/
def lie_ideal_subalgebra (I : lie_ideal R L) : lie_subalgebra R L :=
{ lie_mem' := by { intros x y hx hy, apply lie_mem_right, exact hy, },
  ..I.to_submodule, }

instance : has_coe (lie_ideal R L) (lie_subalgebra R L) := ⟨λ I, lie_ideal_subalgebra R L I⟩

@[norm_cast] lemma lie_ideal.coe_to_subalgebra (I : lie_ideal R L) :
  ((I : lie_subalgebra R L) : set L) = I := rfl

@[norm_cast] lemma lie_ideal.coe_to_lie_subalgebra_to_submodule (I : lie_ideal R L) :
  ((I : lie_subalgebra R L) : submodule R L) = I := rfl

end lie_ideal

variables {R M}

lemma submodule.exists_lie_submodule_coe_eq_iff (p : submodule R M) :
  (∃ (N : lie_submodule R L M), ↑N = p) ↔ ∀ (x : L) (m : M), m ∈ p → ⁅x, m⁆ ∈ p :=
begin
  split,
  { rintros ⟨N, rfl⟩, exact N.lie_mem, },
  { intros h, use { lie_mem := h, ..p }, exact lie_submodule.coe_to_submodule_mk p _, },
end

namespace lie_subalgebra

variables {L} (K : lie_subalgebra R L)

/-- Given a Lie subalgebra `K ⊆ L`, if we view `L` as a `K`-module by restriction, it contains
a distinguished Lie submodule for the action of `K`, namely `K` itself. -/
def to_lie_submodule : lie_submodule R K L :=
{ lie_mem := λ x y hy, K.lie_mem x.property hy,
  .. (K : submodule R L) }

@[simp] lemma coe_to_lie_submodule :
  (K.to_lie_submodule : submodule R L) = K :=
by { rcases K with ⟨⟨⟩⟩, refl, }

variables {K}

@[simp] lemma mem_to_lie_submodule (x : L) :
  x ∈ K.to_lie_submodule ↔ x ∈ K :=
iff.rfl

lemma exists_lie_ideal_coe_eq_iff :
  (∃ (I : lie_ideal R L), ↑I = K) ↔ ∀ (x y : L), y ∈ K → ⁅x, y⁆ ∈ K :=
begin
  simp only [← coe_to_submodule_eq_iff, lie_ideal.coe_to_lie_subalgebra_to_submodule,
    submodule.exists_lie_submodule_coe_eq_iff L],
  exact iff.rfl,
end

lemma exists_nested_lie_ideal_coe_eq_iff {K' : lie_subalgebra R L} (h : K ≤ K') :
  (∃ (I : lie_ideal R K'), ↑I = of_le h) ↔ ∀ (x y : L), x ∈ K' → y ∈ K → ⁅x, y⁆ ∈ K :=
begin
  simp only [exists_lie_ideal_coe_eq_iff, coe_bracket, mem_of_le],
  split,
  { intros h' x y hx hy, exact h' ⟨x, hx⟩ ⟨y, h hy⟩ hy, },
  { rintros h' ⟨x, hx⟩ ⟨y, hy⟩ hy', exact h' x y hx hy', },
end

end lie_subalgebra

end lie_submodule

namespace lie_submodule

variables {R : Type u} {L : Type v} {M : Type w}
variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M]
variables [lie_ring_module L M] [lie_module R L M]
variables (N N' : lie_submodule R L M) (I J : lie_ideal R L)

section lattice_structure

open set

lemma coe_injective : function.injective (coe : lie_submodule R L M → set M) :=
set_like.coe_injective

@[simp, norm_cast] lemma coe_submodule_le_coe_submodule : (N : submodule R M) ≤ N' ↔ N ≤ N' :=
iff.rfl

instance : has_bot (lie_submodule R L M) := ⟨0⟩

@[simp] lemma bot_coe : ((⊥ : lie_submodule R L M) : set M) = {0} := rfl

@[simp] lemma bot_coe_submodule : ((⊥ : lie_submodule R L M) : submodule R M) = ⊥ := rfl

@[simp] lemma mem_bot (x : M) : x ∈ (⊥ : lie_submodule R L M) ↔ x = 0 := mem_singleton_iff

instance : has_top (lie_submodule R L M) :=
⟨{ lie_mem := λ x m h, mem_univ ⁅x, m⁆,
   ..(⊤ : submodule R M) }⟩

@[simp] lemma top_coe : ((⊤ : lie_submodule R L M) : set M) = univ := rfl

@[simp] lemma top_coe_submodule : ((⊤ : lie_submodule R L M) : submodule R M) = ⊤ := rfl

@[simp] lemma mem_top (x : M) : x ∈ (⊤ : lie_submodule R L M) := mem_univ x

instance : has_inf (lie_submodule R L M) :=
⟨λ N N', { lie_mem := λ x m h, mem_inter (N.lie_mem h.1) (N'.lie_mem h.2),
            ..(N ⊓ N' : submodule R M) }⟩

instance : has_Inf (lie_submodule R L M) :=
⟨λ S, { lie_mem := λ x m h, by
        { simp only [submodule.mem_carrier, mem_Inter, submodule.Inf_coe, mem_set_of_eq,
            forall_apply_eq_imp_iff₂, exists_imp_distrib] at *,
          intros N hN, apply N.lie_mem (h N hN), },
        ..Inf {(s : submodule R M) | s ∈ S} }⟩

@[simp] theorem inf_coe : (↑(N ⊓ N') : set M) = N ∩ N' := rfl

@[simp] lemma Inf_coe_to_submodule (S : set (lie_submodule R L M)) :
  (↑(Inf S) : submodule R M) = Inf {(s : submodule R M) | s ∈ S} := rfl

@[simp] lemma Inf_coe (S : set (lie_submodule R L M)) : (↑(Inf S) : set M) = ⋂ s ∈ S, (s : set M) :=
begin
  rw [← lie_submodule.coe_to_submodule, Inf_coe_to_submodule, submodule.Inf_coe],
  ext m,
  simpa only [mem_Inter, mem_set_of_eq, forall_apply_eq_imp_iff₂, exists_imp_distrib],
end

lemma Inf_glb (S : set (lie_submodule R L M)) : is_glb S (Inf S) :=
begin
  have h : ∀ (N N' : lie_submodule R L M), (N : set M) ≤ N' ↔ N ≤ N', { intros, refl },
  apply is_glb.of_image h,
  simp only [Inf_coe],
  exact is_glb_binfi
end

/-- The set of Lie submodules of a Lie module form a complete lattice.

We provide explicit values for the fields `bot`, `top`, `inf` to get more convenient definitions
than we would otherwise obtain from `complete_lattice_of_Inf`.  -/
instance : complete_lattice (lie_submodule R L M) :=
{ le           := (≤),
  lt           := (<),
  bot          := ⊥,
  bot_le       := λ N _ h, by { rw mem_bot at h, rw h, exact N.zero_mem', },
  top          := ⊤,
  le_top       := λ _ _ _, trivial,
  inf          := (⊓),
  le_inf       := λ N₁ N₂ N₃ h₁₂ h₁₃ m hm, ⟨h₁₂ hm, h₁₃ hm⟩,
  inf_le_left  := λ _ _ _, and.left,
  inf_le_right := λ _ _ _, and.right,
  ..set_like.partial_order,
  ..complete_lattice_of_Inf _ Inf_glb }

instance : add_comm_monoid (lie_submodule R L M) :=
{ add       := (⊔),
  add_assoc := λ _ _ _, sup_assoc,
  zero      := ⊥,
  zero_add  := λ _, bot_sup_eq,
  add_zero  := λ _, sup_bot_eq,
  add_comm  := λ _ _, sup_comm, }

@[simp] lemma add_eq_sup : N + N' = N ⊔ N' := rfl

@[norm_cast, simp] lemma sup_coe_to_submodule :
  (↑(N ⊔ N') : submodule R M) = (N : submodule R M) ⊔ (N' : submodule R M) :=
begin
  have aux : ∀ (x : L) m, m ∈ (N ⊔ N' : submodule R M) → ⁅x,m⁆ ∈ (N ⊔ N' : submodule R M),
  { simp only [submodule.mem_sup],
    rintro x m ⟨y, hy, z, hz, rfl⟩,
    refine ⟨⁅x, y⁆, N.lie_mem hy, ⁅x, z⁆, N'.lie_mem hz, (lie_add _ _ _).symm⟩ },
  refine le_antisymm (Inf_le ⟨{ lie_mem := aux, ..(N ⊔ N' : submodule R M) }, _⟩) _,
  { simp only [exists_prop, and_true, mem_set_of_eq, eq_self_iff_true, coe_to_submodule_mk,
      ← coe_submodule_le_coe_submodule, and_self, le_sup_left, le_sup_right] },
  { simp, },
end

@[norm_cast, simp] lemma inf_coe_to_submodule :
  (↑(N ⊓ N') : submodule R M) = (N : submodule R M) ⊓ (N' : submodule R M) := rfl

@[simp] lemma mem_inf (x : M) : x ∈ N ⊓ N' ↔ x ∈ N ∧ x ∈ N' :=
by rw [← mem_coe_submodule, ← mem_coe_submodule, ← mem_coe_submodule, inf_coe_to_submodule,
  submodule.mem_inf]

lemma mem_sup (x : M) : x ∈ N ⊔ N' ↔ ∃ (y ∈ N) (z ∈ N'), y + z = x :=
by { rw [← mem_coe_submodule, sup_coe_to_submodule, submodule.mem_sup], exact iff.rfl, }

lemma eq_bot_iff : N = ⊥ ↔ ∀ (m : M), m ∈ N → m = 0 :=
by { rw eq_bot_iff, exact iff.rfl, }

-- TODO[gh-6025]: make this an instance once safe to do so
lemma subsingleton_of_bot : subsingleton (lie_submodule R L ↥(⊥ : lie_submodule R L M)) :=
begin
  apply subsingleton_of_bot_eq_top,
  ext ⟨x, hx⟩, change x ∈ ⊥ at hx, rw submodule.mem_bot at hx, subst hx,
  simp only [true_iff, eq_self_iff_true, submodule.mk_eq_zero, lie_submodule.mem_bot],
end

instance : is_modular_lattice (lie_submodule R L M) :=
{ sup_inf_le_assoc_of_le := λ N₁ N₂ N₃,
    by { simp only [← coe_submodule_le_coe_submodule, sup_coe_to_submodule, inf_coe_to_submodule],
         exact is_modular_lattice.sup_inf_le_assoc_of_le ↑N₂, }, }

variables (R L M)

lemma well_founded_of_noetherian [is_noetherian R M] :
  well_founded ((>) : lie_submodule R L M → lie_submodule R L M → Prop) :=

let f : ((>) : lie_submodule R L M → lie_submodule R L M → Prop) →r
        ((>) : submodule R M → submodule R M → Prop) :=
{ to_fun       := coe,
  map_rel' := λ N N' h, h, }
in rel_hom_class.well_founded f (is_noetherian_iff_well_founded.mp infer_instance)

@[simp] lemma subsingleton_iff : subsingleton (lie_submodule R L M) ↔ subsingleton M :=
have h : subsingleton (lie_submodule R L M) ↔ subsingleton (submodule R M),
{ rw [← subsingleton_iff_bot_eq_top, ← subsingleton_iff_bot_eq_top, ← coe_to_submodule_eq_iff,
    top_coe_submodule, bot_coe_submodule], },
h.trans $ submodule.subsingleton_iff R

@[simp] lemma nontrivial_iff : nontrivial (lie_submodule R L M) ↔ nontrivial M :=
not_iff_not.mp (
  (not_nontrivial_iff_subsingleton.trans $ subsingleton_iff R L M).trans
  not_nontrivial_iff_subsingleton.symm)

instance [nontrivial M] : nontrivial (lie_submodule R L M) := (nontrivial_iff R L M).mpr ‹_›

lemma nontrivial_iff_ne_bot {N : lie_submodule R L M} : nontrivial N ↔ N ≠ ⊥ :=
begin
  split;
  contrapose!,
  { rintros rfl ⟨⟨m₁, h₁ : m₁ ∈ (⊥ : lie_submodule R L M)⟩,
                 ⟨m₂, h₂ : m₂ ∈ (⊥ : lie_submodule R L M)⟩, h₁₂⟩,
    simpa [(lie_submodule.mem_bot _).mp h₁, (lie_submodule.mem_bot _).mp h₂] using h₁₂, },
  { rw [not_nontrivial_iff_subsingleton, lie_submodule.eq_bot_iff],
    rintros ⟨h⟩ m hm,
    simpa using h ⟨m, hm⟩ ⟨_, N.zero_mem⟩, },
end

variables {R L M}

section inclusion_maps

/-- The inclusion of a Lie submodule into its ambient space is a morphism of Lie modules. -/
def incl : N →ₗ⁅R,L⁆ M :=
{ map_lie' := λ x m, rfl,
  ..submodule.subtype (N : submodule R M) }

@[simp] lemma incl_coe : (N.incl : N →ₗ[R] M) = (N : submodule R M).subtype := rfl

@[simp] lemma incl_apply (m : N) : N.incl m = m := rfl

lemma incl_eq_val : (N.incl : N → M) = subtype.val := rfl

variables {N N'} (h : N ≤ N')

/-- Given two nested Lie submodules `N ⊆ N'`, the inclusion `N ↪ N'` is a morphism of Lie modules.-/
def hom_of_le : N →ₗ⁅R,L⁆ N' :=
{ map_lie' := λ x m, rfl,
  ..submodule.of_le (show N.to_submodule ≤ N'.to_submodule, from h) }

@[simp] lemma coe_hom_of_le (m : N) : (hom_of_le h m : M) = m := rfl

lemma hom_of_le_apply (m : N) : hom_of_le h m = ⟨m.1, h m.2⟩ := rfl

lemma hom_of_le_injective : function.injective (hom_of_le h) :=
λ x y, by simp only [hom_of_le_apply, imp_self, subtype.mk_eq_mk, set_like.coe_eq_coe,
  subtype.val_eq_coe]

end inclusion_maps

section lie_span

variables (R L) (s : set M)
/-- The `lie_span` of a set `s ⊆ M` is the smallest Lie submodule of `M` that contains `s`. -/
def lie_span : lie_submodule R L M := Inf {N | s ⊆ N}

variables {R L s}

lemma mem_lie_span {x : M} : x ∈ lie_span R L s ↔ ∀ N : lie_submodule R L M, s ⊆ N → x ∈ N :=
by { change x ∈ (lie_span R L s : set M) ↔ _, erw Inf_coe, exact mem_Inter₂, }

lemma subset_lie_span : s ⊆ lie_span R L s :=
by { intros m hm, erw mem_lie_span, intros N hN, exact hN hm, }

lemma submodule_span_le_lie_span : submodule.span R s ≤ lie_span R L s :=
by { rw submodule.span_le, apply subset_lie_span, }

lemma lie_span_le {N} : lie_span R L s ≤ N ↔ s ⊆ N :=
begin
  split,
  { exact subset.trans subset_lie_span, },
  { intros hs m hm, rw mem_lie_span at hm, exact hm _ hs, },
end

lemma lie_span_mono {t : set M} (h : s ⊆ t) : lie_span R L s ≤ lie_span R L t :=
by { rw lie_span_le, exact subset.trans h subset_lie_span, }

lemma lie_span_eq : lie_span R L (N : set M) = N :=
le_antisymm (lie_span_le.mpr rfl.subset) subset_lie_span

lemma coe_lie_span_submodule_eq_iff {p : submodule R M} :
  (lie_span R L (p : set M) : submodule R M) = p ↔ ∃ (N : lie_submodule R L M), ↑N = p :=
begin
  rw p.exists_lie_submodule_coe_eq_iff L, split; intros h,
  { intros x m hm, rw [← h, mem_coe_submodule], exact lie_mem _ (subset_lie_span hm), },
  { rw [← coe_to_submodule_mk p h, coe_to_submodule, coe_to_submodule_eq_iff, lie_span_eq], },
end

variables (R L M)

/-- `lie_span` forms a Galois insertion with the coercion from `lie_submodule` to `set`. -/
protected def gi : galois_insertion (lie_span R L : set M → lie_submodule R L M) coe :=
{ choice    := λ s _, lie_span R L s,
  gc        := λ s t, lie_span_le,
  le_l_u    := λ s, subset_lie_span,
  choice_eq := λ s h, rfl }

@[simp] lemma span_empty : lie_span R L (∅ : set M) = ⊥ :=
(lie_submodule.gi R L M).gc.l_bot

@[simp] lemma span_univ : lie_span R L (set.univ : set M) = ⊤ :=
eq_top_iff.2 $ set_like.le_def.2 $ subset_lie_span

lemma lie_span_eq_bot_iff : lie_span R L s = ⊥ ↔ ∀ (m ∈ s), m = (0 : M) :=
by rw [_root_.eq_bot_iff, lie_span_le, bot_coe, subset_singleton_iff]

variables {M}

lemma span_union (s t : set M) : lie_span R L (s ∪ t) = lie_span R L s ⊔ lie_span R L t :=
(lie_submodule.gi R L M).gc.l_sup

lemma span_Union {ι} (s : ι → set M) : lie_span R L (⋃ i, s i) = ⨆ i, lie_span R L (s i) :=
(lie_submodule.gi R L M).gc.l_supr

end lie_span

end lattice_structure

end lie_submodule

section lie_submodule_map_and_comap

variables {R : Type u} {L : Type v} {L' : Type w₂} {M : Type w} {M' : Type w₁}
variables [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L']
variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M]
variables [add_comm_group M'] [module R M'] [lie_ring_module L M'] [lie_module R L M']

namespace lie_submodule

variables (f : M →ₗ⁅R,L⁆ M') (N N₂ : lie_submodule R L M) (N' : lie_submodule R L M')

/-- A morphism of Lie modules `f : M → M'` pushes forward Lie submodules of `M` to Lie submodules
of `M'`. -/
def map : lie_submodule R L M' :=
{ lie_mem := λ x m' h, by
  { rcases h with ⟨m, hm, hfm⟩, use ⁅x, m⁆, split,
    { apply N.lie_mem hm, },
    { norm_cast at hfm, simp [hfm], }, },
  ..(N : submodule R M).map (f : M →ₗ[R] M') }

@[simp] lemma coe_submodule_map :
  (N.map f : submodule R M') = (N : submodule R M).map (f : M →ₗ[R] M') :=
rfl

/-- A morphism of Lie modules `f : M → M'` pulls back Lie submodules of `M'` to Lie submodules of
`M`. -/
def comap : lie_submodule R L M :=
{ lie_mem := λ x m h, by { suffices : ⁅x, f m⁆ ∈ N', { simp [this], }, apply N'.lie_mem h, },
  ..(N' : submodule R M').comap (f : M →ₗ[R] M') }

@[simp] lemma coe_submodule_comap :
  (N'.comap f : submodule R M) = (N' : submodule R M').comap (f : M →ₗ[R] M') :=
rfl

variables {f N N₂ N'}

lemma map_le_iff_le_comap : map f N ≤ N' ↔ N ≤ comap f N' :=
set.image_subset_iff

variables (f)

lemma gc_map_comap : galois_connection (map f) (comap f) :=
λ N N', map_le_iff_le_comap

variables {f}

@[simp] lemma map_sup : (N ⊔ N₂).map f = N.map f ⊔ N₂.map f :=
(gc_map_comap f).l_sup

lemma mem_map (m' : M') : m' ∈ N.map f ↔ ∃ m, m ∈ N ∧ f m = m' :=
submodule.mem_map

@[simp] lemma mem_comap {m : M} : m ∈ comap f N' ↔ f m ∈ N' := iff.rfl

end lie_submodule

namespace lie_ideal

variables (f : L →ₗ⁅R⁆ L') (I I₂ : lie_ideal R L) (J : lie_ideal R L')

@[simp] lemma top_coe_lie_subalgebra : ((⊤ : lie_ideal R L) : lie_subalgebra R L) = ⊤ := rfl

/-- A morphism of Lie algebras `f : L → L'` pushes forward Lie ideals of `L` to Lie ideals of `L'`.

Note that unlike `lie_submodule.map`, we must take the `lie_span` of the image. Mathematically
this is because although `f` makes `L'` into a Lie module over `L`, in general the `L` submodules of
`L'` are not the same as the ideals of `L'`. -/
def map : lie_ideal R L' := lie_submodule.lie_span R L' $ (I : submodule R L).map (f : L →ₗ[R] L')

/-- A morphism of Lie algebras `f : L → L'` pulls back Lie ideals of `L'` to Lie ideals of `L`.

Note that `f` makes `L'` into a Lie module over `L` (turning `f` into a morphism of Lie modules)
and so this is a special case of `lie_submodule.comap` but we do not exploit this fact. -/
def comap : lie_ideal R L :=
{ lie_mem := λ x y h, by { suffices : ⁅f x, f y⁆ ∈ J, { simp [this], }, apply J.lie_mem h, },
  ..(J : submodule R L').comap (f : L →ₗ[R] L') }

@[simp] lemma map_coe_submodule (h : ↑(map f I) = f '' I) :
  (map f I : submodule R L') = (I : submodule R L).map (f : L →ₗ[R] L') :=
by { rw [set_like.ext'_iff, lie_submodule.coe_to_submodule, h, submodule.map_coe], refl, }

@[simp] lemma comap_coe_submodule :
  (comap f J : submodule R L) = (J : submodule R L').comap (f : L →ₗ[R] L') := rfl

lemma map_le : map f I ≤ J ↔ f '' I ⊆ J := lie_submodule.lie_span_le

variables {f I I₂ J}

lemma mem_map {x : L} (hx : x ∈ I) : f x ∈ map f I :=
by { apply lie_submodule.subset_lie_span, use x, exact ⟨hx, rfl⟩, }

@[simp] lemma mem_comap {x : L} : x ∈ comap f J ↔ f x ∈ J := iff.rfl

lemma map_le_iff_le_comap : map f I ≤ J ↔ I ≤ comap f J :=
by { rw map_le, exact set.image_subset_iff, }

variables (f)

lemma gc_map_comap : galois_connection (map f) (comap f) :=
λ I I', map_le_iff_le_comap

variables {f}

@[simp] lemma map_sup : (I ⊔ I₂).map f = I.map f ⊔ I₂.map f :=
(gc_map_comap f).l_sup

lemma map_comap_le : map f (comap f J) ≤ J :=
by { rw map_le_iff_le_comap, exact le_rfl, }

/-- See also `lie_ideal.map_comap_eq`. -/
lemma comap_map_le : I ≤ comap f (map f I) :=
by { rw ← map_le_iff_le_comap, exact le_rfl, }

@[mono] lemma map_mono : monotone (map f) :=
λ I₁ I₂ h,
by { rw set_like.le_def at h, apply lie_submodule.lie_span_mono (set.image_subset ⇑f h), }

@[mono] lemma comap_mono : monotone (comap f) :=
λ J₁ J₂ h, by { rw ← set_like.coe_subset_coe at h ⊢, exact set.preimage_mono h, }

lemma map_of_image (h : f '' I = J) : I.map f = J :=
begin
  apply le_antisymm,
  { erw [lie_submodule.lie_span_le, submodule.map_coe, h], },
  { rw [← set_like.coe_subset_coe, ← h], exact lie_submodule.subset_lie_span, },
end

/-- Note that this is not a special case of `lie_submodule.subsingleton_of_bot`. Indeed, given
`I : lie_ideal R L`, in general the two lattices `lie_ideal R I` and `lie_submodule R L I` are
different (though the latter does naturally inject into the former).

In other words, in general, ideals of `I`, regarded as a Lie algebra in its own right, are not the
same as ideals of `L` contained in `I`. -/
-- TODO[gh-6025]: make this an instance once safe to do so
lemma subsingleton_of_bot : subsingleton (lie_ideal R ↥(⊥ : lie_ideal R L)) :=
begin
  apply subsingleton_of_bot_eq_top,
  ext ⟨x, hx⟩, change x ∈ ⊥ at hx, rw submodule.mem_bot at hx, subst hx,
  simp only [true_iff, eq_self_iff_true, submodule.mk_eq_zero, lie_submodule.mem_bot],
end

end lie_ideal

namespace lie_hom

variables (f : L →ₗ⁅R⁆ L') (I : lie_ideal R L) (J : lie_ideal R L')

/-- The kernel of a morphism of Lie algebras, as an ideal in the domain. -/
def ker : lie_ideal R L := lie_ideal.comap f ⊥

/-- The range of a morphism of Lie algebras as an ideal in the codomain. -/
def ideal_range : lie_ideal R L' := lie_submodule.lie_span R L' f.range

lemma ideal_range_eq_lie_span_range :
  f.ideal_range = lie_submodule.lie_span R L' f.range := rfl

lemma ideal_range_eq_map :
  f.ideal_range = lie_ideal.map f ⊤ :=
by { ext, simp only [ideal_range, range_eq_map], refl }

/-- The condition that the image of a morphism of Lie algebras is an ideal. -/
def is_ideal_morphism : Prop := (f.ideal_range : lie_subalgebra R L') = f.range

@[simp] lemma is_ideal_morphism_def :
  f.is_ideal_morphism ↔ (f.ideal_range : lie_subalgebra R L') = f.range := iff.rfl

lemma is_ideal_morphism_iff :
  f.is_ideal_morphism ↔ ∀ (x : L') (y : L), ∃ (z : L), ⁅x, f y⁆ = f z :=
begin
  simp only [is_ideal_morphism_def, ideal_range_eq_lie_span_range,
    ← lie_subalgebra.coe_to_submodule_eq_iff, ← f.range.coe_to_submodule,
    lie_ideal.coe_to_lie_subalgebra_to_submodule, lie_submodule.coe_lie_span_submodule_eq_iff,
    lie_subalgebra.mem_coe_submodule, mem_range, exists_imp_distrib,
    submodule.exists_lie_submodule_coe_eq_iff],
  split,
  { intros h x y, obtain ⟨z, hz⟩ := h x (f y) y rfl, use z, exact hz.symm, },
  { intros h x y z hz, obtain ⟨w, hw⟩ := h x z, use w, rw [← hw, hz], },
end

lemma range_subset_ideal_range : (f.range : set L') ⊆ f.ideal_range := lie_submodule.subset_lie_span

lemma map_le_ideal_range : I.map f ≤ f.ideal_range :=
begin
  rw f.ideal_range_eq_map,
  exact lie_ideal.map_mono le_top,
end

lemma ker_le_comap : f.ker ≤ J.comap f := lie_ideal.comap_mono bot_le

@[simp] lemma ker_coe_submodule : (ker f : submodule R L) = (f : L →ₗ[R] L').ker := rfl

@[simp] lemma mem_ker {x : L} : x ∈ ker f ↔ f x = 0 :=
show x ∈ (f.ker : submodule R L) ↔ _,
by simp only [ker_coe_submodule, linear_map.mem_ker, coe_to_linear_map]

lemma mem_ideal_range {x : L} : f x ∈ ideal_range f :=
begin
  rw ideal_range_eq_map,
  exact lie_ideal.mem_map (lie_submodule.mem_top x)
end

@[simp]

lemma le_ker_iff : I ≤ f.ker ↔ ∀ x, x ∈ I → f x = 0 :=
begin
  split; intros h x hx,
  { specialize h hx, rw mem_ker at h, exact h, },
  { rw mem_ker, apply h x hx, },
end

lemma ker_eq_bot : f.ker = ⊥ ↔ function.injective f :=
by rw [← lie_submodule.coe_to_submodule_eq_iff, ker_coe_submodule, lie_submodule.bot_coe_submodule,
  linear_map.ker_eq_bot, coe_to_linear_map]

@[simp] lemma range_coe_submodule : (f.range : submodule R L') = (f : L →ₗ[R] L').range := rfl

lemma range_eq_top : f.range = ⊤ ↔ function.surjective f :=
begin
  rw [← lie_subalgebra.coe_to_submodule_eq_iff, range_coe_submodule,
    lie_subalgebra.top_coe_submodule],
  exact linear_map.range_eq_top,
end

@[simp] lemma ideal_range_eq_top_of_surjective (h : function.surjective f) : f.ideal_range = ⊤ :=
begin
  rw ← f.range_eq_top at h,
  rw [ideal_range_eq_lie_span_range, h, ← lie_subalgebra.coe_to_submodule,
    ← lie_submodule.coe_to_submodule_eq_iff, lie_submodule.top_coe_submodule,
      lie_subalgebra.top_coe_submodule, lie_submodule.coe_lie_span_submodule_eq_iff],
  use ⊤,
  exact lie_submodule.top_coe_submodule,
end

lemma is_ideal_morphism_of_surjective (h : function.surjective f) : f.is_ideal_morphism :=
by rw [is_ideal_morphism_def, f.ideal_range_eq_top_of_surjective h, f.range_eq_top.mpr h,
    lie_ideal.top_coe_lie_subalgebra]

end lie_hom

namespace lie_ideal

variables {f : L →ₗ⁅R⁆ L'} {I : lie_ideal R L} {J : lie_ideal R L'}

@[simp] lemma map_eq_bot_iff : I.map f = ⊥ ↔ I ≤ f.ker :=
by { rw ← le_bot_iff, exact lie_ideal.map_le_iff_le_comap }

lemma coe_map_of_surjective (h : function.surjective f) :
  (I.map f : submodule R L') = (I : submodule R L).map (f : L →ₗ[R] L') :=
begin
  let J : lie_ideal R L' :=
  { lie_mem := λ x y hy,
    begin
      have hy' : ∃ (x : L), x ∈ I ∧ f x = y, { simpa [hy], },
      obtain ⟨z₂, hz₂, rfl⟩ := hy',
      obtain ⟨z₁, rfl⟩ := h x,
      simp only [lie_hom.coe_to_linear_map, set_like.mem_coe, set.mem_image,
        lie_submodule.mem_coe_submodule, submodule.mem_carrier, submodule.map_coe],
      use ⁅z₁, z₂⁆,
      exact ⟨I.lie_mem hz₂, f.map_lie z₁ z₂⟩,
    end,
    ..(I : submodule R L).map (f : L →ₗ[R] L'), },
  erw lie_submodule.coe_lie_span_submodule_eq_iff,
  use J,
  apply lie_submodule.coe_to_submodule_mk,
end

lemma mem_map_of_surjective {y : L'} (h₁ : function.surjective f) (h₂ : y ∈ I.map f) :
  ∃ (x : I), f x = y :=
begin
  rw [← lie_submodule.mem_coe_submodule, coe_map_of_surjective h₁, submodule.mem_map] at h₂,
  obtain ⟨x, hx, rfl⟩ := h₂,
  use ⟨x, hx⟩,
  refl,
end

lemma bot_of_map_eq_bot {I : lie_ideal R L} (h₁ : function.injective f) (h₂ : I.map f = ⊥) :
  I = ⊥ :=
begin
  rw ← f.ker_eq_bot at h₁, change comap f ⊥ = ⊥ at h₁,
  rw [eq_bot_iff, map_le_iff_le_comap, h₁] at h₂,
  rw eq_bot_iff, exact h₂,
end

/-- Given two nested Lie ideals `I₁ ⊆ I₂`, the inclusion `I₁ ↪ I₂` is a morphism of Lie algebras. -/
def hom_of_le {I₁ I₂ : lie_ideal R L} (h : I₁ ≤ I₂) : I₁ →ₗ⁅R⁆ I₂ :=
{ map_lie' := λ x y, rfl,
  ..submodule.of_le (show I₁.to_submodule ≤ I₂.to_submodule, from h), }

@[simp] lemma coe_hom_of_le {I₁ I₂ : lie_ideal R L} (h : I₁ ≤ I₂) (x : I₁) :
  (hom_of_le h x : L) = x := rfl

lemma hom_of_le_apply {I₁ I₂ : lie_ideal R L} (h : I₁ ≤ I₂) (x : I₁) :
  hom_of_le h x = ⟨x.1, h x.2⟩ := rfl

lemma hom_of_le_injective {I₁ I₂ : lie_ideal R L} (h : I₁ ≤ I₂) :
  function.injective (hom_of_le h) :=
λ x y, by simp only [hom_of_le_apply, imp_self, subtype.mk_eq_mk, set_like.coe_eq_coe,
  subtype.val_eq_coe]

@[simp] lemma map_sup_ker_eq_map : lie_ideal.map f (I ⊔ f.ker) = lie_ideal.map f I :=
begin
  suffices : lie_ideal.map f (I ⊔ f.ker) ≤ lie_ideal.map f I,
  { exact le_antisymm this (lie_ideal.map_mono le_sup_left), },
  apply lie_submodule.lie_span_mono,
  rintros x ⟨y, hy₁, hy₂⟩, rw ← hy₂,
  erw lie_submodule.mem_sup at hy₁, obtain ⟨z₁, hz₁, z₂, hz₂, hy⟩ := hy₁, rw ← hy,
  rw [f.coe_to_linear_map, f.map_add, f.mem_ker.mp hz₂, add_zero], exact ⟨z₁, hz₁, rfl⟩,
end

@[simp] lemma map_comap_eq (h : f.is_ideal_morphism) : map f (comap f J) = f.ideal_range ⊓ J :=
begin
  apply le_antisymm,
  { rw le_inf_iff, exact ⟨f.map_le_ideal_range _, map_comap_le⟩, },
  { rw f.is_ideal_morphism_def at h,
    rw [← set_like.coe_subset_coe, lie_submodule.inf_coe, ← coe_to_subalgebra, h],
    rintros y ⟨⟨x, h₁⟩, h₂⟩, rw ← h₁ at h₂ ⊢, exact mem_map h₂, },
end

@[simp] lemma comap_map_eq (h : ↑(map f I) = f '' I) : comap f (map f I) = I ⊔ f.ker :=
by rw [← lie_submodule.coe_to_submodule_eq_iff, comap_coe_submodule, I.map_coe_submodule f h,
  lie_submodule.sup_coe_to_submodule, f.ker_coe_submodule, submodule.comap_map_eq]

variables (f I J)

/-- Regarding an ideal `I` as a subalgebra, the inclusion map into its ambient space is a morphism
of Lie algebras. -/
def incl : I →ₗ⁅R⁆ L := (I : lie_subalgebra R L).incl

@[simp] lemma incl_range : I.incl.range = I := (I : lie_subalgebra R L).incl_range

@[simp] lemma incl_apply (x : I) : I.incl x = x := rfl

@[simp] lemma incl_coe : (I.incl : I →ₗ[R] L) = (I : submodule R L).subtype := rfl

@[simp] lemma comap_incl_self : comap I.incl I = ⊤ :=
by { rw ← lie_submodule.coe_to_submodule_eq_iff, exact submodule.comap_subtype_self _, }

@[simp] lemma ker_incl : I.incl.ker = ⊥ :=
by rw [← lie_submodule.coe_to_submodule_eq_iff, I.incl.ker_coe_submodule,
  lie_submodule.bot_coe_submodule, incl_coe, submodule.ker_subtype]

@[simp] lemma incl_ideal_range : I.incl.ideal_range = I :=
begin
  rw [lie_hom.ideal_range_eq_lie_span_range, ← lie_subalgebra.coe_to_submodule,
    ← lie_submodule.coe_to_submodule_eq_iff, incl_range, coe_to_lie_subalgebra_to_submodule,
    lie_submodule.coe_lie_span_submodule_eq_iff],
  use I,
end

lemma incl_is_ideal_morphism : I.incl.is_ideal_morphism :=
begin
  rw [I.incl.is_ideal_morphism_def, incl_ideal_range],
  exact (I : lie_subalgebra R L).incl_range.symm,
end

end lie_ideal

end lie_submodule_map_and_comap

namespace lie_module_hom

variables {R : Type u} {L : Type v} {M : Type w} {N : Type w₁}
variables [comm_ring R] [lie_ring L] [lie_algebra R L]
variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M]
variables [add_comm_group N] [module R N] [lie_ring_module L N] [lie_module R L N]
variables (f : M →ₗ⁅R,L⁆ N)

/-- The kernel of a morphism of Lie algebras, as an ideal in the domain. -/
def ker : lie_submodule R L M := lie_submodule.comap f ⊥

@[simp] lemma ker_coe_submodule : (f.ker : submodule R M) = (f : M →ₗ[R] N).ker := rfl

lemma ker_eq_bot : f.ker = ⊥ ↔ function.injective f :=
by rw [← lie_submodule.coe_to_submodule_eq_iff, ker_coe_submodule, lie_submodule.bot_coe_submodule,
  linear_map.ker_eq_bot, coe_to_linear_map]

variables {f}

@[simp] lemma mem_ker (m : M) : m ∈ f.ker ↔ f m = 0 := iff.rfl

@[simp] lemma ker_id : (lie_module_hom.id : M →ₗ⁅R,L⁆ M).ker = ⊥ := rfl

@[simp] lemma comp_ker_incl : f.comp f.ker.incl = 0 :=
by { ext ⟨m, hm⟩, exact (mem_ker m).mp hm, }

lemma le_ker_iff_map (M' : lie_submodule R L M) :
  M' ≤ f.ker ↔ lie_submodule.map f M' = ⊥ :=
by rw [ker, eq_bot_iff, lie_submodule.map_le_iff_le_comap]

variables (f)

/-- The range of a morphism of Lie modules `f : M → N` is a Lie submodule of `N`.
See Note [range copy pattern]. -/
def range : lie_submodule R L N :=
(lie_submodule.map f ⊤).copy (set.range f) set.image_univ.symm

@[simp] lemma coe_range : (f.range : set N) = set.range f := rfl

@[simp] lemma coe_submodule_range : (f.range : submodule R N) = (f : M →ₗ[R] N).range := rfl

@[simp] lemma mem_range (n : N) : n ∈ f.range ↔ ∃ m, f m = n :=
iff.rfl

lemma map_top : lie_submodule.map f ⊤ = f.range :=
by { ext, simp [lie_submodule.mem_map], }

end lie_module_hom

namespace lie_submodule

variables {R : Type u} {L : Type v} {M : Type w}
variables [comm_ring R] [lie_ring L] [lie_algebra R L]
variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M]
variables (N : lie_submodule R L M)

@[simp] lemma ker_incl : N.incl.ker = ⊥ :=
by simp [← lie_submodule.coe_to_submodule_eq_iff]

@[simp] lemma range_incl : N.incl.range = N :=
by simp [← lie_submodule.coe_to_submodule_eq_iff]

@[simp] lemma comap_incl_self : comap N.incl N = ⊤ :=
by simp [← lie_submodule.coe_to_submodule_eq_iff]

end lie_submodule

section top_equiv_self

variables {R : Type u} {L : Type v}
variables [comm_ring R] [lie_ring L] [lie_algebra R L]

/-- The natural equivalence between the 'top' Lie subalgebra and the enclosing Lie algebra. -/
def lie_subalgebra.top_equiv_self : (⊤ : lie_subalgebra R L) ≃ₗ⁅R⁆ L :=
{ inv_fun   := λ x, ⟨x, set.mem_univ x⟩,
  left_inv  := λ x, by { ext, refl, },
  right_inv := λ x, rfl,
  ..(⊤ : lie_subalgebra R L).incl, }

@[simp] lemma lie_subalgebra.top_equiv_self_apply (x : (⊤ : lie_subalgebra R L)) :
  lie_subalgebra.top_equiv_self x = x := rfl

/-- The natural equivalence between the 'top' Lie ideal and the enclosing Lie algebra. -/
def lie_ideal.top_equiv_self : (⊤ : lie_ideal R L) ≃ₗ⁅R⁆ L :=
lie_subalgebra.top_equiv_self

@[simp] lemma lie_ideal.top_equiv_self_apply (x : (⊤ : lie_ideal R L)) :
  lie_ideal.top_equiv_self x = x := rfl

end top_equiv_self