/-
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 algebra.module.big_operators
import linear_algebra.dfinsupp
import linear_algebra.invariant_basis_number
import linear_algebra.isomorphisms
import linear_algebra.std_basis
import set_theory.cardinal.cofinality

/-!
# 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.
-/
@[irreducible] protected def module.rank : cardinal :=
⨆ ι : {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],
  rw [cardinal.lift_supr (cardinal.bdd_above_range.{v' v'} _),
    cardinal.lift_supr (cardinal.bdd_above_range.{v v} _)],
  apply csupr_mono' (cardinal.bdd_above_range.{v' v} _),
  rintro ⟨s, li⟩,
  refine ⟨⟨f '' s, _⟩, cardinal.lift_mk_le'.mpr ⟨(equiv.set.image f s i).to_embedding⟩⟩,
  exact (li.map' _ $ linear_map.ker_eq_bot.mpr i).image,
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
  rw module.rank,
  apply csupr_le',
  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],
  rw [cardinal.lift_supr (cardinal.bdd_above_range.{v' v'} _)],
  apply csupr_le',
  rintro ⟨s, li⟩,
  apply le_trans,
  swap 2,
  apply cardinal.lift_le.mpr,
  refine (le_csupr (cardinal.bdd_above_range.{v v} _) ⟨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.submodule_map 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, module.rank],
    apply le_trans,
    swap,
    exact le_csupr (cardinal.bdd_above_range.{v v} _) ⟨range v, hv.coe_range⟩,
    exact le_rfl, },
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,
  rw module.rank,
  apply csupr_le',
  rintro ⟨s, li⟩,
  apply le_bot_iff.mpr,
  apply cardinal.mk_emptyc_iff.mpr,
  simp only [subtype.coe_mk],
  by_contradiction h,
  obtain ⟨a, ha⟩ := nonempty_iff_ne_empty.2 h,
  simpa using linear_independent.ne_zero (⟨a, ha⟩ : 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}

/-- A linearly-independent family of vectors in a module over a non-trivial ring must be finite if
the module is Noetherian. -/
lemma linear_independent.finite_of_is_noetherian [is_noetherian R M]
  {v : ι → M} (hv : linear_independent R v) : finite ι :=
begin
  have hwf := is_noetherian_iff_well_founded.mp (by apply_instance : is_noetherian R M),
  refine complete_lattice.well_founded.finite_of_independent hwf
    hv.independent_span_singleton (λ i contra, _),
  apply hv.ne_zero i,
  have : v i ∈ R ∙ v i := submodule.mem_span_singleton_self (v i),
  rwa [contra, submodule.mem_bot] at this,
end

lemma linear_independent.set_finite_of_is_noetherian [is_noetherian R M]
  {s : set M} (hi : linear_independent R (coe : s → M)) : s.finite :=
@set.to_finite _ _ hi.finite_of_is_noetherian

/--
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 := neg_eq_iff_eq_neg.mpr 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 this.not_lt (h.symm ▸ zero_lt_one) },
    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,
  casesI fintype_or_infinite ι,
  { -- `v` is a finite basis, so by `basis_fintype_of_finite_spans` so is `v'`.
    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_finite R R ι).symm.trans v.repr.symm) ≪≫ₗ
      v'.repr) ≪≫ₗ (finsupp.linear_equiv_fun_on_finite 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.
    have w₁ :=
      infinite_basis_le_maximal_linear_independent' v _ v'.linear_independent v'.maximal,
    rcases cardinal.lift_mk_le'.mp w₁ with ⟨f⟩,
    haveI : infinite ι' := infinite.of_injective f f.2,
    have w₂ :=
      infinite_basis_le_maximal_linear_independent' v' _ v.linear_independent v.maximal,
    exact le_antisymm w₁ w₂, }
end

/-- Given two bases 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_umax_eq.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, (cardinal.lt_aleph_0_of_finite _).le },
    { 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

/--
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_of_infinite ι] 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,
  rw module.rank,
  apply le_antisymm,
  { transitivity,
    swap,
    apply le_csupr (cardinal.bdd_above_range.{v v} _),
    exact ⟨set.range v, by { convert v.reindex_range.linear_independent, ext, simp }⟩,
    exact (cardinal.mk_range_eq v v.injective).ge, },
  { apply csupr_le',
    rintro ⟨s, li⟩,
    apply linear_independent_le_basis v _ li, },
end

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_aleph_0 {ι : Type*}
  (b : basis ι R M) (h : module.rank R M < ℵ₀) :
  nonempty (fintype ι) :=
by rwa [← cardinal.lift_lt, ← b.mk_eq_dim,
        -- ensure `aleph_0` has the correct universe
        cardinal.lift_aleph_0, ← cardinal.lift_aleph_0.{u_1 v},
        cardinal.lift_lt, cardinal.lt_aleph_0_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_aleph_0 {ι : Type*}
  (b : basis ι R M) (h : module.rank R M < ℵ₀) :
  fintype ι :=
classical.choice (b.nonempty_fintype_index_of_dim_lt_aleph_0 h)

/-- If a module has a finite dimension, all bases are indexed by a finite set. -/
lemma basis.finite_index_of_dim_lt_aleph_0 {ι : 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_aleph_0 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_aleph_0 (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_aleph_0 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_coe_finset]
                             ... < ℵ₀ : cardinal.nat_lt_aleph_0 _

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
variables [∀i, add_comm_group (φ i)] [∀i, module K (φ i)]

open linear_map

lemma dim_pi [finite η] : module.rank K (Πi, φ i) = cardinal.sum (λi, module.rank K (φ i)) :=
begin
  casesI nonempty_fintype η,
  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

variable [fintype η]

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

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),
by rwa [←range_eq_top, range_coprod, eq_top_iff],
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, pi.prod,
        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,
      submodule.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, pi.prod] 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), submodule.map_sup, submodule.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_rfl
  end
  (ker_of_le _ _ _)
  begin ext ⟨x, hx⟩, refl end
  begin
    rintros ⟨b₁, hb₁⟩ ⟨b₂, hb₂⟩ eq,
    obtain rfl : b₁ = b₂ := congr_arg subtype.val eq,
    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

end division_ring

section rank

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

