{- | The space `L⁰` of measurable elements of a full integration space `L`.

  * {measGauge}: $d_h(f, 0) = I(|f| \wedge h)$; the pseudometrics $d_h(f,g) = I(|f - g| \wedge h)$, $h \in L^+$,
    generate the uniformity of convergence in measure.
  * {L0PreSpace}: `L` with this uniformity, a topological truncated Riesz space.
  * {L0Space}: its separated completion `L⁰`; the Riesz-space operations and the truncation extend to it
    (Lemma `lem:L0`(1)); {l0Inc} is the canonical map `L → L⁰`.
  * {L0Of}: `L⁰(Y)` for a regular integration space `Y`.
  * {PosCone}: the positive cone $L^+$ as a directed set, the index set of nets.
  * {l0Gauge}: the extension of $d_h(\cdot, 0)$ to `L⁰`; {l0Gauge-below}: $d_h(F, 0) \le I(\tau_\varepsilon h)$ if $|F| \le \varepsilon$.
  * {l0-small-bounded}: elements bounded by a small enough $\varepsilon$ lie in a given neighbourhood of `0`;
    {l0-bounded-zero}: an element bounded by every $\varepsilon > 0$ is `0`; {l0-gauge-zero}: so is an element with arbitrarily small gauges.
  * {l0-below-closed}: $\{G \mid |G - c| \le \varepsilon\}$ is closed.
  * {l0-pt-abs}, {l0-bclip}: the canonical map `L → L⁰` preserves `|·|` and clamping.
  * {l0-dense2}, {l0-dense3}, {l0-denseN}, {l0-bound2}: identities and bounds of maps $(\mathrm L^0)^n \to \mathrm L^0$ extend from `L`.
-}

\import Algebra.Group
\import Algebra.Ordered
\import Algebra.Ordered.RieszSpace
\import Algebra.Ordered.TruncRieszSpace
\import Analysis.Integration.FullIntegrationSpace
\import Analysis.Integration.FunctionalCalculus.Pointwise
\import Analysis.Integration.IntegrationSpace
\import Arith.Rat
\import Arith.Real
\import Function.Meta
\import Logic
\import Logic.Meta
\import Order.Biordered
\import Order.Directed
\import Order.Lattice
\import Order.PartialOrder
\import Order.StrictOrder
\import Paths
\import Paths.Meta
\import Set.Set
\import Topology.CoverSpace.Complete
\import Topology.CoverSpace.Product
\import Topology.NormedAbGroup.Real
\import Topology.TopAbGroup.NormFamily
\import Topology.TopAbGroup.NormFamily.Completion
\import Topology.TopAbGroup.Product
\import Topology.TopRieszSpace
\import Topology.TopRieszSpace.Completion
\import Topology.TopSpace
\import Topology.TopSpace.Product
\open LatticeAbGroup(abs)
\open TruncRieszSpace(IsBelow,bclip, IsBelow_truncAt)

-- | $I(|f| \wedge h)$, that is, $d_h(f, 0)$.
\func measGauge {L : FullIntegrationSpace} (h f : L) : Real
  => L.integral (abs f ∧ h)

-- | An element of the positive cone of `L`.
\record PosElem (L : FullIntegrationSpace) (el : L) (el>=0 : L.zro <= el)

-- | The positive cone of `L`, directed by `∨`; used as the index set of nets.
\func PosCone (L : FullIntegrationSpace) : DirectedSet \cowith
  | E => PosElem L
  | <= h h' => h.el <= h'.el
  | <=-refl => <=-refl
  | <=-transitive p q => p <=∘ q
  | isInhabitted => inP (\new PosElem L L.zro <=-refl)
  | isDirected h h' => inP (\new PosElem L (h.el ∨ h'.el) (h.el>=0 <=∘ join-left), join-left, join-right)

