/-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Johannes Hölzl, Sander Dahmen, Scott Morrison
-/
import linear_algebra.dfinsupp
import linear_algebra.std_basis
import linear_algebra.isomorphisms
import set_theory.cofinality
import linear_algebra.invariant_basis_number

/-!
# Dimension of modules and vector spaces

## Main definitions

* The rank of a module is defined as `module.rank : cardinal`.
  This is defined as the supremum of the cardinalities of linearly independent subsets.

* The rank of a linear map is defined as the rank of its range.

## Main statements

* `linear_map.dim_le_of_injective`: the source of an injective linear map has dimension
  at most that of the target.
* `linear_map.dim_le_of_surjective`: the target of a surjective linear map has dimension
  at most that of that source.
* `basis_fintype_of_finite_spans`:
  the existence of a finite spanning set implies that any basis is finite.
* `infinite_basis_le_maximal_linear_independent`:
  if `b` is an infinite basis for a module `M`,
  and `s` is a maximal linearly independent set,
  then the cardinality of `b` is bounded by the cardinality of `s`.

For modules over rings satisfying the rank condition

* `basis.le_span`:
  the cardinality of a basis is bounded by the cardinality of any spanning set

For modules over rings satisfying the strong rank condition

* `linear_independent_le_span`:
  For any linearly independent family `v : ι → M`
  and any finite spanning set `w : set M`,
  the cardinality of `ι` is bounded by the cardinality of `w`.
* `linear_independent_le_basis`:
  If `b` is a basis for a module `M`,
  and `s` is a linearly independent set,
  then the cardinality of `s` is bounded by the cardinality of `b`.

For modules over rings with invariant basis number
(including all commutative rings and all noetherian rings)

* `mk_eq_mk_of_basis`: the dimension theorem, any two bases of the same vector space have the same
  cardinality.

For vector spaces (i.e. modules over a field), we have

* `dim_quotient_add_dim`: if `V₁` is a submodule of `V`, then
  `module.rank (V/V₁) + module.rank V₁ = module.rank V`.
* `dim_range_add_dim_ker`: the rank-nullity theorem.

## Implementation notes

There is a naming discrepancy: most of the theorem names refer to `dim`,
even though the definition is of `module.rank`.
This reflects that `module.rank` was originally called `dim`, and only defined for vector spaces.

Many theorems in this file are not universe-generic when they relate dimensions
in different universes. They should be as general as they can be without
inserting `lift`s. The types `V`, `V'`, ... all live in different universes,
and `V₁`, `V₂`, ... all live in the same universe.
-/

noncomputable theory

universes u v v' v'' u₁' w w'