/-- `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_range (f : V →ₗ[K] V₁) : rank f ≤ module.rank K V₁ :=
dim_submodule_le _

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

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

end rank

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

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_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 _ _

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 _))

/-- 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_set_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 (is_unit.mk0 _ h0) _ },
    { push_neg at hw,
      rw ←submodule.eq_bot_iff at hw,
      simp [hw] } }
end

lemma submodule.rank_le_one_iff_is_principal (W : submodule K V) :
  module.rank K W ≤ 1 ↔ W.is_principal :=
begin
  simp only [dim_le_one_iff, submodule.is_principal_iff, le_antisymm_iff,
    le_span_singleton_iff, span_singleton_le_iff_mem],
  split,
  { rintro ⟨⟨m, hm⟩, hm'⟩,
    choose f hf using hm',
    exact ⟨m, ⟨λ v hv, ⟨f ⟨v, hv⟩, congr_arg coe (hf ⟨v, hv⟩)⟩, hm⟩⟩ },
  { rintro ⟨a, ⟨h, ha⟩⟩,
    choose f hf using h,
    exact ⟨⟨a, ha⟩, λ v, ⟨f v.1 v.2, subtype.ext (hf v.1 v.2)⟩⟩ }
end

lemma module.rank_le_one_iff_top_is_principal :
  module.rank K V ≤ 1 ↔ (⊤ : submodule K V).is_principal :=
by rw [← submodule.rank_le_one_iff_is_principal, dim_top]

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_set_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

end division_ring

end module


/-
Copyright (c) 2022 Arthur Paulino, Damiano Testa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Arthur Paulino, Damiano Testa

! This file was ported from Lean 3 source module tactic.move_add
! leanprover-community/mathlib commit 205a628e1fdc9220cb86832d66a50d1381abc103
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.Tactic.Core
import Mathbin.Algebra.Group.Basic

/-!
# `move_add`: a tactic for moving summands

Calling `move_add [a, ← b, c]`, recursively looks inside the goal for expressions involving a sum.
Whenever it finds one, it moves the summands that unify to `a, b, c`, removing all parentheses.

See the doc-string for `tactic.interactive.move_add` for more information.

##  Implementation notes

This file defines a general `move_op` tactic, intended for reordering terms in an expression
obtained by repeated applications of a given associative, commutative binary operation.  The
user decides the final reordering.  Applying `move_op` without specifying the order will simply
remove all parentheses from the expression.
The main user-facing tactics are `move_add` and `move_mul`, dealing with addition and
multiplication, respectively.

In what is below, we talk about `move_add` for definiteness, but everything applies
to `move_mul` and to the more general `move_op`.

The implementation of `move_add` only moves the terms specified by the user (and rearranges
parentheses).

Note that the tactic `abel` already implements a very solid heuristic for normalizing terms in an
additive commutative semigroup and produces expressions in more or less standard form.
The scope of `move_add` is different: it is designed to make it easy to move individual terms
around a sum.

##  Future work

* Add support for `neg/div/inv` in additive/multiplicative groups?
* Currently the tactic has special support for `+` and `*`.  Every other operation is outsourced
  to `ac_refl` (see the proof of `reorder_hyp`).  Should there be the desire for specialized support
  of other operations (e.g. `∪, ∩, ⊓, ⊔, ...`), that is the definition to modify, at least in the
  first instance.
* Add functionality for moving terms across the two sides of an in/dis/equality.
  E.g. it might be desirable to have `to_lhs [a]` converting `b + c = a + d` to `- a + b + c = d`.
* Add a non-recursive version for use in `conv` mode.
* Revise tests?
-/

namespace Tactic

namespace MoveOp

/-!
Throughout this file, `op : pexpr` denotes an arbitrary (binary) operation.  We do not use,
but implicitly imagine, that this operation is associative, since we extract iterations of
such operations, with complete disregard of the order in which these iterations arise.
-/

/-- Given a list `un` of `α`s and a list `bo` of `bool`s, return the sublist of `un`
consisting of the entries of `un` whose corresponding entry in `bo` is `tt`.

Used for error management: `un` is the list of user inputs, `bo` is the list encoding which input
is unused (`tt`) and which input is used (`ff`).
`return_unused` returns the unused user inputs.

If `bo` is shorter than `un`, `return_unused` will include the remainder of `un`.
-/
def returnUnused {α : Type _} : List α → List Bool → List α
  | un, [] => un
  | [], bo => []
  | u :: us, b :: bs => if b then u :: return_unused us bs else return_unused us bs
#align tactic.move_op.return_unused Tactic.MoveOp.returnUnused

/-- Given a list `lp` of `bool × pexpr` and a list `l_un` of `expr`, scan the elements of `lp` one
at a time and produce 3 sublists of `l_un`.

If `(tf,pe)` is the first element of `lp`, we look for the first element of `l_un` that unifies with
`pe.to_expr`.  If no such element exists, then we discard `(tf,pe)` and move along.
If `eu ∈ l_un` is the first element of `l_un` that unifies with `pe.to_expr`, then we add `eu` as
the next element of either the first or the second list, depending on the boolean `tf` and we remove
`eu` from the list `l_un`.  In this case, we continue our scanning with the next element of `lp`,
replacing `l_un` by `l_un.erase eu`.

Once we exhaust the elements of `lp`, we return the four lists:
* `l_tt`: the list of elements of `l_un` that came from an element of `lp` whose boolean was `tt`,
* `l_ff`: the list of elements of `l_un` that came from an element of `lp` whose boolean was `ff`,
* `l_un`: the un-unified elements of `l_un`,
* `l_m`: a "mask" list of booleans corresponding to the elements of `lp` that were placed in `l_un`.

The ununified elements of `l_un` get used for error management: they keep track of which user inputs
are superfluous. -/
unsafe def move_left_or_right :
    List (Bool × expr) →
      List expr → List Bool → tactic (List expr × List expr × List expr × List Bool)
  | [], l_un, l_m => return ([], [], l_un, l_m)
  | be :: l, l_un, l_m => do
    let ex :: _ ← l_un.filterM fun e' => succeeds <| unify be.2 e' |
      move_left_or_right l l_un (l_m.append [true])
    let (l_tt, l_ff, l_un, l_m) ← move_left_or_right l (l_un.eraseₓ ex) (l_m.append [false])
    if be.1 then return (ex :: l_tt, l_ff, l_un, l_m) else return (l_tt, ex :: l_ff, l_un, l_m)
#align tactic.move_op.move_left_or_right tactic.move_op.move_left_or_right

/-- We adapt `move_left_or_right` to our goal:
1. we convert a list of pairs `bool × pexpr` to a list of pairs `bool × expr`,
2. we use the extra input `sl : list expr` to perform the unification and sorting step
   `move_left_or_right`,
3. we jam the third factor inside the first two.
-/
unsafe def final_sort (lp : List (Bool × pexpr)) (sl : List expr) :
    tactic (List expr × List Bool) := do
  let lp_exp : List (Bool × expr) ←
    lp.mapM fun x => do
        let e ← to_expr x.2 true false
        return (x.1, e)
  let (l1, l2, l3, is_unused) ← move_left_or_right lp_exp sl []
  return (l1 ++ l3 ++ l2, is_unused)
#align tactic.move_op.final_sort tactic.move_op.final_sort

/-- `as_given_op op e` unifies the head term of `e`, which is a ≥2-argument function application,
with the binary operation `op`, failing if it cannot. -/
unsafe def as_given_op (op : pexpr) : expr → tactic expr
  | expr.app (expr.app F a) b => do
    to_expr op tt ff >>= unify F
    return F
  | _ => failed
#align tactic.move_op.as_given_op tactic.move_op.as_given_op

/-- `(e, unused) ← reorder_oper op lp e` converts an expression `e` to a similar looking one.
The tactic scans the expression `e` looking for subexpressions that begin with the given binary
operation `op`.  As soon as `reorder_oper` finds one such subexpression,
* it extracts the "`op`-summands" in the subexpression,
* it rearranges them according to the rules determined by `lp`,
* it recurses into each `op`-summand.

The `unused` output is a list of booleans.  It is keeping track of which of the inputs provided
by `lp` is actually used to perform the rearrangements.  It is useful to report unused inputs.

Here are two examples:
```lean
#eval trace $ reorder_oper ``((=)) [(ff,``(2)), (tt,``(7))] `(∀ x y : ℕ, 2 = 0)
--  (ℕ → ℕ → 0 = 2, [ff, tt])
-- the input `[(ff,``(2)), (tt,``(7))]` instructs Lean to move `2` to the right and `7`
-- to the left.  Lean reports that `2` is not unused and `7` is unused as `[ff, tt]`.