-- | `L` with the uniformity generated by the pseudometrics $d_h$, $h \in L^+$.
\func L0PreSpace (L : FullIntegrationSpace) : NormFamilyTruncRieszSpace L \cowith
  | TruncRieszSpace => L
  | NormIndex => \Sigma (h : L) (L.zro <= h)
  | normAt h f => measGauge h.1 f
  | normAt-zro {h} => pmap L.integral (pmap (__ ∧ h.1) L.abs_zro *> L.meet_<= h.2) *> L.integral-hom.func-zro
  | normAt-negative {h} {x} => pmap (\lam z => L.integral (z ∧ h.1)) L.abs_negative
  | normAt-+ {h} {x} {y} => L.integral-mono (L.meet-monotone L.abs_+ <=-refl <=∘ meet-add {L} {abs x} {abs y} L.abs>=0 L.abs>=0 h.2) <=∘ =_<= L.integral_+
  | normAt-directed h h' => inP ((h.1 ∨ h'.1, h.2 <=∘ join-left), \lam f =>
      (L.integral-mono (L.meet-monotone <=-refl join-left), L.integral-mono (L.meet-monotone <=-refl join-right)))
  | normAt-inh => inP (L.zro, <=-refl)
  | normAt-abs-mono p => L.integral-mono (L.meet-monotone p <=-refl)

-- | The space `L⁰` of measurable elements: the separated completion of {L0PreSpace}.
\func L0Space (L : FullIntegrationSpace) : CompleteTopTruncRieszGroup
  => TopTruncRieszCompletion (L0PreSpace L)

-- | `L⁰(Y)` for a regular integration space `Y`: `L⁰` of the bounded part of the completion of `Y`.
\func L0Of (Y : RegularIntegrationSpace) : CompleteTopTruncRieszGroup
  => L0Space (boundedFull (RegularIntegrationSpaceCompletion Y))

-- | The extension of $d_h(\cdot, 0)$ to `L⁰`.
\func l0Gauge {L : FullIntegrationSpace} {h : L} (h>=0 : L.zro <= h) : CoverMap (L0Space L) RealNormed
  => normAt-lift {L0PreSpace L} (h,h>=0)
  \where
    \lemma char {L : FullIntegrationSpace} {h : L} (h>=0 : L.zro <= h) {f : L} : l0Gauge h>=0 (pointCF {L0PreSpace L} f) = measGauge h f
      => normAt-lift.char {L0PreSpace L} {h,h>=0}

-- | $d_h(F, 0) \le I(\tau_\varepsilon h)$ if $|F| \le \varepsilon$.
\lemma l0Gauge-below {L : FullIntegrationSpace} {h : L} (h>=0 : L.zro <= h) {e : Rat} (e>0 : RatField.zro RatField.< e) {F : L0Space L} (p : IsBelow (abs F) e)
  : l0Gauge h>=0 F <= L.integral (L.truncAt e h)
  => \let | Y => L0Space L
          | i => topTruncCompletion {L0PreSpace L}
     \in \have | ih>=0 : Y.zro <= i h => =_<= (inv i.func-zro) <=∘ i.func-<= h>=0
              | clip-eq : l0Gauge h>=0 F = l0Gauge h>=0 (Y.clip (i h) F)
                  => dense-lift-unique completion completion.isDenseEmbedding.1 (l0Gauge h>=0) (l0Gauge h>=0 CoverMap.∘ clip-cover (i h))
                       (\lam f => l0Gauge.char h>=0 *> pmap L.integral (inv (pmap (__ ∧ h) (L.clip-abs-eq h>=0) *> L.meet-assoc *> pmap (L.abs f ∧) L.meet-idemp)) *> inv (pmap (l0Gauge h>=0) (inv (RieszSpaceHom.func-clip {i})) *> l0Gauge.char h>=0)) F
              | le : abs (Y.clip (i h) F) <= abs (i (L.truncAt e h))
                  => =_<= (Y.clip-abs-eq ih>=0) <=∘ Y.truncAt-greatest e>0 (Y.IsBelow_<= Y.meet-left p) Y.meet-right
                      <=∘ =_<= (inv (Y.abs-ofPos (Y.truncAt-pos e>0 ih>=0)) *> pmap Y.abs (inv i.func-truncAt))
     \in =_<= clip-eq <=∘ normAt-lift-abs-mono {L0PreSpace L} {h,h>=0} le <=∘ =_<= (l0Gauge.char h>=0)
          <=∘ L.integral-mono (L.meet-left <=∘ =_<= (L.abs-ofPos (L.truncAt-pos e>0 h>=0)))