variables {K : Type u} {V V₁ V₂ V₃ : Type v} {V' V'₁ : Type v'} {V'' : Type v''}
variables {ι : Type w} {ι' : Type w'} {η : Type u₁'} {φ : η → Type*}

open_locale classical big_operators cardinal

open basis submodule function set

section module

section
variables [semiring K] [add_comm_monoid V] [module K V]
include K

variables (K V)

/-- The rank of a module, defined as a term of type `cardinal`.

We define this as the supremum of the cardinalities of linearly independent subsets.

For a free module over any ring satisfying the strong rank condition
(e.g. left-noetherian rings, commutative rings, and in particular division rings and fields),
this is the same as the dimension of the space (i.e. the cardinality of any basis).

In particular this agrees with the usual notion of the dimension of a vector space.

The definition is marked as protected to avoid conflicts with `_root_.rank`,
the rank of a linear map.
-/
protected def module.rank : cardinal :=
cardinal.sup.{v v} (λ ι : {s : set V // linear_independent K (coe : s → V)}, #ι.1)

end

section
variables {R : Type u} [ring R]
variables {M : Type v} [add_comm_group M] [module R M]
variables {M' : Type v'} [add_comm_group M'] [module R M']
variables {M₁ : Type v} [add_comm_group M₁] [module R M₁]

theorem linear_map.lift_dim_le_of_injective (f : M →ₗ[R] M') (i : injective f) :
  cardinal.lift.{v'} (module.rank R M) ≤ cardinal.lift.{ v} (module.rank R M') :=
begin
  dsimp [module.rank],
  fapply cardinal.lift_sup_le_lift_sup',
  { rintro ⟨s, li⟩,
    use f '' s,
    convert (li.map' f (linear_map.ker_eq_bot.mpr i)).comp
      (equiv.set.image ⇑f s i).symm (equiv.injective _),
    ext ⟨-, ⟨x, ⟨h, rfl⟩⟩⟩,
    simp, },
  { rintro ⟨s, li⟩,
    exact cardinal.lift_mk_le'.mpr ⟨(equiv.set.image f s i).to_embedding⟩, }
end

theorem linear_map.dim_le_of_injective (f : M →ₗ[R] M₁) (i : injective f) :
  module.rank R M ≤ module.rank R M₁ :=
cardinal.lift_le.1 (f.lift_dim_le_of_injective i)

theorem dim_le {n : ℕ}
  (H : ∀ s : finset M, linear_independent R (λ i : s, (i : M)) → s.card ≤ n) :
  module.rank R M ≤ n :=
begin
  apply cardinal.sup_le.mpr,
  rintro ⟨s, li⟩,
  exact linear_independent_bounded_of_finset_linear_independent_bounded H _ li,
end

lemma lift_dim_range_le (f : M →ₗ[R] M') :
  cardinal.lift.{v} (module.rank R f.range) ≤ cardinal.lift.{v'} (module.rank R M) :=
begin
  dsimp [module.rank],
  apply cardinal.lift_sup_le,
  rintro ⟨s, li⟩,
  apply le_trans,
  swap 2,
  apply cardinal.lift_le.mpr,
  refine (cardinal.le_sup _ ⟨range_splitting f '' s, _⟩),
  { apply linear_independent.of_comp f.range_restrict,
    convert li.comp (equiv.set.range_splitting_image_equiv f s) (equiv.injective _) using 1, },
  { exact (cardinal.lift_mk_eq'.mpr ⟨equiv.set.range_splitting_image_equiv f s⟩).ge, },
end

lemma dim_range_le (f : M →ₗ[R] M₁) : module.rank R f.range ≤ module.rank R M :=
by simpa using lift_dim_range_le f

lemma lift_dim_map_le (f : M →ₗ[R] M') (p : submodule R M) :
  cardinal.lift.{v} (module.rank R (p.map f)) ≤ cardinal.lift.{v'} (module.rank R p) :=
begin
  have h := lift_dim_range_le (f.comp (submodule.subtype p)),
  rwa [linear_map.range_comp, range_subtype] at h,
end

lemma dim_map_le (f : M →ₗ[R] M₁) (p : submodule R M) : module.rank R (p.map f) ≤ module.rank R p :=
by simpa using lift_dim_map_le f p

lemma dim_le_of_submodule (s t : submodule R M) (h : s ≤ t) :
  module.rank R s ≤ module.rank R t :=
(of_le h).dim_le_of_injective $ assume ⟨x, hx⟩ ⟨y, hy⟩ eq,
  subtype.eq $ show x = y, from subtype.ext_iff_val.1 eq

/-- Two linearly equivalent vector spaces have the same dimension, a version with different
universes. -/
theorem linear_equiv.lift_dim_eq (f : M ≃ₗ[R] M') :
  cardinal.lift.{v'} (module.rank R M) = cardinal.lift.{v} (module.rank R M') :=
begin
  apply le_antisymm,
  { exact f.to_linear_map.lift_dim_le_of_injective f.injective, },
  { exact f.symm.to_linear_map.lift_dim_le_of_injective f.symm.injective, },
end

/-- Two linearly equivalent vector spaces have the same dimension. -/
theorem linear_equiv.dim_eq (f : M ≃ₗ[R] M₁) :
  module.rank R M = module.rank R M₁ :=
cardinal.lift_inj.1 f.lift_dim_eq

lemma dim_eq_of_injective (f : M →ₗ[R] M₁) (h : injective f) :
  module.rank R M = module.rank R f.range :=
(linear_equiv.of_injective f h).dim_eq

/-- Pushforwards of submodules along a `linear_equiv` have the same dimension. -/
lemma linear_equiv.dim_map_eq (f : M ≃ₗ[R] M₁) (p : submodule R M) :
  module.rank R (p.map (f : M →ₗ[R] M₁)) = module.rank R p :=
(f.of_submodule p).dim_eq.symm

variables (R M)

@[simp] lemma dim_top : module.rank R (⊤ : submodule R M) = module.rank R M :=
begin
  have : (⊤ : submodule R M) ≃ₗ[R] M := linear_equiv.of_top ⊤ rfl,
  rw this.dim_eq,
end

variables {R M}

lemma dim_range_of_surjective (f : M →ₗ[R] M') (h : surjective f) :
  module.rank R f.range = module.rank R M' :=
by rw [linear_map.range_eq_top.2 h, dim_top]

lemma dim_submodule_le (s : submodule R M) : module.rank R s ≤ module.rank R M :=
begin
  rw ←dim_top R M,
  exact dim_le_of_submodule _ _ le_top,
end

lemma linear_map.dim_le_of_surjective (f : M →ₗ[R] M₁) (h : surjective f) :
  module.rank R M₁ ≤ module.rank R M :=
begin
  rw ←dim_range_of_surjective f h,
  apply dim_range_le,
end

theorem dim_quotient_le (p : submodule R M) :
  module.rank R (M ⧸ p) ≤ module.rank R M :=
(mkq p).dim_le_of_surjective (surjective_quot_mk _)

variables [nontrivial R]

lemma {m} cardinal_lift_le_dim_of_linear_independent
  {ι : Type w} {v : ι → M} (hv : linear_independent R v) :
  cardinal.lift.{(max v m)} (#ι) ≤ cardinal.lift.{(max w m)} (module.rank R M) :=
begin
  apply le_trans,
  { exact cardinal.lift_mk_le.mpr
      ⟨(equiv.of_injective _ hv.injective).to_embedding⟩, },
  { simp only [cardinal.lift_le],
    apply le_trans,
    swap,
    exact cardinal.le_sup _ ⟨range v, hv.coe_range⟩,
    exact le_refl _, },
end

lemma cardinal_lift_le_dim_of_linear_independent'
  {ι : Type w} {v : ι → M} (hv : linear_independent R v) :
  cardinal.lift.{v} (#ι) ≤ cardinal.lift.{w} (module.rank R M) :=
cardinal_lift_le_dim_of_linear_independent.{u v w 0} hv

lemma cardinal_le_dim_of_linear_independent
  {ι : Type v} {v : ι → M} (hv : linear_independent R v) :
  #ι ≤ module.rank R M :=
by simpa using cardinal_lift_le_dim_of_linear_independent hv

lemma cardinal_le_dim_of_linear_independent'
  {s : set M} (hs : linear_independent R (λ x, x : s → M)) :
  #s ≤ module.rank R M :=
cardinal_le_dim_of_linear_independent hs

variables (R M)

@[simp] lemma dim_punit : module.rank R punit = 0 :=
begin
  apply le_bot_iff.mp,
  apply cardinal.sup_le.mpr,
  rintro ⟨s, li⟩,
  apply le_bot_iff.mpr,
  apply cardinal.mk_emptyc_iff.mpr,
  simp only [subtype.coe_mk],
  by_contradiction h,
  have ne : s.nonempty := ne_empty_iff_nonempty.mp h,
  simpa using linear_independent.ne_zero (⟨_, ne.some_mem⟩ : s) li,
end

@[simp] lemma dim_bot : module.rank R (⊥ : submodule R M) = 0 :=
begin
  have : (⊥ : submodule R M) ≃ₗ[R] punit := bot_equiv_punit,
  rw [this.dim_eq, dim_punit],
end

variables {R M}

/--
Over any nontrivial ring, the existence of a finite spanning set implies that any basis is finite.
-/
-- One might hope that a finite spanning set implies that any linearly independent set is finite.
-- While this is true over a division ring
-- (simply because any linearly independent set can be extended to a basis),
-- I'm not certain what more general statements are possible.
def basis_fintype_of_finite_spans (w : set M) [fintype w] (s : span R w = ⊤)
  {ι : Type w} (b : basis ι R M) : fintype ι :=
begin
  -- We'll work by contradiction, assuming `ι` is infinite.
  apply fintype_of_not_infinite _,
  introI i,
  -- Let `S` be the union of the supports of `x ∈ w` expressed as linear combinations of `b`.
  -- This is a finite set since `w` is finite.
  let S : finset ι := finset.univ.sup (λ x : w, (b.repr x).support),
  let bS : set M := b '' S,
  have h : ∀ x ∈ w, x ∈ span R bS,
  { intros x m,
    rw [←b.total_repr x, finsupp.span_image_eq_map_total, submodule.mem_map],
    use b.repr x,
    simp only [and_true, eq_self_iff_true, finsupp.mem_supported],
    change (b.repr x).support ≤ S,
    convert (finset.le_sup (by simp : (⟨x, m⟩ : w) ∈ finset.univ)),
    refl, },
  -- Thus this finite subset of the basis elements spans the entire module.
  have k : span R bS = ⊤ := eq_top_iff.2 (le_trans s.ge (span_le.2 h)),

  -- Now there is some `x : ι` not in `S`, since `ι` is infinite.
  obtain ⟨x, nm⟩ := infinite.exists_not_mem_finset S,
  -- However it must be in the span of the finite subset,
  have k' : b x ∈ span R bS, { rw k, exact mem_top, },
  -- giving the desire contradiction.
  refine b.linear_independent.not_mem_span_image _ k',
  exact nm,
end

/--
Over any ring `R`, if `b` is a basis for a module `M`,
and `s` is a maximal linearly independent set,
then the union of the supports of `x ∈ s` (when written out in the basis `b`) is all of `b`.
-/
-- From [Les familles libres maximales d'un module ont-elles le meme cardinal?][lazarus1973]
lemma union_support_maximal_linear_independent_eq_range_basis
  {ι : Type w} (b : basis ι R M)
  {κ : Type w'} (v : κ → M) (i : linear_independent R v) (m : i.maximal) :
  (⋃ k, ((b.repr (v k)).support : set ι)) = univ :=
begin
  -- If that's not the case,
  by_contradiction h,
  simp only [←ne.def, ne_univ_iff_exists_not_mem, mem_Union, not_exists_not,
    finsupp.mem_support_iff, finset.mem_coe] at h,
  -- We have some basis element `b b'` which is not in the support of any of the `v i`.
  obtain ⟨b', w⟩ := h,
  -- Using this, we'll construct a linearly independent family strictly larger than `v`,
  -- by also using this `b b'`.
  let v' : option κ → M := λ o, o.elim (b b') v,
  have r : range v ⊆ range v',
  { rintro - ⟨k, rfl⟩,
    use some k,
    refl, },
  have r' : b b' ∉ range v,
  { rintro ⟨k, p⟩,
    simpa [w] using congr_arg (λ m, (b.repr m) b') p, },
  have r'' : range v ≠ range v',
  { intro e,
    have p : b b' ∈ range v', { use none, refl, },
    rw ←e at p,
    exact r' p, },
  have inj' : injective v',
  { rintros (_|k) (_|k) z,
    { refl, },
    { exfalso, exact r' ⟨k, z.symm⟩, },
    { exfalso, exact r' ⟨k, z⟩, },
    { congr, exact i.injective z, }, },
  -- The key step in the proof is checking that this strictly larger family is linearly independent.
  have i' : linear_independent R (coe : range v' → M),
  { rw [linear_independent_subtype_range inj', linear_independent_iff],
    intros l z,
    rw [finsupp.total_option] at z,
    simp only [v', option.elim] at z,
    change _ + finsupp.total κ M R v l.some = 0 at z,
    -- We have some linear combination of `b b'` and the `v i`, which we want to show is trivial.
    -- We'll first show the coefficient of `b b'` is zero,
    -- by expressing the `v i` in the basis `b`, and using that the `v i` have no `b b'` term.
    have l₀ : l none = 0,
    { rw ←eq_neg_iff_add_eq_zero at z,
      replace z := eq_neg_of_eq_neg z,
      apply_fun (λ x, b.repr x b') at z,
      simp only [repr_self, linear_equiv.map_smul, mul_one, finsupp.single_eq_same, pi.neg_apply,
        finsupp.smul_single', linear_equiv.map_neg, finsupp.coe_neg] at z,
      erw finsupp.congr_fun (finsupp.apply_total R (b.repr : M →ₗ[R] ι →₀ R) v l.some) b' at z,
      simpa [finsupp.total_apply, w] using z, },
    -- Then all the other coefficients are zero, because `v` is linear independent.
    have l₁ : l.some = 0,
    { rw [l₀, zero_smul, zero_add] at z,
      exact linear_independent_iff.mp i _ z, },
    -- Finally we put those facts together to show the linear combination is trivial.
    ext (_|a),
    { simp only [l₀, finsupp.coe_zero, pi.zero_apply], },
    { erw finsupp.congr_fun l₁ a,
      simp only [finsupp.coe_zero, pi.zero_apply], }, },
  dsimp [linear_independent.maximal] at m,
  specialize m (range v') i' r,
  exact r'' m,
end

/--
Over any ring `R`, if `b` is an infinite basis for a module `M`,
and `s` is a maximal linearly independent set,
then the cardinality of `b` is bounded by the cardinality of `s`.
-/
lemma infinite_basis_le_maximal_linear_independent'
  {ι : Type w} (b : basis ι R M) [infinite ι]
  {κ : Type w'} (v : κ → M) (i : linear_independent R v) (m : i.maximal) :
  cardinal.lift.{w'} (#ι) ≤ cardinal.lift.{w} (#κ) :=
begin
  let Φ := λ k : κ, (b.repr (v k)).support,
  have w₁ : #ι ≤ #(set.range Φ),
  { apply cardinal.le_range_of_union_finset_eq_top,
    exact union_support_maximal_linear_independent_eq_range_basis b v i m, },
  have w₂ :
    cardinal.lift.{w'} (#(set.range Φ)) ≤ cardinal.lift.{w} (#κ) :=
    cardinal.mk_range_le_lift,
  exact (cardinal.lift_le.mpr w₁).trans w₂,
end

/--
Over any ring `R`, if `b` is an infinite basis for a module `M`,
and `s` is a maximal linearly independent set,
then the cardinality of `b` is bounded by the cardinality of `s`.
-/
-- (See `infinite_basis_le_maximal_linear_independent'` for the more general version
-- where the index types can live in different universes.)
lemma infinite_basis_le_maximal_linear_independent
  {ι : Type w} (b : basis ι R M) [infinite ι]
  {κ : Type w} (v : κ → M) (i : linear_independent R v) (m : i.maximal) :
  #ι ≤ #κ :=
cardinal.lift_le.mp (infinite_basis_le_maximal_linear_independent' b v i m)

lemma complete_lattice.independent.subtype_ne_bot_le_rank [no_zero_smul_divisors R M]
  {V : ι → submodule R M} (hV : complete_lattice.independent V) :
  cardinal.lift.{v} (#{i : ι // V i ≠ ⊥}) ≤ cardinal.lift.{w} (module.rank R M) :=
begin
  set I := {i : ι // V i ≠ ⊥},
  have hI : ∀ i : I, ∃ v ∈ V i, v ≠ (0:M),
  { intros i,
    rw ← submodule.ne_bot_iff,
    exact i.prop },
  choose v hvV hv using hI,
  have : linear_independent R v,
  { exact (hV.comp _ subtype.coe_injective).linear_independent _ hvV hv },
  exact cardinal_lift_le_dim_of_linear_independent' this
end

end

section rank_zero

variables {R : Type u} {M : Type v}
variables [ring R] [nontrivial R] [add_comm_group M] [module R M] [no_zero_smul_divisors R M]

lemma dim_zero_iff_forall_zero : module.rank R M = 0 ↔ ∀ x : M, x = 0 :=
begin
  refine ⟨λ h, _, λ h, _⟩,
  { contrapose! h,
    obtain ⟨x, hx⟩ := h,
    suffices : 1 ≤ module.rank R M,
    { intro h, exact lt_irrefl _ (lt_of_lt_of_le cardinal.zero_lt_one (h ▸ this)) },
    suffices : linear_independent R (λ (y : ({x} : set M)), ↑y),
    { simpa using (cardinal_le_dim_of_linear_independent this), },
    exact linear_independent_singleton hx },
  { have : (⊤ : submodule R M) = ⊥,
    { ext x, simp [h x] },
    rw [←dim_top, this, dim_bot] }
end

lemma dim_zero_iff : module.rank R M = 0 ↔ subsingleton M :=
dim_zero_iff_forall_zero.trans (subsingleton_iff_forall_eq 0).symm

lemma dim_pos_iff_exists_ne_zero : 0 < module.rank R M ↔ ∃ x : M, x ≠ 0 :=
begin
  rw ←not_iff_not,
  simpa using dim_zero_iff_forall_zero
end

lemma dim_pos_iff_nontrivial : 0 < module.rank R M ↔ nontrivial M :=
dim_pos_iff_exists_ne_zero.trans (nontrivial_iff_exists_ne 0).symm

lemma dim_pos [h : nontrivial M] : 0 < module.rank R M :=
dim_pos_iff_nontrivial.2 h

end rank_zero

section invariant_basis_number

variables {R : Type u} [ring R] [invariant_basis_number R]
variables {M : Type v} [add_comm_group M] [module R M]

/-- The dimension theorem: if `v` and `v'` are two bases, their index types
have the same cardinalities. -/
theorem mk_eq_mk_of_basis (v : basis ι R M) (v' : basis ι' R M) :
  cardinal.lift.{w'} (#ι) = cardinal.lift.{w} (#ι') :=
begin
  haveI := nontrivial_of_invariant_basis_number R,
  by_cases h : #ι < ω,
  { -- `v` is a finite basis, so by `basis_fintype_of_finite_spans` so is `v'`.
    haveI : fintype ι := (cardinal.lt_omega_iff_fintype.mp h).some,
    haveI : fintype (range v) := set.fintype_range ⇑v,
    haveI := basis_fintype_of_finite_spans _ v.span_eq v',
    -- We clean up a little:
    rw [cardinal.mk_fintype, cardinal.mk_fintype],
    simp only [cardinal.lift_nat_cast, cardinal.nat_cast_inj],
    -- Now we can use invariant basis number to show they have the same cardinality.
    apply card_eq_of_lequiv R,
    exact (((finsupp.linear_equiv_fun_on_fintype R R ι).symm.trans v.repr.symm) ≪≫ₗ
      v'.repr) ≪≫ₗ (finsupp.linear_equiv_fun_on_fintype R R ι'), },
  { -- `v` is an infinite basis,
    -- so by `infinite_basis_le_maximal_linear_independent`, `v'` is at least as big,
    -- and then applying `infinite_basis_le_maximal_linear_independent` again
    -- we see they have the same cardinality.
    simp only [not_lt] at h,
    haveI : infinite ι := cardinal.infinite_iff.mpr h,
    have w₁ :=
      infinite_basis_le_maximal_linear_independent' v _ v'.linear_independent v'.maximal,
    haveI : infinite ι' := cardinal.infinite_iff.mpr (begin
      apply cardinal.lift_le.{w' w}.mp,
      have p := (cardinal.lift_le.mpr h).trans w₁,
      rw cardinal.lift_omega at ⊢ p,
      exact p,
    end),
    have w₂ :=
      infinite_basis_le_maximal_linear_independent' v' _ v.linear_independent v.maximal,
    exact le_antisymm w₁ w₂, }
end

/-- Given two basis indexed by `ι` and `ι'` of an `R`-module, where `R` satisfies the invariant
basis number property, an equiv `ι ≃ ι' `. -/
def basis.index_equiv (v : basis ι R M) (v' : basis ι' R M) : ι ≃ ι' :=
nonempty.some (cardinal.lift_mk_eq.1 (cardinal.lift_max.2 (mk_eq_mk_of_basis v v')))

theorem mk_eq_mk_of_basis' {ι' : Type w} (v : basis ι R M) (v' : basis ι' R M) :
  #ι = #ι' :=
cardinal.lift_inj.1 $ mk_eq_mk_of_basis v v'

end invariant_basis_number

section rank_condition

variables {R : Type u} [ring R] [rank_condition R]
variables {M : Type v} [add_comm_group M] [module R M]

/--
An auxiliary lemma for `basis.le_span`.

If `R` satisfies the rank condition,
then for any finite basis `b : basis ι R M`,
and any finite spanning set `w : set M`,
the cardinality of `ι` is bounded by the cardinality of `w`.
-/
lemma basis.le_span'' {ι : Type*} [fintype ι] (b : basis ι R M)
  {w : set M} [fintype w] (s : span R w = ⊤) :
  fintype.card ι ≤ fintype.card w :=
begin
  -- We construct an surjective linear map `(w → R) →ₗ[R] (ι → R)`,
  -- by expressing a linear combination in `w` as a linear combination in `ι`.
  fapply card_le_of_surjective' R,
  { exact b.repr.to_linear_map.comp (finsupp.total w M R coe), },
  { apply surjective.comp,
   apply linear_equiv.surjective,
   rw [←linear_map.range_eq_top, finsupp.range_total],
   simpa using s, },
end

/--
Another auxiliary lemma for `basis.le_span`, which does not require assuming the basis is finite,
but still assumes we have a finite spanning set.
-/
lemma basis_le_span' {ι : Type*} (b : basis ι R M)
  {w : set M} [fintype w] (s : span R w = ⊤) :
  #ι ≤ fintype.card w :=
begin
  haveI := nontrivial_of_invariant_basis_number R,
  haveI := basis_fintype_of_finite_spans w s b,
  rw cardinal.mk_fintype ι,
  simp only [cardinal.nat_cast_le],
  exact basis.le_span'' b s,
end

/--
If `R` satisfies the rank condition,
then the cardinality of any basis is bounded by the cardinality of any spanning set.
-/
-- Note that if `R` satisfies the strong rank condition,
-- this also follows from `linear_independent_le_span` below.
theorem basis.le_span {J : set M} (v : basis ι R M)
   (hJ : span R J = ⊤) : #(range v) ≤ #J :=
begin
  haveI := nontrivial_of_invariant_basis_number R,
  casesI fintype_or_infinite J,
  { rw [←cardinal.lift_le, cardinal.mk_range_eq_of_injective v.injective, cardinal.mk_fintype J],
    convert cardinal.lift_le.{w v}.2 (basis_le_span' v hJ),
    simp, },
  { have := cardinal.mk_range_eq_of_injective v.injective,
    let S : J → set ι := λ j, ↑(v.repr j).support,
    let S' : J → set M := λ j, v '' S j,
    have hs : range v ⊆ ⋃ j, S' j,
    { intros b hb,
      rcases mem_range.1 hb with ⟨i, hi⟩,
      have : span R J ≤ comap v.repr.to_linear_map (finsupp.supported R R (⋃ j, S j)) :=
        span_le.2 (λ j hj x hx, ⟨_, ⟨⟨j, hj⟩, rfl⟩, hx⟩),
      rw hJ at this,
      replace : v.repr (v i) ∈ (finsupp.supported R R (⋃ j, S j)) := this trivial,
      rw [v.repr_self, finsupp.mem_supported,
        finsupp.support_single_ne_zero one_ne_zero] at this,
      { subst b,
        rcases mem_Union.1 (this (finset.mem_singleton_self _)) with ⟨j, hj⟩,
        exact mem_Union.2 ⟨j, (mem_image _ _ _).2 ⟨i, hj, rfl⟩⟩ },
      { apply_instance } },
    refine le_of_not_lt (λ IJ, _),
    suffices : #(⋃ j, S' j) < #(range v),
    { exact not_le_of_lt this ⟨set.embedding_of_subset _ _ hs⟩ },
    refine lt_of_le_of_lt (le_trans cardinal.mk_Union_le_sum_mk
      (cardinal.sum_le_sum _ (λ _, ω) _)) _,
    { exact λ j, le_of_lt (cardinal.lt_omega_iff_finite.2 $ (finset.finite_to_set _).image _) },
    { simpa } },
end

end rank_condition

section strong_rank_condition

variables {R : Type u} [ring R] [strong_rank_condition R]
variables {M : Type v} [add_comm_group M] [module R M]

open submodule

-- An auxiliary lemma for `linear_independent_le_span'`,
-- with the additional assumption that the linearly independent family is finite.
lemma linear_independent_le_span_aux'
  {ι : Type*} [fintype ι] (v : ι → M) (i : linear_independent R v)
  (w : set M) [fintype w] (s : range v ≤ span R w) :
  fintype.card ι ≤ fintype.card w :=
begin
  -- We construct an injective linear map `(ι → R) →ₗ[R] (w → R)`,
  -- by thinking of `f : ι → R` as a linear combination of the finite family `v`,
  -- and expressing that (using the axiom of choice) as a linear combination over `w`.
  -- We can do this linearly by constructing the map on a basis.
  fapply card_le_of_injective' R,
  { apply finsupp.total,
    exact λ i, span.repr R w ⟨v i, s (mem_range_self i)⟩, },
  { intros f g h,
    apply_fun finsupp.total w M R coe at h,
    simp only [finsupp.total_total, submodule.coe_mk, span.finsupp_total_repr] at h,
    rw [←sub_eq_zero, ←linear_map.map_sub] at h,
    exact sub_eq_zero.mp (linear_independent_iff.mp i _ h), },
end

/--
If `R` satisfies the strong rank condition,
then any linearly independent family `v : ι → M`
contained in the span of some finite `w : set M`,
is itself finite.
-/
def linear_independent_fintype_of_le_span_fintype
  {ι : Type*} (v : ι → M) (i : linear_independent R v)
  (w : set M) [fintype w] (s : range v ≤ span R w) : fintype ι :=
fintype_of_finset_card_le (fintype.card w) (λ t, begin
  let v' := λ x : (t : set ι), v x,
  have i' : linear_independent R v' := i.comp _ subtype.val_injective,
  have s' : range v' ≤ span R w := (range_comp_subset_range _ _).trans s,
  simpa using linear_independent_le_span_aux' v' i' w s',
end)

/--
If `R` satisfies the strong rank condition,
then for any linearly independent family `v : ι → M`
contained in the span of some finite `w : set M`,
the cardinality of `ι` is bounded by the cardinality of `w`.
-/
lemma linear_independent_le_span' {ι : Type*} (v : ι → M) (i : linear_independent R v)
  (w : set M) [fintype w] (s : range v ≤ span R w) :
  #ι ≤ fintype.card w :=
begin
  haveI : fintype ι := linear_independent_fintype_of_le_span_fintype v i w s,
  rw cardinal.mk_fintype,
  simp only [cardinal.nat_cast_le],
  exact linear_independent_le_span_aux' v i w s,
end

/--
If `R` satisfies the strong rank condition,
then for any linearly independent family `v : ι → M`
and any finite spanning set `w : set M`,
the cardinality of `ι` is bounded by the cardinality of `w`.
-/
lemma linear_independent_le_span {ι : Type*} (v : ι → M) (i : linear_independent R v)
  (w : set M) [fintype w] (s : span R w = ⊤) :
  #ι ≤ fintype.card w :=
begin
  apply linear_independent_le_span' v i w,
  rw s,
  exact le_top,
end

/-- A linearly-independent family of vectors in a module over a ring satisfying the strong rank
condition must be finite if the module is Noetherian. -/
noncomputable def fintype_of_is_noetherian_linear_independent [is_noetherian R M]
  {v : ι → M} (hi : linear_independent R v) : fintype ι :=
begin
  have hfg : (⊤ : submodule R M).fg,
  { exact is_noetherian_def.mp infer_instance ⊤, },
  rw submodule.fg_def at hfg,
  choose s hs hs' using hfg,
  haveI : fintype s := hs.fintype,
  apply linear_independent_fintype_of_le_span_fintype v hi s,
  simp only [hs', set.subset_univ, submodule.top_coe, set.le_eq_subset],
end

/-- A linearly-independent subset of a module over a ring satisfying the strong rank condition
must be finite if the module is Noetherian. -/
lemma finite_of_is_noetherian_linear_independent [is_noetherian R M]
  {s : set M} (hi : linear_independent R (coe : s → M)) : s.finite :=
⟨fintype_of_is_noetherian_linear_independent hi⟩

/--
An auxiliary lemma for `linear_independent_le_basis`:
we handle the case where the basis `b` is infinite.
-/
lemma linear_independent_le_infinite_basis
  {ι : Type*} (b : basis ι R M) [infinite ι]
  {κ : Type*} (v : κ → M) (i : linear_independent R v) :
  #κ ≤ #ι :=
begin
  by_contradiction,
  rw [not_le, ← cardinal.mk_finset_eq_mk ι] at h,
  let Φ := λ k : κ, (b.repr (v k)).support,
  obtain ⟨s, w : infinite ↥(Φ ⁻¹' {s})⟩ := cardinal.exists_infinite_fiber Φ h (by apply_instance),
  let v' := λ k : Φ ⁻¹' {s}, v k,
  have i' : linear_independent R v' := i.comp _ subtype.val_injective,
  have w' : fintype (Φ ⁻¹' {s}),
  { apply linear_independent_fintype_of_le_span_fintype v' i' (s.image b),
    rintros m ⟨⟨p,⟨rfl⟩⟩,rfl⟩,
    simp only [set_like.mem_coe, subtype.coe_mk, finset.coe_image],
    apply basis.mem_span_repr_support, },
  exactI w.false,
end

/--
Over any ring `R` satisfying the strong rank condition,
if `b` is a basis for a module `M`,
and `s` is a linearly independent set,
then the cardinality of `s` is bounded by the cardinality of `b`.
-/
lemma linear_independent_le_basis
  {ι : Type*} (b : basis ι R M)
  {κ : Type*} (v : κ → M) (i : linear_independent R v) :
  #κ ≤ #ι :=
begin
  -- We split into cases depending on whether `ι` is infinite.
  cases fintype_or_infinite ι; resetI,
  { -- When `ι` is finite, we have `linear_independent_le_span`,
    rw cardinal.mk_fintype ι,
    haveI : nontrivial R := nontrivial_of_invariant_basis_number R,
    rw fintype.card_congr (equiv.of_injective b b.injective),
    exact linear_independent_le_span v i (range b) b.span_eq, },
  { -- and otherwise we have `linear_indepedent_le_infinite_basis`.
    exact linear_independent_le_infinite_basis b v i, },
end

/-- In an `n`-dimensional space, the rank is at most `m`. -/
lemma basis.card_le_card_of_linear_independent_aux
  {R : Type*} [ring R] [strong_rank_condition R]
  (n : ℕ) {m : ℕ} (v : fin m → fin n → R) :
  linear_independent R v → m ≤ n :=
λ h, by simpa using (linear_independent_le_basis (pi.basis_fun R (fin n)) v h)

/--
Over any ring `R` satisfying the strong rank condition,
if `b` is an infinite basis for a module `M`,
then every maximal linearly independent set has the same cardinality as `b`.

This proof (along with some of the lemmas above) comes from
[Les familles libres maximales d'un module ont-elles le meme cardinal?][lazarus1973]
-/
-- When the basis is not infinite this need not be true!
lemma maximal_linear_independent_eq_infinite_basis
  {ι : Type*} (b : basis ι R M) [infinite ι]
  {κ : Type*} (v : κ → M) (i : linear_independent R v) (m : i.maximal) :
  #κ = #ι :=
begin
  apply le_antisymm,
  { exact linear_independent_le_basis b v i, },
  { haveI : nontrivial R := nontrivial_of_invariant_basis_number R,
    exact infinite_basis_le_maximal_linear_independent b v i m, }
end

theorem basis.mk_eq_dim'' {ι : Type v} (v : basis ι R M) :
  #ι = module.rank R M :=
begin
  haveI := nontrivial_of_invariant_basis_number R,
  apply le_antisymm,
  { transitivity,
    swap,
    apply cardinal.le_sup,
    exact ⟨set.range v, by { convert v.reindex_range.linear_independent, ext, simp }⟩,
    exact (cardinal.mk_range_eq v v.injective).ge, },
  { apply cardinal.sup_le.mpr,
    rintro ⟨s, li⟩,
    apply linear_independent_le_basis v _ li, },
end

-- By this stage we want to have a complete API for `module.rank`,
-- so we set it `irreducible` here, to keep ourselves honest.
attribute [irreducible] module.rank

theorem basis.mk_range_eq_dim (v : basis ι R M) :
  #(range v) = module.rank R M :=
v.reindex_range.mk_eq_dim''

/-- If a vector space has a finite basis, then its dimension (seen as a cardinal) is equal to the
cardinality of the basis. -/
lemma dim_eq_card_basis {ι : Type w} [fintype ι] (h : basis ι R M) :
  module.rank R M = fintype.card ι :=
by {haveI := nontrivial_of_invariant_basis_number R,
  rw [←h.mk_range_eq_dim, cardinal.mk_fintype, set.card_range_of_injective h.injective] }

lemma basis.card_le_card_of_linear_independent {ι : Type*} [fintype ι]
  (b : basis ι R M) {ι' : Type*} [fintype ι'] {v : ι' → M} (hv : linear_independent R v) :
  fintype.card ι' ≤ fintype.card ι :=
begin
  letI := nontrivial_of_invariant_basis_number R,
  simpa [dim_eq_card_basis b, cardinal.mk_fintype] using
    cardinal_lift_le_dim_of_linear_independent' hv
end

lemma basis.card_le_card_of_submodule (N : submodule R M) [fintype ι] (b : basis ι R M)
  [fintype ι'] (b' : basis ι' R N) : fintype.card ι' ≤ fintype.card ι :=
b.card_le_card_of_linear_independent (b'.linear_independent.map' N.subtype N.ker_subtype)

lemma basis.card_le_card_of_le
  {N O : submodule R M} (hNO : N ≤ O) [fintype ι] (b : basis ι R O) [fintype ι']
  (b' : basis ι' R N) : fintype.card ι' ≤ fintype.card ι :=
b.card_le_card_of_linear_independent
  (b'.linear_independent.map' (submodule.of_le hNO) (N.ker_of_le O _))

theorem basis.mk_eq_dim (v : basis ι R M) :
  cardinal.lift.{v} (#ι) = cardinal.lift.{w} (module.rank R M) :=
begin
  haveI := nontrivial_of_invariant_basis_number R,
  rw [←v.mk_range_eq_dim, cardinal.mk_range_eq_of_injective v.injective]
end

theorem {m} basis.mk_eq_dim' (v : basis ι R M) :
  cardinal.lift.{(max v m)} (#ι) = cardinal.lift.{(max w m)} (module.rank R M) :=
by simpa using v.mk_eq_dim

/-- If a module has a finite dimension, all bases are indexed by a finite type. -/
lemma basis.nonempty_fintype_index_of_dim_lt_omega {ι : Type*}
  (b : basis ι R M) (h : module.rank R M < ω) :
  nonempty (fintype ι) :=
by rwa [← cardinal.lift_lt, ← b.mk_eq_dim,
        -- ensure `omega` has the correct universe
        cardinal.lift_omega, ← cardinal.lift_omega.{u_1 v},
        cardinal.lift_lt, cardinal.lt_omega_iff_fintype] at h

/-- If a module has a finite dimension, all bases are indexed by a finite type. -/
noncomputable def basis.fintype_index_of_dim_lt_omega {ι : Type*}
  (b : basis ι R M) (h : module.rank R M < ω) :
  fintype ι :=
classical.choice (b.nonempty_fintype_index_of_dim_lt_omega h)

/-- If a module has a finite dimension, all bases are indexed by a finite set. -/
lemma basis.finite_index_of_dim_lt_omega {ι : Type*} {s : set ι}
  (b : basis s R M) (h : module.rank R M < ω) :
  s.finite :=
finite_def.2 (b.nonempty_fintype_index_of_dim_lt_omega h)

lemma dim_span {v : ι → M} (hv : linear_independent R v) :
  module.rank R ↥(span R (range v)) = #(range v) :=
begin
  haveI := nontrivial_of_invariant_basis_number R,
  rw [←cardinal.lift_inj, ← (basis.span hv).mk_eq_dim,
    cardinal.mk_range_eq_of_injective (@linear_independent.injective ι R M v _ _ _ _ hv)]
end

lemma dim_span_set {s : set M} (hs : linear_independent R (λ x, x : s → M)) :
  module.rank R ↥(span R s) = #s :=
by { rw [← @set_of_mem_eq _ s, ← subtype.range_coe_subtype], exact dim_span hs }

/-- If `N` is a submodule in a free, finitely generated module,
do induction on adjoining a linear independent element to a submodule. -/
def submodule.induction_on_rank [is_domain R] [fintype ι] (b : basis ι R M)
  (P : submodule R M → Sort*) (ih : ∀ (N : submodule R M),
    (∀ (N' ≤ N) (x ∈ N), (∀ (c : R) (y ∈ N'), c • x + y = (0 : M) → c = 0) → P N') →
    P N)
  (N : submodule R M) : P N :=
submodule.induction_on_rank_aux b P ih (fintype.card ι) N (λ s hs hli,
  by simpa using b.card_le_card_of_linear_independent hli)

/-- If `S` a finite-dimensional ring extension of `R` which is free as an `R`-module,
then the rank of an ideal `I` of `S` over `R` is the same as the rank of `S`.
-/
lemma ideal.rank_eq {R S : Type*} [comm_ring R] [strong_rank_condition R] [ring S] [is_domain S]
  [algebra R S] {n m : Type*} [fintype n] [fintype m]
  (b : basis n R S) {I : ideal S} (hI : I ≠ ⊥) (c : basis m R I) :
  fintype.card m = fintype.card n :=
begin
  obtain ⟨a, ha⟩ := submodule.nonzero_mem_of_bot_lt (bot_lt_iff_ne_bot.mpr hI),
  have : linear_independent R (λ i, b i • a),
  { have hb := b.linear_independent,
    rw fintype.linear_independent_iff at ⊢ hb,
    intros g hg,
    apply hb g,
    simp only [← smul_assoc, ← finset.sum_smul, smul_eq_zero] at hg,
    exact hg.resolve_right ha },
  exact le_antisymm
    (b.card_le_card_of_linear_independent (c.linear_independent.map' (submodule.subtype I)
      (linear_map.ker_eq_bot.mpr subtype.coe_injective)))
    (c.card_le_card_of_linear_independent this),
end

variables (R)

@[simp] lemma dim_self : module.rank R R = 1 :=
by rw [←cardinal.lift_inj, ← (basis.singleton punit R).mk_eq_dim, cardinal.mk_punit]

end strong_rank_condition

section division_ring
variables [division_ring K] [add_comm_group V] [module K V] [add_comm_group V₁] [module K V₁]
variables {K V}

/-- If a vector space has a finite dimension, the index set of `basis.of_vector_space` is finite. -/
lemma basis.finite_of_vector_space_index_of_dim_lt_omega (h : module.rank K V < ω) :
  (basis.of_vector_space_index K V).finite :=
finite_def.2 $ (basis.of_vector_space K V).nonempty_fintype_index_of_dim_lt_omega h

variables [add_comm_group V'] [module K V']

/-- Two vector spaces are isomorphic if they have the same dimension. -/
theorem nonempty_linear_equiv_of_lift_dim_eq
  (cond : cardinal.lift.{v'} (module.rank K V) = cardinal.lift.{v} (module.rank K V')) :
  nonempty (V ≃ₗ[K] V') :=
begin
  let B := basis.of_vector_space K V,
  let B' := basis.of_vector_space K V',
  have : cardinal.lift.{v' v} (#_) = cardinal.lift.{v v'} (#_),
    by rw [B.mk_eq_dim'', cond, B'.mk_eq_dim''],
  exact (cardinal.lift_mk_eq.{v v' 0}.1 this).map (B.equiv B')
end

/-- Two vector spaces are isomorphic if they have the same dimension. -/
theorem nonempty_linear_equiv_of_dim_eq (cond : module.rank K V = module.rank K V₁) :
  nonempty (V ≃ₗ[K] V₁) :=
nonempty_linear_equiv_of_lift_dim_eq $ congr_arg _ cond

section

variables (V V' V₁)

/-- Two vector spaces are isomorphic if they have the same dimension. -/
def linear_equiv.of_lift_dim_eq
  (cond : cardinal.lift.{v'} (module.rank K V) = cardinal.lift.{v} (module.rank K V')) :
  V ≃ₗ[K] V' :=
classical.choice (nonempty_linear_equiv_of_lift_dim_eq cond)

/-- Two vector spaces are isomorphic if they have the same dimension. -/
def linear_equiv.of_dim_eq (cond : module.rank K V = module.rank K V₁) : V ≃ₗ[K] V₁ :=
classical.choice (nonempty_linear_equiv_of_dim_eq cond)

end

/-- Two vector spaces are isomorphic if and only if they have the same dimension. -/
theorem linear_equiv.nonempty_equiv_iff_lift_dim_eq :
  nonempty (V ≃ₗ[K] V') ↔
    cardinal.lift.{v'} (module.rank K V) = cardinal.lift.{v} (module.rank K V') :=
⟨λ ⟨h⟩, linear_equiv.lift_dim_eq h, λ h, nonempty_linear_equiv_of_lift_dim_eq h⟩

/-- Two vector spaces are isomorphic if and only if they have the same dimension. -/
theorem linear_equiv.nonempty_equiv_iff_dim_eq :
  nonempty (V ≃ₗ[K] V₁) ↔ module.rank K V = module.rank K V₁ :=
⟨λ ⟨h⟩, linear_equiv.dim_eq h, λ h, nonempty_linear_equiv_of_dim_eq h⟩

-- TODO how far can we generalise this?
-- When `s` is finite, we could prove this for any ring satisfying the strong rank condition
-- using `linear_independent_le_span'`
lemma dim_span_le (s : set V) : module.rank K (span K s) ≤ #s :=
begin
  obtain ⟨b, hb, hsab, hlib⟩ := exists_linear_independent K s,
  convert cardinal.mk_le_mk_of_subset hb,
  rw [← hsab, dim_span_set hlib]
end

lemma dim_span_of_finset (s : finset V) :
  module.rank K (span K (↑s : set V)) < ω :=
calc module.rank K (span K (↑s : set V)) ≤ #(↑s : set V) : dim_span_le ↑s
                             ... = s.card : by rw [finset.coe_sort_coe, cardinal.mk_finset]
                             ... < ω : cardinal.nat_lt_omega _

theorem dim_prod : module.rank K (V × V₁) = module.rank K V + module.rank K V₁ :=
begin
  let b := basis.of_vector_space K V,
  let c := basis.of_vector_space K V₁,
  rw [← cardinal.lift_inj,
      ← (basis.prod b c).mk_eq_dim,
      cardinal.lift_add, ← cardinal.mk_ulift,
      ← b.mk_eq_dim, ← c.mk_eq_dim,
      ← cardinal.mk_ulift, ← cardinal.mk_ulift,
      cardinal.add_def (ulift _)],
  exact cardinal.lift_inj.1 (cardinal.lift_mk_eq.2
      ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm ⟩),
end

section fintype
variable [fintype η]
variables [∀i, add_comm_group (φ i)] [∀i, module K (φ i)]

open linear_map

lemma dim_pi : module.rank K (Πi, φ i) = cardinal.sum (λi, module.rank K (φ i)) :=
begin
  let b := assume i, basis.of_vector_space K (φ i),
  let this : basis (Σ j, _) K (Π j, φ j) := pi.basis b,
  rw [← cardinal.lift_inj, ← this.mk_eq_dim],
  simp [← (b _).mk_range_eq_dim]
end

lemma dim_fun {V η : Type u} [fintype η] [add_comm_group V] [module K V] :
  module.rank K (η → V) = fintype.card η * module.rank K V :=
by rw [dim_pi, cardinal.sum_const', cardinal.mk_fintype]

lemma dim_fun_eq_lift_mul :
  module.rank K (η → V) = (fintype.card η : cardinal.{max u₁' v}) *
    cardinal.lift.{u₁'} (module.rank K V) :=
by rw [dim_pi, cardinal.sum_const, cardinal.mk_fintype, cardinal.lift_nat_cast]

lemma dim_fun' : module.rank K (η → K) = fintype.card η :=
by rw [dim_fun_eq_lift_mul, dim_self, cardinal.lift_one, mul_one, cardinal.nat_cast_inj]

lemma dim_fin_fun (n : ℕ) : module.rank K (fin n → K) = n :=
by simp [dim_fun']

end fintype

end division_ring

section field
variables [field K] [add_comm_group V] [module K V] [add_comm_group V₁] [module K V₁]
variables [add_comm_group V'] [module K V']
variables {K V}

theorem dim_quotient_add_dim (p : submodule K V) :
  module.rank K (V ⧸ p) + module.rank K p = module.rank K V :=
by classical; exact let ⟨f⟩ := quotient_prod_linear_equiv p in dim_prod.symm.trans f.dim_eq

/-- rank-nullity theorem -/
theorem dim_range_add_dim_ker (f : V →ₗ[K] V₁) :
  module.rank K f.range + module.rank K f.ker = module.rank K V :=
begin
  haveI := λ (p : submodule K V), classical.dec_eq (V ⧸ p),
  rw [← f.quot_ker_equiv_range.dim_eq, dim_quotient_add_dim]
end

lemma dim_eq_of_surjective (f : V →ₗ[K] V₁) (h : surjective f) :
  module.rank K V = module.rank K V₁ + module.rank K f.ker :=
by rw [← dim_range_add_dim_ker f, ← dim_range_of_surjective f h]

section
variables [add_comm_group V₂] [module K V₂]
variables [add_comm_group V₃] [module K V₃]
open linear_map

/-- This is mostly an auxiliary lemma for `dim_sup_add_dim_inf_eq`. -/
lemma dim_add_dim_split
  (db : V₂ →ₗ[K] V) (eb : V₃ →ₗ[K] V) (cd : V₁ →ₗ[K] V₂) (ce : V₁ →ₗ[K] V₃)
  (hde : ⊤ ≤ db.range ⊔ eb.range)
  (hgd : ker cd = ⊥)
  (eq : db.comp cd = eb.comp ce)
  (eq₂ : ∀d e, db d = eb e → (∃c, cd c = d ∧ ce c = e)) :
  module.rank K V + module.rank K V₁ = module.rank K V₂ + module.rank K V₃ :=
have hf : surjective (coprod db eb),
begin
  refine (range_eq_top.1 $ top_unique $ _),
  rwa [← map_top, ← prod_top, map_coprod_prod, ←range_eq_map, ←range_eq_map]
end,
begin
  conv {to_rhs, rw [← dim_prod, dim_eq_of_surjective _ hf] },
  congr' 1,
  apply linear_equiv.dim_eq,
  refine linear_equiv.of_bijective _ _ _,
  { refine cod_restrict _ (prod cd (- ce)) _,
    { assume c,
      simp only [add_eq_zero_iff_eq_neg, linear_map.prod_apply, mem_ker,
        coprod_apply, neg_neg, map_neg, neg_apply],
      exact linear_map.ext_iff.1 eq c } },
  { rw [← ker_eq_bot, ker_cod_restrict, ker_prod, hgd, bot_inf_eq] },
  { rw [← range_eq_top, eq_top_iff, range_cod_restrict, ← map_le_iff_le_comap,
      map_top, range_subtype],
    rintros ⟨d, e⟩,
    have h := eq₂ d (-e),
    simp only [add_eq_zero_iff_eq_neg, linear_map.prod_apply, mem_ker, set_like.mem_coe,
      prod.mk.inj_iff, coprod_apply, map_neg, neg_apply, linear_map.mem_range] at ⊢ h,
    assume hde,
    rcases h hde with ⟨c, h₁, h₂⟩,
    refine ⟨c, h₁, _⟩,
    rw [h₂, _root_.neg_neg] }
end

lemma dim_sup_add_dim_inf_eq (s t : submodule K V) :
  module.rank K (s ⊔ t : submodule K V) + module.rank K (s ⊓ t : submodule K V) =
    module.rank K s + module.rank K t :=
dim_add_dim_split (of_le le_sup_left) (of_le le_sup_right) (of_le inf_le_left) (of_le inf_le_right)
  begin
    rw [← map_le_map_iff' (ker_subtype $ s ⊔ t), map_sup, map_top,
      ← linear_map.range_comp, ← linear_map.range_comp, subtype_comp_of_le, subtype_comp_of_le,
      range_subtype, range_subtype, range_subtype],
    exact le_refl _
  end
  (ker_of_le _ _ _)
  begin ext ⟨x, hx⟩, refl end
  begin
    rintros ⟨b₁, hb₁⟩ ⟨b₂, hb₂⟩ eq,
    have : b₁ = b₂ := congr_arg subtype.val eq,
    subst this,
    exact ⟨⟨b₁, hb₁, hb₂⟩, rfl, rfl⟩
  end

lemma dim_add_le_dim_add_dim (s t : submodule K V) :
  module.rank K (s ⊔ t : submodule K V) ≤ module.rank K s + module.rank K t :=
by { rw [← dim_sup_add_dim_inf_eq], exact self_le_add_right _ _ }

end

lemma exists_mem_ne_zero_of_dim_pos {s : submodule K V} (h : 0 < module.rank K s) :
  ∃ b : V, b ∈ s ∧ b ≠ 0 :=
exists_mem_ne_zero_of_ne_bot $ assume eq, by rw [eq, dim_bot] at h; exact lt_irrefl _ h

section rank

-- TODO This definition, and some of the results about it, could be generalized to arbitrary rings.
/-- `rank f` is the rank of a `linear_map f`, defined as the dimension of `f.range`. -/
def rank (f : V →ₗ[K] V') : cardinal := module.rank K f.range

lemma rank_le_domain (f : V →ₗ[K] V₁) : rank f ≤ module.rank K V :=
by { rw [← dim_range_add_dim_ker f], exact self_le_add_right _ _ }

lemma rank_le_range (f : V →ₗ[K] V₁) : rank f ≤ module.rank K V₁ :=
dim_submodule_le _

lemma rank_add_le (f g : V →ₗ[K] V') : rank (f + g) ≤ rank f + rank g :=
calc rank (f + g) ≤ module.rank K (f.range ⊔ g.range : submodule K V') :
  begin
    refine dim_le_of_submodule _ _ _,
    exact (linear_map.range_le_iff_comap.2 $ eq_top_iff'.2 $
      assume x, show f x + g x ∈ (f.range ⊔ g.range : submodule K V'), from
        mem_sup.2 ⟨_, ⟨x, rfl⟩, _, ⟨x, rfl⟩, rfl⟩)
  end
  ... ≤ rank f + rank g : dim_add_le_dim_add_dim _ _

@[simp] lemma rank_zero : rank (0 : V →ₗ[K] V') = 0 :=
by rw [rank, linear_map.range_zero, dim_bot]

lemma rank_finset_sum_le {η} (s : finset η) (f : η → V →ₗ[K] V') :
  rank (∑ d in s, f d) ≤ ∑ d in s, rank (f d) :=
@finset.sum_hom_rel _ _ _ _ _ (λa b, rank a ≤ b) f (λ d, rank (f d)) s (le_of_eq rank_zero)
      (λ i g c h, le_trans (rank_add_le _ _) (add_le_add_left h _))

variables [add_comm_group V''] [module K V'']

lemma rank_comp_le1 (g : V →ₗ[K] V') (f : V' →ₗ[K] V'') : rank (f.comp g) ≤ rank f :=
begin
  refine dim_le_of_submodule _ _ _,
  rw [linear_map.range_comp],
  exact linear_map.map_le_range,
end

variables [add_comm_group V'₁] [module K V'₁]

lemma rank_comp_le2 (g : V →ₗ[K] V') (f : V' →ₗ[K] V'₁) : rank (f.comp g) ≤ rank g :=
by rw [rank, rank, linear_map.range_comp]; exact dim_map_le _ _

end rank

-- TODO The remainder of this file could be generalized to arbitrary rings.

/-- The `ι` indexed basis on `V`, where `ι` is an empty type and `V` is zero-dimensional.

See also `finite_dimensional.fin_basis`.
-/
def basis.of_dim_eq_zero {ι : Type*} [is_empty ι] (hV : module.rank K V = 0) :
  basis ι K V :=
begin
  haveI : subsingleton V := dim_zero_iff.1 hV,
  exact basis.empty _
end

@[simp] lemma basis.of_dim_eq_zero_apply {ι : Type*} [is_empty ι]
  (hV : module.rank K V = 0) (i : ι) :
  basis.of_dim_eq_zero hV i = 0 :=
rfl

lemma le_dim_iff_exists_linear_independent {c : cardinal} :
  c ≤ module.rank K V ↔ ∃ s : set V, #s = c ∧ linear_independent K (coe : s → V) :=
begin
  split,
  { intro h,
    let t := basis.of_vector_space K V,
    rw [← t.mk_eq_dim'', cardinal.le_mk_iff_exists_subset] at h,
    rcases h with ⟨s, hst, hsc⟩,
    exact ⟨s, hsc, (of_vector_space_index.linear_independent K V).mono hst⟩ },
  { rintro ⟨s, rfl, si⟩,
    exact cardinal_le_dim_of_linear_independent si }
end

lemma le_dim_iff_exists_linear_independent_finset {n : ℕ} :
  ↑n ≤ module.rank K V ↔
    ∃ s : finset V, s.card = n ∧ linear_independent K (coe : (s : set V) → V) :=
begin
  simp only [le_dim_iff_exists_linear_independent, cardinal.mk_eq_nat_iff_finset],
  split,
  { rintro ⟨s, ⟨t, rfl, rfl⟩, si⟩,
    exact ⟨t, rfl, si⟩ },
  { rintro ⟨s, rfl, si⟩,
    exact ⟨s, ⟨s, rfl, rfl⟩, si⟩ }
end

lemma le_rank_iff_exists_linear_independent {c : cardinal} {f : V →ₗ[K] V'} :
  c ≤ rank f ↔
  ∃ s : set V, cardinal.lift.{v'} (#s) = cardinal.lift.{v} c ∧
    linear_independent K (λ x : s, f x) :=
begin
  rcases f.range_restrict.exists_right_inverse_of_surjective f.range_range_restrict with ⟨g, hg⟩,
  have fg : left_inverse f.range_restrict g, from linear_map.congr_fun hg,
  refine ⟨λ h, _, _⟩,
  { rcases le_dim_iff_exists_linear_independent.1 h with ⟨s, rfl, si⟩,
    refine ⟨g '' s, cardinal.mk_image_eq_lift _ _ fg.injective, _⟩,
    replace fg : ∀ x, f (g x) = x, by { intro x, convert congr_arg subtype.val (fg x) },
    replace si : linear_independent K (λ x : s, f (g x)),
      by simpa only [fg] using si.map' _ (ker_subtype _),
    exact si.image_of_comp s g f },
  { rintro ⟨s, hsc, si⟩,
    have : linear_independent K (λ x : s, f.range_restrict x),
      from linear_independent.of_comp (f.range.subtype) (by convert si),
    convert cardinal_le_dim_of_linear_independent this.image,
    rw [← cardinal.lift_inj, ← hsc, cardinal.mk_image_eq_of_inj_on_lift],
    exact inj_on_iff_injective.2 this.injective }
end

lemma le_rank_iff_exists_linear_independent_finset {n : ℕ} {f : V →ₗ[K] V'} :
  ↑n ≤ rank f ↔ ∃ s : finset V, s.card = n ∧ linear_independent K (λ x : (s : set V), f x) :=
begin
  simp only [le_rank_iff_exists_linear_independent, cardinal.lift_nat_cast,
    cardinal.lift_eq_nat_iff, cardinal.mk_eq_nat_iff_finset],
  split,
  { rintro ⟨s, ⟨t, rfl, rfl⟩, si⟩,
    exact ⟨t, rfl, si⟩ },
  { rintro ⟨s, rfl, si⟩,
    exact ⟨s, ⟨s, rfl, rfl⟩, si⟩ }
end

/-- A vector space has dimension at most `1` if and only if there is a
single vector of which all vectors are multiples. -/
lemma dim_le_one_iff : module.rank K V ≤ 1 ↔ ∃ v₀ : V, ∀ v, ∃ r : K, r • v₀ = v :=
begin
  let b := basis.of_vector_space K V,
  split,
  { intro hd,
    rw [← b.mk_eq_dim'', cardinal.le_one_iff_subsingleton, subsingleton_coe] at hd,
    rcases eq_empty_or_nonempty (of_vector_space_index K V) with hb | ⟨⟨v₀, hv₀⟩⟩,
    { use 0,
      have h' : ∀ v : V, v = 0, { simpa [hb, submodule.eq_bot_iff] using b.span_eq.symm },
      intro v,
      simp [h' v] },
    { use v₀,
      have h' : (K ∙ v₀) = ⊤, { simpa [hd.eq_singleton_of_mem hv₀] using b.span_eq },
      intro v,
      have hv : v ∈ (⊤ : submodule K V) := mem_top,
      rwa [←h', mem_span_singleton] at hv } },
  { rintros ⟨v₀, hv₀⟩,
    have h : (K ∙ v₀) = ⊤,
    { ext, simp [mem_span_singleton, hv₀] },
    rw [←dim_top, ←h],
    convert dim_span_le _,
    simp }
end

/-- A submodule has dimension at most `1` if and only if there is a
single vector in the submodule such that the submodule is contained in
its span. -/
lemma dim_submodule_le_one_iff (s : submodule K V) : module.rank K s ≤ 1 ↔ ∃ v₀ ∈ s, s ≤ K ∙ v₀ :=
begin
  simp_rw [dim_le_one_iff, le_span_singleton_iff],
  split,
  { rintro ⟨⟨v₀, hv₀⟩, h⟩,
    use [v₀, hv₀],
    intros v hv,
    obtain ⟨r, hr⟩ := h ⟨v, hv⟩,
    use r,
    simp_rw [subtype.ext_iff, coe_smul, submodule.coe_mk] at hr,
    exact hr },
  { rintro ⟨v₀, hv₀, h⟩,
    use ⟨v₀, hv₀⟩,
    rintro ⟨v, hv⟩,
    obtain ⟨r, hr⟩ := h v hv,
    use r,
    simp_rw [subtype.ext_iff, coe_smul, submodule.coe_mk],
    exact hr }
end

/-- A submodule has dimension at most `1` if and only if there is a
single vector, not necessarily in the submodule, such that the
submodule is contained in its span. -/
lemma dim_submodule_le_one_iff' (s : submodule K V) : module.rank K s ≤ 1 ↔ ∃ v₀, s ≤ K ∙ v₀ :=
begin
  rw dim_submodule_le_one_iff,
  split,
  { rintros ⟨v₀, hv₀, h⟩,
    exact ⟨v₀, h⟩ },
  { rintros ⟨v₀, h⟩,
    by_cases hw : ∃ w : V, w ∈ s ∧ w ≠ 0,
    { rcases hw with ⟨w, hw, hw0⟩,
      use [w, hw],
      rcases mem_span_singleton.1 (h hw) with ⟨r', rfl⟩,
      have h0 : r' ≠ 0,
      { rintro rfl,
        simpa using hw0 },
      rwa span_singleton_smul_eq _ h0 },
    { push_neg at hw,
      rw ←submodule.eq_bot_iff at hw,
      simp [hw] } }
end

end field

end module


import Duper.RuleM
import Duper.Selection
import Duper.Util.ProofReconstruction

namespace Duper
open RuleM
open Lean
open Meta

initialize Lean.registerTraceClass `Rule.clausifyPropEq

theorem c1_soundness {p : Prop} {q : Prop} (h : p = q) : (p = True) ∨ (q = False) := by
  rw [h]
  exact Classical.propComplete q

/-  From a parent clause that has the literal p = q, we want to prove c which is identical to the parent clause except:
    1. The literal p = q is removed from c
    2. The literals p = True and q = False are appended to the end of c (in that order)
-/
def mkC1Proof (i : Nat) (premises : List Expr) (parents : List ProofParent) (transferExprs : Array Expr) (c : Clause) : MetaM Expr := do
  Meta.forallTelescope c.toForallExpr fun xs body => do
    let cLits := c.lits.map (fun l => l.map (fun e => e.instantiateRev xs))
    let (parentsLits, appliedPremises, transferExprs) ← instantiatePremises parents premises xs transferExprs
    let parentLits := parentsLits[0]!
    let appliedPremise := appliedPremises[0]!
    let mut proofCases : Array Expr := Array.mkEmpty parentLits.size
    for j in [:parentLits.size] do
      let lit := parentLits[j]!
      if j == i then
        --lit has the form p = q and is the propositional equality that is currently being clausified
        --We want to derive `p = q -> L_1 ∨ ... ∨ L_{n-1} ∨ L_n` by showing p = q -> L_{n-1} ∨ L_n where L_{n-1} is p = True and L_n = q = False
        let proofCase ← Meta.withLocalDeclD `h lit.toExpr fun h => do
          let proofCase ← Meta.mkAppM ``c1_soundness #[h]
          Meta.mkLambdaFVars #[h] $ ← orSubclause (cLits.map Lit.toExpr) 2 proofCase
        proofCases := proofCases.push proofCase
      else
        --lit is not the propositional equality that is currently being clausified
        let proofCase ← Meta.withLocalDeclD `h lit.toExpr fun h => do
          let idx := if j ≥ i then j - 1 else j
          Meta.mkLambdaFVars #[h] $ ← orIntro (cLits.map Lit.toExpr) idx h
        proofCases := proofCases.push proofCase
    let r ← orCases (parentLits.map Lit.toExpr) proofCases
    Meta.mkLambdaFVars xs $ mkApp r appliedPremise

theorem c2_soundness {p : Prop} {q : Prop} (h : p = q) : (p = False) ∨ (q = True) := by
  rw [h]
  cases Classical.propComplete q with
  | inl q_true => exact Or.intro_right _ q_true
  | inr q_false => exact Or.intro_left _ q_false

/-  From a parent clause that has the literal p = q, we want to prove c which is identical to the parent clause except:
    1. The literal p = q is removed from c
    2. The literals p = False and q = True are appended to the end of c (in that order)
-/
def mkC2Proof (i : Nat) (premises : List Expr) (parents : List ProofParent) (transferExprs : Array Expr) (c : Clause) : MetaM Expr :=
  Meta.forallTelescope c.toForallExpr fun xs body => do
    let cLits := c.lits.map (fun l => l.map (fun e => e.instantiateRev xs))
    let (parentsLits, appliedPremises, transferExprs) ← instantiatePremises parents premises xs transferExprs
    let parentLits := parentsLits[0]!
    let appliedPremise := appliedPremises[0]!
    let mut proofCases : Array Expr := Array.mkEmpty parentLits.size
    for j in [:parentLits.size] do
      let lit := parentLits[j]!
      if j == i then
        --lit has the form p = q and is the propositional equality that is currently being clausified
        --We want to derive `p = q -> L_1 ∨ ... ∨ L_{n-1} ∨ L_n` by showing p = q -> L_{n-1} ∨ L_n where L_{n-1} is p = False and L_n = q = True
        let proofCase ← Meta.withLocalDeclD `h lit.toExpr fun h => do
          let proofCase ← Meta.mkAppM ``c2_soundness #[h]
          Meta.mkLambdaFVars #[h] $ ← orSubclause (cLits.map Lit.toExpr) 2 proofCase
        proofCases := proofCases.push proofCase
      else
        --lit is not the propositional equality that is currently being clausified
        let proofCase ← Meta.withLocalDeclD `h lit.toExpr fun h => do
          let idx := if j ≥ i then j - 1 else j
          Meta.mkLambdaFVars #[h] $ ← orIntro (cLits.map Lit.toExpr) idx h
        proofCases := proofCases.push proofCase
    let r ← orCases (parentLits.map Lit.toExpr) proofCases
    Meta.mkLambdaFVars xs $ mkApp r appliedPremise

def clausifyPropEq (given : Clause)(c : MClause) (cNum : Nat) : RuleM (Array ClauseStream) := do
  trace[Rule.clausifyPropEq] "ClausifyPropEq inferences with {c.lits}"
  let mut streams := #[]
  for i in [:c.lits.size] do
    let lit := c.lits[i]!
    if lit.sign = true && lit.ty.isProp && litSelectedOrNothingSelected c i then
      -- TODO: check both sides?
      if ¬ lit.rhs.isConstOf ``True && ¬ lit.rhs.isConstOf ``False then
        let c' := c.eraseLit i
        let c1 := c'.appendLits #[Lit.fromSingleExpr lit.lhs true, Lit.fromSingleExpr lit.rhs false]
        let c2 := c'.appendLits #[Lit.fromSingleExpr lit.lhs false, Lit.fromSingleExpr lit.rhs true]
        trace[Rule.clausifyPropEq] "clausifyPropEq called on {lit} in {c.lits} to produce {c1.lits} and {c2.lits}"
        let loaded ← getLoadedClauses
        let ug ← unifierGenerator #[]
        let yield1 := do
          setLoadedClauses loaded
          yieldClause c1 "clausify Prop equality" (mkProof := some (mkC1Proof i))
        let yield2 := do
          setLoadedClauses loaded
          yieldClause c2 "clausify Prop equality" (mkProof := some (mkC2Proof i))
        streams := streams.append #[ClauseStream.mk ug given yield1 "clausify Prop equality", ClauseStream.mk ug given yield2 "clausify Prop equality"]
  return streams

end Duper


/-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel, Floris van Doorn, Mario Carneiro, Martin Dvorak

! This file was ported from Lean 3 source module data.list.join
! leanprover-community/mathlib commit be24ec5de6701447e5df5ca75400ffee19d65659
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Data.List.BigOperators.Basic

/-!
# Join of a list of lists

> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.

This file proves basic properties of `list.join`, which concatenates a list of lists. It is defined
in [`data.list.defs`](./defs).
-/

variable {α β : Type _}

namespace List

attribute [simp] join

#print List.join_singleton /-
@[simp]
theorem join_singleton (l : List α) : [l].join = l := by rw [join, join, append_nil]
#align list.join_singleton List.join_singleton
-/

#print List.join_eq_nil /-
@[simp]
theorem join_eq_nil : ∀ {L : List (List α)}, join L = [] ↔ ∀ l ∈ L, l = []
  | [] => iff_of_true rfl (forall_mem_nil _)
  | l :: L => by simp only [join, append_eq_nil, join_eq_nil, forall_mem_cons]
#align list.join_eq_nil List.join_eq_nil
-/

#print List.join_append /-
@[simp]
theorem join_append (L₁ L₂ : List (List α)) : join (L₁ ++ L₂) = join L₁ ++ join L₂ := by
  induction L₁ <;> [rfl, simp only [*, join, cons_append, append_assoc]]
#align list.join_append List.join_append
-/

#print List.join_concat /-
theorem join_concat (L : List (List α)) (l : List α) : join (L.concat l) = join L ++ l := by simp
#align list.join_concat List.join_concat
-/

/- warning: list.join_filter_empty_eq_ff -> List.join_filter_isEmpty_eq_false is a dubious translation:
lean 3 declaration is
  forall {α : Type.{u1}} [_inst_1 : DecidablePred.{succ u1} (List.{u1} α) (fun (l : List.{u1} α) => Eq.{1} Bool (List.isEmpty.{u1} α l) Bool.false)] {L : List.{u1} (List.{u1} α)}, Eq.{succ u1} (List.{u1} α) (List.join.{u1} α (List.filterₓ.{u1} (List.{u1} α) (fun (l : List.{u1} α) => Eq.{1} Bool (List.isEmpty.{u1} α l) Bool.false) (fun (a : List.{u1} α) => _inst_1 a) L)) (List.join.{u1} α L)
but is expected to have type
  forall {α : Type.{u1}} [_inst_1 : DecidablePred.{succ u1} (List.{u1} α) (fun (l : List.{u1} α) => Eq.{1} Bool (List.isEmpty.{u1} α l) Bool.false)] {L : List.{u1} (List.{u1} α)}, Eq.{succ u1} (List.{u1} α) (List.join.{u1} α (List.filter.{u1} (List.{u1} α) (fun (a : List.{u1} α) => Decidable.decide (Eq.{1} Bool (List.isEmpty.{u1} α a) Bool.false) (_inst_1 a)) L)) (List.join.{u1} α L)
Case conversion may be inaccurate. Consider using '#align list.join_filter_empty_eq_ff List.join_filter_isEmpty_eq_falseₓ'. -/
@[simp]
theorem join_filter_isEmpty_eq_false [DecidablePred fun l : List α => l.Empty = false] :
    ∀ {L : List (List α)}, join (L.filterₓ fun l => l.Empty = false) = L.join
  | [] => rfl
  | [] :: L => by simp [@join_filter_empty_eq_ff L]
  | (a :: l) :: L => by simp [@join_filter_empty_eq_ff L]
#align list.join_filter_empty_eq_ff List.join_filter_isEmpty_eq_false

/- warning: list.join_filter_ne_nil -> List.join_filter_ne_nil is a dubious translation:
lean 3 declaration is
  forall {α : Type.{u1}} [_inst_1 : DecidablePred.{succ u1} (List.{u1} α) (fun (l : List.{u1} α) => Ne.{succ u1} (List.{u1} α) l (List.nil.{u1} α))] {L : List.{u1} (List.{u1} α)}, Eq.{succ u1} (List.{u1} α) (List.join.{u1} α (List.filterₓ.{u1} (List.{u1} α) (fun (l : List.{u1} α) => Ne.{succ u1} (List.{u1} α) l (List.nil.{u1} α)) (fun (a : List.{u1} α) => _inst_1 a) L)) (List.join.{u1} α L)
but is expected to have type
  forall {α : Type.{u1}} [_inst_1 : DecidablePred.{succ u1} (List.{u1} α) (fun (l : List.{u1} α) => Ne.{succ u1} (List.{u1} α) l (List.nil.{u1} α))] {L : List.{u1} (List.{u1} α)}, Eq.{succ u1} (List.{u1} α) (List.join.{u1} α (List.filter.{u1} (List.{u1} α) (fun (a : List.{u1} α) => Decidable.decide (Ne.{succ u1} (List.{u1} α) a (List.nil.{u1} α)) (_inst_1 a)) L)) (List.join.{u1} α L)
Case conversion may be inaccurate. Consider using '#align list.join_filter_ne_nil List.join_filter_ne_nilₓ'. -/
@[simp]
theorem join_filter_ne_nil [DecidablePred fun l : List α => l ≠ []] {L : List (List α)} :
    join (L.filterₓ fun l => l ≠ []) = L.join := by
  simp [join_filter_empty_eq_ff, ← empty_iff_eq_nil]
#align list.join_filter_ne_nil List.join_filter_ne_nil

#print List.join_join /-
theorem join_join (l : List (List (List α))) : l.join.join = (l.map join).join :=
  by
  induction l
  simp
  simp [l_ih]
#align list.join_join List.join_join
-/

#print List.length_join /-
@[simp]
theorem length_join (L : List (List α)) : length (join L) = sum (map length L) := by
  induction L <;> [rfl, simp only [*, join, map, sum_cons, length_append]]
#align list.length_join List.length_join
-/

/- warning: list.length_bind -> List.length_bind is a dubious translation:
lean 3 declaration is
  forall {α : Type.{u1}} {β : Type.{u2}} (l : List.{u1} α) (f : α -> (List.{u2} β)), Eq.{1} Nat (List.length.{u2} β (List.bind.{u1, u2} α β l f)) (List.sum.{0} Nat Nat.hasAdd Nat.hasZero (List.map.{u1, 0} α Nat (Function.comp.{succ u1, succ u2, 1} α (List.{u2} β) Nat (List.length.{u2} β) f) l))
but is expected to have type
  forall {α : Type.{u2}} {β : Type.{u1}} (l : List.{u2} α) (f : α -> (List.{u1} β)), Eq.{1} Nat (List.length.{u1} β (List.bind.{u2, u1} α β l f)) (List.sum.{0} Nat instAddNat (LinearOrderedCommMonoidWithZero.toZero.{0} Nat Nat.linearOrderedCommMonoidWithZero) (List.map.{u2, 0} α Nat (Function.comp.{succ u2, succ u1, 1} α (List.{u1} β) Nat (List.length.{u1} β) f) l))
Case conversion may be inaccurate. Consider using '#align list.length_bind List.length_bindₓ'. -/
@[simp]
theorem length_bind (l : List α) (f : α → List β) :
    length (List.bind l f) = sum (map (length ∘ f) l) := by rw [List.bind, length_join, map_map]
#align list.length_bind List.length_bind

/- warning: list.bind_eq_nil -> List.bind_eq_nil is a dubious translation:
lean 3 declaration is
  forall {α : Type.{u1}} {β : Type.{u2}} {l : List.{u1} α} {f : α -> (List.{u2} β)}, Iff (Eq.{succ u2} (List.{u2} β) (List.bind.{u1, u2} α β l f) (List.nil.{u2} β)) (forall (x : α), (Membership.Mem.{u1, u1} α (List.{u1} α) (List.hasMem.{u1} α) x l) -> (Eq.{succ u2} (List.{u2} β) (f x) (List.nil.{u2} β)))
but is expected to have type
  forall {α : Type.{u2}} {β : Type.{u1}} {l : List.{u2} α} {f : α -> (List.{u1} β)}, Iff (Eq.{succ u1} (List.{u1} β) (List.bind.{u2, u1} α β l f) (List.nil.{u1} β)) (forall (x : α), (Membership.mem.{u2, u2} α (List.{u2} α) (List.instMembershipList.{u2} α) x l) -> (Eq.{succ u1} (List.{u1} β) (f x) (List.nil.{u1} β)))
Case conversion may be inaccurate. Consider using '#align list.bind_eq_nil List.bind_eq_nilₓ'. -/
@[simp]
theorem bind_eq_nil {l : List α} {f : α → List β} : List.bind l f = [] ↔ ∀ x ∈ l, f x = [] :=
  join_eq_nil.trans <| by
    simp only [mem_map, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂]
#align list.bind_eq_nil List.bind_eq_nil

#print List.take_sum_join /-
/-- In a join, taking the first elements up to an index which is the sum of the lengths of the
first `i` sublists, is the same as taking the join of the first `i` sublists. -/
theorem take_sum_join (L : List (List α)) (i : ℕ) :
    L.join.take ((L.map length).take i).Sum = (L.take i).join :=
  by
  induction L generalizing i; · simp
  cases i; · simp
  simp [take_append, L_ih]
#align list.take_sum_join List.take_sum_join
-/

#print List.drop_sum_join /-
/-- In a join, dropping all the elements up to an index which is the sum of the lengths of the
first `i` sublists, is the same as taking the join after dropping the first `i` sublists. -/
theorem drop_sum_join (L : List (List α)) (i : ℕ) :
    L.join.drop ((L.map length).take i).Sum = (L.drop i).join :=
  by
  induction L generalizing i; · simp
  cases i; · simp
  simp [drop_append, L_ih]
#align list.drop_sum_join List.drop_sum_join
-/

#print List.drop_take_succ_eq_cons_nthLe /-
/-- Taking only the first `i+1` elements in a list, and then dropping the first `i` ones, one is
left with a list of length `1` made of the `i`-th element of the original list. -/
theorem drop_take_succ_eq_cons_nthLe (L : List α) {i : ℕ} (hi : i < L.length) :
    (L.take (i + 1)).drop i = [nthLe L i hi] :=
  by
  induction L generalizing i
  · simp only [length] at hi
    exact (Nat.not_succ_le_zero i hi).elim
  cases i
  · simp
  have : i < L_tl.length := by
    simp at hi
    exact Nat.lt_of_succ_lt_succ hi
  simp [L_ih this]
  rfl
#align list.drop_take_succ_eq_cons_nth_le List.drop_take_succ_eq_cons_nthLe
-/

#print List.drop_take_succ_join_eq_nthLe /-
/-- In a join of sublists, taking the slice between the indices `A` and `B - 1` gives back the
original sublist of index `i` if `A` is the sum of the lenghts of sublists of index `< i`, and
`B` is the sum of the lengths of sublists of index `≤ i`. -/
theorem drop_take_succ_join_eq_nthLe (L : List (List α)) {i : ℕ} (hi : i < L.length) :
    (L.join.take ((L.map length).take (i + 1)).Sum).drop ((L.map length).take i).Sum =
      nthLe L i hi :=
  by
  have : (L.map length).take i = ((L.take (i + 1)).map length).take i := by
    simp [map_take, take_take]
  simp [take_sum_join, this, drop_sum_join, drop_take_succ_eq_cons_nth_le _ hi]
#align list.drop_take_succ_join_eq_nth_le List.drop_take_succ_join_eq_nthLe
-/

#print List.sum_take_map_length_lt1 /-
/-- Auxiliary lemma to control elements in a join. -/
theorem sum_take_map_length_lt1 (L : List (List α)) {i j : ℕ} (hi : i < L.length)
    (hj : j < (nthLe L i hi).length) :
    ((L.map length).take i).Sum + j < ((L.map length).take (i + 1)).Sum := by
  simp [hi, sum_take_succ, hj]
#align list.sum_take_map_length_lt1 List.sum_take_map_length_lt1
-/

#print List.sum_take_map_length_lt2 /-
/-- Auxiliary lemma to control elements in a join. -/
theorem sum_take_map_length_lt2 (L : List (List α)) {i j : ℕ} (hi : i < L.length)
    (hj : j < (nthLe L i hi).length) : ((L.map length).take i).Sum + j < L.join.length :=
  by
  convert lt_of_lt_of_le (sum_take_map_length_lt1 L hi hj) (monotone_sum_take _ hi)
  have : L.length = (L.map length).length := by simp
  simp [this, -length_map]
#align list.sum_take_map_length_lt2 List.sum_take_map_length_lt2
-/

#print List.nthLe_join /-
/-- The `n`-th element in a join of sublists is the `j`-th element of the `i`th sublist,
where `n` can be obtained in terms of `i` and `j` by adding the lengths of all the sublists
of index `< i`, and adding `j`. -/
theorem nthLe_join (L : List (List α)) {i j : ℕ} (hi : i < L.length)
    (hj : j < (nthLe L i hi).length) :
    nthLe L.join (((L.map length).take i).Sum + j) (sum_take_map_length_lt2 L hi hj) =
      nthLe (nthLe L i hi) j hj :=
  by
  rw [nth_le_take L.join (sum_take_map_length_lt2 L hi hj) (sum_take_map_length_lt1 L hi hj),
    nth_le_drop, nth_le_of_eq (drop_take_succ_join_eq_nth_le L hi)]
#align list.nth_le_join List.nthLe_join
-/

#print List.eq_iff_join_eq /-
/-- Two lists of sublists are equal iff their joins coincide, as well as the lengths of the
sublists. -/
theorem eq_iff_join_eq (L L' : List (List α)) :
    L = L' ↔ L.join = L'.join ∧ map length L = map length L' :=
  by
  refine' ⟨fun H => by simp [H], _⟩
  rintro ⟨join_eq, length_eq⟩
  apply ext_le
  · have : length (map length L) = length (map length L') := by rw [length_eq]
    simpa using this
  · intro n h₁ h₂
    rw [← drop_take_succ_join_eq_nth_le, ← drop_take_succ_join_eq_nth_le, join_eq, length_eq]
#align list.eq_iff_join_eq List.eq_iff_join_eq
-/

#print List.join_drop_length_sub_one /-
theorem join_drop_length_sub_one {L : List (List α)} (h : L ≠ []) :
    (L.drop (L.length - 1)).join = L.getLast h :=
  by
  induction L using List.reverseRecOn
  · cases h rfl
  · simp
#align list.join_drop_length_sub_one List.join_drop_length_sub_one
-/

#print List.append_join_map_append /-
/-- We can rebracket `x ++ (l₁ ++ x) ++ (l₂ ++ x) ++ ... ++ (lₙ ++ x)` to
`(x ++ l₁) ++ (x ++ l₂) ++ ... ++ (x ++ lₙ) ++ x` where `L = [l₁, l₂, ..., lₙ]`. -/
theorem append_join_map_append (L : List (List α)) (x : List α) :
    x ++ (List.map (fun l => l ++ x) L).join = (List.map (fun l => x ++ l) L).join ++ x :=
  by
  induction L
  · rw [map_nil, join, append_nil, map_nil, join, nil_append]
  · rw [map_cons, join, map_cons, join, append_assoc, L_ih, append_assoc, append_assoc]
#align list.append_join_map_append List.append_join_map_append
-/

#print List.reverse_join /-
/-- Reversing a join is the same as reversing the order of parts and reversing all parts. -/
theorem reverse_join (L : List (List α)) :
    L.join.reverse = (List.map List.reverse L).reverse.join :=
  by
  induction L
  · rfl
  · rw [join, reverse_append, L_ih, map_cons, reverse_cons', join_concat]
#align list.reverse_join List.reverse_join
-/

#print List.join_reverse /-
/-- Joining a reverse is the same as reversing all parts and reversing the joined result. -/
theorem join_reverse (L : List (List α)) :
    L.reverse.join = (List.map List.reverse L).join.reverse := by
  simpa [reverse_reverse] using congr_arg List.reverse (reverse_join L.reverse)
#align list.join_reverse List.join_reverse
-/

end List


import ground_zero.cubical.cubes
open ground_zero.cubical ground_zero.types ground_zero.HITs
open ground_zero.HITs.interval (i₀ i₁ seg)

/-
  * Coercions.
  * Basic path lemmas: refl, symm, cong, funext...
  * Connections.
  * Singleton contractibility, J elimination rule.
  * PathP.
-/

namespace ground_zero.cubical

namespace Path
universes u v

def coe.forward (π : I → Sort u) (i : I) (x : π i₀) : π i :=
interval.ind x (equiv.subst seg x) (equiv.path_over_subst eq.rfl) i

def coe.back (π : I → Sort u) (i : I) (x : π i₁) : π i :=
interval.ind (equiv.subst seg⁻¹ x) x (begin
  apply equiv.path_over_subst, transitivity,
  { symmetry, apply equiv.subst_comp }, transitivity,
  { apply eq.map (λ p, equiv.subst p x), apply eq.inv_comp },
  reflexivity
end) i

def coe (i k : I) (π : I → Sort u) : π i → π k :=
coe.forward (λ i, π i → π k) i (coe.forward π k)

def coe_inv (i k : I) (π : I → Sort u) : π i → π k :=
coe.back (λ i, π i → π k) i (coe.back π k)

notation `coe⁻¹` := coe_inv

@[refl] def refl {α : Sort u} (a : α) : a ⇝ a := <i> a
def rfl {α : Sort u} {a : α} : a ⇝ a := <i> a

@[symm] def symm {α : Sort u} {a b : α} (p : a ⇝ b) : b ⇝ a :=
<i> p # −i
postfix `⁻¹` := symm

abbreviation inv {α : Sort u} {a b : α} (p : a ⇝ b) := p⁻¹

example {α : Sort u} {a b : α} (p : a ⇝ b) : b ⇝ a :=
coe 1 0 (λ i, b ⇝ p # i) rfl

def funext {α : Sort u} {β : α → Sort v} {f g : Π (x : α), β x}
  (p : Π (x : α), f x ⇝ g x) : f ⇝ g :=
<i> λ x, p x # i

def cong {α : Sort u} {β : Sort v} {a b : α}
  (f : α → β) (p : a ⇝ b) : f a ⇝ f b :=
<i> f (p # i)

def ap {α : Sort u} {β : α → Sort v} {a b : α}
  (f : α → β a) (p : a ⇝ b) : f a ⇝ f b :=
<i> f (p # i)

def subst {α : Sort u} {π : α → Sort v} {a b : α}
  (p : a ⇝ b) (x : π a) : π b :=
coe 0 1 (λ i, π (p # i)) x

abbreviation transport {α : Sort u} (π : α → Sort v) {a b : α}
  (p : a ⇝ b) : π a → π b := subst p

def trans {α β : Sort u} (p : α ⇝ β) : α → β :=
coe 0 1 (λ i, p # i)
abbreviation coerce {α β : Sort u} : (α ⇝ β) → (α → β) := trans

def trans_neg {α β : Sort u} (p : α ⇝ β) : β → α :=
coe 1 0 (λ i, p # i)

def transK {α β : Sort u} (p : α ⇝ β) (x : α) :
  x ⇝ trans_neg p (trans p x) :=
<i> coe i 0 (λ i, p # i) (coe 0 i (λ i, p # i) x)

def idtoeqv {α β : Sort u} (p : α ⇝ β) : α ≃ β :=
trans (<i> α ≃ p # i) (equiv.id α)

def test_eta {α : Sort u} {a b : α} (p : a ⇝ b) : p ⇝ p := rfl
def face₀ {α : Sort u} {a b : α} (p : a ⇝ b) : α := p # 0
def face₁ {α : Sort u} {a b : α} (p : a ⇝ b) : α := p # 1

def comp_test₀ {α : Sort u} {a b : α} (p : a ⇝ b) : p # 0 ⇝ a := rfl
def comp_test₁ {α : Sort u} {a b : α} (p : a ⇝ b) : p # 1 ⇝ b := rfl

-- fail
--def symm_test {α : Type u} {a b : α} (p : a ⇝ b) : (p⁻¹)⁻¹ ⇝ p := rfl
@[trans] def composition {α : Sort u} {a b c : α}
  (p : a ⇝ b) (q : b ⇝ c) : a ⇝ c := subst q p

infix ⬝ := composition

-- this will be replaced by a more general version in future
def kan {α : Sort u} {a b c d : α}
  (bottom : b ⇝ c) (left : b ⇝ a) (right : c ⇝ d) : a ⇝ d :=
left⁻¹ ⬝ bottom ⬝ right

def kan_op {α : Sort u} {a b : α} (p : a ⇝ a) (q : a ⇝ b) : b ⇝ b :=
kan p q q

def interval_contr (i : I) : i₀ ⇝ i := coe 0 i (λ i, i₀ ⇝ i) rfl
def seg_path : i₀ ⇝ i₁ := interval_contr i₁

-- or too direct way
example : i₀ ⇝ i₁ := <i> i

def conn_and {α : Sort u} {a b : α} (p : a ⇝ b) :
  LineP (λ i, a ⇝ p # i) :=
λ i, <j> p # i ∧ j

def conn_or {α : Sort u} {a b : α} (p : a ⇝ b) :
  LineP (λ i, p # i ⇝ b) :=
λ i, <j> p # i ∨ j

def singl {α : Sort u} (a : α) :=
Σ' (x : α), a ⇝ x

def eta {α : Sort u} (a : α) : singl a := ⟨a, refl a⟩

def refl_contr {α : Sort u} {a b : α} (p : a ⇝ b) :
  LineP (λ i, a ⇝ p # i) :=
interval.hrec _ (refl a) p (begin
  cases p with f, unfold refl,
  apply heq.map, funext,
  refine interval.prop_rec _ _ i,
  { reflexivity },
  { apply ground_zero.support.truncation,
    apply eq.map, exact seg }
end)

/-
This doesn’t pass typechecking.

def J {α : Type u} {a : α} {π : Π (b : α), a ⇝ b → Type u}
  (h : π a (refl a)) (b : α) (p : a ⇝ b) : π b (<i> p # i) :=
coe (λ i, π (p # i) (conn_and p i)) h i₁

def J {α : Type u} {a : α} {π : Π (b : α), a ⇝ b → Type u}
  (h : π a (refl a)) (b : α) (p : a ⇝ b) : π b (<i> p # i) :=
transport (<i> π (p # i) (<j> p # i ∧ j)) h
-/

def J {α : Sort u} {a : α} (π : Π (b : α), a ⇝ b → Sort v)
  (h : π a (refl a)) {b : α} (p : a ⇝ b) : π b p :=
trans (<i> π (p # i) (refl_contr p i)) h

end Path

def {u} PathP (σ : I → Sort u) (a : σ 0) (b : σ 1) :=
Path (equiv.subst interval.seg a) b

def {u} PathP.lam (σ : I → Sort u) (f : Π i, σ i) : PathP σ (f 0) (f 1) :=
Path.lam (interval.rec _ _ (equiv.apd f interval.seg))

end ground_zero.cubical


/-
Copyright (c) 2022 Abby J. Goldberg. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Abby J. Goldberg, Mario Carneiro
-/
import Mathlib.Tactic.Ring

/-!
# linear_combination Tactic

In this file, the `linear_combination` tactic is created.  This tactic, which
works over `Ring`s, attempts to simplify the target by creating a linear combination
of a list of equalities and subtracting it from the target.  This file also includes a
definition for `linear_combination_config`.  A `linear_combination_config`
object can be passed into the tactic, allowing the user to specify a
normalization tactic.

## Implementation Notes

This tactic works by creating a weighted sum of the given equations with the
given coefficients.  Then, it subtracts the right side of the weighted sum
from the left side so that the right side equals 0, and it does the same with
the target.  Afterwards, it sets the goal to be the equality between the
lefthand side of the new goal and the lefthand side of the new weighted sum.
Lastly, calls a normalization tactic on this target.

## References

* <https://leanprover.zulipchat.com/#narrow/stream/239415-metaprogramming-.2F.20tactics/topic/Linear.20algebra.20tactic/near/213928196>

-/

namespace Mathlib.Tactic.LinearCombination
open Lean hiding Rat
open Elab Meta Term

theorem pf_add_c [Add α] (p : a = b) (c : α) : a + c = b + c := p ▸ rfl
theorem c_add_pf [Add α] (p : b = c) (a : α) : a + b = a + c := p ▸ rfl
theorem add_pf [Add α] (p₁ : (a₁:α) = b₁) (p₂ : a₂ = b₂) : a₁ + a₂ = b₁ + b₂ := p₁ ▸ p₂ ▸ rfl
theorem pf_sub_c [Sub α] (p : a = b) (c : α) : a - c = b - c := p ▸ rfl
theorem c_sub_pf [Sub α] (p : b = c) (a : α) : a - b = a - c := p ▸ rfl
theorem sub_pf [Sub α] (p₁ : (a₁:α) = b₁) (p₂ : a₂ = b₂) : a₁ - a₂ = b₁ - b₂ := p₁ ▸ p₂ ▸ rfl
theorem neg_pf [Neg α] (p : (a:α) = b) : -a = -b := p ▸ rfl
theorem pf_mul_c [Mul α] (p : a = b) (c : α) : a * c = b * c := p ▸ rfl
theorem c_mul_pf [Mul α] (p : b = c) (a : α) : a * b = a * c := p ▸ rfl
theorem mul_pf [Mul α] (p₁ : (a₁:α) = b₁) (p₂ : a₂ = b₂) : a₁ * a₂ = b₁ * b₂ := p₁ ▸ p₂ ▸ rfl
theorem inv_pf [Inv α] (p : (a:α) = b) : a⁻¹ = b⁻¹ := p ▸ rfl
theorem pf_div_c [Div α] (p : a = b) (c : α) : a / c = b / c := p ▸ rfl
theorem c_div_pf [Div α] (p : b = c) (a : α) : a / b = a / c := p ▸ rfl
theorem div_pf [Div α] (p₁ : (a₁:α) = b₁) (p₂ : a₂ = b₂) : a₁ / a₂ = b₁ / b₂ := p₁ ▸ p₂ ▸ rfl

/--
Performs macro expansion of a linear combination expression,
using `+`/`-`/`*`/`/` on equations and values.
* `some p` means that `p` is a syntax corresponding to a proof of an equation.
  For example, if `h : a = b` then `expandLinearCombo (2 * h)` returns `some (c_add_pf 2 h)`
  which is a proof of `2 * a = 2 * b`.
* `none` means that the input expression is not an equation but a value;
  the input syntax itself is used in this case.
-/
partial def expandLinearCombo (stx : Syntax.Term) : TermElabM (Option Syntax.Term) := do
  let mut result ← match stx with
  | `(($e)) => expandLinearCombo e
  | `($e₁ + $e₂) => do
    match ← expandLinearCombo e₁, ← expandLinearCombo e₂ with
    | none, none => pure none
    | some p₁, none => ``(pf_add_c $p₁ $e₂)
    | none, some p₂ => ``(c_add_pf $p₂ $e₁)
    | some p₁, some p₂ => ``(add_pf $p₁ $p₂)
  | `($e₁ - $e₂) => do
    match ← expandLinearCombo e₁, ← expandLinearCombo e₂ with
    | none, none => pure none
    | some p₁, none => ``(pf_sub_c $p₁ $e₂)
    | none, some p₂ => ``(c_sub_pf $p₂ $e₁)
    | some p₁, some p₂ => ``(sub_pf $p₁ $p₂)
  | `(-$e) => do
    match ← expandLinearCombo e with
    | none => pure none
    | some p => ``(neg_pf $p)
  | `(← $e) => do
    match ← expandLinearCombo e with
    | none => pure none
    | some p => ``(Eq.symm $p)
  | `($e₁ * $e₂) => do
    match ← expandLinearCombo e₁, ← expandLinearCombo e₂ with
    | none, none => pure none
    | some p₁, none => ``(pf_mul_c $p₁ $e₂)
    | none, some p₂ => ``(c_mul_pf $p₂ $e₁)
    | some p₁, some p₂ => ``(mul_pf $p₁ $p₂)
  | `($e⁻¹) => do
    match ← expandLinearCombo e with
    | none => pure none
    | some p => ``(inv_pf $p)
  | `($e₁ / $e₂) => do
    match ← expandLinearCombo e₁, ← expandLinearCombo e₂ with
    | none, none => pure none
    | some p₁, none => ``(pf_div_c $p₁ $e₂)
    | none, some p₂ => ``(c_div_pf $p₂ $e₁)
    | some p₁, some p₂ => ``(div_pf $p₁ $p₂)
  | e => do
    let e ← elabTerm e none
    let eType ← inferType e
    let .true := (← withReducible do whnf eType).isEq | pure none
    some <$> e.toSyntax
  return result.map fun r => ⟨r.raw.setInfo (SourceInfo.fromRef stx true)⟩

/-- A configuration object for `linear_combination`. -/
structure Config where
  /-- whether or not the normalization step should be used -/
  normalize := true
  /-- whether to make separate subgoals for both sides or just one for `lhs - rhs = 0` -/
  twoGoals := false
  /-- the tactic used for normalization when checking
  if the weighted sum is equivalent to the goal (when `normalize` is `true`). -/
  normTac : Syntax.Tactic := Unhygienic.run `(tactic| ring_nf)
  deriving Inhabited

/-- Function elaborating `LinearCombination.Config` -/
declare_config_elab elabConfig Config

theorem eq_trans₃ (p : (a:α) = b) (p₁ : a = a') (p₂ : b = b') : a' = b' := p₁ ▸ p₂ ▸ p

theorem eq_of_add [AddGroup α] (p : (a:α) = b) (H : (a' - b') - (a - b) = 0) : a' = b' := by
  rw [← sub_eq_zero] at p ⊢; rwa [sub_eq_zero, p] at H

/-- Implementation of `linear_combination` and `linear_combination2`. -/
def elabLinearCombination
    (norm? : Option Syntax.Tactic) (input : Option Syntax.Term)
    (twoGoals := false) : Tactic.TacticM Unit := Tactic.withMainContext do
  let p ← match input with
  | none => `(Eq.refl 0)
  | some e => withSynthesize do
    match ← expandLinearCombo e with
    | none => `(Eq.refl $e)
    | some p => pure p
  let norm := norm?.getD (Unhygienic.run `(tactic| ring1))
  Tactic.evalTactic <|← withFreshMacroScope <| if twoGoals then
    `(tactic| (
      refine eq_trans₃ $p ?a ?b
      case' a => $norm:tactic
      case' b => $norm:tactic))
  else
    `(tactic| (refine eq_of_add $p ?a; case' a => $norm:tactic))

/--
The `(norm := $tac)` syntax says to use `tac` as a normalization postprocessor for
`linear_combination`. The default normalizer is `ring1`, but you can override it with `ring_nf`
to get subgoals from `linear_combination` or with `skip` to disable normalization.
-/
syntax normStx := atomic(" (" &"norm" " := ") withoutPosition(tactic) ")"

/--
`linear_combination` attempts to simplify the target by creating a linear combination
  of a list of equalities and subtracting it from the target.
  The tactic will create a linear
  combination by adding the equalities together from left to right, so the order
  of the input hypotheses does matter.  If the `normalize` field of the
  configuration is set to false, then the tactic will simply set the user up to
  prove their target using the linear combination instead of normalizing the subtraction.

Note: The left and right sides of all the equalities should have the same
  type, and the coefficients should also have this type.  There must be
  instances of `Mul` and `AddGroup` for this type.

* The input `e` in `linear_combination e` is a linear combination of proofs of equalities,
  given as a sum/difference of coefficients multiplied by expressions.
  The coefficients may be arbitrary expressions.
  The expressions can be arbitrary proof terms proving equalities.
  Most commonly they are hypothesis names `h1, h2, ...`.
* `linear_combination (norm := tac) e` runs the "normalization tactic" `tac`
  on the subgoal(s) after constructing the linear combination.
  * The default normalization tactic is `ring1`, which closes the goal or fails.
  * To get a subgoal in the case that it is not immediately provable, use
    `ring_nf` as the normalization tactic.
  * To avoid normalization entirely, use `skip` as the normalization tactic.
* `linear_combination2 e` is the same as `linear_combination e` but it produces two
  subgoals instead of one: rather than proving that `(a - b) - (a' - b') = 0` where
  `a' = b'` is the linear combination from `e` and `a = b` is the goal,
  it instead attempts to prove `a = a'` and `b = b'`.
  Because it does not use subtraction, this form is applicable also to semirings.
  * Note that a goal which is provable by `linear_combination e` may not be provable
    by `linear_combination2 e`; in general you may need to add a coefficient to `e`
    to make both sides match, as in `linear_combination2 e + c`.
  * You can also reverse equalities using `← h`, so for example if `h₁ : a = b`
    then `2 * (← h)` is a proof of `2 * b = 2 * a`.

Example Usage:
```
example (x y : ℤ) (h1 : x*y + 2*x = 1) (h2 : x = y) : x*y = -2*y + 1 := by
  linear_combination 1*h1 - 2*h2

example (x y : ℤ) (h1 : x*y + 2*x = 1) (h2 : x = y) : x*y = -2*y + 1 := by
  linear_combination h1 - 2*h2

example (x y : ℤ) (h1 : x*y + 2*x = 1) (h2 : x = y) : x*y = -2*y + 1 := by
  linear_combination (norm := ring_nf) -2*h2
  /- Goal: x * y + x * 2 - 1 = 0 -/

example (x y z : ℝ) (ha : x + 2*y - z = 4) (hb : 2*x + y + z = -2)
    (hc : x + 2*y + z = 2) :
    -3*x - 3*y - 4*z = 2 := by
  linear_combination ha - hb - 2*hc

example (x y : ℚ) (h1 : x + y = 3) (h2 : 3*x = 7) :
    x*x*y + y*x*y + 6*x = 3*x*y + 14 := by
  linear_combination x*y*h1 + 2*h2

example (x y : ℤ) (h1 : x = -3) (h2 : y = 10) : 2*x = -6 := by
  linear_combination (norm := skip) 2*h1
  simp

axiom qc : ℚ
axiom hqc : qc = 2*qc

example (a b : ℚ) (h : ∀ p q : ℚ, p = q) : 3*a + qc = 3*b + 2*qc := by
  linear_combination 3 * h a b + hqc
```
-/
syntax (name := linearCombination) "linear_combination" (normStx)? (ppSpace colGt term)? : tactic
elab_rules : tactic
  | `(tactic| linear_combination $[(norm := $tac)]? $(e)?) => elabLinearCombination tac e

@[inherit_doc linearCombination]
syntax "linear_combination2" (normStx)? (ppSpace colGt term)? : tactic
elab_rules : tactic
  | `(tactic| linear_combination2 $[(norm := $tac)]? $(e)?) => elabLinearCombination tac e true


/-
Copyright (c) 2018 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Reid Barton, Bhavik Mehta
-/
import category_theory.limits.creates
import category_theory.over
import category_theory.is_connected

/-!
# Connected limits in the over category

Shows that the forgetful functor `over B ⥤ C` creates connected limits, in particular `over B` has
any connected limit which `C` has.
-/

universes v u -- morphism levels before object levels. See note [category_theory universes].

noncomputable theory

open category_theory category_theory.limits

variables {J : Type v} [small_category J]
variables {C : Type u} [category.{v} C]
variable {X : C}

namespace category_theory.over

namespace creates_connected

/--
(Impl) Given a diagram in the over category, produce a natural transformation from the
diagram legs to the specific object.
-/
def nat_trans_in_over {B : C} (F : J ⥤ over B) :
  F ⋙ forget B ⟶ (category_theory.functor.const J).obj B :=
{ app := λ j, (F.obj j).hom }

local attribute [tidy] tactic.case_bash

/--
(Impl) Given a cone in the base category, raise it to a cone in the over category. Note this is
where the connected assumption is used.
-/
@[simps]
def raise_cone [is_connected J] {B : C} {F : J ⥤ over B} (c : cone (F ⋙ forget B)) :
  cone F :=
{ X := over.mk (c.π.app (classical.arbitrary J) ≫ (F.obj (classical.arbitrary J)).hom),
  π :=
  { app := λ j,
      over.hom_mk (c.π.app j) (nat_trans_from_is_connected (c.π ≫ nat_trans_in_over F) j _) } }

lemma raised_cone_lowers_to_original [is_connected J] {B : C} {F : J ⥤ over B}
  (c : cone (F ⋙ forget B)) (t : is_limit c) :
  (forget B).map_cone (raise_cone c) = c :=
by tidy

/-- (Impl) Show that the raised cone is a limit. -/
def raised_cone_is_limit [is_connected J] {B : C} {F : J ⥤ over B}
  {c : cone (F ⋙ forget B)} (t : is_limit c) :
  is_limit (raise_cone c) :=
{ lift := λ s, over.hom_mk (t.lift ((forget B).map_cone s)) (by { dsimp, simp }),
  uniq' := λ s m K, by { ext1, apply t.hom_ext, intro j, simp [← K j] } }

end creates_connected

/-- The forgetful functor from the over category creates any connected limit. -/
instance forget_creates_connected_limits
  [is_connected J] {B : C} : creates_limits_of_shape J (forget B) :=
{ creates_limit := λ K,
    creates_limit_of_reflects_iso (λ c t,
      { lifted_cone := creates_connected.raise_cone c,
        valid_lift := eq_to_iso (creates_connected.raised_cone_lowers_to_original c t),
        makes_limit := creates_connected.raised_cone_is_limit t } ) }

/-- The over category has any connected limit which the original category has. -/
instance has_connected_limits
  {B : C} [is_connected J] [has_limits_of_shape J C] : has_limits_of_shape J (over B) :=
{ has_limit := λ F, has_limit_of_created F (forget B) }

end category_theory.over


import GroundZero.Theorems.Pullback

open GroundZero GroundZero.Types
open GroundZero.Types.Equiv
open GroundZero.Proto

open GroundZero.Structures (prop contr)

universe u v u' v' w w' k k'

-- exercise 2.1

section
  variable {A : Type u} {a b c : A}

  hott def trans₁ (p : a = b) (q : b = c) : a = c :=
  @Id.casesOn A a (λ x _, x = c → a = c) b p (@Id.casesOn A a (λ x _, a = x) c · (idp a)) q

  infixl:99 " ⬝₁ " => trans₁

  hott def trans₂ (p : a = b) (q : b = c) : a = c :=
  @Id.casesOn A a (λ x _, x = c → a = c) b p idfun q

  infixl:99 " ⬝₂ " => trans₂

  hott def trans₃ (p : a = b) (q : b = c) : a = c :=
  @Id.casesOn A b (λ x _, a = b → a = x) c q idfun p

  infixl:99 " ⬝₃ " => trans₃

  hott def eq₁₂ (p : a = b) (q : b = c) : p ⬝₁ q = p ⬝₂ q :=
  begin induction p; induction q; reflexivity end

  hott def eq₂₃ (p : a = b) (q : b = c) : p ⬝₂ q = p ⬝₃ q :=
  begin induction p; induction q; reflexivity end

  hott def eq₁₃ (p : a = b) (q : b = c) : p ⬝₁ q = p ⬝₃ q :=
  begin induction p; induction q; reflexivity end
end

-- exercise 2.2

section
  variable {A : Type u} {a b c : A} (p : a = b) (q : b = c)

  example : eq₁₂ p q ⬝ eq₂₃ p q = eq₁₃ p q :=
  begin induction p; induction q; reflexivity end
end

-- exercise 2.3

section
  variable {A : Type u} {a b c : A}

  hott def trans₄ (p : a = b) (q : b = c) : a = c :=
  @Id.casesOn A b (λ x _, a = b → a = x) c q (@Id.casesOn A a (λ x _, a = x) b · (idp a)) p

  infixl:99 " ⬝₄ " => trans₄

  /-
  example (p : a = b) (q : b = c) : p ⬝₁ q = p ⬝₄ q := idp _
  example (p : a = b) (q : b = c) : p ⬝₂ q = p ⬝₄ q := idp _
  example (p : a = b) (q : b = c) : p ⬝₃ q = p ⬝₄ q := idp _
  -/

  example (p : a = b) (q : b = c) : p ⬝₁ q = p ⬝₄ q :=
  begin induction p; induction q; reflexivity end
end

-- exercise 2.4

hott def nPath (A : Type u) : ℕ → Type u
| Nat.zero   => A
| Nat.succ n => Σ (a b : nPath A n), a = b

hott def boundary {A : Type u} {n : ℕ} :
  nPath A (n + 1) → (nPath A n) × (nPath A n) :=
λ ⟨a, b, _⟩, (a, b)

-- exercise 2.5

namespace «2.5»
  variable {A : Type u} {B : Type v} {x y : A} (p : x = y)

  hott def transconst (b : B) : transport (λ _, B) p b = b :=
  begin induction p; reflexivity end

  hott def f (φ : A → B) : φ x = φ y → transport (λ _, B) p (φ x) = φ y :=
  λ q, transconst p (φ x) ⬝ q

  hott def g (φ : A → B) : transport (λ _, B) p (φ x) = φ y → φ x = φ y :=
  λ q, (transconst p (φ x))⁻¹ ⬝ q

  example (φ : A → B) : f p φ ∘ g p φ ~ id :=
  begin induction p; reflexivity end

  example (φ : A → B) : g p φ ∘ f p φ ~ id :=
  begin induction p; reflexivity end
end «2.5»

-- exercise 2.6

example {A : Type u} {x y z : A} (p : x = y) : biinv (@Id.trans A x y z p) :=
begin apply Prod.mk <;> existsi Id.trans p⁻¹ <;> intro q <;> induction p <;> induction q <;> reflexivity end

-- exercise 2.7

namespace «2.7»
  variable {A : Type u} {A' : Type u'} {B : A → Type v} {B' : A' → Type v'}
           (g : A → A') (h : Π a, B a → B' (g a))

  def φ (x : Σ a, B a) : Σ a', B' a' := ⟨g x.1, h x.1 x.2⟩

  hott def prodMap : Π (x y : Σ a, B a) (p : x.1 = y.1) (q : x.2 =[p] y.2),
      Id.map (φ g h) (Sigma.prod p q)
    = @Sigma.prod A' B' (φ g h x) (φ g h y)
        (@Id.map A A' x.1 y.1 g p) (depPathMap' g h q) :=
  begin
    intro ⟨x, H⟩ ⟨y, G⟩ (p : x = y); induction p;
    intro (q : H = G); induction q; reflexivity
  end
end «2.7»

-- exercise 2.8

namespace «2.8»
  variable {A A' B B' : Type u} (g : A → A') (h : B → B')

  def φ : A + B → A' + B' :=
  Coproduct.elim (Coproduct.inl ∘ g) (Coproduct.inr ∘ h)

  hott def ρ : Π {x y : A + B}, Coproduct.code x y → Coproduct.code (φ g h x) (φ g h y)
  | Sum.inl _, Sum.inl _, p => Id.map _ p
  | Sum.inr _, Sum.inl _, p => Empty.elim p
  | Sum.inl _, Sum.inr _, p => Empty.elim p
  | Sum.inr _, Sum.inr _, p => Id.map _ p

  hott def mapPathSum (x y : A + B) : Π p,
      Id.map (φ g h) (Coproduct.pathSum x y p)
    = Coproduct.pathSum (φ g h x) (φ g h y) (ρ g h p) :=
  begin
    match x, y with
    | Sum.inl x, Sum.inl y => _
    | Sum.inr _, Sum.inl _ => _
    | Sum.inl _, Sum.inr _ => _
    | Sum.inr x, Sum.inr y => _;

    { intro (p : x = y); induction p; reflexivity };
    { intro; apply Empty.elim; assumption };
    { intro; apply Empty.elim; assumption };
    { intro (p : x = y); induction p; reflexivity }
  end
end «2.8»

-- exercise 2.9

hott def Coproduct.depUnivProperty (A : Type u) (B : Type v) (X : A + B → Type w) :
  (Π x, X x) ≃ (Π a, X (Coproduct.inl a)) × (Π b, X (Coproduct.inr b)) :=
begin
  fapply Sigma.mk; { intro φ; exact (λ a, φ (Coproduct.inl a), λ b, φ (Coproduct.inr b)) };
  apply Qinv.toBiinv; fapply Sigma.mk;
  { intros φ x; induction x using Sum.casesOn; apply φ.1; apply φ.2 };
  apply Prod.mk; { intro (φ, ψ); reflexivity };
  { intro f; apply Theorems.funext; intro z; induction z using Sum.casesOn <;> reflexivity }
end

hott def Coproduct.univProperty (A : Type u) (B : Type v) (X : Type w) :
  (A + B → X) ≃ (A → X) × (B → X) :=
Coproduct.depUnivProperty A B (λ _, X)

-- exercise 2.10

hott def sigma.assoc (A : Type u) (B : A → Type v) (C : (Σ x, B x) → Type w) :
  (Σ x, Σ y, C ⟨x, y⟩) ≃ (Σ p, C p) :=
begin
  fapply Sigma.mk; { intro w; existsi ⟨w.1, w.2.1⟩; exact w.2.2 };
  apply Qinv.toBiinv; fapply Sigma.mk;
  { intro w; existsi w.1.1; existsi w.1.2; apply transport C;
    symmetry; exact Sigma.uniq w.1; exact w.2 }; apply Prod.mk;
  { intro ⟨⟨a, b⟩, c⟩; reflexivity };
  { intro ⟨a, ⟨b, c⟩⟩; reflexivity }
end

-- exercise 2.11

namespace «2.11»
  variable {P : Type k} {A : Type u} {B : Type v} {C : Type w}
           (η : pullbackSquare P A B C)

  example : P ≃ pullback C η.1.right η.1.bot :=
  Theorems.pullbackCorner η
end «2.11»

-- exercise 2.12

namespace «2.12»
  variable {A B C D E F : Type u}
           {f : A → C} {g : C → E} {i : A → B} {j : C → D}
           {k : E → F} {h : B → D} {s : D → F}
           (α : j ∘ f = h ∘ i) (β : k ∘ g = s ∘ j)

  def left  : hcommSquare A C B D := ⟨j, h, f, i, α⟩
  def right : hcommSquare C E D F := ⟨k, s, g, j, β⟩

  def outer : hcommSquare A E B F :=
  ⟨k, s ∘ h, g ∘ f, i, @Id.map (C → F) (A → F) _ _ (· ∘ f) β
                     ⬝ @Id.map _ (A → F) _ _ (s ∘ ·) α⟩

  hott def pullbackLemma (H : (right β).isPullback) :
    (left α).isPullback ↔ (outer α β).isPullback :=
  sorry
end «2.12»

-- exercise 2.13

example : (𝟐 ≃ 𝟐) ≃ 𝟐 := Theorems.Equiv.boolEquivEqvBool

-- exercise 2.14

-- Assume Γ, p : x = y ⊢ x ≡ y, let Γ = A : U, a : A. Then Γ, b : A, p : a = b ⊢ p = idp a : U,
-- because in this context we have p : a = b, so a ≡ b, so p : a = a.
-- “@Id.rec A a (λ b, p = idp a) (λ x, idp a) a” is then well-typed.
-- This means that we have a proof of “Π (p : a = a), p = idp a” leading to contradiction.

-- exercise 2.15

hott def transportMap {A : Type u} {B : A → Type v} {x y : A} (p : x = y) :
  transport B p = idtoeqv (Id.map B p) :=
begin induction p; reflexivity end

-- exercise 2.18

hott def transportSquare {A : Type u} {B : A → Type v} {f g : Π x, B x} (H : f ~ g) {x y : A} (p : x = y) :
  Id.map (transport B p) (H x) ⬝ apd g p = apd f p ⬝ H y :=
begin induction p; transitivity; apply Id.reflRight; apply Equiv.idmap end