#eval trace $ reorder_oper ``((+)) [(ff,``(2)), (tt,``(5))]
  `(λ (e : ℕ), ∀ (x : ℕ), ∃ (y : ℕ),
      2 + x * (y + (e + 5)) + y = x + 2 + e → 2 + x = x + 5 + (2 + y))
/-  `2` moves to the right, `5` moves to the left.  Lean reports that `2, 5` are not unused
    as `[ff,ff]`
   (λ (e : ℕ), ∀ (x : ℕ), ∃ (y : ℕ),
      x * (5 + y + e) + y + 2   = x + e + 2 → x + 2 = 5 + x + y + 2, [ff, ff]) -/
```

TODO: use `ext_simplify_core` instead of traversing the expression manually
-/
unsafe def reorder_oper (op : pexpr) (lp : List (Bool × pexpr)) : expr → tactic (expr × List Bool)
  | F'@(expr.app F b) => do
    let is_op ← try_core (as_given_op op F')
    match is_op with
      | some op => do
        let (sort_list, is_unused) ← list_binary_operands op F' >>= final_sort lp
        let sort_all ←
          sort_list fun e => do
              let (e, lu) ← reorder_oper e
              pure (e, [lu, is_unused].transpose.map List.and)
        let (recs, list_unused) := sort_all
        let recs_0 :: recs_rest ← pure recs |
          throwError"internal error: cannot have 0 operands"
        let summed := recs_rest (fun e f => op [e, f]) recs_0
        return (summed, list_unused List.and)
      | none => do
        let [(Fn, unused_F), (bn, unused_b)] ← [F, b].mapM <| reorder_oper
        return <| (expr.app Fn bn, [unused_F, unused_b].transpose.map List.and)
  | expr.pi na bi e f => do
    let [en, fn] ← [e, f].mapM <| reorder_oper
    return (expr.pi na bi en.1 fn.1, [en.2, fn.2].transpose.map List.and)
  | expr.lam na bi e f => do
    let [en, fn] ← [e, f].mapM <| reorder_oper
    return (expr.lam na bi en.1 fn.1, [en.2, fn.2].transpose.map List.and)
  | expr.mvar na pp e => do
    let en
      ←-- is it really needed to recurse here?
          reorder_oper
          e
    return (expr.mvar na pp en.1, [en.2].transpose.map List.and)
  | expr.local_const na pp bi e => do
    let en
      ←-- is it really needed to recurse here?
          reorder_oper
          e
    return (expr.local_const na pp bi en.1, [en.2].transpose.map List.and)
  | expr.elet na e f g => do
    let [en, fn, gn] ← [e, f, g].mapM <| reorder_oper
    return (expr.elet na en.1 fn.1 gn.1, [en.2, fn.2, gn.2].transpose.map List.and)
  | expr.macro ma le => do
    let len
      ←-- is it really needed to recurse here?
            le.mapM <|
          reorder_oper
    let (lee, lb) := len.unzip
    return (expr.macro ma lee, lb List.and)
  | e => pure (e, lp.map fun _ => true)
#align tactic.move_op.reorder_oper tactic.move_op.reorder_oper

/- ./././Mathport/Syntax/Translate/Expr.lean:330:4: warning: unsupported (TODO): `[tacs] -/
/- ./././Mathport/Syntax/Translate/Expr.lean:330:4: warning: unsupported (TODO): `[tacs] -/
/-- Passes the user input `na` to `reorder_oper` at a single location, that could either be
`none` (referring to the goal) or `some name` (referring to hypothesis `name`).  Replaces the
given hypothesis/goal with the rearranged one that `reorder_hyp` receives from `reorder_oper`.
Returns a pair consisting of a boolean and a further list of booleans.
The single boolean is `tt` iff the tactic did *not* change the goal on which it was acting.
The list of booleans records which variable in `ll` has been unified in the application:
`tt` means that the corresponding variable has *not* been unified.

This definition is useful to streamline error catching. -/
unsafe def reorder_hyp (op : pexpr) (lp : List (Bool × pexpr)) (na : Option Name) :
    tactic (Bool × List Bool) := do
  let (thyp, hyploc) ←
    match na with
      | none => do
        let t ← target
        return (t, none)
      | some na => do
        let hl ← get_local na
        let th ← infer_type hl
        return (th, some hl)
  let (reordered, is_unused) ← reorder_oper op lp thyp
  unify reordered thyp >> return (tt, is_unused) <|> do
      let neq
        ←-- the current `do` block takes place where the reordered expression is not equal to the original
            mk_app
            `eq [thyp, reordered]
      let nop ← to_expr op tt ff
      let pre ← pp reordered
      let (_, prf) ←
        solve_aux neq <|
            match nop with
            | q(Add.add) => sorry
            | q(Mul.mul) => sorry
            | _ =>
              ac_refl <|>
                fail
                  f! "the associative/commutative lemmas used do not suffice to prove that the initial goal equals:

                    {pre}
                    Hint: try adding `is_associative` or `is_commutative` instances.
                    "
      match hyploc with
        | none => replace_target reordered prf
        | some hyploc => replace_hyp hyploc reordered prf >> skip
      return (ff, is_unused)
#align tactic.move_op.reorder_hyp tactic.move_op.reorder_hyp

section ParsingArgumentsForMoveOp

/- ./././Mathport/Syntax/Translate/Tactic/Mathlib/Core.lean:38:34: unsupported: setup_tactic_parser -/
/-- `move_op_arg` is a single elementary argument that `move_op` takes for the
variables to be moved.  It is either a `pexpr`, or a `pexpr` preceded by a `←`. -/
unsafe def move_op_arg (prec : Nat) : parser (Bool × pexpr) :=
  Prod.mk <$> Option.isSome <$> (tk "<-")? <*> parser.pexpr prec
#align tactic.move_op.move_op_arg tactic.move_op.move_op_arg

/-- `move_pexpr_list_or_texpr` is either a list of `move_op_arg`, possibly empty, or a single
`move_op_arg`. -/
unsafe def move_pexpr_list_or_texpr : parser (List (Bool × pexpr)) :=
  list_of (move_op_arg 0) <|> List.ret <$> move_op_arg tac_rbp <|> return []
#align tactic.move_op.move_pexpr_list_or_texpr tactic.move_op.move_pexpr_list_or_texpr

end ParsingArgumentsForMoveOp

end MoveOp

/- ./././Mathport/Syntax/Translate/Tactic/Mathlib/Core.lean:38:34: unsupported: setup_tactic_parser -/
open MoveOp

/-- `move_op args locat op` is the non-interactive version of the main tactics `move_add` and
`move_mul` of this file.  Given as input `args` (a list of terms of a sequence of operands),
`locat` (hypotheses or goal where the tactic should act) and `op` (the operation to use),
`move_op` attempts to perform the rearrangement of the terms determined by `args`.

Currently, the tactic uses only `add/mul_comm, add/mul_assoc, add/mul_left_comm`, so other
operations will not actually work.
-/
unsafe def move_op (args : parse move_pexpr_list_or_texpr) (locat : parse location) (op : pexpr) :
    tactic Unit := do
  let locas ← locat.get_locals
  let tg ← target
  let locas_with_tg := if locat.include_goal then locas ++ [tg] else locas
  let ner ←
    locas_with_tg.mapM fun e => reorder_hyp op args e.local_pp_name <|> reorder_hyp op args none
  let (unch_tgts, unus_vars) := ner.unzip
  let str_unva ←
    match
        (returnUnused args (unus_vars.transpose.map List.and)).map fun e : Bool × pexpr => e.2 with
      | [] => pure []
      | [pe] => do
        let nm ← to_expr pe true false >>= fun ex => pp ex.replace_mvars
        return [f! "'{nm}' is an unused variable"]
      | pes => do
        let nms ←
          (pes.mapM fun e => to_expr e true false) >>= fun exs =>
              (exs.map expr.replace_mvars).mapM pp
        return [f! "'{nms}' are unused variables"]
  let str_tgts :=
    match locat with
    | loc.wildcard => if unch_tgts.and then [f!"nothing changed"] else []
    | loc.ns names =>
      let linames := returnUnused locas unch_tgts
      (if none ∈ returnUnused names unch_tgts then [f!"Goal did not change"] else []) ++
        if linames ≠ [] then [f! "'{linames.reverse}' did not change"] else []
  let [] ← pure (str_tgts ++ str_unva) |
    fail (format.intercalate "\n" (str_tgts ++ str_unva))
  assumption <|> try (tactic.reflexivity reducible)
#align tactic.move_op tactic.move_op

namespace Interactive

/--
Calling `move_add [a, ← b, c]`, recursively looks inside the goal for expressions involving a sum.
Whenever it finds one, it moves the summands that unify to `a, b, c`, removing all parentheses.
Repetitions are allowed, and are processed following the user-specified ordering.
The terms preceded by a `←` get placed to the left, the ones without the arrow get placed to the
right.  Unnamed terms stay in place.  Due to re-parenthesizing, doing `move_add` with no argument
may change the goal. Also, the *order* in which the terms are provided matters: the tactic reads
them from left to right.  This is especially important if there are multiple matches for the typed
terms in the given expressions.

A single call of `move_add` moves terms across different sums in the same expression.
Here is an example.

```lean
import tactic.move_add

example {a b c d : ℕ} (h : c = d) : c + b + a = b + a + d :=
begin
  move_add [← a, b],  -- Goal: `a + c + b = a + d + b`  -- both sides changed
  congr,
  exact h
end

example {a b c d : ℕ} (h : c = d) : c + b * c + a * c = a * d + d + b * d :=
begin
  move_add [_ * c, ← _ * c], -- Goal: `a * c + c + b * c = a * d + d + b * d`
  -- the first `_ * c` unifies with `b * c` and moves to the right
  -- the second `_ * c` unifies with `a * c` and moves to the left
  congr;
  assumption
end
```

The list of expressions that `move_add` takes is optional and a single expression can be passed
without brackets.  Thus `move_add ← f` and `move_add [← f]` mean the same.

Finally, `move_add` can also target one or more hypotheses.  If `hp₁, hp₂` are in the
local context, then `move_add [f, ← g] at hp₁ hp₂` performs the rearranging at `hp₁` and `hp₂`.
As usual, passing `⊢` refers to acting on the goal.

##  Reporting sub-optimal usage

The tactic could fail to prove the reordering.  One potential cause is when there are multiple
matches for the rearrangements and an earlier rewrite makes a subsequent one fail.  Another
possibility is that the rearranged expression changes the *Type* of some expression and the
tactic gets stumped.  Please, report bugs and failures in the Zulip chat!

There are three kinds of unwanted use for `move_add` that result in errors, where the tactic fails
and flags the unwanted use.
1. `move_add [vars]? at *` reports globally unused variables and whether *all* goals
   are unchanged, not *each unchanged goal*.
2. If a target of `move_add [vars]? at targets` is left unchanged by the tactic, then this will be
   flagged (unless we are using `at *`).
3. If a user-provided expression never unifies, then the variable is flagged.

In these cases, the tactic produces an error, reporting unused inputs and unchanged targets as
appropriate.

For instance, `move_add ← _` always fails reporting an unchanged goal, but never an unused variable.

##  Comparison with existing tactics

* `tactic.interactive.abel`
  performs a "reduction to normal form" that allows it to close goals involving sums with higher
  success rate than `move_add`.  If the goal is an equality of two sums that are simply obtained by
  reparenthesizing and permuting summands, then `move_add [appropriate terms]` can close the goal.
  Compared to `abel`, `move_add` has the advantage of allowing the user to specify the beginning and
  the end of the final sum, so that from there the user can continue with the proof.

* `tactic.interactive.ac_change`
  supports a wide variety of operations.  At the moment, `move_add` works with addition, `move_mul`
  works with multiplication.  There is the possibility of supporting other operations, using the
  non-interactive tactic `tactic.move_op`.
  Still, on several experiments, `move_add` had a much quicker performance than `ac_change`.
  Also, for `move_add` the user need only specify a few terms: the tactic itself takes care of
  producing the full rearrangement and proving it "behind the scenes".

###  Remark:
It is still possible that the same output of `move_add [exprs]` can be achieved by a proper sublist
of `[exprs]`, even if the tactic does not flag anything.  For instance, giving the full re-ordering
of the expressions in the target that we want to achieve will not complain that there are unused
variables, since all the user-provided variables have been matched.  Of course, specifying the order
of all-but-the-last variable suffices to determine the permutation.  E.g., with a goal of
`a + b = 0`, applying either one of `move_add [b,a]`, or `move_add a`, or `move_add ← b` has the
same effect and changes the goal to `b + a = 0`.  These are all valid uses of `move_add`.
-/
unsafe def move_add (args : parse move_pexpr_list_or_texpr) (locat : parse location) :
    tactic Unit :=
  move_op args locat ``((· + ·))
#align tactic.interactive.move_add tactic.interactive.move_add

/-- See the doc-string for `tactic.interactive.move_add` and mentally
replace addition with multiplication throughout. ;-) -/
unsafe def move_mul (args : parse move_pexpr_list_or_texpr) (locat : parse location) :
    tactic Unit :=
  move_op args locat ``(Mul.mul)
#align tactic.interactive.move_mul tactic.interactive.move_mul

/-- `move_oper` behaves like `move_add` except that it also takes an associative, commutative,
binary operation as input.  The operation must be passed as a list consisting of a single element.
For instance
```lean
example (a b : ℕ) : max a b = max b a :=
by move_oper [max] [← a, b] at *
```
solves the goal.  For more details, see the `move_add` doc-string, replacing `add` with your
intended operation.
-/
unsafe def move_oper (op : parse pexpr_list) (args : parse move_pexpr_list_or_texpr)
    (locat : parse location) : tactic Unit := do
  let [op] ← pure op |
    fail "only one operation is allowed"
  move_op args locat op
#align tactic.interactive.move_oper tactic.interactive.move_oper

add_tactic_doc
  { Name := "move_add"
    category := DocCategory.tactic
    declNames := [`tactic.interactive.move_add]
    tags := ["arithmetic"] }