-- | Elements bounded by a small enough $\varepsilon$ lie in a given neighbourhood of `0`.
\lemma l0-small-bounded {L : FullIntegrationSpace} {U : Set (L0Space L)} (Uo : isOpen U) (U0 : U (L0Space L).zro)
  : ∃ (e : Rat) (RatField.zro RatField.< e) ∀ {F : L0Space L} (IsBelow (abs F) e -> U F)
  => \case completion-neighborhood {L0PreSpace L} Uo U0 \with {
    | inP ((h,h>=0),eps,eps>0,f) => \case real_<-char.1 eps>0 \with {
      | inP (r,r>0,r<eps) => \case L.integral-trunc-small h>=0 (rat_real_<.2 r>0) \with {
        | inP (e,e>0,small) => inP (e, e>0, \lam p => f $ l0Gauge-below h>=0 e>0 p <∘r small <∘ r<eps)
      }
    }
  }

-- | An element bounded by every $\varepsilon > 0$ is `0`.
\lemma l0-bounded-zero {L : FullIntegrationSpace} {F : L0Space L} (p : \Pi {e : Rat} -> RatField.zro RatField.< e -> IsBelow (abs F) e) : F = (L0Space L).zro
  => (L0Space L).isHausdorff \lam {U} {V} Uo Vo UF V0 => \case l0-small-bounded Vo V0 \with {
    | inP (e,e>0,g) => inP (F, (UF, g (p e>0)))
  }

-- | An element all of whose gauges $d_h(F, 0)$ are arbitrarily small is `0`.
\lemma l0-gauge-zero {L : FullIntegrationSpace} {F : L0Space L}
                     (p : \Pi {h : L} (h>=0 : L.zro <= h) {d : Rat} -> RatField.zro RatField.< d -> l0Gauge h>=0 F < Real.fromRat d)
  : F = (L0Space L).zro
  => (L0Space L).isHausdorff \lam {U} {V} Uo Vo UF V0 => \case completion-neighborhood {L0PreSpace L} Vo V0 \with {
    | inP ((h,h>=0),eps,eps>0,f) => \case real_<-char.1 eps>0 \with {
      | inP (r,r>0,r<eps) => inP (F, (UF, f (p h>=0 (rat_real_<.2 r>0) <∘ r<eps)))
    }
  }

-- | The canonical map `L → L⁰` preserves clamping.
\lemma l0-bclip {L : FullIntegrationSpace} {M : Rat} {f : L} : pointCF {L0PreSpace L} (L.bclip M f) = bclip M (pointCF {L0PreSpace L} f)
  => TruncRieszSpaceHom.func-bclip {topTruncCompletion {L0PreSpace L}}

-- | The canonical map `L → L⁰` preserves `|·|`.
\lemma l0-pt-abs {L : FullIntegrationSpace} {f : L} : pointCF {L0PreSpace L} (L.abs f) = abs (pointCF {L0PreSpace L} f)
  => RieszSpaceHom.func-abs {topTruncCompletion {L0PreSpace L}}

-- | `L × L` is dense in `L⁰ × L⁰`.
\lemma l0-dense2-embedding {L : FullIntegrationSpace} : CoverMap.IsDenseEmbedding {ProductCoverSpace.prod (completion {L0PreSpace L}) (completion {L0PreSpace L})}
  => ProductCoverSpace.prod.isDenseEmbedding {L0PreSpace L} {L0PreSpace L} {_} {_} {completion} {completion} completion.isDenseEmbedding completion.isDenseEmbedding

-- | Two maps $\mathrm L^0 \times \mathrm L^0 \to \mathrm L^0$ that agree on `L × L` are equal.
\lemma l0-dense2 {L : FullIntegrationSpace} (P Q : CoverMap (ProductCoverSpace (L0Space L) (L0Space L)) (L0Space L))
                 (p : \Pi (f g : L) -> P (pointCF {L0PreSpace L} f, pointCF {L0PreSpace L} g) = Q (pointCF {L0PreSpace L} f, pointCF {L0PreSpace L} g)) (s : \Sigma (L0Space L) (L0Space L))
  : P s = Q s
  => dense-lift-unique (ProductCoverSpace.prod (completion {L0PreSpace L}) (completion {L0PreSpace L})) (l0-dense2-embedding {L}).1 P Q (\lam t => p t.1 t.2) s

