/-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers

! This file was ported from Lean 3 source module linear_algebra.affine_space.affine_map
! leanprover-community/mathlib commit bd1fc183335ea95a9519a1630bcf901fe9326d83
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathlib.Data.Set.Pointwise.Interval
import Mathlib.LinearAlgebra.AffineSpace.Basic
import Mathlib.LinearAlgebra.BilinearMap
import Mathlib.LinearAlgebra.Pi
import Mathlib.LinearAlgebra.Prod

/-!
# Affine maps

This file defines affine maps.

## Main definitions

* `AffineMap` is the type of affine maps between two affine spaces with the same ring `k`.  Various
  basic examples of affine maps are defined, including `const`, `id`, `lineMap` and `homothety`.

## Notations

* `P1 →ᵃ[k] P2` is a notation for `AffineMap k P1 P2`;
* `AffineSpace V P`: a localized notation for `AddTorsor V P` defined in
  `LinearAlgebra.AffineSpace.Basic`.

## Implementation notes

`out_param` is used in the definition of `[AddTorsor V P]` to make `V` an implicit argument
(deduced from `P`) in most cases. As for modules, `k` is an explicit argument rather than implied by
`P` or `V`.

This file only provides purely algebraic definitions and results. Those depending on analysis or
topology are defined elsewhere; see `Analysis.NormedSpace.AddTorsor` and
`Topology.Algebra.Affine`.

## References

* https://en.wikipedia.org/wiki/Affine_space
* https://en.wikipedia.org/wiki/Principal_homogeneous_space
-/

-- Porting note: Workaround for lean4#2074
attribute [-instance] Ring.toNonAssocRing

open Affine

/-- An `AffineMap k P1 P2` (notation: `P1 →ᵃ[k] P2`) is a map from `P1` to `P2` that
induces a corresponding linear map from `V1` to `V2`. -/
structure AffineMap (k : Type _) {V1 : Type _} (P1 : Type _) {V2 : Type _} (P2 : Type _) [Ring k]
  [AddCommGroup V1] [Module k V1] [AffineSpace V1 P1] [AddCommGroup V2] [Module k V2]
  [AffineSpace V2 P2] where
  toFun : P1 → P2
  linear : V1 →ₗ[k] V2
  map_vadd' : ∀ (p : P1) (v : V1), toFun (v +ᵥ p) = linear v +ᵥ toFun p
#align affine_map AffineMap

/-- An `AffineMap k P1 P2` (notation: `P1 →ᵃ[k] P2`) is a map from `P1` to `P2` that
induces a corresponding linear map from `V1` to `V2`. -/
notation:25 P1 " →ᵃ[" k:25 "] " P2:0 => AffineMap k P1 P2

instance AffineMap.funLike (k : Type _) {V1 : Type _} (P1 : Type _) {V2 : Type _} (P2 : Type _)
    [Ring k] [AddCommGroup V1] [Module k V1] [AffineSpace V1 P1] [AddCommGroup V2] [Module k V2]
    [AffineSpace V2 P2] : FunLike (P1 →ᵃ[k] P2) P1 fun _ => P2
    where
  coe := AffineMap.toFun
  coe_injective' := fun ⟨f, f_linear, f_add⟩ ⟨g, g_linear, g_add⟩ => fun (h : f = g) => by
    cases' (AddTorsor.Nonempty : Nonempty P1) with p
    congr with v
    apply vadd_right_cancel (f p)
    erw [← f_add, h, ← g_add]
#align affine_map.fun_like AffineMap.funLike

instance AffineMap.hasCoeToFun (k : Type _) {V1 : Type _} (P1 : Type _) {V2 : Type _} (P2 : Type _)
    [Ring k] [AddCommGroup V1] [Module k V1] [AffineSpace V1 P1] [AddCommGroup V2] [Module k V2]
    [AffineSpace V2 P2] : CoeFun (P1 →ᵃ[k] P2) fun _ => P1 → P2 :=
  FunLike.hasCoeToFun
#align affine_map.has_coe_to_fun AffineMap.hasCoeToFun

namespace LinearMap

variable {k : Type _} {V₁ : Type _} {V₂ : Type _} [Ring k] [AddCommGroup V₁] [Module k V₁]
  [AddCommGroup V₂] [Module k V₂] (f : V₁ →ₗ[k] V₂)

/-- Reinterpret a linear map as an affine map. -/
def toAffineMap : V₁ →ᵃ[k] V₂ where
  toFun := f
  linear := f
  map_vadd' p v := f.map_add v p
#align linear_map.to_affine_map LinearMap.toAffineMap

@[simp]
theorem coe_toAffineMap : ⇑f.toAffineMap = f :=
  rfl
#align linear_map.coe_to_affine_map LinearMap.coe_toAffineMap

@[simp]
theorem toAffineMap_linear : f.toAffineMap.linear = f :=
  rfl
#align linear_map.to_affine_map_linear LinearMap.toAffineMap_linear

end LinearMap

namespace AffineMap

variable {k : Type _} {V1 : Type _} {P1 : Type _} {V2 : Type _} {P2 : Type _} {V3 : Type _}
  {P3 : Type _} {V4 : Type _} {P4 : Type _} [Ring k] [AddCommGroup V1] [Module k V1]
  [AffineSpace V1 P1] [AddCommGroup V2] [Module k V2] [AffineSpace V2 P2] [AddCommGroup V3]
  [Module k V3] [AffineSpace V3 P3] [AddCommGroup V4] [Module k V4] [AffineSpace V4 P4]

/-- Constructing an affine map and coercing back to a function
produces the same map. -/
@[simp]
theorem coe_mk (f : P1 → P2) (linear add) : ((mk f linear add : P1 →ᵃ[k] P2) : P1 → P2) = f :=
  rfl
#align affine_map.coe_mk AffineMap.coe_mk

/-- `to_fun` is the same as the result of coercing to a function. -/
@[simp]
theorem toFun_eq_coe (f : P1 →ᵃ[k] P2) : f.toFun = ⇑f :=
  rfl
#align affine_map.to_fun_eq_coe AffineMap.toFun_eq_coe

/-- An affine map on the result of adding a vector to a point produces
the same result as the linear map applied to that vector, added to the
affine map applied to that point. -/
@[simp]
theorem map_vadd (f : P1 →ᵃ[k] P2) (p : P1) (v : V1) : f (v +ᵥ p) = f.linear v +ᵥ f p :=
  f.map_vadd' p v
#align affine_map.map_vadd AffineMap.map_vadd

/-- The linear map on the result of subtracting two points is the
result of subtracting the result of the affine map on those two
points. -/
@[simp]
theorem linearMap_vsub (f : P1 →ᵃ[k] P2) (p1 p2 : P1) : f.linear (p1 -ᵥ p2) = f p1 -ᵥ f p2 := by
  conv_rhs => rw [← vsub_vadd p1 p2, map_vadd, vadd_vsub]
#align affine_map.linear_map_vsub AffineMap.linearMap_vsub

/-- Two affine maps are equal if they coerce to the same function. -/
@[ext]
theorem ext {f g : P1 →ᵃ[k] P2} (h : ∀ p, f p = g p) : f = g :=
  FunLike.ext _ _ h
#align affine_map.ext AffineMap.ext

theorem ext_iff {f g : P1 →ᵃ[k] P2} : f = g ↔ ∀ p, f p = g p :=
  ⟨fun h _ => h ▸ rfl, ext⟩
#align affine_map.ext_iff AffineMap.ext_iff

theorem coeFn_injective : @Function.Injective (P1 →ᵃ[k] P2) (P1 → P2) (⇑) :=
  FunLike.coe_injective
#align affine_map.coe_fn_injective AffineMap.coeFn_injective

protected theorem congr_arg (f : P1 →ᵃ[k] P2) {x y : P1} (h : x = y) : f x = f y :=
  congr_arg _ h
#align affine_map.congr_arg AffineMap.congr_arg

protected theorem congr_fun {f g : P1 →ᵃ[k] P2} (h : f = g) (x : P1) : f x = g x :=
  h ▸ rfl
#align affine_map.congr_fun AffineMap.congr_fun

variable (k P1)

/-- The constant function as an `AffineMap`. -/
def const (p : P2) : P1 →ᵃ[k] P2 where
  toFun := Function.const P1 p
  linear := 0
  map_vadd' _ _ := by simp
#align affine_map.const AffineMap.const

@[simp]
theorem coe_const (p : P2) : ⇑(const k P1 p) = Function.const P1 p :=
  rfl
#align affine_map.coe_const AffineMap.coe_const

-- Porting note: new theorem
@[simp]
theorem const_apply (p : P2) : (const k P1 p) q = p := rfl

@[simp]
theorem const_linear (p : P2) : (const k P1 p).linear = 0 :=
  rfl
#align affine_map.const_linear AffineMap.const_linear

variable {k P1}

theorem linear_eq_zero_iff_exists_const (f : P1 →ᵃ[k] P2) : f.linear = 0 ↔ ∃ q, f = const k P1 q :=
  by
  refine' ⟨fun h => _, fun h => _⟩
  · use f (Classical.arbitrary P1)
    ext
    rw [coe_const, Function.const_apply, ← @vsub_eq_zero_iff_eq V2, ← f.linearMap_vsub, h,
      LinearMap.zero_apply]
  · rcases h with ⟨q, rfl⟩
    exact const_linear k P1 q
#align affine_map.linear_eq_zero_iff_exists_const AffineMap.linear_eq_zero_iff_exists_const

instance nonempty : Nonempty (P1 →ᵃ[k] P2) :=
  (AddTorsor.Nonempty : Nonempty P2).elim fun p => ⟨const k P1 p⟩
#align affine_map.nonempty AffineMap.nonempty