add_tactic_doc
  { Name := "move_mul"
    category := DocCategory.tactic
    declNames := [`tactic.interactive.move_mul]
    tags := ["arithmetic"] }

end Interactive

end Tactic


/- Copyright 2022 ACL & MIdFF-/

import algebra.module.graded_module

section direct_sum

universes u v w
variables {ι : Type v} [decidable_eq ι]

section mk

variables {β : ι → Type w} [Π (i : ι), add_comm_monoid (β i)]

lemma direct_sum.mk_apply_of_mem {s : finset ι} {f : Π (i : (↑s : set ι)), β i.val}
  {n : ι} (hn : n ∈ s):
  direct_sum.mk β s f n = f ⟨n, hn⟩ :=
by simp only [direct_sum.mk, add_monoid_hom.coe_mk, dfinsupp.mk_apply, dif_pos hn]

lemma direct_sum.mk_apply_of_not_mem {s : finset ι} {f : Π (i : (↑s : set ι)), β i.val}
  {n : ι} (hn : n ∉ s):
  direct_sum.mk β s f n = 0 :=
by simp only [direct_sum.mk, add_monoid_hom.coe_mk, dfinsupp.mk_apply, dif_neg hn]

end mk

section internal

variables {M : Type w} [decidable_eq M] [add_comm_monoid M]

lemma direct_sum.coe_add_monoid_hom_eq_dfinsupp_sum
  {M : Type w} [decidable_eq M] [add_comm_monoid M]
  (A : ι → add_submonoid M) (x : direct_sum ι (λ i, A i)) :
  direct_sum.coe_add_monoid_hom A x = dfinsupp.sum x (λ i, coe):=
by simp only [direct_sum.coe_add_monoid_hom, direct_sum.to_add_monoid,
  dfinsupp.lift_add_hom, add_equiv.coe_mk, dfinsupp.sum_add_hom_apply,
  add_submonoid_class.coe_subtype]

lemma direct_sum.coe_linear_map_eq_dfinsupp_sum
  {R : Type u} [semiring R] [module R M] (A : ι → submodule R M)
  (x : direct_sum ι (λ i, A i)) :
  direct_sum.coe_linear_map A x = dfinsupp.sum x (λ i, coe):=
by simp only [direct_sum.coe_linear_map, direct_sum.to_module, dfinsupp.lsum,
  linear_equiv.coe_mk, linear_map.coe_mk, dfinsupp.sum_add_hom_apply,
  linear_map.to_add_monoid_hom_coe, submodule.coe_subtype]

lemma direct_sum.support_subset (A : ι → add_submonoid M)
  (x : direct_sum ι (λ i, A i)) :
  function.support  (λ i, (x i : M)) ⊆ ↑(dfinsupp.support x) :=
begin
  intro m,
  rw [function.mem_support, finset.mem_coe, dfinsupp.mem_support_to_fun, not_imp_not],
  intro hm',
  rw [hm', add_submonoid.coe_zero],
end

lemma direct_sum.support_subset_submodule (R : Type*) [comm_semiring R]
  [module R M] (A : ι → submodule R M)
  (x : direct_sum ι (λ i, A i)) :
  function.support  (λ i, (x i : M)) ⊆ ↑(dfinsupp.support x) :=
begin
  intro m,
  rw [function.mem_support, finset.mem_coe, dfinsupp.mem_support_to_fun, not_imp_not],
  intro hm',
  simp only [hm', submodule.coe_zero],
end

lemma direct_sum.finite_support (A : ι → add_submonoid M)
  (x : direct_sum ι (λ i, A i)) :
  (function.support (λ i, (x i : M))).finite :=
set.finite.subset (dfinsupp.support x : set ι).to_finite (direct_sum.support_subset _ x)

end internal

end direct_sum

section

theorem linear_map.map_finsum {α R S M N : Type*} [semiring R] [semiring S] (σ : R →+* S)
  [add_comm_monoid M] [add_comm_monoid N]  [module R M] [module S N] {f : α → M} (g : M →ₛₗ[σ] N)
  (hf : (function.support f).finite) :
  g (finsum (λ (i : α), f i)) = finsum (λ (i : α), g (f i)) :=
begin
  rw ← linear_map.to_add_monoid_hom_coe,
  exact add_monoid_hom.map_finsum _ hf,
end

end

noncomputable theory

section direct_sum

open direct_sum

/- Given an R-algebra A and a family (ι → submodule R A) of submodules
parameterized by an additive monoid
and statisfying `set_like.graded_monoid M` (essentially, is multiplicative)
such that `direct_sum.is_internal M` (A is the direct sum of the M i),
we endow A with the structure of a graded algebra.
The submodules are the *homogeneous* parts -/

variables (R : Type*) [comm_semiring R] (A : Type*) [comm_semiring A] [algebra R A]
variables (ι : Type*) [decidable_eq ι]

variables (M : ι → submodule R A) [add_monoid ι] [set_like.graded_monoid M]

variables {R A ι M}

-- The following lines were given on Zulip by Adam Topaz

def direct_sum.is_internal.coe_alg_iso (hM : direct_sum.is_internal M) :
  direct_sum ι (λ i, ↥(M i)) ≃ₐ[R] A :=
{ commutes' := λ r, by simp,
  ..(ring_equiv.of_bijective (direct_sum.coe_alg_hom M) hM) }

def direct_sum.is_internal.graded_algebra (hM : direct_sum.is_internal M) :
  graded_algebra M :=
{ decompose' := hM.coe_alg_iso.symm,
    -- (coe_alg_iso_of_is_internal hM).symm,
  left_inv := hM.coe_alg_iso.symm.left_inv,
    -- (coe_alg_iso_of_is_internal hM).symm.left_inv,
  right_inv := hM.coe_alg_iso.left_inv,
  -- (coe_alg_iso_of_is_internal hM).left_inv,
  ..(infer_instance : set_like.graded_monoid M) }

def direct_sum.decomposition.graded_algebra (dM : direct_sum.decomposition M) :
  graded_algebra M :=
{ to_decomposition  := dM,
  ..(infer_instance : set_like.graded_monoid M) }

end direct_sum

#exit

section weighted_homogeneous

/- Here, given a weight `w : σ → M`, where `M` is an additive and commutative monoid, we endow the
  ring of multivariate polynomials `mv_polynomial σ R` with the structure of a graded algebra -/

variables {R : Type*} [comm_semiring R]
variables {M : Type*} [add_comm_monoid M] [decidable_eq M]
variables {σ : Type*}
variable (w : σ → M)

namespace mv_polynomial

lemma weighted_homogeneous_component_mem (w : σ → M) (φ : mv_polynomial σ R)
  (m : M) :
  weighted_homogeneous_component R w m φ ∈ weighted_homogeneous_submodule R w m :=
begin
  rw mem_weighted_homogeneous_submodule,
  exact weighted_homogeneous_component_is_weighted_homogeneous m φ,
end

/-
lemma toto (p : Prop) [decidable p] (u v : M) :
  (ite p u v = u) ↔ (¬ p → u = v) :=
begin
  by_cases hp : p,
  simp only [hp, if_true, eq_self_iff_true, not_true, is_empty.forall_iff],
  simp only [hp, if_false, not_false_iff, forall_true_left],
  exact comm,
end
 -/

lemma decompose'_aux (φ : mv_polynomial σ R) (i : M)
  (hi : i ∉ finset.image (weighted_degree' w) φ.support) :
  weighted_homogeneous_component R w i φ = 0 :=
begin
  apply weighted_homogeneous_component_eq_zero',
  simp only [finset.mem_image, mem_support_iff, ne.def, exists_prop, not_exists, not_and] at hi,
  intros m hm,
  apply hi m,
  rw mem_support_iff at hm,
  exact hm,
end

/-
lemma decompose'_aux' (φ : mv_polynomial σ R) (i : M) :
  ite (i ∈ finset.image (weighted_degree' w) φ.support)
    ((weighted_homogeneous_component R w i) φ) 0
    = (weighted_homogeneous_component R w i) φ :=
begin
  split_ifs with hi hi,
  refl,
  rw decompose'_aux w φ i hi,
end -/

variable (R)
def decompose'_fun := λ (φ : mv_polynomial σ R), direct_sum.mk
  (λ (i : M), ↥(weighted_homogeneous_submodule R w i))
  (finset.image (weighted_degree' w) φ.support)
  (λ m, ⟨weighted_homogeneous_component R w m φ, weighted_homogeneous_component_mem w φ m⟩)

lemma decompose'_fun_apply (φ : mv_polynomial σ R) (m : M):
  (decompose'_fun R w φ m : mv_polynomial σ R) =
  weighted_homogeneous_component R w m φ :=
begin
  rw decompose'_fun,
  by_cases hm :  m ∈ finset.image (weighted_degree' w) φ.support,
  simp only [direct_sum.mk_apply_of_mem hm, subtype.coe_mk],
  rw [direct_sum.mk_apply_of_not_mem hm, submodule.coe_zero, decompose'_aux w φ m hm],
end

instance [decidable_eq σ] [decidable_eq R] :
  Π (i : M) (x : ↥(weighted_homogeneous_submodule R w i)), decidable (x ≠ 0) :=
begin
  intros m x,
  rw [ne.def, ← set_like.coe_eq_coe],
  apply_instance,
end

-- Rewrite direct_sum.coe_linear_map
lemma direct_sum.coe_linear_map_eq_support_sum [decidable_eq σ] [decidable_eq R]
  (x : direct_sum M (λ (i : M), ↥(weighted_homogeneous_submodule R w i))) :
  ((direct_sum.coe_linear_map (λ (i : M), weighted_homogeneous_submodule R w i)) x) =
  dfinsupp.sum x  (λ m, coe) :=
begin
  rw direct_sum.coe_linear_map_eq_dfinsupp_sum,
  -- WEIRD: this is not yet finished
  simp only [dfinsupp.sum],
  apply finset.sum_congr,
  ext m,
  simp only [dfinsupp.mem_support_iff],
  intros m hm, refl,
end

-- Rewrite direct_sum.coe_add_monoid_hom
lemma direct_sum.coe_add_monoid_hom_eq_support_sum [decidable_eq σ] [decidable_eq R]
  (x : direct_sum M (λ (i : M), ↥(weighted_homogeneous_submodule R w i))) :
  ((direct_sum.coe_add_monoid_hom (λ (i : M), weighted_homogeneous_submodule R w i)) x) =
  dfinsupp.sum x  (λ m, coe) :=
  direct_sum.coe_linear_map_eq_support_sum R w x

-- Variants for finsum
lemma direct_sum.coe_linear_map_eq_finsum [decidable_eq σ] [decidable_eq R]
  (x : direct_sum M (λ (i : M), ↥(weighted_homogeneous_submodule R w i)))
  /- [h_dec : Π (i : M) (x : ↥(weighted_homogeneous_submodule R w i)), decidable (x ≠ 0)]  -/:
  ((direct_sum.coe_linear_map (λ (i : M), weighted_homogeneous_submodule R w i)) x) =
  finsum (λ m, x m) :=
begin
  rw [direct_sum.coe_linear_map_eq_support_sum, dfinsupp.sum],
  rw finsum_eq_sum_of_support_subset,
  -- direct_sum.support_subset ne marche pas…
  intro m,
  rw [function.mem_support, finset.mem_coe, dfinsupp.mem_support_to_fun, not_imp_not],
  intro hm',
  rw [hm', submodule.coe_zero],
end

lemma direct_sum.coe_add_monoid_hom_eq_finsum [decidable_eq σ] [decidable_eq R]
  (x : direct_sum M (λ (i : M), ↥(weighted_homogeneous_submodule R w i)))
  /- [h_dec : Π (i : M) (x : ↥(weighted_homogeneous_submodule R w i)), decidable (x ≠ 0)]  -/:
  ((direct_sum.coe_add_monoid_hom (λ (i : M), weighted_homogeneous_submodule R w i)) x) =
  finsum (λ m, x m) :=
  direct_sum.coe_linear_map_eq_finsum R w x

-- TODO: move to weighted_homogeneous file
lemma weighted_homogeneous_component_weighted_homogeneous_polynomial' (m : M)
  (x : weighted_homogeneous_submodule R w m) :
  (weighted_homogeneous_component  R w m) ↑x = x :=
by rw [weighted_homogeneous_component_weighted_homogeneous_polynomial m m _ x.prop, if_pos rfl]

lemma weighted_homogeneous_component_direct_sum [decidable_eq σ] [decidable_eq R]
  (x : direct_sum M (λ (i : M), ↥(weighted_homogeneous_submodule R w i))) (m : M) :
  (weighted_homogeneous_component R w m)
    ((direct_sum.coe_linear_map (λ (i : M), weighted_homogeneous_submodule R w i)) x) = x m :=
begin
  rw [direct_sum.coe_linear_map_eq_dfinsupp_sum],
  rw dfinsupp.sum,
  rw map_sum,
  rw finset.sum_eq_single m,
  { rw weighted_homogeneous_component_of_weighted_homogeneous_polynomial_same,
    rw ← mem_weighted_homogeneous_submodule,
    exact (x m).prop, },
  { intros n hn hmn,
    rw weighted_homogeneous_component_of_weighted_homogeneous_polynomial_other,
    rw ← mem_weighted_homogeneous_submodule,
    exact (x n).prop, exact ne.symm hmn, },
  { rw dfinsupp.not_mem_support_iff,
    intro hm, rw [hm, submodule.coe_zero, map_zero], },
end

def mv_polynomial_weighted_decomposition [decidable_eq σ] [decidable_eq R] :
  direct_sum.decomposition (weighted_homogeneous_submodule R w) :=
{ decompose'  := decompose'_fun R w,
  left_inv    := λ φ,
  begin
    conv_rhs { rw [← sum_weighted_homogeneous_component w φ], },
    rw ← direct_sum.sum_support_of (λ m, ↥(weighted_homogeneous_submodule R w m))
      (decompose'_fun R w φ),
    simp only [direct_sum.coe_add_monoid_hom_of, mv_polynomial.coeff_sum, map_sum],
    apply congr_arg2,
    { ext m,
      simp only [dfinsupp.mem_support_to_fun, ne.def, set.finite.mem_to_finset,
        function.mem_support, not_iff_not],
      conv_lhs { rw ← subtype.coe_inj },
      rw [decompose'_fun_apply, submodule.coe_zero], },
    { apply funext, intro m, rw decompose'_fun_apply, },
  end,
  right_inv   := λ x,
  begin
    apply dfinsupp.ext, intro m,
    rw ← subtype.coe_inj,
    rw decompose'_fun_apply,
    change (weighted_homogeneous_component R w m) ((direct_sum.coe_linear_map (weighted_homogeneous_submodule R w)) x) = ↑(x m),
    rw direct_sum.coe_linear_map_eq_dfinsupp_sum,
    rw dfinsupp.sum,
    rw map_sum,
    rw finset.sum_eq_single m,
    { rw weighted_homogeneous_component_of_weighted_homogeneous_polynomial_same,
      exact (x m).prop,  },
    { intros n hn hmn,
      rw weighted_homogeneous_component_of_weighted_homogeneous_polynomial_other,
      exact (x n).prop,
      exact ne.symm hmn, },
    { intro hm, rw dfinsupp.not_mem_support_iff at hm,
      simp only [hm, submodule.coe_zero, map_zero], },
  end }

/-- mv_polynomial as a graded algebra, for an arbitrary weight -/
def mv_polynomial_weighted_graded_algebra
  [decidable_eq σ] [decidable_eq R] :
  graded_algebra (weighted_homogeneous_submodule R w) :=
{ to_decomposition  := mv_polynomial_weighted_decomposition R w,
  to_graded_monoid  := infer_instance, }

end mv_polynomial

end weighted_homogeneous

#exit --Unused draft below

/- import algebra.free_algebra
import algebra.ring_quot
import algebra.triv_sq_zero_ext
import algebra.algebra.operations
import linear_algebra.multilinear.basic
import ring_theory.graded_algebra.basic
import ring_theory.tensor_product

import divided_powers.basic
import divided_powers.ideal_add
import ..weighted_homogeneous -- PR #17855
 -/

section
/- Here, the goal is to define a graded_algebra structure on mv_polynomial with respect to a given degree map…
For the moment, I am stuck. -/

variables (R : Type*) [semiring R]
variables (ι : Type*) [decidable_eq ι]
  {M : ι → Type* } [Π (i : ι), add_comm_monoid (M i)] [Π (i : ι), module R (M i)]
variables {N : Type*} [add_comm_monoid N] [module R N]

lemma yala
  (g : Π (i : ι), N →ₗ[R] M i)
  (hg : ∀ n, {i | g i n ≠ 0}.finite)
  (h : Π (i : ι), M i →ₗ[R] N) (n : N) :
  (direct_sum.to_module R ι N h) (direct_sum.mk M (hg n).to_finset (λ i, g i n)) = finsum (λ i, h i (g i n)) :=
begin
  classical,
  suffices : (function.support ((λ (i : ι), (h i) ((g i) n)) ∘ plift.down)).finite,
  let s := { i | g i n ≠ 0},
  unfold finsum,
  rw dif_pos this,

  unfold direct_sum.mk,dsimp,
end

example (f : ℕ →+ ℕ) (a : ι →₀ ℕ) :
  f (finsupp.sum a (λ i m, m)) =
  finsupp.sum (finsupp.map_range f (f.map_zero) a) (λ i m, m)
:=
begin
  rw map_finsupp_sum,
  rw finsupp.sum_map_range_index,
  intro i, refl,
end

example (f : ℕ →+ ℕ) (a : ι → ℕ) (ha : (function.support a).finite):
  f (finsum a) = finsum (λ i, f (a i)) := add_monoid_hom.map_finsum f ha

#check yala

end

/-!
The divided power algebra of a module -/

open finset mv_polynomial ring_quot

section graded_algebra
/-  The mv_polynomial algebra with a degree, as a graded algebra -/

namespace mv_polynomial

variables {R M : Type*} [comm_semiring R] [add_comm_monoid M] [decidable_eq M]

variables {σ : Type*}
variable (w : σ → M)
#check weighted_degree'
def w_degree : (σ →₀ ℕ) → M := λ p, finsupp.sum p (λ s n, n • (w s))

/- def weighted_degrees' (w : σ → M) (s : finset (σ →₀ ℕ)) :
finset M := finset.image (weighted_degree' w) s -/

lemma weighted_homogeneous_component_mem (w : σ → M) (φ : mv_polynomial σ R) (m : M) :
  weighted_homogeneous_component w m φ ∈ weighted_homogeneous_submodule R w m :=
begin
  rw mem_weighted_homogeneous_submodule,
  exact weighted_homogeneous_component_is_weighted_homogeneous m φ,
end

example (s : finset ℕ) : s = ∅ ↔ s ⊆ ∅ :=
begin
  rw [← finset.bot_eq_empty, eq_bot_iff, le_iff_subset],
end

lemma decompose'_aux (φ : mv_polynomial σ R) (i : M) :
  ite (i ∈ finset.image (weighted_degree' w) φ.support) ((weighted_homogeneous_component w i) φ) 0 = (weighted_homogeneous_component w i) φ :=
begin
  split_ifs with hi hi,
  refl,
  apply symm,
  apply weighted_homogeneous_component_eq_zero',
  simp only [mem_image, mem_support_iff, ne.def, exists_prop, not_exists, not_and] at hi,
  intros m hm,
  apply hi m,
  rw mem_support_iff at hm,
  exact hm,
end

variable (R)

/-- The linear map from polynomials to the direct sum of the homogeneous components -/
def decompose' : mv_polynomial σ R →ₗ[R] direct_sum M (λ (i : M), ↥(weighted_homogeneous_submodule R w i)) := {
to_fun  := λ φ, direct_sum.mk
  (λ (i : M), ↥(weighted_homogeneous_submodule R w i))
  (finset.image (weighted_degree' w) φ.support)
  (λ m, ⟨weighted_homogeneous_component w m φ, weighted_homogeneous_component_mem w φ m⟩),
map_add'  := λ φ ψ,
begin
  rw dfinsupp.ext_iff,
  simp only [direct_sum.mk],
  intro i,
  dsimp,
  rw ← subtype.coe_inj,
  rw submodule.coe_add,
  simp only [apply_ite coe, subtype.coe_mk, submodule.coe_zero],
  simp only [decompose'_aux],
  rw [map_add],
end,
map_smul' :=
begin
  intros a φ,
  rw dfinsupp.ext_iff,
  simp only [direct_sum.mk],
  intro i,
  dsimp,
  rw ← subtype.coe_inj,
  rw submodule.coe_smul,
  simp only [apply_ite coe, subtype.coe_mk, submodule.coe_zero],
  simp only [decompose'_aux], rw [map_smul],
end }

#check decompose'

def decompose'_fun : mv_polynomial σ R → direct_sum M (λ (i : M), ↥(weighted_homogeneous_submodule R w i)) := λ φ, direct_sum.mk
  (λ (i : M), ↥(weighted_homogeneous_submodule R w i))
  (finset.image (weighted_degree' w) φ.support)
  (λ m, ⟨weighted_homogeneous_component w m φ, weighted_homogeneous_component_mem w φ m⟩)
fintype
lemma decompose'_fun_coe_apply (φ : mv_polynomial σ R) (m : M) : (decompose'_fun R w φ m : mv_polynomial σ R) = weighted_homogeneous_component w m φ :=
begin
  simp only [decompose'_fun],
--   simp only [direct_sum.mk, dfinsupp.mk_apply],
  simp only [direct_sum.mk, subtype.coe_mk, add_monoid_hom.coe_mk, dfinsupp.mk_apply, apply_dite coe, dite_eq_ite],
  exact decompose'_aux w φ m,
end

lemma decompose'_add' : ∀ (φ ψ : mv_polynomial σ R), decompose'_fun R w (φ + ψ) = decompose'_fun R w φ + decompose'_fun R w ψ :=
begin
  intros φ ψ,
  simp only [decompose'_fun],
  rw dfinsupp.ext_iff,
  simp only [direct_sum.mk],
  intro i,
  simp only [add_monoid_hom.coe_mk, dfinsupp.mk_apply],
  dsimp,
  rw ← subtype.coe_inj,
  rw submodule.coe_add,
  simp only [apply_dite coe, subtype.coe_mk, submodule.coe_zero, dite_eq_ite],
  simp only [decompose'_aux],
  rw [map_add],
end

lemma decompose'_map_zero' : decompose'_fun R w 0 = 0 :=
begin
  simp only [decompose'_fun],
  rw dfinsupp.ext_iff,
  simp only [direct_sum.mk],
  intro i,
  simp only [mem_image, mem_support_iff, coeff_zero, ne.def, eq_self_iff_true, not_true, is_empty.exists_iff, exists_false,
  not_false_iff, add_monoid_hom.coe_mk, dfinsupp.mk_apply, dif_neg, direct_sum.zero_apply],
end

lemma direct_sum_one_coeffs (i : M) :
  (((1 : direct_sum M (λ (i : M), ↥(weighted_homogeneous_submodule R w i))) i) : mv_polynomial σ R)
  = ite (i = 0) (1 : mv_polynomial σ R) (0 : mv_polynomial σ R) :=
begin
  conv_lhs { dsimp [has_one.one], },
  split_ifs,
  rw h,
  rw direct_sum.of_eq_same,
  refl,
  rw direct_sum.of_eq_of_ne,
  refl,
  exact ne.symm h,
end

lemma decompose'_map_one' : decompose'_fun R w 1 = 1 :=
begin
  classical,
  simp only [decompose'_fun],
  rw dfinsupp.ext_iff,
  simp only [direct_sum.mk],
  intro i,
  simp only [subtype.coe_mk, add_monoid_hom.coe_mk, dfinsupp.mk_apply],
  rw ← subtype.coe_inj,
  simp only [apply_dite coe, subtype.coe_mk, submodule.coe_zero, dite_eq_ite],
  simp only [decompose'_aux],

  rw direct_sum_one_coeffs,
  rw weighted_homogeneous_component_weighted_homogeneous_polynomial,
  swap,
  apply is_weighted_homogeneous_one,
  by_cases hi : i = 0,
  rw [if_pos, if_pos], exact hi, exact hi,
  rw [if_neg hi, if_neg], exact hi,
end

lemma decompose'_map_mul' : ∀ (φ ψ : mv_polynomial σ R), decompose'_fun R w (φ * ψ) = decompose'_fun R w φ * decompose'_fun R w ψ :=
begin
sorry,
end

/-- The alg_hom map from polynomials to the direct sum of the homogeneous components -/
def decompose'a : mv_polynomial σ R →ₐ[R] direct_sum M (λ (i : M), ↥(weighted_homogeneous_submodule R w i)) := {
to_fun  := λ φ, direct_sum.mk
  (λ (i : M), ↥(weighted_homogeneous_submodule R w i))
  (finset.image (weighted_degree' w) φ.support)
  (λ m, ⟨weighted_homogeneous_component w m φ, weighted_homogeneous_component_mem w φ m⟩),
map_add'  := decompose'_add' R w,
/- map_smul' :=
begin
  intros a φ,
  rw dfinsupp.ext_iff,
  simp only [direct_sum.mk],
  intro i,
  dsimp,
  rw ← subtype.coe_inj,
  rw submodule.coe_smul,
  simp only [apply_ite coe, subtype.coe_mk, submodule.coe_zero],
  simp only [decompose'_aux], rw [map_smul],
end, -/
map_mul'  :=
begin
  intros φ ψ,
  rw dfinsupp.ext_iff,
  simp only [direct_sum.mk],
  intro i,
  -- dsimp,
  rw ← subtype.coe_inj,
  sorry,
  /-
  rw submodule.coe_mul,
  simp only [apply_ite coe, subtype.coe_mk, submodule.coe_zero],
  simp only [decompose'_aux], rw [map_mul], -/
end,
map_one'  := decompose'_map_one' R w,
map_zero' := decompose'_map_zero' R w,
commutes' := sorry }

/- Better approach : this will work! -/
lemma is_internal_direct_sum_of_weighted_homogeneous_submodules :
  direct_sum.is_internal (weighted_homogeneous_submodule R w) :=
begin
  classical,
  split,
  { -- injectivity
    intros p q,
    intro hpq,
    rw mv_polynomial.ext_iff  at hpq,
    ext,
    specialize hpq m,
    rw [← direct_sum.sum_support_of _ p, ← direct_sum.sum_support_of _ q ] at hpq,
    simp only [map_sum, direct_sum.coe_add_monoid_hom_of, mv_polynomial.coeff_sum] at hpq,
    by_cases hi : weighted_degree' w m = i,
    { suffices this : ∀ (x : direct_sum M (λ (i : M), ↥(weighted_homogeneous_submodule R w i))) (c : M), c ≠ i → coeff m ((x c) : mv_polynomial σ R) = 0,
      suffices this' : ∀ (x : direct_sum M (λ (i : M), ↥(weighted_homogeneous_submodule R w i))),
      i ∉ dfinsupp.support x → coeff m ((x i) : mv_polynomial σ R) = 0,
      rw [finset.sum_eq_single i, finset.sum_eq_single i] at hpq,
      exact hpq,
      exact λ b hb, this q b,
      exact this' q,
      exact λ b hb, this p b,
      exact this' p,
      { intros x hx,
        simp only [dfinsupp.mem_support_to_fun, not_not] at hx, rw hx,
        exact mv_polynomial.coeff_zero m, },
      { intros x b hbi,
        apply is_weighted_homogeneous.coeff_eq_zero _ m,
        rw hi,
        exact ne.symm hbi,
        rw ← mem_weighted_homogeneous_submodule,
        exact (x b).prop, } },
    rw is_weighted_homogeneous.coeff_eq_zero (p i).prop m hi,
    rw is_weighted_homogeneous.coeff_eq_zero (q i).prop m hi, },
  { -- surjectivity
    intro φ,
    use decompose'_fun R w φ,
    conv_lhs { rw ← direct_sum.sum_support_of _ (decompose'_fun R w φ) },
    simp only [map_sum, direct_sum.coe_add_monoid_hom_of],
    simp_rw decompose'_fun_coe_apply,

    conv_rhs { rw ← sum_weighted_homogeneous_component w φ},
    rw finsum_eq_sum _ (weighted_homogeneous_component_finsupp φ),
    apply congr_arg2 _ _ rfl,
    ext m,
    rw [dfinsupp.mem_support_to_fun, ne.def, set.finite.mem_to_finset, function.mem_support, not_iff_not],
    conv_lhs { rw [← subtype.coe_inj, decompose'_fun_coe_apply, submodule.coe_zero], } },
end

def graded_polynomial_algebra : graded_algebra
(weighted_homogeneous_submodule R w) := graded_algebra.of_alg_hom (weighted_homogeneous_submodule R w) (decompose'a R w) (sorry) (sorry)

end mv_polynomial

end graded_algebra