-- | A bound on `L × L` of a map $\mathrm L^0 \times \mathrm L^0 \to \mathrm L^0$ holds everywhere.
\lemma l0-bound2 {L : FullIntegrationSpace} (P : CoverMap (ProductCoverSpace (L0Space L) (L0Space L)) (L0Space L)) {r : Rat} (r>0 : RatField.zro RatField.< r)
                 (p : \Pi (f g : L) -> IsBelow (abs (P (pointCF {L0PreSpace L} f, pointCF {L0PreSpace L} g))) r) (s : \Sigma (L0Space L) (L0Space L))
  : IsBelow (abs (P s)) r
  => (IsBelow_truncAt r>0).2 $ l0-dense2 (truncAt-cover r CoverMap.∘ (L0Space L).abs-uniform CoverMap.∘ P) ((L0Space L).abs-uniform CoverMap.∘ P)
      (\lam f g => (IsBelow_truncAt r>0).1 (p f g)) s

-- | Two maps $(\mathrm L^0 \times \mathrm L^0) \times \mathrm L^0 \to \mathrm L^0$ that agree on `L³` are equal.
\lemma l0-dense3 {L : FullIntegrationSpace} (P Q : CoverMap (ProductCoverSpace (ProductCoverSpace (L0Space L) (L0Space L)) (L0Space L)) (L0Space L))
                 (p : \Pi (f g h : L) -> P ((pointCF {L0PreSpace L} f, pointCF {L0PreSpace L} g), pointCF {L0PreSpace L} h) = Q ((pointCF {L0PreSpace L} f, pointCF {L0PreSpace L} g), pointCF {L0PreSpace L} h))
                 (s : \Sigma (\Sigma (L0Space L) (L0Space L)) (L0Space L))
  : P s = Q s
  => dense-lift-unique (ProductCoverSpace.prod (ProductCoverSpace.prod (completion {L0PreSpace L}) (completion {L0PreSpace L})) (completion {L0PreSpace L}))
      (ProductTopSpace.prod.isDense {_} {_} {_} {_} {ProductCoverSpace.prod (completion {L0PreSpace L}) (completion {L0PreSpace L})} {completion {L0PreSpace L}} (l0-dense2-embedding {L}).1 completion.isDenseEmbedding.1)
      P Q (\lam t => p t.1.1 t.1.2 t.2) s

-- | $L^n$ is dense in $(\mathrm L^0)^n$.
\lemma l0-denseN-embedding {L : FullIntegrationSpace} {n : Nat} : CoverMap.IsDenseEmbedding {ArrayCoverSpace.map {n} (completion {L0PreSpace L})}
  => ArrayCoverSpace.map.isDenseEmbedding completion.isDenseEmbedding

-- | Two maps $(\mathrm L^0)^n \to \mathrm L^0$ that agree on $L^n$ are equal.
\lemma l0-denseN {L : FullIntegrationSpace} {n : Nat} (P Q : CoverMap (ArrayCoverSpace n (L0Space L)) (L0Space L))
                  (p : \Pi (f : Array L n) -> P (\lam j => pointCF {L0PreSpace L} (f j)) = Q (\lam j => pointCF {L0PreSpace L} (f j))) (s : Array (L0Space L) n)
  : P s = Q s
  => dense-lift-unique (ArrayCoverSpace.map {n} (completion {L0PreSpace L})) (l0-denseN-embedding {L} {n}).1 P Q p s

-- | $\{G \mid |G - c| \le \varepsilon\}$ is closed in `L⁰`.
\lemma l0-below-closed {L : FullIntegrationSpace} (c : L0Space L) {e : Rat} (e>0 : RatField.zro RatField.< e) : (L0Space L).IsClosed (\lam y => IsBelow (abs (y - c)) e)
  => \let D : CoverMap (L0Space L) (L0Space L) => (L0Space L).abs-uniform CoverMap.∘ subtract-uniform {L0Space L} CoverMap.∘ ProductCoverSpace.tuple CoverMap.id (CoverMap.const c)
     \in transport (\lam (S : Set (L0Space L)) => (L0Space L).IsClosed S) (ext \lam (y : L0Space L) => ext ((IsBelow_truncAt e>0).2, (IsBelow_truncAt e>0).1))
                   (equalizer-closed (truncAt-cover e CoverMap.∘ D) D)