/-- Construct an affine map by verifying the relation between the map and its linear part at one
base point. Namely, this function takes a map `f : P₁ → P₂`, a linear map `f' : V₁ →ₗ[k] V₂`, and
a point `p` such that for any other point `p'` we have `f p' = f' (p' -ᵥ p) +ᵥ f p`. -/
def mk' (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p : P1) (h : ∀ p' : P1, f p' = f' (p' -ᵥ p) +ᵥ f p) :
    P1 →ᵃ[k] P2 where
  toFun := f
  linear := f'
  map_vadd' p' v := by rw [h, h p', vadd_vsub_assoc, f'.map_add, vadd_vadd]
#align affine_map.mk' AffineMap.mk'

@[simp]
theorem coe_mk' (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p h) : ⇑(mk' f f' p h) = f :=
  rfl
#align affine_map.coe_mk' AffineMap.coe_mk'

@[simp]
theorem mk'_linear (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p h) : (mk' f f' p h).linear = f' :=
  rfl
#align affine_map.mk'_linear AffineMap.mk'_linear

section SMul

variable {R : Type _} [Monoid R] [DistribMulAction R V2] [SMulCommClass k R V2]
/-- The space of affine maps to a module inherits an `R`-action from the action on its codomain. -/
instance mulAction : MulAction R (P1 →ᵃ[k] V2) where
  -- porting note: `map_vadd` is `simp`, but we still have to pass it explicitly
  smul c f := ⟨c • ⇑f, c • f.linear, fun p v => by simp [smul_add, map_vadd f]⟩
  one_smul f := ext fun p => one_smul _ _
  mul_smul c₁ c₂ f := ext fun p => mul_smul _ _ _

@[simp, norm_cast]
theorem coe_smul (c : R) (f : P1 →ᵃ[k] V2) : ⇑(c • f) = c • ⇑f :=
  rfl
#align affine_map.coe_smul AffineMap.coe_smul

@[simp]
theorem smul_linear (t : R) (f : P1 →ᵃ[k] V2) : (t • f).linear = t • f.linear :=
  rfl
#align affine_map.smul_linear AffineMap.smul_linear

-- Porting note: Workaround for lean4#2074
instance [DistribMulAction Rᵐᵒᵖ V2] [IsCentralScalar R V2] : SMulCommClass k Rᵐᵒᵖ V2 :=
SMulCommClass.op_right

instance isCentralScalar [DistribMulAction Rᵐᵒᵖ V2] [IsCentralScalar R V2] :
  IsCentralScalar R (P1 →ᵃ[k] V2) where
    op_smul_eq_smul _r _x := ext fun _ => op_smul_eq_smul _ _

end SMul

instance : Zero (P1 →ᵃ[k] V2) where zero := ⟨0, 0, fun _ _ => (zero_vadd _ _).symm⟩

instance : Add (P1 →ᵃ[k] V2)
    where add f g := ⟨f + g, f.linear + g.linear,
      -- porting note: `simp` needs lemmas to be expressions
      fun p v => by simp [add_add_add_comm, (map_vadd)]⟩

instance : Sub (P1 →ᵃ[k] V2)
    where sub f g := ⟨f - g, f.linear - g.linear,
      -- porting note: `simp` needs lemmas to be expressions
      fun p v => by simp [sub_add_sub_comm, (map_vadd)]⟩

instance : Neg (P1 →ᵃ[k] V2)
    where neg f := ⟨-f, -f.linear, fun p v => by simp [add_comm, map_vadd f]⟩

@[simp, norm_cast]
theorem coe_zero : ⇑(0 : P1 →ᵃ[k] V2) = 0 :=
  rfl
#align affine_map.coe_zero AffineMap.coe_zero

@[simp, norm_cast]
theorem coe_add (f g : P1 →ᵃ[k] V2) : ⇑(f + g) = f + g :=
  rfl
#align affine_map.coe_add AffineMap.coe_add

@[simp, norm_cast]
theorem coe_neg (f : P1 →ᵃ[k] V2) : ⇑(-f) = -f :=
  rfl
#align affine_map.coe_neg AffineMap.coe_neg

@[simp, norm_cast]
theorem coe_sub (f g : P1 →ᵃ[k] V2) : ⇑(f - g) = f - g :=
  rfl
#align affine_map.coe_sub AffineMap.coe_sub

@[simp]
theorem zero_linear : (0 : P1 →ᵃ[k] V2).linear = 0 :=
  rfl
#align affine_map.zero_linear AffineMap.zero_linear

@[simp]
theorem add_linear (f g : P1 →ᵃ[k] V2) : (f + g).linear = f.linear + g.linear :=
  rfl
#align affine_map.add_linear AffineMap.add_linear

@[simp]
theorem sub_linear (f g : P1 →ᵃ[k] V2) : (f - g).linear = f.linear - g.linear :=
  rfl
#align affine_map.sub_linear AffineMap.sub_linear

@[simp]
theorem neg_linear (f : P1 →ᵃ[k] V2) : (-f).linear = -f.linear :=
  rfl
#align affine_map.neg_linear AffineMap.neg_linear

/-- The set of affine maps to a vector space is an additive commutative group. -/
instance : AddCommGroup (P1 →ᵃ[k] V2) :=
  coeFn_injective.addCommGroup _ coe_zero coe_add coe_neg coe_sub (fun _ _ => coe_smul _ _)
    fun _ _ => coe_smul _ _

/-- The space of affine maps from `P1` to `P2` is an affine space over the space of affine maps
from `P1` to the vector space `V2` corresponding to `P2`. -/
instance : AffineSpace (P1 →ᵃ[k] V2) (P1 →ᵃ[k] P2) where
  vadd f g :=
    ⟨fun p => f p +ᵥ g p, f.linear + g.linear,
      -- porting note: `simp` needs lemmas to be expressions
      fun p v => by simp [vadd_vadd, add_right_comm, (map_vadd)]⟩
  zero_vadd f := ext fun p => zero_vadd _ (f p)
  add_vadd f₁ f₂ f₃ := ext fun p => add_vadd (f₁ p) (f₂ p) (f₃ p)
  vsub f g :=
    ⟨fun p => f p -ᵥ g p, f.linear - g.linear, fun p v => by
      -- porting note: `simp` needs lemmas to be expressions
      simp [(map_vadd), (vsub_vadd_eq_vsub_sub), (vadd_vsub_assoc),
        add_sub, sub_add_eq_add_sub]⟩
  vsub_vadd' f g := ext fun p => vsub_vadd (f p) (g p)
  vadd_vsub' f g := ext fun p => vadd_vsub (f p) (g p)

@[simp]
theorem vadd_apply (f : P1 →ᵃ[k] V2) (g : P1 →ᵃ[k] P2) (p : P1) : (f +ᵥ g) p = f p +ᵥ g p :=
  rfl
#align affine_map.vadd_apply AffineMap.vadd_apply

@[simp]
theorem vsub_apply (f g : P1 →ᵃ[k] P2) (p : P1) : (f -ᵥ g : P1 →ᵃ[k] V2) p = f p -ᵥ g p :=
  rfl
#align affine_map.vsub_apply AffineMap.vsub_apply

/-- `Prod.fst` as an `AffineMap`. -/
def fst : P1 × P2 →ᵃ[k] P1 where
  toFun := Prod.fst
  linear := LinearMap.fst k V1 V2
  map_vadd' _ _ := rfl
#align affine_map.fst AffineMap.fst

@[simp]
theorem coe_fst : ⇑(fst : P1 × P2 →ᵃ[k] P1) = Prod.fst :=
  rfl
#align affine_map.coe_fst AffineMap.coe_fst

@[simp]
theorem fst_linear : (fst : P1 × P2 →ᵃ[k] P1).linear = LinearMap.fst k V1 V2 :=
  rfl
#align affine_map.fst_linear AffineMap.fst_linear

/-- `Prod.snd` as an `AffineMap`. -/
def snd : P1 × P2 →ᵃ[k] P2 where
  toFun := Prod.snd
  linear := LinearMap.snd k V1 V2
  map_vadd' _ _ := rfl
#align affine_map.snd AffineMap.snd

@[simp]
theorem coe_snd : ⇑(snd : P1 × P2 →ᵃ[k] P2) = Prod.snd :=
  rfl
#align affine_map.coe_snd AffineMap.coe_snd

@[simp]
theorem snd_linear : (snd : P1 × P2 →ᵃ[k] P2).linear = LinearMap.snd k V1 V2 :=
  rfl
#align affine_map.snd_linear AffineMap.snd_linear

variable (k P1)
/-- Identity map as an affine map. -/
nonrec def id : P1 →ᵃ[k] P1 where
  toFun := id
  linear := LinearMap.id
  map_vadd' _ _ := rfl
#align affine_map.id AffineMap.id

/-- The identity affine map acts as the identity. -/
@[simp]
theorem coe_id : ⇑(id k P1) = _root_.id :=
  rfl
#align affine_map.coe_id AffineMap.coe_id

@[simp]
theorem id_linear : (id k P1).linear = LinearMap.id :=
  rfl
#align affine_map.id_linear AffineMap.id_linear

variable {P1}

/-- The identity affine map acts as the identity. -/
theorem id_apply (p : P1) : id k P1 p = p :=
  rfl
#align affine_map.id_apply AffineMap.id_apply

variable {k}

instance : Inhabited (P1 →ᵃ[k] P1) :=
  ⟨id k P1⟩

/-- Composition of affine maps. -/
def comp (f : P2 →ᵃ[k] P3) (g : P1 →ᵃ[k] P2) : P1 →ᵃ[k] P3 where
  toFun := f ∘ g
  linear := f.linear.comp g.linear
  map_vadd' := by
    intro p v
    rw [Function.comp_apply, g.map_vadd, f.map_vadd]
    rfl
#align affine_map.comp AffineMap.comp

/-- Composition of affine maps acts as applying the two functions. -/
@[simp]
theorem coe_comp (f : P2 →ᵃ[k] P3) (g : P1 →ᵃ[k] P2) : ⇑(f.comp g) = f ∘ g :=
  rfl
#align affine_map.coe_comp AffineMap.coe_comp

/-- Composition of affine maps acts as applying the two functions. -/
theorem comp_apply (f : P2 →ᵃ[k] P3) (g : P1 →ᵃ[k] P2) (p : P1) : f.comp g p = f (g p) :=
  rfl
#align affine_map.comp_apply AffineMap.comp_apply

@[simp]
theorem comp_id (f : P1 →ᵃ[k] P2) : f.comp (id k P1) = f :=
  ext fun _ => rfl
#align affine_map.comp_id AffineMap.comp_id

@[simp]
theorem id_comp (f : P1 →ᵃ[k] P2) : (id k P2).comp f = f :=
  ext fun _ => rfl
#align affine_map.id_comp AffineMap.id_comp

theorem comp_assoc (f₃₄ : P3 →ᵃ[k] P4) (f₂₃ : P2 →ᵃ[k] P3) (f₁₂ : P1 →ᵃ[k] P2) :
    (f₃₄.comp f₂₃).comp f₁₂ = f₃₄.comp (f₂₃.comp f₁₂) :=
  rfl
#align affine_map.comp_assoc AffineMap.comp_assoc

instance : Monoid (P1 →ᵃ[k] P1) where
  one := id k P1
  mul := comp
  one_mul := id_comp
  mul_one := comp_id
  mul_assoc := comp_assoc

@[simp]
theorem coe_mul (f g : P1 →ᵃ[k] P1) : ⇑(f * g) = f ∘ g :=
  rfl
#align affine_map.coe_mul AffineMap.coe_mul

@[simp]
theorem coe_one : ⇑(1 : P1 →ᵃ[k] P1) = _root_.id :=
  rfl
#align affine_map.coe_one AffineMap.coe_one

/-- `AffineMap.linear` on endomorphisms is a `MonoidHom`. -/
@[simps]
def linearHom : (P1 →ᵃ[k] P1) →* V1 →ₗ[k] V1 where
  toFun := linear
  map_one' := rfl
  map_mul' _ _ := rfl
#align affine_map.linear_hom AffineMap.linearHom

@[simp]
theorem linear_injective_iff (f : P1 →ᵃ[k] P2) :
    Function.Injective f.linear ↔ Function.Injective f := by
  obtain ⟨p⟩ := (inferInstance : Nonempty P1)
  have h : ⇑f.linear = (Equiv.vaddConst (f p)).symm ∘ f ∘ Equiv.vaddConst p :=
    by
    ext v
    simp [f.map_vadd, vadd_vsub_assoc]
  rw [h, Equiv.comp_injective, Equiv.injective_comp]
#align affine_map.linear_injective_iff AffineMap.linear_injective_iff

@[simp]
theorem linear_surjective_iff (f : P1 →ᵃ[k] P2) :
    Function.Surjective f.linear ↔ Function.Surjective f := by
  obtain ⟨p⟩ := (inferInstance : Nonempty P1)
  have h : ⇑f.linear = (Equiv.vaddConst (f p)).symm ∘ f ∘ Equiv.vaddConst p :=
    by
    ext v
    simp [f.map_vadd, vadd_vsub_assoc]
  rw [h, Equiv.comp_surjective, Equiv.surjective_comp]
#align affine_map.linear_surjective_iff AffineMap.linear_surjective_iff

@[simp]
theorem linear_bijective_iff (f : P1 →ᵃ[k] P2) :
    Function.Bijective f.linear ↔ Function.Bijective f :=
  and_congr f.linear_injective_iff f.linear_surjective_iff
#align affine_map.linear_bijective_iff AffineMap.linear_bijective_iff

theorem image_vsub_image {s t : Set P1} (f : P1 →ᵃ[k] P2) :
    f '' s -ᵥ f '' t = f.linear '' (s -ᵥ t) := by
  ext v
  -- porting note: `simp` needs `Set.mem_vsub` to be an expression
  simp only [(Set.mem_vsub), Set.mem_image,
    exists_exists_and_eq_and, exists_and_left, ← f.linearMap_vsub]
  constructor
  · rintro ⟨x, hx, y, hy, hv⟩
    exact ⟨x -ᵥ y, ⟨x, hx, y, hy, rfl⟩, hv⟩
  · rintro ⟨-, ⟨x, hx, y, hy, rfl⟩, rfl⟩
    exact ⟨x, hx, y, hy, rfl⟩
#align affine_map.image_vsub_image AffineMap.image_vsub_image

/-! ### Definition of `AffineMap.lineMap` and lemmas about it -/

-- Porting note: Workaround for lean4#2074
instance : Module k k := Semiring.toModule

/-- The affine map from `k` to `P1` sending `0` to `p₀` and `1` to `p₁`. -/
def lineMap (p₀ p₁ : P1) : k →ᵃ[k] P1 :=
  ((LinearMap.id : k →ₗ[k] k).smulRight (p₁ -ᵥ p₀)).toAffineMap +ᵥ const k k p₀
#align affine_map.line_map AffineMap.lineMap

theorem coe_lineMap (p₀ p₁ : P1) : (lineMap p₀ p₁ : k → P1) = fun c => c • (p₁ -ᵥ p₀) +ᵥ p₀ :=
  rfl
#align affine_map.coe_line_map AffineMap.coe_lineMap

theorem lineMap_apply (p₀ p₁ : P1) (c : k) : lineMap p₀ p₁ c = c • (p₁ -ᵥ p₀) +ᵥ p₀ :=
  rfl
#align affine_map.line_map_apply AffineMap.lineMap_apply

theorem lineMap_apply_module' (p₀ p₁ : V1) (c : k) : lineMap p₀ p₁ c = c • (p₁ - p₀) + p₀ :=
  rfl
#align affine_map.line_map_apply_module' AffineMap.lineMap_apply_module'

theorem lineMap_apply_module (p₀ p₁ : V1) (c : k) : lineMap p₀ p₁ c = (1 - c) • p₀ + c • p₁ := by
  simp [lineMap_apply_module', smul_sub, sub_smul]; abel
#align affine_map.line_map_apply_module AffineMap.lineMap_apply_module

theorem lineMap_apply_ring' (a b c : k) : lineMap a b c = c * (b - a) + a :=
  rfl
#align affine_map.line_map_apply_ring' AffineMap.lineMap_apply_ring'

theorem lineMap_apply_ring (a b c : k) : lineMap a b c = (1 - c) * a + c * b :=
  lineMap_apply_module a b c
#align affine_map.line_map_apply_ring AffineMap.lineMap_apply_ring

theorem lineMap_vadd_apply (p : P1) (v : V1) (c : k) : lineMap p (v +ᵥ p) c = c • v +ᵥ p := by
  rw [lineMap_apply, vadd_vsub]
#align affine_map.line_map_vadd_apply AffineMap.lineMap_vadd_apply

@[simp]
theorem lineMap_linear (p₀ p₁ : P1) :
    (lineMap p₀ p₁ : k →ᵃ[k] P1).linear = LinearMap.id.smulRight (p₁ -ᵥ p₀) :=
  add_zero _
#align affine_map.line_map_linear AffineMap.lineMap_linear

theorem lineMap_same_apply (p : P1) (c : k) : lineMap p p c = p := by
  -- porting note: `simp` needs lemmas to be expressions
  simp [(lineMap_apply), (vsub_self)]
#align affine_map.line_map_same_apply AffineMap.lineMap_same_apply

@[simp]
theorem lineMap_same (p : P1) : lineMap p p = const k k p :=
  ext <| lineMap_same_apply p
#align affine_map.line_map_same AffineMap.lineMap_same

@[simp]
theorem lineMap_apply_zero (p₀ p₁ : P1) : lineMap p₀ p₁ (0 : k) = p₀ := by
  -- porting note: `simp` needs lemmas to be expressions
  simp [(lineMap_apply)]
#align affine_map.line_map_apply_zero AffineMap.lineMap_apply_zero

@[simp]
theorem lineMap_apply_one (p₀ p₁ : P1) : lineMap p₀ p₁ (1 : k) = p₁ := by
  -- porting note: `simp` needs lemmas to be expressions
  simp [(lineMap_apply), (vsub_vadd)]
#align affine_map.line_map_apply_one AffineMap.lineMap_apply_one

@[simp]
theorem lineMap_eq_lineMap_iff [NoZeroSMulDivisors k V1] {p₀ p₁ : P1} {c₁ c₂ : k} :
    lineMap p₀ p₁ c₁ = lineMap p₀ p₁ c₂ ↔ p₀ = p₁ ∨ c₁ = c₂ := by
  rw [lineMap_apply, lineMap_apply, ← @vsub_eq_zero_iff_eq V1, vadd_vsub_vadd_cancel_right, ←
    sub_smul, smul_eq_zero, sub_eq_zero, vsub_eq_zero_iff_eq, or_comm, eq_comm]
#align affine_map.line_map_eq_line_map_iff AffineMap.lineMap_eq_lineMap_iff

@[simp]
theorem lineMap_eq_left_iff [NoZeroSMulDivisors k V1] {p₀ p₁ : P1} {c : k} :
    lineMap p₀ p₁ c = p₀ ↔ p₀ = p₁ ∨ c = 0 := by
  rw [← @lineMap_eq_lineMap_iff k V1, lineMap_apply_zero]
#align affine_map.line_map_eq_left_iff AffineMap.lineMap_eq_left_iff

@[simp]
theorem lineMap_eq_right_iff [NoZeroSMulDivisors k V1] {p₀ p₁ : P1} {c : k} :
    lineMap p₀ p₁ c = p₁ ↔ p₀ = p₁ ∨ c = 1 := by
  rw [← @lineMap_eq_lineMap_iff k V1, lineMap_apply_one]
#align affine_map.line_map_eq_right_iff AffineMap.lineMap_eq_right_iff

variable (k)

theorem lineMap_injective [NoZeroSMulDivisors k V1] {p₀ p₁ : P1} (h : p₀ ≠ p₁) :
    Function.Injective (lineMap p₀ p₁ : k → P1) := fun _c₁ _c₂ hc =>
  (lineMap_eq_lineMap_iff.mp hc).resolve_left h
#align affine_map.line_map_injective AffineMap.lineMap_injective

variable {k}

@[simp]
theorem apply_lineMap (f : P1 →ᵃ[k] P2) (p₀ p₁ : P1) (c : k) :
    f (lineMap p₀ p₁ c) = lineMap (f p₀) (f p₁) c := by
  -- porting note: `simp` needs lemmas to be expressions
  simp [(lineMap_apply), (map_vadd), (linearMap_vsub)]
#align affine_map.apply_line_map AffineMap.apply_lineMap

@[simp]
theorem comp_lineMap (f : P1 →ᵃ[k] P2) (p₀ p₁ : P1) :
    f.comp (lineMap p₀ p₁) = lineMap (f p₀) (f p₁) :=
  ext <| f.apply_lineMap p₀ p₁
#align affine_map.comp_line_map AffineMap.comp_lineMap

@[simp]
theorem fst_lineMap (p₀ p₁ : P1 × P2) (c : k) : (lineMap p₀ p₁ c).1 = lineMap p₀.1 p₁.1 c :=
  fst.apply_lineMap p₀ p₁ c
#align affine_map.fst_line_map AffineMap.fst_lineMap

@[simp]
theorem snd_lineMap (p₀ p₁ : P1 × P2) (c : k) : (lineMap p₀ p₁ c).2 = lineMap p₀.2 p₁.2 c :=
  snd.apply_lineMap p₀ p₁ c
#align affine_map.snd_line_map AffineMap.snd_lineMap

theorem lineMap_symm (p₀ p₁ : P1) :
    lineMap p₀ p₁ = (lineMap p₁ p₀).comp (lineMap (1 : k) (0 : k)) := by
  rw [comp_lineMap]
  simp
#align affine_map.line_map_symm AffineMap.lineMap_symm

theorem lineMap_apply_one_sub (p₀ p₁ : P1) (c : k) : lineMap p₀ p₁ (1 - c) = lineMap p₁ p₀ c := by
  rw [lineMap_symm p₀, comp_apply]
  congr
  simp [lineMap_apply]
#align affine_map.line_map_apply_one_sub AffineMap.lineMap_apply_one_sub

@[simp]
theorem lineMap_vsub_left (p₀ p₁ : P1) (c : k) : lineMap p₀ p₁ c -ᵥ p₀ = c • (p₁ -ᵥ p₀) :=
  vadd_vsub _ _
#align affine_map.line_map_vsub_left AffineMap.lineMap_vsub_left

@[simp]
theorem left_vsub_lineMap (p₀ p₁ : P1) (c : k) : p₀ -ᵥ lineMap p₀ p₁ c = c • (p₀ -ᵥ p₁) := by
  rw [← neg_vsub_eq_vsub_rev, lineMap_vsub_left, ← smul_neg, neg_vsub_eq_vsub_rev]
#align affine_map.left_vsub_line_map AffineMap.left_vsub_lineMap

@[simp]
theorem lineMap_vsub_right (p₀ p₁ : P1) (c : k) : lineMap p₀ p₁ c -ᵥ p₁ = (1 - c) • (p₀ -ᵥ p₁) := by
  rw [← lineMap_apply_one_sub, lineMap_vsub_left]
#align affine_map.line_map_vsub_right AffineMap.lineMap_vsub_right

@[simp]
theorem right_vsub_lineMap (p₀ p₁ : P1) (c : k) : p₁ -ᵥ lineMap p₀ p₁ c = (1 - c) • (p₁ -ᵥ p₀) := by
  rw [← lineMap_apply_one_sub, left_vsub_lineMap]
#align affine_map.right_vsub_line_map AffineMap.right_vsub_lineMap

theorem lineMap_vadd_lineMap (v₁ v₂ : V1) (p₁ p₂ : P1) (c : k) :
    lineMap v₁ v₂ c +ᵥ lineMap p₁ p₂ c = lineMap (v₁ +ᵥ p₁) (v₂ +ᵥ p₂) c :=
  ((fst : V1 × P1 →ᵃ[k] V1) +ᵥ (snd : V1 × P1 →ᵃ[k] P1)).apply_lineMap (v₁, p₁) (v₂, p₂) c
#align affine_map.line_map_vadd_line_map AffineMap.lineMap_vadd_lineMap

theorem lineMap_vsub_lineMap (p₁ p₂ p₃ p₄ : P1) (c : k) :
    lineMap p₁ p₂ c -ᵥ lineMap p₃ p₄ c = lineMap (p₁ -ᵥ p₃) (p₂ -ᵥ p₄) c :=
  ((fst : P1 × P1 →ᵃ[k] P1) -ᵥ (snd : P1 × P1 →ᵃ[k] P1)).apply_lineMap (_, _) (_, _) c
#align affine_map.line_map_vsub_line_map AffineMap.lineMap_vsub_lineMap

/-- Decomposition of an affine map in the special case when the point space and vector space
are the same. -/
theorem decomp (f : V1 →ᵃ[k] V2) : (f : V1 → V2) = ⇑f.linear + fun _ => f 0 := by
  ext x
  calc
    f x = f.linear x +ᵥ f 0 := by rw [← f.map_vadd, vadd_eq_add, add_zero]
    _ = (f.linear + fun _ : V1 => f 0) x := rfl

#align affine_map.decomp AffineMap.decomp

/-- Decomposition of an affine map in the special case when the point space and vector space
are the same. -/
theorem decomp' (f : V1 →ᵃ[k] V2) : (f.linear : V1 → V2) = ⇑f - fun _ => f 0 := by
  rw [decomp]
  simp only [LinearMap.map_zero, Pi.add_apply, add_sub_cancel, zero_add]
#align affine_map.decomp' AffineMap.decomp'

theorem image_uIcc {k : Type _} [LinearOrderedField k] (f : k →ᵃ[k] k) (a b : k) :
    f '' Set.uIcc a b = Set.uIcc (f a) (f b) := by
  have : ⇑f = (fun x => x + f 0) ∘ fun x => x * (f 1 - f 0) := by
    ext x
    change f x = x • (f 1 -ᵥ f 0) +ᵥ f 0
    rw [← f.linearMap_vsub, ← f.linear.map_smul, ← f.map_vadd]
    simp only [vsub_eq_sub, add_zero, mul_one, vadd_eq_add, sub_zero, smul_eq_mul]
  rw [this, Set.image_comp]
  simp only [Set.image_add_const_uIcc, Set.image_mul_const_uIcc, Function.comp_apply]
#align affine_map.image_uIcc AffineMap.image_uIcc

section

variable {ι : Type _} {V : ∀ _ : ι, Type _} {P : ∀ _ : ι, Type _} [∀ i, AddCommGroup (V i)]
  [∀ i, Module k (V i)] [∀ i, AddTorsor (V i) (P i)]

-- Workaround for lean4#2074
instance : AffineSpace (∀ i : ι, (V i)) (∀ i : ι, P i) := Pi.instAddTorsorForAllForAllAddGroup

/-- Evaluation at a point as an affine map. -/
def proj (i : ι) : (∀ i : ι, P i) →ᵃ[k] P i where
  toFun f := f i
  linear := @LinearMap.proj k ι _ V _ _ i
  map_vadd' _ _ := rfl
#align affine_map.proj AffineMap.proj

@[simp]
theorem proj_apply (i : ι) (f : ∀ i, P i) : @proj k _ ι V P _ _ _ i f = f i :=
  rfl
#align affine_map.proj_apply AffineMap.proj_apply

@[simp]
theorem proj_linear (i : ι) : (@proj k _ ι V P _ _ _ i).linear = @LinearMap.proj k ι _ V _ _ i :=
  rfl
#align affine_map.proj_linear AffineMap.proj_linear

theorem pi_lineMap_apply (f g : ∀ i, P i) (c : k) (i : ι) :
    lineMap f g c i = lineMap (f i) (g i) c :=
  (proj i : (∀ i, P i) →ᵃ[k] P i).apply_lineMap f g c
#align affine_map.pi_line_map_apply AffineMap.pi_lineMap_apply

end

end AffineMap

namespace AffineMap

variable {R k V1 P1 V2 : Type _}

section Ring

variable [Ring k] [AddCommGroup V1] [AffineSpace V1 P1] [AddCommGroup V2]

variable [Module k V1] [Module k V2]

section DistribMulAction

variable [Monoid R] [DistribMulAction R V2] [SMulCommClass k R V2]

/-- The space of affine maps to a module inherits an `R`-action from the action on its codomain. -/
instance distribMulAction : DistribMulAction R (P1 →ᵃ[k] V2) where
  smul_add _c _f _g := ext fun _p => smul_add _ _ _
  smul_zero _c := ext fun _p => smul_zero _

end DistribMulAction

section Module

variable [Semiring R] [Module R V2] [SMulCommClass k R V2]

/-- The space of affine maps taking values in an `R`-module is an `R`-module. -/
instance : Module R (P1 →ᵃ[k] V2) :=
  { AffineMap.distribMulAction with
    smul := (· • ·)
    add_smul := fun _ _ _ => ext fun _ => add_smul _ _ _
    zero_smul := fun _ => ext fun _ => zero_smul _ _ }

variable (R)

-- Porting note: Workarounds for lean4#2074
instance : AddCommMonoid (V1 →ₗ[k] V2) := LinearMap.addCommMonoid
instance : AddCommMonoid (V2 × (V1 →ₗ[k] V2)) := Prod.instAddCommMonoidSum
instance : Module R (V1 →ₗ[k] V2) := LinearMap.instModuleLinearMapAddCommMonoid
instance : Module R (V2 × (V1 →ₗ[k] V2)) := Prod.module

/-- The space of affine maps between two modules is linearly equivalent to the product of the
domain with the space of linear maps, by taking the value of the affine map at `(0 : V1)` and the
linear part.

See note [bundled maps over different rings]-/
@[simps]
def toConstProdLinearMap : (V1 →ᵃ[k] V2) ≃ₗ[R] V2 × (V1 →ₗ[k] V2) where
  toFun f := ⟨f 0, f.linear⟩
  invFun p := p.2.toAffineMap + const k V1 p.1
  left_inv f := by
    ext
    rw [f.decomp]
    simp [const_apply _ _]  -- porting note: `simp` needs `_`s to use this lemma
  right_inv := by
    rintro ⟨v, f⟩
    ext <;> simp [const_apply _ _, const_linear _ _]  -- porting note: `simp` needs `_`s
  map_add' := by simp
  map_smul' := by simp
#align affine_map.to_const_prod_linear_map AffineMap.toConstProdLinearMap

end Module

end Ring

section CommRing

variable [CommRing k] [AddCommGroup V1] [AffineSpace V1 P1] [AddCommGroup V2]

variable [Module k V1] [Module k V2]

/-- `homothety c r` is the homothety (also known as dilation) about `c` with scale factor `r`. -/
def homothety (c : P1) (r : k) : P1 →ᵃ[k] P1 :=
  r • (id k P1 -ᵥ const k P1 c) +ᵥ const k P1 c
#align affine_map.homothety AffineMap.homothety

theorem homothety_def (c : P1) (r : k) :
    homothety c r = r • (id k P1 -ᵥ const k P1 c) +ᵥ const k P1 c :=
  rfl
#align affine_map.homothety_def AffineMap.homothety_def

theorem homothety_apply (c : P1) (r : k) (p : P1) : homothety c r p = r • (p -ᵥ c : V1) +ᵥ c :=
  rfl
#align affine_map.homothety_apply AffineMap.homothety_apply

theorem homothety_eq_lineMap (c : P1) (r : k) (p : P1) : homothety c r p = lineMap c p r :=
  rfl
#align affine_map.homothety_eq_line_map AffineMap.homothety_eq_lineMap

@[simp]
theorem homothety_one (c : P1) : homothety c (1 : k) = id k P1 := by
  ext p
  simp [homothety_apply]
#align affine_map.homothety_one AffineMap.homothety_one

@[simp]
theorem homothety_apply_same (c : P1) (r : k) : homothety c r c = c :=
  lineMap_same_apply c r
#align affine_map.homothety_apply_same AffineMap.homothety_apply_same

theorem homothety_mul_apply (c : P1) (r₁ r₂ : k) (p : P1) :
    homothety c (r₁ * r₂) p = homothety c r₁ (homothety c r₂ p) := by
  simp only [homothety_apply, mul_smul, vadd_vsub]
#align affine_map.homothety_mul_apply AffineMap.homothety_mul_apply

theorem homothety_mul (c : P1) (r₁ r₂ : k) :
    homothety c (r₁ * r₂) = (homothety c r₁).comp (homothety c r₂) :=
  ext <| homothety_mul_apply c r₁ r₂
#align affine_map.homothety_mul AffineMap.homothety_mul

@[simp]
theorem homothety_zero (c : P1) : homothety c (0 : k) = const k P1 c := by
  ext p
  simp [homothety_apply]
#align affine_map.homothety_zero AffineMap.homothety_zero

@[simp]
theorem homothety_add (c : P1) (r₁ r₂ : k) :
    homothety c (r₁ + r₂) = r₁ • (id k P1 -ᵥ const k P1 c) +ᵥ homothety c r₂ := by
  simp only [homothety_def, add_smul, vadd_vadd]
#align affine_map.homothety_add AffineMap.homothety_add

/-- `homothety` as a multiplicative monoid homomorphism. -/
def homothetyHom (c : P1) : k →* P1 →ᵃ[k] P1 where
  toFun := homothety c
  map_one' := homothety_one c
  map_mul' := homothety_mul c
#align affine_map.homothety_hom AffineMap.homothetyHom

@[simp]
theorem coe_homothetyHom (c : P1) : ⇑(homothetyHom c : k →* _) = homothety c :=
  rfl
#align affine_map.coe_homothety_hom AffineMap.coe_homothetyHom

/-- `homothety` as an affine map. -/
def homothetyAffine (c : P1) : k →ᵃ[k] P1 →ᵃ[k] P1 :=
  ⟨homothety c, (LinearMap.lsmul k _).flip (id k P1 -ᵥ const k P1 c),
    Function.swap (homothety_add c)⟩
#align affine_map.homothety_affine AffineMap.homothetyAffine

@[simp]

end CommRing

end AffineMap

section

variable {𝕜 E F : Type _} [Ring 𝕜] [AddCommGroup E] [AddCommGroup F] [Module 𝕜 E] [Module 𝕜 F]

/-- Applying an affine map to an affine combination of two points yields an affine combination of
the images. -/
theorem Convex.combo_affine_apply {x y : E} {a b : 𝕜} {f : E →ᵃ[𝕜] F} (h : a + b = 1) :
    f (a • x + b • y) = a • f x + b • f y := by
  simp only [Convex.combo_eq_smul_sub_add h, ← vsub_eq_sub]
  exact f.apply_lineMap _ _ _
#align convex.combo_affine_apply Convex.combo_affine_apply

end


/-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import analysis.calculus.cont_diff
import geometry.manifold.charted_space

/-!
# Smooth manifolds (possibly with boundary or corners)

A smooth manifold is a manifold modelled on a normed vector space, or a subset like a
half-space (to get manifolds with boundaries) for which the changes of coordinates are smooth maps.
We define a model with corners as a map `I : H → E` embedding nicely the topological space `H` in
the vector space `E` (or more precisely as a structure containing all the relevant properties).
Given such a model with corners `I` on `(E, H)`, we define the groupoid of local
homeomorphisms of `H` which are smooth when read in `E` (for any regularity `n : with_top ℕ`).
With this groupoid at hand and the general machinery of charted spaces, we thus get the notion
of `C^n` manifold with respect to any model with corners `I` on `(E, H)`. We also introduce a
specific type class for `C^∞` manifolds as these are the most commonly used.

## Main definitions

* `model_with_corners 𝕜 E H` :
  a structure containing informations on the way a space `H` embeds in a
  model vector space E over the field `𝕜`. This is all that is needed to
  define a smooth manifold with model space `H`, and model vector space `E`.
* `model_with_corners_self 𝕜 E` :
  trivial model with corners structure on the space `E` embedded in itself by the identity.
* `cont_diff_groupoid n I` :
  when `I` is a model with corners on `(𝕜, E, H)`, this is the groupoid of local homeos of `H`
  which are of class `C^n` over the normed field `𝕜`, when read in `E`.
* `smooth_manifold_with_corners I M` :
  a type class saying that the charted space `M`, modelled on the space `H`, has `C^∞` changes of
  coordinates with respect to the model with corners `I` on `(𝕜, E, H)`. This type class is just
  a shortcut for `has_groupoid M (cont_diff_groupoid ∞ I)`.
* `ext_chart_at I x`:
  in a smooth manifold with corners with the model `I` on `(E, H)`, the charts take values in `H`,
  but often we may want to use their `E`-valued version, obtained by composing the charts with `I`.
  Since the target is in general not open, we can not register them as local homeomorphisms, but
  we register them as local equivs. `ext_chart_at I x` is the canonical such local equiv around `x`.

As specific examples of models with corners, we define (in the file `real_instances.lean`)
* `model_with_corners_self ℝ (euclidean_space (fin n))` for the model space used to define
  `n`-dimensional real manifolds without boundary (with notation `𝓡 n` in the locale `manifold`)
* `model_with_corners ℝ (euclidean_space (fin n)) (euclidean_half_space n)` for the model space
  used to define `n`-dimensional real manifolds with boundary (with notation `𝓡∂ n` in the locale
  `manifold`)
* `model_with_corners ℝ (euclidean_space (fin n)) (euclidean_quadrant n)` for the model space used
  to define `n`-dimensional real manifolds with corners

With these definitions at hand, to invoke an `n`-dimensional real manifold without boundary,
one could use

  `variables {n : ℕ} {M : Type*} [topological_space M] [charted_space (euclidean_space (fin n)) M]
   [smooth_manifold_with_corners (𝓡 n) M]`.

However, this is not the recommended way: a theorem proved using this assumption would not apply
for instance to the tangent space of such a manifold, which is modelled on
`(euclidean_space (fin n)) × (euclidean_space (fin n))` and not on `euclidean_space (fin (2 * n))`!
In the same way, it would not apply to product manifolds, modelled on
`(euclidean_space (fin n)) × (euclidean_space (fin m))`.
The right invocation does not focus on one specific construction, but on all constructions sharing
the right properties, like

  `variables {E : Type*} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E]
  {I : model_with_corners ℝ E E} [I.boundaryless]
  {M : Type*} [topological_space M] [charted_space E M] [smooth_manifold_with_corners I M]`

Here, `I.boundaryless` is a typeclass property ensuring that there is no boundary (this is for
instance the case for `model_with_corners_self`, or products of these). Note that one could consider
as a natural assumption to only use the trivial model with corners `model_with_corners_self ℝ E`,
but again in product manifolds the natural model with corners will not be this one but the product
one (and they are not defeq as `(λp : E × F, (p.1, p.2))` is not defeq to the identity). So, it is
important to use the above incantation to maximize the applicability of theorems.

## Implementation notes

We want to talk about manifolds modelled on a vector space, but also on manifolds with
boundary, modelled on a half space (or even manifolds with corners). For the latter examples,
we still want to define smooth functions, tangent bundles, and so on. As smooth functions are
well defined on vector spaces or subsets of these, one could take for model space a subtype of a
vector space. With the drawback that the whole vector space itself (which is the most basic
example) is not directly a subtype of itself: the inclusion of `univ : set E` in `set E` would
show up in the definition, instead of `id`.

A good abstraction covering both cases it to have a vector
space `E` (with basic example the Euclidean space), a model space `H` (with basic example the upper
half space), and an embedding of `H` into `E` (which can be the identity for `H = E`, or
`subtype.val` for manifolds with corners). We say that the pair `(E, H)` with their embedding is a
model with corners, and we encompass all the relevant properties (in particular the fact that the
image of `H` in `E` should have unique differentials) in the definition of `model_with_corners`.

We concentrate on `C^∞` manifolds: all the definitions work equally well for `C^n` manifolds, but
later on it is a pain to carry all over the smoothness parameter, especially when one wants to deal
with `C^k` functions as there would be additional conditions `k ≤ n` everywhere. Since one deals
almost all the time with `C^∞` (or analytic) manifolds, this seems to be a reasonable choice that
one could revisit later if needed. `C^k` manifolds are still available, but they should be called
using `has_groupoid M (cont_diff_groupoid k I)` where `I` is the model with corners.

I have considered using the model with corners `I` as a typeclass argument, possibly `out_param`, to
get lighter notations later on, but it did not turn out right, as on `E × F` there are two natural
model with corners, the trivial (identity) one, and the product one, and they are not defeq and one
needs to indicate to Lean which one we want to use.
This means that when talking on objects on manifolds one will most often need to specify the model
with corners one is using. For instance, the tangent bundle will be `tangent_bundle I M` and the
derivative will be `mfderiv I I' f`, instead of the more natural notations `tangent_bundle 𝕜 M` and
`mfderiv 𝕜 f` (the field has to be explicit anyway, as some manifolds could be considered both as
real and complex manifolds).
-/

noncomputable theory

universes u v w u' v' w'

open set filter
open_locale manifold filter topological_space

localized "notation `∞` := (⊤ : with_top ℕ)" in manifold

section model_with_corners
/-! ### Models with corners. -/

/-- A structure containing informations on the way a space `H` embeds in a
model vector space `E` over the field `𝕜`. This is all what is needed to
define a smooth manifold with model space `H`, and model vector space `E`.
-/
@[nolint has_inhabited_instance]
structure model_with_corners (𝕜 : Type*) [nondiscrete_normed_field 𝕜]
  (E : Type*) [normed_group E] [normed_space 𝕜 E] (H : Type*) [topological_space H]
  extends local_equiv H E :=
(source_eq          : source = univ)
(unique_diff'       : unique_diff_on 𝕜 to_local_equiv.target)
(continuous_to_fun  : continuous to_fun . tactic.interactive.continuity')
(continuous_inv_fun : continuous inv_fun . tactic.interactive.continuity')

attribute [simp, mfld_simps] model_with_corners.source_eq

/-- A vector space is a model with corners. -/
def model_with_corners_self (𝕜 : Type*) [nondiscrete_normed_field 𝕜]
  (E : Type*) [normed_group E] [normed_space 𝕜 E] : model_with_corners 𝕜 E E :=
{ to_local_equiv := local_equiv.refl E,
  source_eq    := rfl,
  unique_diff' := unique_diff_on_univ,
  continuous_to_fun  := continuous_id,
  continuous_inv_fun := continuous_id }

localized "notation `𝓘(` 𝕜 `, ` E `)` := model_with_corners_self 𝕜 E" in manifold

localized "notation `𝓘(` 𝕜 `)` := model_with_corners_self 𝕜 𝕜" in manifold

section
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
  {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H]
  (I : model_with_corners 𝕜 E H)

namespace model_with_corners

instance : has_coe_to_fun (model_with_corners 𝕜 E H) (λ _, H → E) := ⟨λ e, e.to_fun⟩

/-- The inverse to a model with corners, only registered as a local equiv. -/
protected def symm : local_equiv E H := I.to_local_equiv.symm

/- Register a few lemmas to make sure that `simp` puts expressions in normal form -/
@[simp, mfld_simps] lemma to_local_equiv_coe : (I.to_local_equiv : H → E) = I :=
rfl

@[simp, mfld_simps] lemma mk_coe (e : local_equiv H E) (a b c d) :
  ((model_with_corners.mk e a b c d : model_with_corners 𝕜 E H) : H → E) = (e : H → E) := rfl

@[simp, mfld_simps] lemma to_local_equiv_coe_symm : (I.to_local_equiv.symm : E → H) = I.symm := rfl

@[simp, mfld_simps] lemma mk_symm (e : local_equiv H E) (a b c d) :
  (model_with_corners.mk e a b c d : model_with_corners 𝕜 E H).symm = e.symm :=
rfl

@[continuity] protected lemma continuous : continuous I := I.continuous_to_fun

protected lemma continuous_at {x} : continuous_at I x := I.continuous.continuous_at

protected lemma continuous_within_at {s x} : continuous_within_at I s x :=
I.continuous_at.continuous_within_at

@[continuity] lemma continuous_symm : continuous I.symm := I.continuous_inv_fun

lemma continuous_at_symm {x} : continuous_at I.symm x := I.continuous_symm.continuous_at

lemma continuous_within_at_symm {s x} : continuous_within_at I.symm s x :=
I.continuous_symm.continuous_within_at

lemma continuous_on_symm {s} : continuous_on I.symm s := I.continuous_symm.continuous_on

@[simp, mfld_simps] lemma target_eq : I.target = range (I : H → E) :=
by { rw [← image_univ, ← I.source_eq], exact (I.to_local_equiv.image_source_eq_target).symm }

protected lemma unique_diff : unique_diff_on 𝕜 (range I) := I.target_eq ▸ I.unique_diff'

@[simp, mfld_simps] protected lemma left_inv (x : H) : I.symm (I x) = x :=
by { refine I.left_inv' _, simp }

protected lemma left_inverse : function.left_inverse I.symm I := I.left_inv

@[simp, mfld_simps] lemma symm_comp_self : I.symm ∘ I = id :=
I.left_inverse.comp_eq_id

protected lemma right_inv_on : right_inv_on I.symm I (range I) :=
I.left_inverse.right_inv_on_range

@[simp, mfld_simps] protected lemma right_inv {x : E} (hx : x ∈ range I) : I (I.symm x) = x :=
I.right_inv_on hx

protected lemma image_eq (s : set H) : I '' s = I.symm ⁻¹' s ∩ range I :=
begin
  refine (I.to_local_equiv.image_eq_target_inter_inv_preimage _).trans _,
  { rw I.source_eq, exact subset_univ _ },
  { rw [inter_comm, I.target_eq, I.to_local_equiv_coe_symm] }
end

protected lemma closed_embedding : closed_embedding I :=
I.left_inverse.closed_embedding I.continuous_symm I.continuous

lemma closed_range : is_closed (range I) :=
I.closed_embedding.closed_range

lemma map_nhds_eq (x : H) : map I (𝓝 x) = 𝓝[range I] (I x) :=
I.closed_embedding.to_embedding.map_nhds_eq x

lemma image_mem_nhds_within {x : H} {s : set H} (hs : s ∈ 𝓝 x) :
  I '' s ∈ 𝓝[range I] (I x) :=
I.map_nhds_eq x ▸ image_mem_map hs

lemma symm_map_nhds_within_range (x : H) :
  map I.symm (𝓝[range I] (I x)) = 𝓝 x :=
by rw [← I.map_nhds_eq, map_map, I.symm_comp_self, map_id]

lemma unique_diff_preimage {s : set H} (hs : is_open s) :
  unique_diff_on 𝕜 (I.symm ⁻¹' s ∩ range I) :=
by { rw inter_comm, exact I.unique_diff.inter (hs.preimage I.continuous_inv_fun) }

lemma unique_diff_preimage_source {β : Type*} [topological_space β]
  {e : local_homeomorph H β} : unique_diff_on 𝕜 (I.symm ⁻¹' (e.source) ∩ range I) :=
I.unique_diff_preimage e.open_source

lemma unique_diff_at_image {x : H} : unique_diff_within_at 𝕜 (range I) (I x) :=
I.unique_diff _ (mem_range_self _)

protected lemma locally_compact [locally_compact_space E] (I : model_with_corners 𝕜 E H) :
  locally_compact_space H :=
begin
  have : ∀ (x : H), (𝓝 x).has_basis (λ s, s ∈ 𝓝 (I x) ∧ is_compact s)
    (λ s, I.symm '' (s ∩ range ⇑I)),
  { intro x,
    rw ← I.symm_map_nhds_within_range,
    exact ((compact_basis_nhds (I x)).inf_principal _).map _ },
  refine locally_compact_space_of_has_basis this _,
  rintro x s ⟨-, hsc⟩,
  exact (hsc.inter_right I.closed_range).image I.continuous_symm
end

open topological_space

protected lemma second_countable_topology [second_countable_topology E]
  (I : model_with_corners 𝕜 E H) : second_countable_topology H :=
I.closed_embedding.to_embedding.second_countable_topology

end model_with_corners

section
variables (𝕜 E)

/-- In the trivial model with corners, the associated local equiv is the identity. -/
@[simp, mfld_simps] lemma model_with_corners_self_local_equiv :
  (𝓘(𝕜, E)).to_local_equiv = local_equiv.refl E := rfl

@[simp, mfld_simps] lemma model_with_corners_self_coe :
  (𝓘(𝕜, E) : E → E) = id := rfl

@[simp, mfld_simps] lemma model_with_corners_self_coe_symm :
  (𝓘(𝕜, E).symm : E → E) = id := rfl

end

end

section model_with_corners_prod

/-- Given two model_with_corners `I` on `(E, H)` and `I'` on `(E', H')`, we define the model with
corners `I.prod I'` on `(E × E', model_prod H H')`. This appears in particular for the manifold
structure on the tangent bundle to a manifold modelled on `(E, H)`: it will be modelled on
`(E × E, H × E)`. See note [Manifold type tags] for explanation about `model_prod H H'`
vs `H × H'`. -/
def model_with_corners.prod
  {𝕜 : Type u} [nondiscrete_normed_field 𝕜]
  {E : Type v} [normed_group E] [normed_space 𝕜 E] {H : Type w} [topological_space H]
  (I : model_with_corners 𝕜 E H)
  {E' : Type v'} [normed_group E'] [normed_space 𝕜 E'] {H' : Type w'} [topological_space H']
  (I' : model_with_corners 𝕜 E' H') : model_with_corners 𝕜 (E × E') (model_prod H H') :=
{ to_fun := λ x, (I x.1, I' x.2),
  inv_fun := λ x, (I.symm x.1, I'.symm x.2),
  source := {x | x.1 ∈ I.source ∧ x.2 ∈ I'.source},
  source_eq    := by simp only [set_of_true] with mfld_simps,
  unique_diff' := I.unique_diff'.prod I'.unique_diff',
  continuous_to_fun := I.continuous_to_fun.prod_map I'.continuous_to_fun,
  continuous_inv_fun := I.continuous_inv_fun.prod_map I'.continuous_inv_fun,
  .. I.to_local_equiv.prod I'.to_local_equiv }

/-- Given a finite family of `model_with_corners` `I i` on `(E i, H i)`, we define the model with
corners `pi I` on `(Π i, E i, model_pi H)`. See note [Manifold type tags] for explanation about
`model_pi H`. -/
def model_with_corners.pi
  {𝕜 : Type u} [nondiscrete_normed_field 𝕜] {ι : Type v} [fintype ι]
  {E : ι → Type w} [Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)]
  {H : ι → Type u'} [Π i, topological_space (H i)] (I : Π i, model_with_corners 𝕜 (E i) (H i)) :
  model_with_corners 𝕜 (Π i, E i) (model_pi H) :=
{ to_local_equiv := local_equiv.pi (λ i, (I i).to_local_equiv),
  source_eq := by simp only [set.pi_univ] with mfld_simps,
  unique_diff' := unique_diff_on.pi ι E _ _ (λ i _, (I i).unique_diff'),
  continuous_to_fun := continuous_pi $ λ i, (I i).continuous.comp (continuous_apply i),
  continuous_inv_fun := continuous_pi $ λ i, (I i).continuous_symm.comp (continuous_apply i) }

/-- Special case of product model with corners, which is trivial on the second factor. This shows up
as the model to tangent bundles. -/
@[reducible] def model_with_corners.tangent
  {𝕜 : Type u} [nondiscrete_normed_field 𝕜]
  {E : Type v} [normed_group E] [normed_space 𝕜 E] {H : Type w} [topological_space H]
  (I : model_with_corners 𝕜 E H) : model_with_corners 𝕜 (E × E) (model_prod H E) :=
I.prod (𝓘(𝕜, E))

variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E] {E' : Type*} [normed_group E'] [normed_space 𝕜 E']
{F : Type*} [normed_group F] [normed_space 𝕜 F] {F' : Type*} [normed_group F'] [normed_space 𝕜 F']
{H : Type*} [topological_space H] {H' : Type*} [topological_space H']
{G : Type*} [topological_space G] {G' : Type*} [topological_space G']
{I : model_with_corners 𝕜 E H} {J : model_with_corners 𝕜 F G}

@[simp, mfld_simps] lemma model_with_corners_prod_to_local_equiv :
  (I.prod J).to_local_equiv = I.to_local_equiv.prod (J.to_local_equiv) :=
rfl

@[simp, mfld_simps] lemma model_with_corners_prod_coe
  (I : model_with_corners 𝕜 E H) (I' : model_with_corners 𝕜 E' H') :
  (I.prod I' : _ × _ → _ × _) = prod.map I I' := rfl

@[simp, mfld_simps] lemma model_with_corners_prod_coe_symm
  (I : model_with_corners 𝕜 E H) (I' : model_with_corners 𝕜 E' H') :
  ((I.prod I').symm : _ × _ → _ × _) = prod.map I.symm I'.symm := rfl

end model_with_corners_prod

section boundaryless

/-- Property ensuring that the model with corners `I` defines manifolds without boundary. -/
class model_with_corners.boundaryless {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
  {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H]
  (I : model_with_corners 𝕜 E H) : Prop :=
(range_eq_univ : range I = univ)

/-- The trivial model with corners has no boundary -/
instance model_with_corners_self_boundaryless (𝕜 : Type*) [nondiscrete_normed_field 𝕜]
  (E : Type*) [normed_group E] [normed_space 𝕜 E] : (model_with_corners_self 𝕜 E).boundaryless :=
⟨by simp⟩

/-- If two model with corners are boundaryless, their product also is -/
instance model_with_corners.range_eq_univ_prod {𝕜 : Type u} [nondiscrete_normed_field 𝕜]
  {E : Type v} [normed_group E] [normed_space 𝕜 E] {H : Type w} [topological_space H]
  (I : model_with_corners 𝕜 E H) [I.boundaryless]
  {E' : Type v'} [normed_group E'] [normed_space 𝕜 E'] {H' : Type w'} [topological_space H']
  (I' : model_with_corners 𝕜 E' H') [I'.boundaryless] :
  (I.prod I').boundaryless :=
begin
  split,
  dsimp [model_with_corners.prod, model_prod],
  rw [← prod_range_range_eq, model_with_corners.boundaryless.range_eq_univ,
      model_with_corners.boundaryless.range_eq_univ, univ_prod_univ]
end

end boundaryless

section cont_diff_groupoid
/-! ### Smooth functions on models with corners -/

variables {m n : with_top ℕ} {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E]
{H : Type*} [topological_space H]
(I : model_with_corners 𝕜 E H)
{M : Type*} [topological_space M]

variable (n)
/-- Given a model with corners `(E, H)`, we define the groupoid of `C^n` transformations of `H` as
the maps that are `C^n` when read in `E` through `I`. -/
def cont_diff_groupoid : structure_groupoid H :=
pregroupoid.groupoid
{ property := λf s, cont_diff_on 𝕜 n (I ∘ f ∘ I.symm) (I.symm ⁻¹' s ∩ range I),
  comp     := λf g u v hf hg hu hv huv, begin
    have : I ∘ (g ∘ f) ∘ I.symm = (I ∘ g ∘ I.symm) ∘ (I ∘ f ∘ I.symm),
      by { ext x, simp },
    rw this,
    apply cont_diff_on.comp hg _,
    { rintros x ⟨hx1, hx2⟩,
      simp only with mfld_simps at ⊢ hx1,
      exact hx1.2 },
    { refine hf.mono _,
      rintros x ⟨hx1, hx2⟩,
      exact ⟨hx1.1, hx2⟩ }
  end,
  id_mem   := begin
    apply cont_diff_on.congr (cont_diff_id.cont_diff_on),
    rintros x ⟨hx1, hx2⟩,
    rcases mem_range.1 hx2 with ⟨y, hy⟩,
    rw ← hy,
    simp only with mfld_simps,
  end,
  locality := λf u hu H, begin
    apply cont_diff_on_of_locally_cont_diff_on,
    rintros y ⟨hy1, hy2⟩,
    rcases mem_range.1 hy2 with ⟨x, hx⟩,
    rw ← hx at ⊢ hy1,
    simp only with mfld_simps at ⊢ hy1,
    rcases H x hy1 with ⟨v, v_open, xv, hv⟩,
    have : ((I.symm ⁻¹' (u ∩ v)) ∩ (range I))
        = ((I.symm ⁻¹' u) ∩ (range I) ∩ I.symm ⁻¹' v),
    { rw [preimage_inter, inter_assoc, inter_assoc],
      congr' 1,
      rw inter_comm },
    rw this at hv,
    exact ⟨I.symm ⁻¹' v, v_open.preimage I.continuous_symm, by simpa, hv⟩
  end,
  congr    := λf g u hu fg hf, begin
    apply hf.congr,
    rintros y ⟨hy1, hy2⟩,
    rcases mem_range.1 hy2 with ⟨x, hx⟩,
    rw ← hx at ⊢ hy1,
    simp only with mfld_simps at ⊢ hy1,
    rw fg _ hy1
  end }

variable {n}
/-- Inclusion of the groupoid of `C^n` local diffeos in the groupoid of `C^m` local diffeos when
`m ≤ n` -/
lemma cont_diff_groupoid_le (h : m ≤ n) :
  cont_diff_groupoid n I ≤ cont_diff_groupoid m I :=
begin
  rw [cont_diff_groupoid, cont_diff_groupoid],
  apply groupoid_of_pregroupoid_le,
  assume f s hfs,
  exact cont_diff_on.of_le hfs h
end

/-- The groupoid of `0`-times continuously differentiable maps is just the groupoid of all
local homeomorphisms -/
lemma cont_diff_groupoid_zero_eq :
  cont_diff_groupoid 0 I = continuous_groupoid H :=
begin
  apply le_antisymm le_top,
  assume u hu,
  -- we have to check that every local homeomorphism belongs to `cont_diff_groupoid 0 I`,
  -- by unfolding its definition
  change u ∈ cont_diff_groupoid 0 I,
  rw [cont_diff_groupoid, mem_groupoid_of_pregroupoid],
  simp only [cont_diff_on_zero],
  split,
  { refine I.continuous.comp_continuous_on (u.continuous_on.comp I.continuous_on_symm _),
    exact (maps_to_preimage _ _).mono_left (inter_subset_left _ _) },
  { refine I.continuous.comp_continuous_on (u.symm.continuous_on.comp I.continuous_on_symm _),
    exact (maps_to_preimage _ _).mono_left (inter_subset_left _ _) },
end

variable (n)
/-- An identity local homeomorphism belongs to the `C^n` groupoid. -/
lemma of_set_mem_cont_diff_groupoid {s : set H} (hs : is_open s) :
  local_homeomorph.of_set s hs ∈ cont_diff_groupoid n I :=
begin
  rw [cont_diff_groupoid, mem_groupoid_of_pregroupoid],
  suffices h : cont_diff_on 𝕜 n (I ∘ I.symm) (I.symm ⁻¹' s ∩ range I),
    by simp [h],
  have : cont_diff_on 𝕜 n id (univ : set E) :=
    cont_diff_id.cont_diff_on,
  exact this.congr_mono (λ x hx, by simp [hx.2]) (subset_univ _)
end

/-- The composition of a local homeomorphism from `H` to `M` and its inverse belongs to
the `C^n` groupoid. -/
lemma symm_trans_mem_cont_diff_groupoid (e : local_homeomorph M H) :
  e.symm.trans e ∈ cont_diff_groupoid n I :=
begin
  have : e.symm.trans e ≈ local_homeomorph.of_set e.target e.open_target :=
    local_homeomorph.trans_symm_self _,
  exact structure_groupoid.eq_on_source _
    (of_set_mem_cont_diff_groupoid n I e.open_target) this
end

variables {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H']

/-- The product of two smooth local homeomorphisms is smooth. -/
lemma cont_diff_groupoid_prod
  {I : model_with_corners 𝕜 E H} {I' : model_with_corners 𝕜 E' H'}
  {e : local_homeomorph H H} {e' : local_homeomorph H' H'}
  (he : e ∈ cont_diff_groupoid ⊤ I) (he' : e' ∈ cont_diff_groupoid ⊤ I') :
  e.prod e' ∈ cont_diff_groupoid ⊤ (I.prod I') :=
begin
  cases he with he he_symm,
  cases he' with he' he'_symm,
  simp only at he he_symm he' he'_symm,
  split;
  simp only [local_equiv.prod_source, local_homeomorph.prod_to_local_equiv],
  { have h3 := cont_diff_on.prod_map he he',
    rw [← I.image_eq, ← I'.image_eq, set.prod_image_image_eq] at h3,
    rw ← (I.prod I').image_eq,
    exact h3, },
  { have h3 := cont_diff_on.prod_map he_symm he'_symm,
    rw [← I.image_eq, ← I'.image_eq, set.prod_image_image_eq] at h3,
    rw ← (I.prod I').image_eq,
    exact h3, }
end

/-- The `C^n` groupoid is closed under restriction. -/
instance : closed_under_restriction (cont_diff_groupoid n I) :=
(closed_under_restriction_iff_id_le _).mpr
begin
  apply structure_groupoid.le_iff.mpr,
  rintros e ⟨s, hs, hes⟩,
  apply (cont_diff_groupoid n I).eq_on_source' _ _ _ hes,
  exact of_set_mem_cont_diff_groupoid n I hs,
end

end cont_diff_groupoid

end model_with_corners

section smooth_manifold_with_corners

/-! ### Smooth manifolds with corners -/

/-- Typeclass defining smooth manifolds with corners with respect to a model with corners, over a
field `𝕜` and with infinite smoothness to simplify typeclass search and statements later on. -/
@[ancestor has_groupoid]
class smooth_manifold_with_corners {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
  {E : Type*} [normed_group E] [normed_space 𝕜 E]
  {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H)
  (M : Type*) [topological_space M] [charted_space H M] extends
  has_groupoid M (cont_diff_groupoid ∞ I) : Prop

lemma smooth_manifold_with_corners.mk' {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
  {E : Type*} [normed_group E] [normed_space 𝕜 E]
  {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H)
  (M : Type*) [topological_space M] [charted_space H M]
  [gr : has_groupoid M (cont_diff_groupoid ∞ I)] :
  smooth_manifold_with_corners I M := { ..gr }

lemma smooth_manifold_with_corners_of_cont_diff_on
  {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
  {E : Type*} [normed_group E] [normed_space 𝕜 E]
  {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H)
  (M : Type*) [topological_space M] [charted_space H M]
  (h : ∀ (e e' : local_homeomorph M H), e ∈ atlas H M → e' ∈ atlas H M →
    cont_diff_on 𝕜 ⊤ (I ∘ (e.symm ≫ₕ e') ∘ I.symm)
      (I.symm ⁻¹' (e.symm ≫ₕ e').source ∩ range I)) :
  smooth_manifold_with_corners I M :=
{ compatible :=
  begin
    haveI : has_groupoid M (cont_diff_groupoid ∞ I) := has_groupoid_of_pregroupoid _ h,
    apply structure_groupoid.compatible,
  end }

/-- For any model with corners, the model space is a smooth manifold -/
instance model_space_smooth {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
  {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H]
  {I : model_with_corners 𝕜 E H} :
  smooth_manifold_with_corners I H := { .. has_groupoid_model_space _ _ }

end smooth_manifold_with_corners

namespace smooth_manifold_with_corners
/- We restate in the namespace `smooth_manifolds_with_corners` some lemmas that hold for general
charted space with a structure groupoid, avoiding the need to specify the groupoid
`cont_diff_groupoid ∞ I` explicitly. -/

variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
  {E : Type*} [normed_group E] [normed_space 𝕜 E]
  {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H)
  (M : Type*) [topological_space M] [charted_space H M]

/-- The maximal atlas of `M` for the smooth manifold with corners structure corresponding to the
model with corners `I`. -/
def maximal_atlas := (cont_diff_groupoid ∞ I).maximal_atlas M

variable {M}

lemma mem_maximal_atlas_of_mem_atlas [smooth_manifold_with_corners I M]
  {e : local_homeomorph M H} (he : e ∈ atlas H M) : e ∈ maximal_atlas I M :=
structure_groupoid.mem_maximal_atlas_of_mem_atlas _ he

lemma chart_mem_maximal_atlas [smooth_manifold_with_corners I M] (x : M) :
  chart_at H x ∈ maximal_atlas I M :=
structure_groupoid.chart_mem_maximal_atlas _ x

variable {I}

lemma compatible_of_mem_maximal_atlas
  {e e' : local_homeomorph M H} (he : e ∈ maximal_atlas I M) (he' : e' ∈ maximal_atlas I M) :
  e.symm.trans e' ∈ cont_diff_groupoid ∞ I :=
structure_groupoid.compatible_of_mem_maximal_atlas he he'

/-- The product of two smooth manifolds with corners is naturally a smooth manifold with corners. -/
instance prod {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
  {E : Type*} [normed_group E] [normed_space 𝕜 E]
  {E' : Type*} [normed_group E'] [normed_space 𝕜 E']
  {H : Type*} [topological_space H] {I : model_with_corners 𝕜 E H}
  {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'}
  (M : Type*) [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M]
  (M' : Type*) [topological_space M'] [charted_space H' M'] [smooth_manifold_with_corners I' M'] :
  smooth_manifold_with_corners (I.prod I') (M×M') :=
{ compatible :=
  begin
    rintros f g ⟨f1, f2, hf1, hf2, rfl⟩ ⟨g1, g2, hg1, hg2, rfl⟩,
    rw [local_homeomorph.prod_symm, local_homeomorph.prod_trans],
    have h1 := has_groupoid.compatible (cont_diff_groupoid ⊤ I) hf1 hg1,
    have h2 := has_groupoid.compatible (cont_diff_groupoid ⊤ I') hf2 hg2,
    exact cont_diff_groupoid_prod h1 h2,
  end }

end smooth_manifold_with_corners

lemma local_homeomorph.singleton_smooth_manifold_with_corners
  {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
  {E : Type*} [normed_group E] [normed_space 𝕜 E]
  {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H)
  {M : Type*} [topological_space M]
  (e : local_homeomorph M H) (h : e.source = set.univ) :
  @smooth_manifold_with_corners 𝕜 _ E _ _ H _ I M _ (e.singleton_charted_space h) :=
@smooth_manifold_with_corners.mk' _ _ _ _ _ _ _ _ _ _ (id _) $
e.singleton_has_groupoid h (cont_diff_groupoid ∞ I)

lemma open_embedding.singleton_smooth_manifold_with_corners
  {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
  {E : Type*} [normed_group E] [normed_space 𝕜 E]
  {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H)
  {M : Type*} [topological_space M]
  [nonempty M] {f : M → H} (h : open_embedding f) :
  @smooth_manifold_with_corners 𝕜 _ E _ _ H _ I M _ h.singleton_charted_space :=
(h.to_local_homeomorph f).singleton_smooth_manifold_with_corners I (by simp)

namespace topological_space.opens

open topological_space

variables  {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
  {E : Type*} [normed_group E] [normed_space 𝕜 E]
  {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H)
  {M : Type*} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M]
  (s : opens M)

instance : smooth_manifold_with_corners I s := { ..s.has_groupoid (cont_diff_groupoid ∞ I) }

end topological_space.opens

section extended_charts
open_locale topological_space

variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
  {E : Type*} [normed_group E] [normed_space 𝕜 E]
  {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H)
  {M : Type*} [topological_space M] [charted_space H M]
  (x : M) {s t : set M}

/-!
### Extended charts

In a smooth manifold with corners, the model space is the space `H`. However, we will also
need to use extended charts taking values in the model vector space `E`. These extended charts are
not `local_homeomorph` as the target is not open in `E` in general, but we can still register them
as `local_equiv`.
-/

/-- The preferred extended chart on a manifold with corners around a point `x`, from a neighborhood
of `x` to the model vector space. -/
@[simp, mfld_simps] def ext_chart_at (x : M) : local_equiv M E :=
(chart_at H x).to_local_equiv.trans I.to_local_equiv

lemma ext_chart_at_coe : ⇑(ext_chart_at I x) = I ∘ chart_at H x := rfl

lemma ext_chart_at_coe_symm :
  ⇑(ext_chart_at I x).symm = (chart_at H x).symm ∘ I.symm := rfl

lemma ext_chart_at_source : (ext_chart_at I x).source = (chart_at H x).source :=
by rw [ext_chart_at, local_equiv.trans_source, I.source_eq, preimage_univ, inter_univ]

lemma ext_chart_at_open_source : is_open (ext_chart_at I x).source :=
by { rw ext_chart_at_source, exact (chart_at H x).open_source }

lemma mem_ext_chart_source : x ∈ (ext_chart_at I x).source :=
by simp only [ext_chart_at_source, mem_chart_source]

lemma ext_chart_at_to_inv :
  (ext_chart_at I x).symm ((ext_chart_at I x) x) = x :=
(ext_chart_at I x).left_inv (mem_ext_chart_source I x)

lemma ext_chart_at_source_mem_nhds' {x' : M} (h : x' ∈ (ext_chart_at I x).source) :
  (ext_chart_at I x).source ∈ 𝓝 x' :=
is_open.mem_nhds (ext_chart_at_open_source I x) h

lemma ext_chart_at_source_mem_nhds : (ext_chart_at I x).source ∈ 𝓝 x :=
ext_chart_at_source_mem_nhds' I x (mem_ext_chart_source I x)

lemma ext_chart_at_source_mem_nhds_within' {x' : M} (h : x' ∈ (ext_chart_at I x).source) :
  (ext_chart_at I x).source ∈ 𝓝[s] x' :=
mem_nhds_within_of_mem_nhds (ext_chart_at_source_mem_nhds' I x h)

lemma ext_chart_at_source_mem_nhds_within :
  (ext_chart_at I x).source ∈ 𝓝[s] x :=
mem_nhds_within_of_mem_nhds (ext_chart_at_source_mem_nhds I x)

lemma ext_chart_at_continuous_on :
  continuous_on (ext_chart_at I x) (ext_chart_at I x).source :=
begin
  refine I.continuous.comp_continuous_on _,
  rw ext_chart_at_source,
  exact (chart_at H x).continuous_on
end

lemma ext_chart_at_continuous_at' {x' : M} (h : x' ∈ (ext_chart_at I x).source) :
  continuous_at (ext_chart_at I x) x' :=
(ext_chart_at_continuous_on I x).continuous_at $ ext_chart_at_source_mem_nhds' I x h

lemma ext_chart_at_continuous_at : continuous_at (ext_chart_at I x) x :=
ext_chart_at_continuous_at' _ _ (mem_ext_chart_source I x)

lemma ext_chart_at_continuous_on_symm :
  continuous_on (ext_chart_at I x).symm (ext_chart_at I x).target :=
(chart_at H x).continuous_on_symm.comp I.continuous_on_symm $
  (maps_to_preimage _ _).mono_left (inter_subset_right _ _)

lemma ext_chart_at_map_nhds' {x y : M} (hy : y ∈ (ext_chart_at I x).source) :
  map (ext_chart_at I x) (𝓝 y) = 𝓝[range I] (ext_chart_at I x y) :=
begin
  rw [ext_chart_at_coe, (∘), ← I.map_nhds_eq, ← (chart_at H x).map_nhds_eq, map_map],
  rwa ext_chart_at_source at hy
end

lemma ext_chart_at_map_nhds :
  map (ext_chart_at I x) (𝓝 x) = 𝓝[range I] (ext_chart_at I x x) :=
ext_chart_at_map_nhds' I $ mem_ext_chart_source I x

lemma ext_chart_at_target_mem_nhds_within' {y : M} (hy : y ∈ (ext_chart_at I x).source) :
  (ext_chart_at I x).target ∈ 𝓝[range I] (ext_chart_at I x y) :=
begin
  rw [← local_equiv.image_source_eq_target, ← ext_chart_at_map_nhds' I hy],
  exact image_mem_map (ext_chart_at_source_mem_nhds' _ _ hy)
end

lemma ext_chart_at_target_mem_nhds_within :
  (ext_chart_at I x).target ∈ 𝓝[range I] (ext_chart_at I x x) :=
ext_chart_at_target_mem_nhds_within' I x (mem_ext_chart_source I x)

lemma ext_chart_at_target_subset_range : (ext_chart_at I x).target ⊆ range I :=
by simp only with mfld_simps

lemma nhds_within_ext_chart_target_eq' {y : M} (hy : y ∈ (ext_chart_at I x).source) :
  𝓝[(ext_chart_at I x).target] (ext_chart_at I x y) =
  𝓝[range I] (ext_chart_at I x y) :=
(nhds_within_mono _ (ext_chart_at_target_subset_range _ _)).antisymm $
  nhds_within_le_of_mem (ext_chart_at_target_mem_nhds_within' _ _ hy)

lemma nhds_within_ext_chart_target_eq :
  𝓝[(ext_chart_at I x).target] ((ext_chart_at I x) x) =
  𝓝[range I] ((ext_chart_at I x) x) :=
nhds_within_ext_chart_target_eq' I x (mem_ext_chart_source I x)

lemma ext_chart_continuous_at_symm'' {y : E} (h : y ∈ (ext_chart_at I x).target) :
  continuous_at (ext_chart_at I x).symm y :=
continuous_at.comp ((chart_at H x).continuous_at_symm h.2) (I.continuous_symm.continuous_at)

lemma ext_chart_continuous_at_symm' {x' : M} (h : x' ∈ (ext_chart_at I x).source) :
  continuous_at (ext_chart_at I x).symm (ext_chart_at I x x') :=
ext_chart_continuous_at_symm'' I _ $ (ext_chart_at I x).map_source h

lemma ext_chart_continuous_at_symm :
  continuous_at (ext_chart_at I x).symm ((ext_chart_at I x) x) :=
ext_chart_continuous_at_symm' I x (mem_ext_chart_source I x)

lemma ext_chart_continuous_on_symm :
  continuous_on (ext_chart_at I x).symm (ext_chart_at I x).target :=
λ y hy, (ext_chart_continuous_at_symm'' _ _ hy).continuous_within_at

lemma ext_chart_preimage_open_of_open' {s : set E} (hs : is_open s) :
  is_open ((ext_chart_at I x).source ∩ ext_chart_at I x ⁻¹' s) :=
(ext_chart_at_continuous_on I x).preimage_open_of_open (ext_chart_at_open_source _ _) hs

lemma ext_chart_preimage_open_of_open {s : set E} (hs : is_open s) :
  is_open ((chart_at H x).source ∩ ext_chart_at I x ⁻¹' s) :=
by { rw ← ext_chart_at_source I, exact ext_chart_preimage_open_of_open' I x hs }

lemma ext_chart_at_map_nhds_within_eq_image' {y : M} (hy : y ∈ (ext_chart_at I x).source) :
  map (ext_chart_at I x) (𝓝[s] y) =
    𝓝[ext_chart_at I x '' ((ext_chart_at I x).source ∩ s)] (ext_chart_at I x y) :=
by set e := ext_chart_at I x;
calc map e (𝓝[s] y) = map e (𝓝[e.source ∩ s] y) :
  congr_arg (map e) (nhds_within_inter_of_mem (ext_chart_at_source_mem_nhds_within' I x hy)).symm
... = 𝓝[e '' (e.source ∩ s)] (e y) :
  ((ext_chart_at I x).left_inv_on.mono $ inter_subset_left _ _).map_nhds_within_eq
    ((ext_chart_at I x).left_inv hy)
    (ext_chart_continuous_at_symm' I x hy).continuous_within_at
    (ext_chart_at_continuous_at' I x hy).continuous_within_at

lemma ext_chart_at_map_nhds_within_eq_image :
  map (ext_chart_at I x) (𝓝[s] x) =
    𝓝[ext_chart_at I x '' ((ext_chart_at I x).source ∩ s)] (ext_chart_at I x x) :=
ext_chart_at_map_nhds_within_eq_image' I x (mem_ext_chart_source I x)

lemma ext_chart_at_map_nhds_within' {y : M} (hy : y ∈ (ext_chart_at I x).source) :
  map (ext_chart_at I x) (𝓝[s] y) =
    𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] (ext_chart_at I x y) :=
by rw [ext_chart_at_map_nhds_within_eq_image' I x hy, nhds_within_inter,
  ← nhds_within_ext_chart_target_eq' _ _ hy, ← nhds_within_inter,
  (ext_chart_at I x).image_source_inter_eq', inter_comm]

lemma ext_chart_at_map_nhds_within :
  map (ext_chart_at I x) (𝓝[s] x) =
    𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] (ext_chart_at I x x) :=
ext_chart_at_map_nhds_within' I x (mem_ext_chart_source I x)

lemma ext_chart_at_symm_map_nhds_within' {y : M} (hy : y ∈ (ext_chart_at I x).source) :
  map (ext_chart_at I x).symm
    (𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] (ext_chart_at I x y)) = 𝓝[s] y :=
begin
  rw [← ext_chart_at_map_nhds_within' I x hy, map_map, map_congr, map_id],
  exact (ext_chart_at I x).left_inv_on.eq_on.eventually_eq_of_mem
    (ext_chart_at_source_mem_nhds_within' _ _ hy)
end

lemma ext_chart_at_symm_map_nhds_within_range' {y : M} (hy : y ∈ (ext_chart_at I x).source) :
  map (ext_chart_at I x).symm (𝓝[range I] (ext_chart_at I x y)) = 𝓝 y :=
by rw [← nhds_within_univ, ← ext_chart_at_symm_map_nhds_within' I x hy, preimage_univ, univ_inter]

lemma ext_chart_at_symm_map_nhds_within :
  map (ext_chart_at I x).symm
    (𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] (ext_chart_at I x x)) = 𝓝[s] x :=
ext_chart_at_symm_map_nhds_within' I x (mem_ext_chart_source I x)

lemma ext_chart_at_symm_map_nhds_within_range :
  map (ext_chart_at I x).symm (𝓝[range I] (ext_chart_at I x x)) = 𝓝 x :=
ext_chart_at_symm_map_nhds_within_range' I x (mem_ext_chart_source I x)

/-- Technical lemma ensuring that the preimage under an extended chart of a neighborhood of a point
in the source is a neighborhood of the preimage, within a set. -/
lemma ext_chart_preimage_mem_nhds_within' {x' : M} (h : x' ∈ (ext_chart_at I x).source)
  (ht : t ∈ 𝓝[s] x') :
  (ext_chart_at I x).symm ⁻¹' t ∈
    𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] ((ext_chart_at I x) x') :=
by rwa [← ext_chart_at_symm_map_nhds_within' I x h, mem_map] at ht

/-- Technical lemma ensuring that the preimage under an extended chart of a neighborhood of the
base point is a neighborhood of the preimage, within a set. -/
lemma ext_chart_preimage_mem_nhds_within (ht : t ∈ 𝓝[s] x) :
  (ext_chart_at I x).symm ⁻¹' t ∈
    𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] ((ext_chart_at I x) x) :=
ext_chart_preimage_mem_nhds_within' I x (mem_ext_chart_source I x) ht

/-- Technical lemma ensuring that the preimage under an extended chart of a neighborhood of a point
is a neighborhood of the preimage. -/
lemma ext_chart_preimage_mem_nhds (ht : t ∈ 𝓝 x) :
  (ext_chart_at I x).symm ⁻¹' t ∈ 𝓝 ((ext_chart_at I x) x) :=
begin
  apply (ext_chart_continuous_at_symm I x).preimage_mem_nhds,
  rwa (ext_chart_at I x).left_inv (mem_ext_chart_source _ _)
end

/-- Technical lemma to rewrite suitably the preimage of an intersection under an extended chart, to
bring it into a convenient form to apply derivative lemmas. -/
lemma ext_chart_preimage_inter_eq :
  ((ext_chart_at I x).symm ⁻¹' (s ∩ t) ∩ range I)
  = ((ext_chart_at I x).symm ⁻¹' s ∩ range I) ∩ ((ext_chart_at I x).symm ⁻¹' t) :=
by mfld_set_tac

end extended_charts

/-- In the case of the manifold structure on a vector space, the extended charts are just the
identity.-/
lemma ext_chart_model_space_eq_id (𝕜 : Type*) [nondiscrete_normed_field 𝕜]
  {E : Type*} [normed_group E] [normed_space 𝕜 E] (x : E) :
  ext_chart_at (model_with_corners_self 𝕜 E) x = local_equiv.refl E :=
by simp only with mfld_simps