(* -------------------------------------------------------------------- *)
(* ------- *) Require Import Setoid Morphisms.
From mathcomp Require Import all_ssreflect all_algebra.
From mathcomp.analysis Require Import boolp ereal reals realseq realsum distr.
From xhl.pwhile Require Import notations inhabited pwhile psemantic passn range.

Set   Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Unset SsrOldRewriteGoalsOrder.

Import GRing.Theory Num.Theory Order.Theory.

Local Open Scope ring_scope.
Local Open Scope syn_scope.
Local Open Scope sem_scope.
Local Open Scope mem_scope.

(* -------------------------------------------------------------------- *)
Local Notation iwhilen k b c := (iterc k (IfT b then c)).

(* -------------------------------------------------------------------- *)
Implicit Types P Q S : dassn.
Implicit Types c     : cmd.
Implicit Types mu    : dmem.

(* -------------------------------------------------------------------- *)
Definition detm (P : assn) :=
  [pred mu : dmem | `[< forall x, x \in dinsupp mu -> x \in P >]].

Definition oplus P Q (mu : dmem) :=
  exists2 smu : dmem * dmem,
    forall x, mu x = smu.1 x + smu.2 x & P smu.1 /\ Q smu.2.

Definition oplusb P Q :=
  [pred mu | `[< oplus P Q mu >]].

Notation "'□' P" := (detm P) (at level 20).
Notation "P ⊕ Q" := (oplusb P Q) (at level 40).

Lemma detmP (P : assn) mu :
  reflect (forall x, x \in dinsupp mu -> x \in P) (mu \in □ P).
Proof. by apply/asboolP. Qed.

Lemma oplusP P Q mu :
  reflect (oplus P Q mu) (mu \in P ⊕ Q).
Proof. by apply/asboolP. Qed.

(* -------------------------------------------------------------------- *)
Definition tclosed (P : nat -> dassn) (Pinf : dassn) :=
  forall (mu : nat -> dmem),
      (forall n, mu n \in P n)
   -> (forall x, exists l, ncvg (fun n => mu n x) l%:E)
   -> \dlim_(n) mu n \in Pinf.

(* -------------------------------------------------------------------- *)
Lemma tclosed_and (P Q : nat -> dassn) Pinf Qinf :
   tclosed P Pinf ->
   tclosed Q Qinf ->
   tclosed (fun n => P n /\ Q n)%A (Pinf /\ Qinf)%A.
Proof.
move=> cP cQ mu hmu hmu'; apply/andP; split.
+ by apply cP=> n //; case/andP: (hmu n).
+ by apply cQ=> n //; case/andP: (hmu n).
Qed.

(* -------------------------------------------------------------------- *)
Lemma tclosed_square (P : assn) : tclosed (fun n => □ P)%A (□ P).
Proof.
move=> mu hmu mucvg; apply/detmP => m; case/dinsupp_dlim.
by move=> n mux; have/asboolP := hmu n => /(_ _ mux).
Qed.

(* -------------------------------------------------------------------- *)
Definition uclosed (P : nat -> dassn) (Pinf : dassn) :=
  forall (mu : nat -> dmem),
      (forall n, mu n \in P n)
   -> (forall n m, (n <= m)%N -> mu n <=1 mu m)
   -> \dlim_(n) mu n \in Pinf.

(* -------------------------------------------------------------------- *)
Lemma tclosed_uclosed (P : nat -> dassn) Pinf :
  tclosed P Pinf -> uclosed P Pinf.
Proof.
move=> uc mu h1 h2; apply/uc => // x; apply/ncvg_mono_bnd => [??/h2|] //.
apply/asboolP/nboundedP; exists 2%:R => // n; apply/(@le_lt_trans _ _ 1).
+ by rewrite ger0_norm ?(ge0_mu, le1_mu1). + by rewrite (@ltr_nat _ 1).
Qed.

(* -------------------------------------------------------------------- *)
Lemma uclosed_and (P Q : nat -> dassn) Pinf Qinf :
   uclosed P Pinf ->
   uclosed Q Qinf ->
   uclosed (fun n => P n /\ Q n)%A (Pinf /\ Qinf)%A.
Proof.
move=> cP cQ mu hmu hmu'; apply/andP; split.
+ by apply cP=> // n; case/andP: (hmu n).
+ by apply cQ=> // n; case/andP: (hmu n).
Qed.

(* -------------------------------------------------------------------- *)
Lemma uclosed_square (P : assn) : uclosed (fun n => □ P)%A (□ P).
Proof. by apply/tclosed_uclosed/tclosed_square. Qed.

(* -------------------------------------------------------------------- *)
Definition tclosed0 P :=
   forall (mu : nat -> dmem),
      (forall n, mu n \in P)
    -> (forall x, exists l, ncvg (fun n => mu n x) l%:E)
   -> \dlim_(n) mu n \in P.

Definition dclosed P := tclosed0 P /\
  (forall mu, mu \in P -> forall mu', mu' <=1 mu -> mu' \in P).

(* -------------------------------------------------------------------- *)
Local Lemma Xclosed_while P b c : tclosed0 P ->
     (forall mu n, mu \in P -> dssem (whilen b c n.+1) mu \in P)
  -> (forall mu, mu \in P -> dssem (While b Do c) mu \in P).
Proof. move=> tcP h mu muP.
rewrite /dssem bsemE -dlim_let; first by apply/homo_whilen.
set F := (F in \dlim_(n) F n).
have ->: \dlim_(n) F n = \dlim_(n) F n.+1.
  by apply/distr_eqP=> m; rewrite dlim_bump.
rewrite {}/F; apply/tcP=> [|m]; first by move=> n; apply/h.
apply/ncvg_mono_bnd => [n p le_np|]; last first.
  apply/asboolP/nboundedP; exists 2%:R => // n.
  apply/(@le_lt_trans _ _ 1); last by rewrite (@ltr_nat _ 1).
  by rewrite ger0_norm ?(ge0_mu, le1_mu1).
by apply/le_in_dlet=> {}m _ m'; apply/homo_whilen.
Qed.

(* -------------------------------------------------------------------- *)
Local Lemma Xclosed_iterc P b c n:
     (forall mu, mu \in P -> dssem (IfT b then c) mu \in P)
  -> (forall mu, mu \in P -> dssem (iterc n (IfT b then c)) mu \in P).
Proof.
move=> h mu muP; rewrite ssem_iterop_iter.
elim: n mu muP => [|n ihn] mu muP /=.
  by rewrite /dssem bsemE dlet_dunit_id.
by rewrite /dssem bsemE -dlet_dlet; apply/ihn/h.
Qed.

(* -------------------------------------------------------------------- *)
Lemma dclosed_while P b c : dclosed P ->
     (forall mu, mu \in P -> dssem (IfT b then c) mu \in P)
  -> (forall mu, mu \in P -> dssem (While b Do c) mu \in P).
Proof.
move=> [tcP dwP] h mu muP; apply/Xclosed_while => // {muP} mu n muP.
rewrite whilen_iterc; set cn := iterc _ _.
move/(_ (dssem cn mu)): dwP; apply; first by apply/Xclosed_iterc.
move=> m; apply/le_in_dlet=> {}m _ m'; rewrite ssemE.
rewrite -[X in _ <= _ X _]dlet_dunit_id; apply/le_in_dlet.
move=> {m'} m _ m'; rewrite ssemE; case: ifP=> _.
  by rewrite ssemE; apply/lef_dnull. by rewrite ssemE.
Qed.

(* -------------------------------------------------------------------- *)
Definition dassn_map P (F : dmem -> dmem) mu := nosimpl (F mu \in P).

Notation "P .[ F ]" := (dassn_map P F) : assn.

(* -------------------------------------------------------------------- *)
Definition ellora P Q c :=
  forall mu, mu \in P -> dssem c mu \in Q.

Arguments ellora P%A Q%A c.

(* -------------------------------------------------------------------- *)
Lemma ellora_skip P : ellora P P skip.
Proof. by move=> mu; rewrite /dssem bsemE dlet_dunit_id. Qed.

(* -------------------------------------------------------------------- *)
Lemma ellora_abort P : ellora P (□ pred0) abort.
Proof.
move=> mu _; rewrite /dssem bsemE; apply/detmP=> m; apply/contraLR=> _.
by apply/dinsuppPn; rewrite dletC dnullE mulr0.
Qed.

(* -------------------------------------------------------------------- *)
Lemma ellora_seq S P Q c1 c2 :
  ellora P S c1 -> ellora S Q c2 -> ellora P Q (c1 ;; c2).
Proof. by move=> e1 e2 mu /e1 /e2; rewrite /dssem bsemE dlet_dlet. Qed.

(* -------------------------------------------------------------------- *)
Lemma ellora_conseq P' Q' P Q c :
    (forall mu, mu \in P  -> mu \in P')
  -> (forall mu, mu \in Q' -> mu \in Q )
  -> ellora P' Q' c
  -> ellora P  Q  c.
Proof. by move=> hP hQ h mu /hP /h /hQ. Qed.

(* -------------------------------------------------------------------- *)
Lemma ellora_sem c1 P Q c2 :
    (forall mu, mu \in P -> dssem c1 mu = dssem c2 mu)
  -> ellora P Q c1 -> ellora P Q c2.
Proof. by move=> eq h mu Pmu; have := h _ Pmu; rewrite eq. Qed.

(* -------------------------------------------------------------------- *)
Lemma ellora_and P Q1 Q2 c :
  ellora P Q1 c -> ellora P Q2 c -> ellora P (Q1 /\ Q2) c.
Proof.
move=> h1 h2 mu muP; apply/andP; split.
  by apply/h1. by apply/h2.
Qed.

(* -------------------------------------------------------------------- *)
Lemma ellora_or P1 P2 c Q :
  ellora P1 Q c -> ellora P2 Q c -> ellora (P1 \/ P2)%A Q c.
Proof. by move=> h1 h2 mu /orP[/h1|/h2]. Qed.

(* -------------------------------------------------------------------- *)
Lemma ellora_sem_condT P Q (e : expr bool) c1 c2 :
  (forall mu, mu \in P -> forall m, m \in dinsupp mu -> `[{ e }] m)
  -> ellora P Q c1 -> ellora P Q (If e then c1 else c2).
Proof.
move=> h; apply/ellora_sem=> mu /h em; apply/eq_in_dlet=> //.
by move=> m /em; rewrite !ssemE => ->.
Qed.

(* -------------------------------------------------------------------- *)
Lemma ellora_sem_condF P Q (e : expr bool) c1 c2 :
  (forall mu, mu \in P -> forall m, m \in dinsupp mu -> `[{ ~~ e }] m)
  -> ellora P Q c2 -> ellora P Q (If e then c1 else c2).
Proof.
move=> h; apply/ellora_sem=> mu /h em; apply/eq_in_dlet=> //.
by move=> m /em; rewrite !ssemE => /negbTE ->.
Qed.

(* -------------------------------------------------------------------- *)
Lemma ellora_split P P' Q Q' c :
  ellora P Q c -> ellora P' Q' c -> ellora (P ⊕ P') (Q ⊕ Q') c.
Proof.
move=> h1 h2 mu /oplusP[] [mu1 mu2] /= muE []  /h1 hQ1 /h2 hQ2.
apply/oplusP; exists (dssem c mu1, dssem c mu2)=> /=; last by split.
by move=> m; apply/dlet_additive.
Qed.

(* -------------------------------------------------------------------- *)
Lemma ellora_cond P P' Q Q' e c1 c2 :
  let SP := (P /\ □ [pred m | `[{    e }] m])%A in
  let SQ := (Q /\ □ [pred m | `[{ ~~ e }] m])%A in

     ellora SP P' c1
  -> ellora SQ Q' c2
  -> ellora (SP ⊕ SQ) (P' ⊕ Q') (If e then c1 else c2).
Proof.
move=> SP SQ hP hQ; apply/ellora_split.
+ by apply/ellora_sem_condT=> // mu /andP[_] /detmP.
+ by apply/ellora_sem_condF=> // mu /andP[_] /detmP.
Qed.

(* -------------------------------------------------------------------- *)
Lemma ellora_semmap P c : ellora P.[fun mu => dssem c mu] P c.
Proof. by []. Qed.

(* -------------------------------------------------------------------- *)
Lemma ellora_while_cond b c :
  ellora (□ predT) (□ `[{~~ b}]) (While b Do c).
Proof.
move=> mu _; apply/detmP=> m; rewrite /dssem bsemE => /dinsupp_dlet[m' _].
rewrite dlimE; apply/contra=> bm; pose u0 := fun _ : nat => 0 : R.
rewrite (@eq_nlim _ u0) ?nlimC // {}/u0 => n; elim: n m' => [|n ihn].
  by move=> m'; rewrite ssemE dnullE.
move=> m'; rewrite ssemE; case: ifP=> bm'; rewrite !ssemE.
  by unlock dlet; rewrite /= /mlet psum_eq0 // => m''; rewrite ihn mulr0.
by rewrite dunit1E (rwP eqP) pnatr_eq0 eqb0; apply/contraFN: bm' => /eqP->.
Qed.

(* -------------------------------------------------------------------- *)
Lemma ellora_while_dclosed P b c :
  dclosed P -> ellora P P (IfT b then c)
    -> ellora P (P /\ □ `[{~~ b}]) (While b Do c).
Proof.
move=> dcP hIf; apply/ellora_and; first by apply/dclosed_while.
apply/(ellora_conseq _ _ (ellora_while_cond _ _)) => //.
by move=> mu _; apply/detmP.
Qed.

(* -------------------------------------------------------------------- *)
Lemma ellora_while_uclosed (P Q : nat -> dassn) Qinf b c :
     (forall n, ellora (P n) (P n.+1) (IfT b then c))
  -> (forall n, ellora (P n) (Q n) (IfT b then abort))
  -> uclosed Q Qinf
  -> ellora (P 0)%N (Qinf /\ □ `[{~~ b}]) (While b Do c).
Proof.
move=> hP hQ Quclosed mu P0_mu.
rewrite /dssem bsemE -dlim_let; first by apply/homo_whilen.
pose F n := \dlet_(x <- mu) ssem (whilen b c n) x.
have ->: \dlim_(n) F n = \dlim_(n) F n.+1.
+ by apply/distr_eqP=> m; rewrite dlim_bump.
apply: (uclosed_and Quclosed (@uclosed_square (`[{~~ b}])%A)).
+ move=> n; pose R := ssem (iwhilen n b c ;; IfT b then abort).
  rewrite [X in X \in _](_ : _ = \dlet_(x <- mu) R x) {}/R {}/F.
  * by apply eq_in_dlet => // m _; rewrite whilen_iterc.
  move: P0_mu; rewrite -(subnn n); move: mu (leqnn n).
  elim: {1 4 5}n => [|m ihm] mu Hn.
  * rewrite [dlet _ _](_ : _ = \dlet_(x <- mu) ssem (IfT b then abort) x).
    - by apply eq_in_dlet=> // m _;rewrite iterc0 !bsemE dlet_unit.
    rewrite subn0 => Pmu_nl; apply/(ellora_and (hQ n)) => //.
    move=> m _; apply/asboolP => m' /dinsupp_dlet [y] Hy.
    rewrite !bsemE; case: ifPn; first by rewrite dnullE eqxx.
    by rewrite dunit1E pnatr_eq0 eqb0 negbK => ? /eqP<-.
  move=> PS_mu; pose d := \dlet_(x <- mu) ssem (IfT b then c) x.
  pose R x := ssem (iterc m (IfT b then c) ;; IfT b then abort) x.
  rewrite [dlet _ _](_ : _ = \dlet_(x <- d) R x) {}/R {}/d.
  + rewrite dlet_dlet; apply eq_in_dlet=> // m1 _.
    by rewrite ssem_seqE itercSl -ssem_seqE sem_seqA ssem_seqE.
  apply ihm; first by apply ltnW. by rewrite -subnSK //; apply hP.
move=> n m le_mn x; rewrite {}/F; apply/le_dlet=> // y _ z.
by apply/homo_whilen.
Qed.

(* -------------------------------------------------------------------- *)
Lemma ellora_while_tclosed (P Q : nat -> dassn) Qinf b c :
     (forall n, ellora (P n) (P n.+1) (IfT b then c))
  -> (forall n, ellora (P n) (Q n) (IfT b then abort))
  -> tclosed Q Qinf
  -> ellora (P 0)%N (Qinf /\ □ `[{~~ b}]) (While b Do c).
Proof.
move=> h1 h2 uc; apply/ellora_while_uclosed => //.
by apply/tclosed_uclosed.
Qed.

(* -------------------------------------------------------------------- *)
Lemma ellora_while_certain_ct P b c :
    (forall mu, mu \in P -> exists k,
       \P_[dssem (iwhilen k b c) mu] [eta `[{ b }]] = 0)
  -> ellora P P (IfT b then c)
  -> ellora P (P /\ □ `[{ ~~ b}]) (While b Do c).
Proof.
move=> ct hIf; apply/ellora_and; last first.
  apply/(ellora_conseq _ _ (ellora_while_cond _ _)) => //.
  by move=> mu _; apply/detmP.
move=> mu muP; case/(_ _ muP): ct => k ct.
suff ->: dssem (While b Do c) mu = dssem (iwhilen k b c) mu.
  by apply/Xclosed_iterc.
apply/eq_in_dlet=> // m m_in_mu; rewrite (unrolln_while k).
apply/distr_eqP=> m'; rewrite -[X in _ = _ X _]dlet_dunit_id.
rewrite ssemE; apply/distr_eqP: m'; apply/eq_in_dlet=> //.
move=> m' hm'; rewrite ssem_while0 //; apply/negP=> bm'.
have: m' \in dinsupp (dssem (iwhilen k b c) mu).
  apply/dinsuppP; rewrite /dssem => /eq0_dlet /(_ _ m_in_mu).
  by move/dinsuppP=> -/(_ hm').
by move/pr_eq0: ct => /(_ _ bm') /dinsuppP.
Qed.

(* -------------------------------------------------------------------- *)
Lemma ellora_while_certain (P : nat -> dassn) k e c :
     (forall n, ellora (P n) (P n.+1) (IfT e then c))
  -> (forall mu, P 0%N mu -> dssem (While e Do c) =
                             dssem (iterc k (IfT e then c)))
  -> ellora (P 0%N) (P k /\ □ `[{~~ e}]) (While e Do c).
Proof.
move=> el ds mu P0_mu; rewrite (ds _ P0_mu); apply/andP; split.
+ elim: {ds} k => [|k ih]; first by rewrite iterc0 dssem_skipE.
  by move/el: ih; rewrite -dssem_seqE -itercSr.
apply/detmP=> m; rewrite -(ds mu) //; case/dinsupp_dlet.
move=> m' _; rewrite ssemE -(funext (dlim_bump _)).
case/dinsupp_dlim=> p; rewrite whilen_iterc bsemE.
case/dinsupp_dlet=> m'' _; rewrite !bsemE; case: ifPn.
+ by move=> _; rewrite dnullE eqxx.
+ by move=> ne; rewrite dunit1E pnatr_eq0 eqb0 negbK => /eqP<-.
Qed.

(* -------------------------------------------------------------------- *)
Lemma ellora_frame P c :
  separated (mod c) P -> lossless predT c -> ellora P P c.
Proof. by move=> spc llc mu; apply/spc=> m; apply/modll. Qed.

(* -------------------------------------------------------------------- *)
Hint Resolve ellora_skip             : ellora.
Hint Resolve ellora_abort            : ellora.
Hint Resolve ellora_seq              : ellora.
Hint Resolve ellora_conseq           : ellora.
Hint Resolve ellora_sem              : ellora.
Hint Resolve ellora_and              : ellora.
Hint Resolve ellora_or               : ellora.
Hint Resolve ellora_sem_condT        : ellora.
Hint Resolve ellora_sem_condF        : ellora.
Hint Resolve ellora_split            : ellora.
Hint Resolve ellora_cond             : ellora.
Hint Resolve ellora_semmap           : ellora.
Hint Resolve ellora_while_cond       : ellora.
Hint Resolve ellora_while_dclosed    : ellora.
Hint Resolve ellora_while_tclosed    : ellora.
Hint Resolve ellora_while_uclosed    : ellora.
Hint Resolve ellora_while_certain    : ellora.
Hint Resolve ellora_while_certain_ct : ellora.
Hint Resolve ellora_frame            : ellora.


(* Copyright © 1998-2006
 * Henk Barendregt
 * Luís Cruz-Filipe
 * Herman Geuvers
 * Mariusz Giero
 * Rik van Ginneken
 * Dimitri Hendriks
 * Sébastien Hinderer
 * Bart Kirkels
 * Pierre Letouzey
 * Iris Loeb
 * Lionel Mamane
 * Milad Niqui
 * Russell O’Connor
 * Randy Pollack
 * Nickolay V. Shmyrev
 * Bas Spitters
 * Dan Synek
 * Freek Wiedijk
 * Jan Zwanenburg
 *
 * This work is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This work is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this work; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *)

Require Export CoRN.ftc.FunctSequence.
Require Export CoRN.reals.Series.

(** printing fun_seq_part_sum %\ensuremath{\sum^n}% #∑n# *)
(** printing Fun_Series_Sum %\ensuremath{\sum_0^{\infty}}% #∑0∞# *)

Section Definitions.

(**
* Series of Functions

We now turn our attention to series of functions.  Like it was already
the case for sequences, we will mainly rewrite the results we proved
for series of real numbers in a different way.

%\begin{convention}% Throughout this section:
 - [a] and [b] will be real numbers and the interval [[a,b]] will be denoted
by [I];
 - [f, g] and [h] will denote sequences of continuous functions;
 - [F, G] and [H] will denote continuous functions.

%\end{convention}%

** Definitions

As before, we will consider only sequences of continuous functions
defined in a compact interval.  For this, partial sums are defined and
convergence is simply the convergence of the sequence of partial sums.
*)

Variables a b : IR.
Hypothesis Hab : a [<=] b.
(* begin hide *)
Let I := Compact Hab.
(* end hide *)

Variable f : nat -> PartIR.

Definition fun_seq_part_sum (n : nat) := FSum0 n f.

Lemma fun_seq_part_sum_cont : (forall n, Continuous_I Hab (f n)) -> forall n,
 Continuous_I Hab (fun_seq_part_sum n).
Proof.
 intros; unfold fun_seq_part_sum in |- *.
 Contin.
Qed.

Definition fun_series_convergent := {contf : _ |
  Cauchy_fun_seq _ _ Hab fun_seq_part_sum (fun_seq_part_sum_cont contf)}.

(**
For what comes up next we need to know that the convergence of a
series of functions implies pointwise convergence of the corresponding
real number series.
*)

Lemma fun_series_conv_imp_conv : fun_series_convergent ->
 forall x, I x -> forall Hx, convergent (fun n => f n x (Hx n)).
Proof.
 intros H x H0 Hx e He.
 elim H; intros incF convF.
 elim (convF _ He).
 intros N HN.
 exists N; intros.
 apply AbsIR_imp_AbsSmall.
 simpl in HN.
 eapply leEq_wdl.
  apply (HN m N H1 (le_n N) x H0).
 apply AbsIR_wd.
 apply cg_minus_wd; unfold seq_part_sum in |- *; apply Sum0_wd; intros; rational.
Qed.

(** We then define the sum of the series as being the pointwise sum of
the corresponding series.
*)

(* begin show *)
Hypothesis H : fun_series_convergent.
(* end show *)

(* begin hide *)
Let contf := ProjT1 H.
Let incf (n : nat) := contin_imp_inc _ _ _ _ (contf n).
(* end hide *)

Lemma Fun_Series_Sum_strext : forall x y Hx Hy,
 series_sum _ (fun_series_conv_imp_conv H x Hx (fun n => incf n x Hx)) [#]
  series_sum _ (fun_series_conv_imp_conv H y Hy (fun n => incf n y Hy)) -> x [#] y.
Proof.
 intros x y Hx Hy H0.
 unfold series_sum in H0.
 elim (Lim_strext _ _ H0); intros m Hm.
 simpl in Hm; unfold seq_part_sum in Hm.
 elim (Sum0_strext _ _ _ _ Hm); intros i H1 H2.
 exact (pfstrx _ _ _ _ _ _ H2).
Qed.

Definition Fun_Series_Sum : PartIR.
Proof.
 apply Build_PartFunct with (pfpfun := fun (x : IR) (Hx : I x) => series_sum _
   (fun_series_conv_imp_conv H x Hx (fun n : nat => incf n x Hx))).
  unfold I in |- *; apply compact_wd.
 exact Fun_Series_Sum_strext.
Defined.

End Definitions.

Arguments Fun_Series_Sum [a b Hab f].

#[global]
Hint Resolve fun_seq_part_sum_cont: continuous.

Section More_Definitions.

Variables a b : IR.
Hypothesis Hab : a [<=] b.

Variable f : nat -> PartIR.

(** A series can also be absolutely convergent. *)

Definition fun_series_abs_convergent := fun_series_convergent _ _ Hab
 (fun n => FAbs (f n)).

End More_Definitions.

Section Operations.

(* **Algebraic Properties

All of these are analogous to the properties for series of real numbers, so we won't comment much about them.
*)

Variables a b : IR.
Hypothesis Hab : a [<=] b.
(* begin hide *)
Let I := Compact Hab.
(* end hide *)

Lemma fun_seq_part_sum_n : forall f (H' : forall n, Continuous_I Hab (f n)) m n,
 0 < n -> m <= n -> Feq I (fun_seq_part_sum f n{-}fun_seq_part_sum f m) (FSum m (pred n) f).
Proof.
 intros.
 unfold fun_seq_part_sum in |- *.
 apply eq_imp_Feq.
   unfold I in |- *; apply contin_imp_inc; Contin.
  unfold I in |- *; apply contin_imp_inc; Contin.
 intros; simpl in |- *.
 unfold Sum, Sum1 in |- *.
 rewrite (S_pred n 0); auto.
 apply cg_minus_wd; apply Sum0_wd; intros; rational.
Qed.

Lemma conv_fun_const_series : forall x, convergent x ->
 fun_series_convergent _ _ Hab (fun n => [-C-] (x n)).
Proof.
 intros x H.
 exists (fun n : nat => Continuous_I_const _ _ Hab (x n)).
 apply Cauchy_fun_seq2_seq.
 red in |- *; intros e He.
 elim (H e He); intros N HN.
 exists N; intros.
 simpl in |- *.
 apply AbsSmall_imp_AbsIR.
 apply AbsSmall_wdr_unfolded with (seq_part_sum x m[-]seq_part_sum x N).
  apply HN; assumption.
 unfold seq_part_sum in |- *; simpl in |- *.
 apply cg_minus_wd; apply Sum0_wd; algebra.
Qed.

Lemma fun_const_series_sum : forall y H
 (H' : fun_series_convergent _ _ Hab (fun n => [-C-] (y n))) x Hx, Fun_Series_Sum H' x Hx [=] series_sum y H.
Proof.
 intros.
 simpl in |- *.
 apply series_sum_wd.
 algebra.
Qed.

Lemma conv_zero_fun_series : fun_series_convergent _ _ Hab (fun n => [-C-][0]).
Proof.
 apply conv_fun_const_series with (x := fun n : nat => ZeroR).
 apply conv_zero_series.
Qed.

Lemma Fun_Series_Sum_zero : forall (H : fun_series_convergent _ _ Hab (fun n => [-C-][0]))
 x Hx, Fun_Series_Sum H x Hx [=] [0].
Proof.
 intros.
 simpl in |- *.
 apply series_sum_zero.
Qed.

(* begin show *)
Variables f g : nat -> PartIR.
(* end show *)

Lemma fun_series_convergent_wd : (forall n, Feq I (f n) (g n)) ->
 fun_series_convergent _ _ Hab f -> fun_series_convergent _ _ Hab g.
Proof.
 intros H H0.
 elim H0; intros contF convF.
 cut (forall n : nat, Continuous_I Hab (g n)). intro H1.
  exists H1.
  apply Cauchy_fun_seq_wd with (fun_seq_part_sum f) (fun_seq_part_sum_cont _ _ _ _ contF).
   2: assumption.
  intros.
  apply eq_imp_Feq.
    apply contin_imp_inc; Contin.
   apply contin_imp_inc; Contin.
  intros x H2 Hx Hx'; simpl in |- *.
  apply Sum0_wd.
  intro i; elim (H i); intros.
  inversion_clear b0; auto.
 intro; apply Continuous_I_wd with (f n); auto.
Qed.

(* begin show *)
Hypothesis convF : fun_series_convergent _ _ Hab f.
Hypothesis convG : fun_series_convergent _ _ Hab g.
(* end show *)

Lemma Fun_Series_Sum_wd' : (forall n, Feq I (f n) (g n)) -> Feq I (Fun_Series_Sum convF) (Fun_Series_Sum convG).
Proof.
 intro H.
 apply eq_imp_Feq.
   Included.
  Included.
 intros x H0 Hx Hx'; simpl in |- *.
 apply series_sum_wd.
 intro; elim (H n); intros.
 inversion_clear b0; auto.
Qed.

Lemma conv_fun_series_plus : fun_series_convergent _ _ Hab (fun n => f n{+}g n).
Proof.
 elim convF; intros contF convF'.
 elim convG; intros contG convG'.
 assert (H := fun n : nat => Continuous_I_plus _ _ _ _ _ (contF n) (contG n)); exists H.
 cut (forall n : nat, Continuous_I Hab (fun_seq_part_sum f n{+}fun_seq_part_sum g n));
   [ intro H0 | Contin ].
 apply Cauchy_fun_seq_wd with (f := fun n : nat => fun_seq_part_sum f n{+}fun_seq_part_sum g n)
   (contf := H0).
  2: eapply fun_Cauchy_prop_plus; auto; [ apply convF' | apply convG' ].
 intros; apply eq_imp_Feq.
   Included.
  apply contin_imp_inc; Contin.
 intros; simpl in |- *.
 apply eq_symmetric_unfolded; eapply eq_transitive_unfolded.
  2: apply Sum0_plus_Sum0.
 apply Sum0_wd; intros; rational.
Qed.

Lemma Fun_Series_Sum_plus : forall H : fun_series_convergent _ _ Hab (fun n => f n{+}g n),
 Feq I (Fun_Series_Sum H) (Fun_Series_Sum convF{+}Fun_Series_Sum convG).
Proof.
 intros.
 apply eq_imp_Feq.
   Included.
  Included.
 intros x H0 Hx Hx'; simpl in |- *.
 elim convF; intros contF convF'.
 elim convG; intros contG convG'.
 cut (convergent (fun n : nat => Part _ _ (contin_imp_inc _ _ _ _ (contF n) x (ProjIR1 Hx')) [+]
   Part _ _ (contin_imp_inc _ _ _ _ (contG n) x (ProjIR2 Hx')))). intro H1.
  eapply eq_transitive_unfolded.
   2: apply series_sum_plus with (x := fun n : nat =>
     Part _ _ (contin_imp_inc _ _ _ _ (contF n) x (ProjIR1 Hx'))) (y := fun n : nat =>
       Part _ _ (contin_imp_inc _ _ _ _ (contG n) x (ProjIR2 Hx'))) (H := H1).
  apply series_sum_wd; intro; rational.
 intros e H1.
 elim H; intros cont H'.
 elim (H' _ H1); intros N HN.
 exists N; intros.
 apply AbsIR_imp_AbsSmall.
 eapply leEq_wdl.
  apply (HN m N H2 (le_n N) x H0).
 apply AbsIR_wd; unfold fun_seq_part_sum in |- *.
 simpl in |- *.
 unfold seq_part_sum in |- *; apply cg_minus_wd; apply Sum0_wd; intros; rational.
Qed.

Lemma conv_fun_series_minus : fun_series_convergent _ _ Hab (fun n => f n{-}g n).
Proof.
 elim convF; intros contF convF'.
 elim convG; intros contG convG'.
 assert (H := fun n : nat => Continuous_I_minus _ _ _ _ _ (contF n) (contG n)); exists H.
 cut (forall n : nat, Continuous_I Hab (fun_seq_part_sum f n{-}fun_seq_part_sum g n));
   [ intro H0 | Contin ].
 apply Cauchy_fun_seq_wd with (f := fun n : nat => fun_seq_part_sum f n{-}fun_seq_part_sum g n)
   (contf := H0).
  2: eapply fun_Cauchy_prop_minus; auto; [ apply convF' | apply convG' ].
 intros; apply eq_imp_Feq.
   Included.
  apply contin_imp_inc; Contin.
 intros; simpl in |- *.
 apply eq_symmetric_unfolded.
 apply eq_transitive_unfolded with (Sum0 n (fun i : nat => f i x (ProjIR1 Hx i)) [+]
   Sum0 n (fun i : nat => [--] (g i x (ProjIR2 Hx i)))).
  eapply eq_transitive_unfolded.
   2: apply Sum0_plus_Sum0.
  apply Sum0_wd; intros; rational.
 unfold cg_minus in |- *.
 apply bin_op_wd_unfolded.
  algebra.
 eapply eq_transitive_unfolded.
  2: apply inv_Sum0.
 apply Sum0_wd; algebra.
Qed.

Lemma Fun_Series_Sum_min : forall H : fun_series_convergent _ _ Hab (fun n => f n{-}g n),
 Feq I (Fun_Series_Sum H) (Fun_Series_Sum convF{-}Fun_Series_Sum convG).
Proof.
 intros.
 apply eq_imp_Feq.
   Included.
  Included.
 intros x H0 Hx Hx'; simpl in |- *.
 elim convF; intros contF convF'.
 elim convG; intros contG convG'.
 cut (convergent (fun n : nat => Part _ _ (contin_imp_inc _ _ _ _ (contF n) x (ProjIR1 Hx')) [-]
   Part _ _ (contin_imp_inc _ _ _ _ (contG n) x (ProjIR2 Hx')))). intro H1.
  apply eq_transitive_unfolded with (series_sum _
    (fun_series_conv_imp_conv _ _ _ _ convF x (ProjIR1 Hx')
      (fun n : nat => contin_imp_inc _ _ _ _ (contF n) x (ProjIR1 Hx'))) [-] series_sum _
        (fun_series_conv_imp_conv _ _ _ _ convG x (ProjIR2 Hx')
          (fun n : nat => contin_imp_inc _ _ _ _ (contG n) x (ProjIR2 Hx')))).
   eapply eq_transitive_unfolded.
    2: apply series_sum_minus with (x := fun n : nat =>
      Part _ _ (contin_imp_inc _ _ _ _ (contF n) x (ProjIR1 Hx'))) (y := fun n : nat =>
        Part _ _ (contin_imp_inc _ _ _ _ (contG n) x (ProjIR2 Hx'))) (H := H1).
   apply series_sum_wd; intro; rational.
  apply cg_minus_wd; apply series_sum_wd; intro; rational.
 intros e H1.
 elim H; intros cont H'.
 elim (H' _ H1); intros N HN.
 exists N; intros.
 apply AbsIR_imp_AbsSmall.
 eapply leEq_wdl.
  apply (HN m N H2 (le_n N) x H0).
 apply AbsIR_wd; unfold fun_seq_part_sum in |- *.
 simpl in |- *.
 unfold seq_part_sum in |- *; apply cg_minus_wd; apply Sum0_wd; intros; rational.
Qed.

(**
%\begin{convention}% Let [c:IR].
%\end{convention}%
*)

Variable c : IR.
Variable H : PartIR.
Hypothesis contH : Continuous_I Hab H.

Lemma conv_fun_series_scal : fun_series_convergent _ _ Hab (fun n => H{*}f n).
Proof.
 elim convF; intros contF convF'.
 set (H' := fun n : nat => Continuous_I_mult _ _ _ _ _ contH (contF n)) in *; exists H'.
 cut (forall n : nat, Continuous_I Hab (fun_seq_part_sum f n)); [ intro H0 | Contin ].
 cut (forall n : nat, Continuous_I Hab (H{*}fun_seq_part_sum f n)); [ intro H1 | Contin ].
 unfold I in |- *; apply Cauchy_fun_seq_wd with (fun n : nat => H{*}fun_seq_part_sum f n) H1.
  2: apply fun_Cauchy_prop_mult with (f := fun n : nat => H) (contf := fun n : nat => contH)
    (g := fun_seq_part_sum f) (contg := H0).
   intro; FEQ.
    apply contin_imp_inc; Contin.
   simpl in |- *.
   unfold seq_part_sum in |- *.
   apply eq_symmetric_unfolded.
   eapply eq_transitive_unfolded.
    2: apply Sum0_comm_scal' with (s := fun m : nat => f m x (ProjIR2 Hx m)).
   apply Sum0_wd; intros; rational.
  apply fun_Cauchy_prop_const.
 apply Cauchy_fun_seq_wd with (f := fun_seq_part_sum f)
   (contf := fun_seq_part_sum_cont _ _ _ _ contF).
  2: assumption.
 intro; apply Feq_reflexive; Included.
Qed.

Lemma Fun_Series_Sum_scal : forall H' : fun_series_convergent _ _ Hab (fun n => H{*}f n),
 Feq I (Fun_Series_Sum H') (H{*}Fun_Series_Sum convF).
Proof.
 elim convF; intros contF convF'.
 intros.
 unfold I in |- *; FEQ. try rename X into H0.
 cut (convergent (fun n : nat => Part H x (ProjIR1 Hx') [*]
   f n x (contin_imp_inc _ _ _ _ (contF n) _ (ProjIR2 Hx')))). intro H1.
  apply eq_transitive_unfolded with (series_sum (fun n : nat => Part H x (ProjIR1 Hx') [*]
    f n x (contin_imp_inc _ _ _ _ (contF n) _ (ProjIR2 Hx'))) H1).
   2: simpl in |- *; apply series_sum_mult_scal with (x := fun n : nat =>
     f n x (contin_imp_inc _ _ _ _ (contF n) _ (ProjIR2 Hx'))).
  simpl in |- *; unfold series_sum in |- *.
  apply Lim_wd'; intros; simpl in |- *.
  unfold seq_part_sum in |- *; apply Sum0_wd; intros; rational.
 intros e H1.
 elim H'; intros H'' H'''.
 elim (H''' _ H1); intros N HN.
 exists N; intros.
 apply AbsIR_imp_AbsSmall.
 eapply leEq_wdl.
  apply (HN m N H2 (le_n N) x Hx).
 apply AbsIR_wd; simpl in |- *.
 unfold seq_part_sum in |- *; apply cg_minus_wd; apply Sum0_wd; intros; rational.
Qed.

End Operations.

Section More_Operations.

Variables a b : IR.
Hypothesis Hab : a [<=] b.
(* begin hide *)
Let I := Compact Hab.
(* end hide *)

Variable f : nat -> PartIR.
Hypothesis convF : fun_series_convergent _ _ Hab f.

Lemma conv_fun_series_inv : fun_series_convergent _ _ Hab (fun n => {--} (f n)).
Proof.
 elim convF; intros contF convF'.
 exists (fun n : nat => Continuous_I_inv _ _ _ _ (contF n)).
 cut (forall n : nat, Continuous_I Hab {--} (fun_seq_part_sum f n)). intro H.
  apply Cauchy_fun_seq_wd with (f := fun n : nat => {--} (fun_seq_part_sum f n)) (contf := H).
   2: apply fun_Cauchy_prop_inv with (fun_seq_part_sum_cont _ _ _ _ contF).
   intro; FEQ.
    apply contin_imp_inc; Contin.
   simpl in |- *; unfold seq_part_sum in |- *.
   apply eq_symmetric_unfolded; eapply eq_transitive_unfolded.
    2: apply inv_Sum0.
   apply Sum0_wd; intro; rational.
  assumption.
 Contin.
Qed.

Lemma Fun_Series_Sum_inv : forall H : fun_series_convergent _ _ Hab (fun n => {--} (f n)),
 Feq I (Fun_Series_Sum H) {--} (Fun_Series_Sum convF).
Proof.
 intros.
 FEQ. try rename X into H0.
 cut (convergent (fun n : nat =>
   [--] (f n x (contin_imp_inc _ _ _ _ (ProjT1 convF n) x Hx')))). intro H1.
  simpl in |- *; apply eq_transitive_unfolded with (series_sum _ H1).
   2: apply series_sum_inv with (x := fun n : nat =>
     f n x (contin_imp_inc _ _ _ _ (ProjT1 convF n) x Hx')).
  unfold series_sum in |- *; apply Lim_wd'; intros; simpl in |- *.
  unfold seq_part_sum in |- *; apply Sum0_wd; intros.
  rational.
 apply conv_series_inv with (x := fun n : nat =>
   f n x (contin_imp_inc _ _ _ _ (ProjT1 convF n) x Hx')).
 apply fun_series_conv_imp_conv with (Hab := Hab)
   (Hx := fun n : nat => contin_imp_inc _ _ _ _ (ProjT1 convF n) x Hx'); assumption.
Qed.

End More_Operations.

Section Other_Results.

Variables a b : IR.
Hypothesis Hab : a [<=] b.

Variable f : nat -> PartIR.

Hypothesis convF : fun_series_convergent a b Hab f.

(**
The following relate the sum series with the limit of the sequence of
partial sums; as a corollary we get the continuity of the sum of the
series.
*)

Lemma Fun_Series_Sum_char' : forall contf H,
 Feq (Compact Hab) (Fun_Series_Sum convF) (Cauchy_fun_seq_Lim _ _ Hab (fun_seq_part_sum f) contf H).
Proof.
 intros.
 FEQ.
 simpl in |- *; unfold series_sum in |- *.
 apply Lim_wd'; simpl in |- *; intros.
 unfold seq_part_sum in |- *; apply Sum0_wd; intros; algebra.
Qed.

Lemma fun_series_conv : forall H H',
 conv_fun_seq' a b Hab (fun_seq_part_sum f) (Fun_Series_Sum convF) H H'.
Proof.
 intros.
 inversion_clear convF. try rename X into H0.
 apply conv_fun_seq'_wdr with (contf := fun_seq_part_sum_cont _ _ _ _ x)
   (contF := Cauchy_cont_Lim _ _ _ _ _ H0).
  2: apply Cauchy_conv_fun_seq'.
 apply Feq_symmetric; apply Fun_Series_Sum_char'.
Qed.

Lemma Fun_Series_Sum_cont : Continuous_I Hab (Fun_Series_Sum convF).
Proof.
 intros.
 inversion_clear convF. try rename X into H.
 eapply Continuous_I_wd.
  apply Feq_symmetric; apply
    (Fun_Series_Sum_char' (fun n : nat => fun_seq_part_sum_cont _ _ _ _ x n) H).
 Contin.
Qed.

Lemma Fun_Series_Sum_char : Feq (Compact Hab)
 (Cauchy_fun_seq_Lim _ _ Hab (fun_seq_part_sum f) _ (ProjT2 convF)) (Fun_Series_Sum convF).
Proof.
 intros.
 FEQ.
 simpl in |- *.
 unfold series_sum in |- *; apply Lim_wd'.
 intro; simpl in |- *.
 unfold seq_part_sum in |- *; apply Sum0_wd; intros; algebra.
Qed.

Lemma Fun_Series_Sum_as_Lim : forall Hf H',
 conv_fun_seq' _ _ Hab (fun_seq_part_sum f) (Fun_Series_Sum convF) Hf H'.
Proof.
 intros.
 apply conv_fun_seq'_wdr with (fun_seq_part_sum_cont _ _ _ _ (ProjT1 convF))
   (Cauchy_fun_seq_Lim _ _ _ _ _ (ProjT2 convF)) (Cauchy_cont_Lim _ _ _ _ _ (ProjT2 convF)).
  apply Fun_Series_Sum_char.
 apply Cauchy_conv_fun_seq'.
Qed.

End Other_Results.

#[global]
Hint Resolve Fun_Series_Sum_cont: continuous.

Section Convergence_Criteria.

(**
** Convergence Criteria

Most of the convergence criteria for series of real numbers carry over to series of real-valued functions, so again we just present them without comments.
*)

Variables a b : IR.
Hypothesis Hab : a [<=] b.
(* begin hide *)
Let I := Compact Hab.
(* end hide *)

Variable f : nat -> PartIR.
Hypothesis contF : forall n : nat, Continuous_I Hab (f n).

Lemma fun_str_comparison : forall g, fun_series_convergent _ _ Hab g ->
 {k : nat | forall n, k <= n -> forall x, I x -> forall Hx Hx', AbsIR (f n x Hx) [<=] g n x Hx'} ->
 fun_series_convergent _ _ Hab f.
Proof.
 set (H0 := contF) in *.
 intros g H H1.
 elim H1; intros k Hk.
 exists H0.
 apply Cauchy_fun_seq2_seq.
 intros e H2.
 elim H; intros contG convG.
 cut {N : nat | k < N /\ (forall m : nat, N <= m -> forall x : IR, I x -> forall Hx Hx', AbsSmall e
   (Part (fun_seq_part_sum g m) x Hx[-]Part (fun_seq_part_sum g N) x Hx'))}. intro H3.
  elim H3; clear H3.
  intros N HN; elim HN; clear HN; intros HN' HN.
  exists N; intros.
  assert (H' := fun n : nat => contin_imp_inc _ _ _ _ (fun_seq_part_sum_cont _ _ _ _ contG n)).
  apply leEq_transitive with (Part (fun_seq_part_sum g m) x (H' m x Hx) [-]
    Part (fun_seq_part_sum g N) x (H' N x Hx)).
   cut (forall n : nat, included (Compact Hab) (Dom (FAbs (f n)))). intro H4.
    cut (Dom (FSum N (pred m) (fun n : nat => FRestr (H4 n))) x). intro H5.
     apply leEq_transitive with (Part (FSum N (pred m) (fun n : nat => FRestr (H4 n))) x H5).
      cut (Dom (FSum N (pred m) (fun n : nat => FRestr (contin_imp_inc _ _ _ _ (H0 n)))) x). intro H6.
       apply leEq_wdl with (AbsIR (Part (FSum N (pred m)
         (fun n : nat => FRestr (contin_imp_inc _ _ _ _ (H0 n)))) x H6)).
        Opaque Frestr.
        simpl in |- *.
        Transparent Frestr.
        eapply leEq_wdr.
         apply triangle_SumIR.
         rewrite <- (S_pred m k); auto; apply lt_le_trans with N; auto.
        apply Sum_wd; intros.
        Opaque FAbs.
        simpl in |- *.
        Transparent FAbs.
        apply eq_symmetric_unfolded.
        eapply eq_transitive_unfolded.
         apply FAbs_char with (Hx' := contin_imp_inc _ _ _ _ (contF i) x Hx).
        apply AbsIR_wd; rational.
       apply AbsIR_wd; apply eq_symmetric_unfolded.
       cut (Dom (fun_seq_part_sum f m{-}fun_seq_part_sum f N) x). intro H7.
        Opaque fun_seq_part_sum.
        apply eq_transitive_unfolded with (Part _ _ H7).
         simpl in |- *; rational.
        unfold Frestr in |- *.
        apply Feq_imp_eq with I.
         apply Feq_transitive with (FSum N (pred m) f).
          unfold I in |- *; apply fun_seq_part_sum_n; auto with arith.
          apply le_lt_trans with k; [ idtac | apply lt_le_trans with N ]; auto with arith.
         apply eq_imp_Feq.
           unfold I in |- *; apply contin_imp_inc; Contin.
          simpl in |- *.
          red in |- *; intros; auto.
         simpl in |- *.
         intros. apply Sum_wd; intros; rational.
        auto.
       split; simpl in |- *.
        apply (contin_imp_inc _ _ _ _ (fun_seq_part_sum_cont _ _ _ _ H0 m)); auto.
       apply (contin_imp_inc _ _ _ _ (fun_seq_part_sum_cont _ _ _ _ H0 N)); auto.
      simpl in |- *; auto.
     cut (Dom (FSum N (pred m) g) x). intro H6.
      apply leEq_wdr with (Part _ _ H6).
       apply FSum_resp_leEq.
        rewrite <- (S_pred m k); auto; apply lt_le_trans with N; auto.
       intros.
       Opaque FAbs.
       simpl in |- *.
       eapply leEq_wdl.
        2: apply eq_symmetric_unfolded;
          apply FAbs_char with (Hx' := contin_imp_inc _ _ _ _ (contF i) x0 (HxF i)).
       apply Hk.
        apply le_trans with N; auto with arith.
       simpl in HxF.
       apply (HxF 0).
      cut (Dom (fun_seq_part_sum g m{-}fun_seq_part_sum g N) x). intro H7.
       apply eq_symmetric_unfolded.
       apply eq_transitive_unfolded with (Part _ _ H7).
        simpl in |- *; rational.
       apply Feq_imp_eq with I.
        unfold I in |- *; apply fun_seq_part_sum_n; auto with arith.
        apply le_lt_trans with k; [ idtac | apply lt_le_trans with N ]; auto with arith.
       auto.
      split; simpl in |- *.
       apply (contin_imp_inc _ _ _ _ (fun_seq_part_sum_cont _ _ _ _ contG m)); auto.
      apply (contin_imp_inc _ _ _ _ (fun_seq_part_sum_cont _ _ _ _ contG N)); auto.
     simpl in |- *; intro; apply (contin_imp_inc _ _ _ _ (contG n)); auto.
    Transparent FAbs.
    simpl in |- *; auto.
   Opaque FAbs.
   unfold I in |- *; simpl in |- *; Included.
  eapply leEq_transitive.
   apply leEq_AbsIR.
  apply AbsSmall_imp_AbsIR.
  apply HN; assumption.
 elim (convG _ H2).
 intros N HN; exists (S (max N k)).
 cut (N <= max N k); [ intro | apply le_max_l ].
 cut (k <= max N k); [ intro | apply le_max_r ].
 split.
  auto with arith.
 intros m H5 x H6 Hx Hx'.
 apply AbsIR_imp_AbsSmall.
 cut (N <= m); [ intro | apply le_trans with (max N k); auto with arith ].
 eapply leEq_wdl.
  Transparent fun_seq_part_sum.
  simpl in Hx'.
  apply (HN m _ H7 (le_S _ _ H3) x H6).
 Opaque fun_seq_part_sum.
 apply AbsIR_wd; rational.
Qed.

Transparent FAbs.

Lemma fun_comparison : forall g, fun_series_convergent _ _ Hab g ->
 (forall n x,  I x -> forall Hx Hx', AbsIR (f n x Hx) [<=] g n x Hx') ->
 fun_series_convergent _ _ Hab f.
Proof.
 intros g H H0.
 apply fun_str_comparison with g; auto.
 exists 0; intros; apply H0; auto.
Qed.

Lemma abs_imp_conv : fun_series_abs_convergent _ _ Hab f ->
 fun_series_convergent _ _ Hab f.
Proof.
 intro H.
 apply fun_comparison with (fun n : nat => FAbs (f n)).
  apply H.
 intros; apply eq_imp_leEq; apply eq_symmetric_unfolded; apply FAbs_char.
Qed.

Lemma fun_ratio_test_conv : {N : nat | {c : IR | c [<] [1] | [0] [<=] c /\
 (forall x, I x -> forall n, N <= n -> forall Hx Hx', AbsIR (f (S n) x Hx') [<=] c[*]AbsIR (f n x Hx))}} ->
 fun_series_convergent _ _ Hab f.
Proof.
 intro H.
 elim H; clear H; intros N H.
 elim H; clear H; intros c Hc1 H.
 elim H; clear H; intros H0c H.
 cut (forall x : IR, I x -> forall n : nat, N <= n ->
   forall Hx Hx', AbsIR (f n x Hx') [<=] AbsIR (f N x Hx) [*]c[^] (n - N)).
  intro H0.
  apply fun_str_comparison with (fun n : nat => FAbs (f N) {*} [-C-] (c[^] (n - N))).
   2: exists N; intros.
   2: eapply leEq_wdr.
    2: apply H0 with (Hx' := Hx) (Hx := ProjIR1 (ProjIR1 Hx')); auto with arith.
   Opaque FAbs.
   2: simpl in |- *; apply mult_wd; [ apply eq_symmetric_unfolded; apply FAbs_char | algebra ].
  apply conv_fun_series_scal with (f := fun n : nat => [-C-] (c[^] (n - N))).
   apply conv_fun_const_series with (x := fun n : nat => c[^] (n - N)).
   apply join_series with (power_series c).
    apply power_series_conv.
    apply AbsIR_less.
     assumption.
    apply less_leEq_trans with [0].
     rstepr ([--][0]:IR).
     apply inv_resp_less.
     apply pos_one.
    assumption.
   exists N.
   exists 0.
   intro.
   rewrite plus_comm; rewrite Minus.minus_plus.
   algebra.
  Contin.
 intros x H0 n; induction  n as [| n Hrecn].
  intro.
  cut (N = 0); [ intro | auto with arith ].
  rewrite H2.
  intros.
  apply eq_imp_leEq.
  simpl in |- *.
  astepl (AbsIR (Part _ _ Hx') [*][1]); apply mult_wdl; apply AbsIR_wd; algebra.
 intro.
 elim (le_lt_eq_dec _ _ H1); intro.
  intros; apply leEq_transitive with (c[*]AbsIR (f n x (contin_imp_inc _ _ _ _ (contF n) x H0))).
   apply H; auto with arith.
  apply leEq_wdr with (AbsIR (f N x Hx) [*]c[^] (n - N) [*]c).
   rstepr (c[*] (AbsIR (Part _ _ Hx) [*]c[^] (n - N))).
   apply mult_resp_leEq_lft.
    apply Hrecn; auto with arith.
   assumption.
  rewrite <- minus_Sn_m.
   simpl in |- *; rational.
  auto with arith.
 rewrite b0; intros.
 rewrite <- minus_n_n.
 apply eq_imp_leEq.
 simpl in |- *; eapply eq_transitive_unfolded.
  2: apply eq_symmetric_unfolded; apply mult_one.
 apply AbsIR_wd; algebra.
Qed.

End Convergence_Criteria.


Require Export XR_R.
Require Export XR_R0.
Require Export XR_R1.
Require Export XR_Rplus_opp_r.
Require Export XR_Rmult.
Require Export XR_Rmult_comm.
Require Export XR_Rmult_1_l.
Require Export XR_Rmult_plus_distr_l.
Require Export XR_Rplus_eq_reg_r.
Require Export XR_Rplus_0_r.

Local Open Scope R_scope.
Implicit Type r : R.

Lemma Rmult_0_r : forall r, r * R0 = R0.
Proof.
  assert (Rmult_comm := Rmult_comm).
  assert (Rplus_assoc := Rplus_assoc).
  assert (Rplus_opp_r := Rplus_opp_r).
  assert (Rplus_opp_l := Rplus_opp_l).
  assert (Rplus_0_r := Rplus_0_r).
  assert (Rmult_1_l := Rmult_1_l).
  assert (Rmult_plus_distr_l := Rmult_plus_distr_l).
  assert (Rplus_eq_reg_r := Rplus_eq_reg_r).

  intro x.
  pattern R0 at 2;rewrite <- Rplus_opp_r with x.
  apply Rplus_eq_reg_r with x.
  rewrite Rplus_assoc.
  rewrite Rplus_opp_l.
  rewrite Rplus_0_r.
  pattern x at 2 ; rewrite <- Rmult_1_l.
  rewrite (Rmult_comm R1).
  rewrite <- Rmult_plus_distr_l.
  rewrite Rplus_0_l.
  rewrite Rmult_comm.
  rewrite Rmult_1_l.
  reflexivity.
Qed.


Require Import CRtrans.
Require Import Qmetric.

(* For comparison with Pattison's paper:
The ODE:
f'=λx.2f(x)+1
f(0)=0
*)

Section ODE.
Open Scope uc_scope.
Require Import ProductMetric CompleteProduct.
Require Import Unicode.Utf8.
Require Import CPoly_Newton.
Require Import metric2.Classified.
Require Import Circle.
Notation "X * Y":=(ProductMS X Y).
Notation " f >> g ":= (Cbind_slow f ∘ g) (at level 50).
Notation " x >>= f ":= (Cbind_slow f x) (at level 50).

Section Picard_op.
Require Import AbstractIntegration.
(*
Require Import stdlib_omissions.Pair.
For diagonal*)

Variable v: (Q*Q) -->CR.
Variable f:Q-->CR.
Notation "( f , g )":= (together f g).
Definition vxfx:= (v >> Couple ∘ (Cunit, f) ∘ diag _).

Require Import SimpleIntegration.

(* Uniformly continuous function should be a type class
so that we can define functions using Program Instance *)
(* Integration takes a width, need the integral from a to b.*)

Definition integral:  ((Q-->CR) * Q * Q) -> CR.
intros [[g a] b].
destruct (QMinMax.Qlt_le_dec_fast b a).
assert (a_min_b:Qpos).  exists (a-b) . admit.
exact (- ∫ g b (a_min_b))%CR.

(* Do the zero case *)
assert (b_min_a:Qpos).  exists (b-a). admit.
exact ( ∫ g a (b_min_a))%CR.
Defined.

(* Need continuous Q--> CR then continuous CR --> CR *)

(* The integral is locally uniformly continuous *)
(* Context (f: Q -> CR) `{!LocallyUniformlyContinuous_mu f} `{!LocallyUniformlyContinuous f}.*)
(* Definition intregral_uc:= (is_UniformlyContinuousFunction integral (fun e => e)%Qpos ). *)

Definition Picard_raw:=fun t:Q => integral (f, 0, t).

Lemma Picard_uc: (is_UniformlyContinuousFunction Picard_raw (fun e => e)%Qpos).
admit.
Qed.
(* Locally Lipschitz:
∫ 0 t f - ∫ 0 s f = ∫ s t f ≤ |t-s| sup_[s,t] f
Hence the constant is: r  sup_B f on the ball B(t,r).
differentiable maps are Lipschitz.
Locally Lipschitz functions compose
on B(x,r),
| f x - f y |  ≤ L_B |x -y|
Hence fB ⊂ B(f x, L r) and g is Lipschitz cont on this ball.
*)

Definition Picard:=(Cbind_slow (Build_UniformlyContinuousFunction Picard_uc)).
End Picard_op.

Section Banach_it.
Context {X} `(F:X-->X).
Fixpoint Banach_seq (n : nat) : X --> X :=
         match n with
         | O => F
         | S m => F ∘ (Banach_seq m)
         end.

Variable f:CR-->CR.
Check Picard.
Fixpoint Picard_seq (n : nat) : Q --> CR :=
         match n with
         | O => f ∘ Cunit
         | S m => (Picard (Picard_seq m) )∘ Cunit
         end.
End Banach_it.

Section Picard.
Variable L:Qpos.
Variable c:Qpos.
Hypothesis c_unit:1-c>0.
Program Definition oneminc:=(1-c):Qpos.
Next Obligation.
admit.
Defined.
Variables a K:Q.
Hypothesis aL_le_c:(a*L<c).
Require Import Qabs.
Require Export CRabs.
Require Import Interval.

Variable v: (Q*Q) -->CR.

Hypothesis Lipschitz: forall x, -a<=x -> x<=a -> forall y, -K<=y -> y<=K ->
  forall y':Q, -K<=y' -> y <=K ->
 ((CRabs ((v  (x,  y)) -  (v (x, y'))))<= 'L* 'Qabs (y-y'))%CR.

Section BanachFPT.
Context (X: MetricSpace).
Context (d:X->X->CR).

(*
Notation Qset:=QArith.QArith_base.Q.
Coercion inject_Q:Qset>-> (msp_is_setoid CR).
*)
Variable metric_function: forall e x y, ball e x y <-> ((d x y) <='e)%CR.
Class Contraction `(F:X-->X)`(c:Qpos):= contraction:
  c<1-> forall x x', ((d x x') <= 'c*(d (F x) (F x')))%CR.

(* forall ϵ, (ball ϵ x x')-> (ball (c*ϵ) (F x) (F x' )) *)
Context {F}`{conF: Contraction F}.
Require Export CRGeometricSum.

(*
Definition InfiniteSum_raw_F rec (err_prop: (Stream X) -> bool) (s:Stream X) : X :=
if (err_prop s) then 0 else (Qplus' (hd s) (rec err_prop (tl s))).

Definition InfiniteGeometricSum_raw series (e:QposInf) : X :=
match e with
| ∞ => 0
| Qpos2QposInf err => InfiniteSum_raw_N (InfiniteGeometricSum_maxIter series err)
  (fun err s => 0) (err_prop err) series
end.
*)

Lemma bla: forall n m:nat, forall x:X,
  (ball (c^m) (@Banach_seq _ F n x) (@Banach_seq _ F (n+m) x)).
Admitted.

Lemma bla2: forall n:nat, forall x:X,  (ball (Qpos_inv oneminc) x (@Banach_seq _ F n x)).
Admitted.

Lemma bla3: forall n m:nat, forall x:X, forall e,
  (ball e x (F x)) ->
  (ball (c^m*(Qpos_inv oneminc)*e) (@Banach_seq _ F n x) (@Banach_seq _ F m x)).
Admitted.

Variable x:X.
Definition DiffSeries:=fun n => d (@Banach_seq _ F n x) (@Banach_seq _ F (S n) x).
Require Import StreamMemo.
Definition DiffStream:=(memo_list _ DiffSeries).
Require Import CoqStreams.

(* ForAll_map in CoqStreams ?? *)
Definition GeometricSeriesCR (c:CR):=
  (ForAll (fun s:Stream CR => (CRabs ((hd (tl s))) <= c*(CRabs(hd s)))%CR)).

Lemma GeomDiff:GeometricSeriesCR ('c)%CR DiffStream.
unfold GeometricSeriesCR.
unfold DiffStream.
unfold memo_list.
unfold memo_make.
simpl.
admit.
Qed.

(* The Banach sequence is a Cauchy sequence.*)

(* Use:
Lemma GeometricCovergenceLemma : forall (n:positive) (e:Qpos),
 /(e*(1 - a)) <= n -> a^n <= e.
with e:=ϵ *oneminc/ (d x0 x1)
*)

Lemma BanachCauchy: forall ϵ:Qpos, exists N, forall n m:nat , n >=N-> m>= N ->
   (ball ϵ (@Banach_seq _ F n x) (@Banach_seq _ F m x)).
intros.
(* Needs to be of type Qpos, want Qpos as a type class *)
(* A rational number bigger than (d x0 x1) *)
set ceil:=(Qabs (approximate (d (@Banach_seq _ F 0 x) (@Banach_seq _ F 1 x))
  (Qpos2QposInf (1#1))))+1:Qpos.

exists ( /((ϵ*oneminc/ceil)(oneminc))).

(* Note that to apply the geomSum we do compute all the norms *)

End BanachFPT.

Section BanachFPT2.
Context {X} (F:Complete X--> Complete X) `{conF: Contraction (Complete X) F}.
Theorem BanachFPT : exists x, (F x) =x.
eexists y.
Admitted.
(* x= lim F^n
F x - x = F lim F^n - lim F^n = lim F^n+1 - lim F^n.
*)

(* Moreover, it is unique *)

Theorem PicardFPT: exists f, (Picard f) = (f ∘ Cunit).
apply BanachFPT.
Qed.


From mathcomp.ssreflect Require Import all_ssreflect.
Set Implicit Arguments.
Unset Strict Implicit.
Import Prenex Implicits.

Require Import MPST.Common.AtomSets.
Require Import MPST.Common.Member.

Definition alt (x : Type) := (lbl * (mty * x))%type.

Definition empty A : (lbl -> option A) := fun=> None.
Definition extend A (L : lbl) (X : A) f :=
  fun L' => if L == L' then Some X else f L'.

Fixpoint find_cont A (c : seq (lbl * A))
  : lbl -> option A
  := match c with
     | [::] => empty A
     | (k, v) :: c => extend k v (find_cont c)
     end.

Lemma find_member A (c : seq (lbl * (mty * A))) l Ty G :
  find_cont c l = Some (Ty, G) -> member (l, (Ty, G)) c.
Proof.
  elim: c=>//= [[k v]] ks Ih; rewrite /extend/=.
  case: ifP=>[/eqP->[->]|]//; first by left.
  by move=> _ /Ih-H; right.
Qed.

Lemma in_cons_tail (A : eqType) B (t : seq (A * B)) (x : A) k v :
  x <> k ->
  x \in [seq y.1 | y <- (k, v) :: t] ->
  x \in [seq y.1 | y <- t].
Proof. by rewrite /= in_cons=>/eqP/negPf->. Qed.

Fixpoint get_v B (ls : seq (lbl * B)) x
  : find_cont ls x -> B
  := match find_cont ls x as P return P -> B with
     | Some y => fun=> y
     | None => fun P => match not_false_is_true P with end
     end.

Definition same_dom T T'
           (C : lbl -> option (mty * T)) (C' : lbl -> option (mty * T'))
  := forall L Ty,
       (exists G, C L = Some (Ty, G)) <-> (exists G', C' L = Some (Ty, G')).

Lemma same_dom_refl A C1 : @same_dom A A C1 C1.
Proof. by []. Qed.

Lemma same_dom_sym A B C1 C2 : @same_dom A B C1 C2 <-> @same_dom B A C2 C1.
Proof. by split=>H l Ty; move: (H l Ty)=>->. Qed.

Lemma same_dom_trans A B C C1 C2 C3 :
  @same_dom A B C1 C2 -> @same_dom B C C2 C3 -> @same_dom A C C1 C3.
Proof. by move=>H0 H1 l Ty; move: (H0 l Ty) (H1 l Ty)=>->. Qed.

Lemma same_dom_extend T1 T2 l Ty G1 G2 C1 C2 :
  @same_dom T1 T2 C1 C2 ->
  @same_dom T1 T2 (extend l (Ty, G1) C1) (extend l (Ty, G2) C2).
Proof.
  rewrite /extend /same_dom; move=> hp l0 Ty0; case: ifP =>//=; move=> eq.
  by split; elim; move=> GG [eqTy eqG]; rewrite eqTy; [exists G2 | exists G1].
Qed.

Lemma same_dom_extend_some_l T1 T2 l Ty G1 G2 C1 C2 :
  @same_dom T1 T2 C1 C2 -> C1 l = Some (Ty, G1) ->
  @same_dom T1 T2 C1 (extend l (Ty, G2) C2).
Proof.
  rewrite /extend /same_dom; move=> hp eq l0 Ty0.
  case: ifP =>//=; rewrite -(rwP eqP); move=> eql; rewrite -eql.
  split; [| by elim; move=> GG [eq1 eq2]; rewrite -eq1; exists G1].
  by elim=> GG; rewrite eq; move=> [eq1 eq2]; exists G2; rewrite eq1.
Qed.

Definition same_dom_const T1 T2 (C: lbl -> option (mty * T1)) (t2 : T2) L :=
match C L with
  | None => None
  | Some (Ty,t1) => Some (Ty,t2)
end.

Lemma same_dom_const_same_dom A B C t : @same_dom A B C (same_dom_const C t).
Proof.
  rewrite /same_dom /same_dom_const; move=> L Ty; split.
  + by elim=> G hp; exists t; rewrite hp.
  + elim=> G; case: (C L) => //=; move=> a.
    by case: a => Tyy t1 [eq1 eq2]; exists t1; rewrite eq1.
Qed.

Lemma same_dom_const_some A B C t L Ty t':
  @same_dom_const A B C t L = Some (Ty, t') -> t' = t.
Proof.
  by rewrite /same_dom_const; case: (C L) => //=; move=> [Tyy _ []].
Qed.

Lemma dom T T' C0 C1 (DOM : @same_dom T T' C0 C1)
  : forall l Ty G, C0 l = Some (Ty, G) -> exists G', C1 l = Some (Ty, G').
Proof. by move=> l Ty; move: (DOM l Ty)=>[/(_ (ex_intro _ _ _))-H _]. Qed.

Lemma dom' T T' C0 C1 (DOM : @same_dom T T' C0 C1)
  : forall l Ty G, C1 l = Some (Ty, G) -> exists G', C0 l = Some (Ty, G').
Proof. by move=> l Ty; move: (DOM l Ty)=>[_ /(_ (ex_intro _ _ _))-H]. Qed.

Lemma dom_none A B C0 C1
  : @same_dom A B C0 C1 -> forall l, C0 l = None -> C1 l = None.
Proof.
  move=>DOM l Cl; case C1l: (C1 l)=>[[Ty] b|]//.
    by move: (dom' DOM C1l)=>[G0]; rewrite Cl.
Qed.

Lemma dom_none' A B C0 C1
  : @same_dom A B C0 C1 -> forall l, C1 l = None -> C0 l = None.
Proof. by rewrite same_dom_sym; apply/dom_none. Qed.

Lemma samedom_nilp T T'
      (C0 : seq (lbl * (mty * T))) (C1 : seq (lbl * (mty * T')))
  : same_dom (find_cont C0) (find_cont C1) -> nilp C1 -> nilp C0.
Proof.
  case: C0=>// [][l [Ty G]] C0; case: C1=>// /(_ l Ty)-[/(_ (ex_intro _ G _))].
  by move=>/=; rewrite /extend eq_refl=>/(_ erefl)=>[][]//.
Qed.

Lemma same_dom_eta A B C
      (f : lbl -> option (mty * A))
      (g : lbl -> option (mty * B)) (h : B -> C) :
  same_dom f g ->
  same_dom f (fun l => match g l with
                       | Some (Ty, x) => Some (Ty, h x)
                       | None => None
                       end).
Proof.
  move=> DOM l T; case EQ: (f l)=>[[T' G']|];
    last by move: (dom_none DOM EQ)=>->; split=>[][].
  by move: (dom DOM EQ)=>[b->]; split=>[][x][<- _];
       [exists (h b)|exists G'].
Qed.

Definition P_all A (P : A -> Prop) (F : lbl -> option (mty * A)) :=
  forall l Ty a, F l = Some (Ty, a) -> P a.

Definition R_all T T' (R : T -> T' -> Prop)
           (C : lbl -> option (mty * T)) (C' : lbl -> option (mty * T')) :=
    forall L Ty G G',
    C L = Some (Ty, G) -> C' L = Some (Ty, G') -> R G G'.


(** * Focused Sequent system
This file specifies a one-sided focused system for MMLL The system is
   parametric to [theory: oo->Prop], defining the formulas that can be used in
   rule [tri_dec3]. In this implementation, all the atoms are assumed to be
   positive and then, proofs must finish with the initial rule focusing on
   atomic propositions of the form [perp A]. The exchange rule is embedded in
   the definition, e.g., of [tri_tensor].
 *)

Require Export LL.Misc.Utils.
Require Export LL.SL.MMLL.Locations.

Export ListNotations.
Set Implicit Arguments.

Section LLSequent.
  Context `{SI : SigMMLL}.
  Context `{OLS: OLSig}.

  Variable theory : oo -> Prop. (* theory Definition *)

  (* Andreoli's triadic system for linear logic *)
  Reserved Notation " n '|-F-' B ';' L ';' X " (at level 80).

  (** Sequent rules. in [n '|-F-' B ';' L ';' X], [n] is the height of
  the derivation ; [B] a list representing the classical context ; [L]
  the linear context and [X] and [Arrow] that can be [DW F] (for the
  positive phase) or [UP L] (for the negative phase). *)
  Inductive seqN:  nat -> list TypedFormula -> list oo -> Arrow -> Prop :=
  | tri_init1 : forall B A n, SetU B -> n |-F- B ; [atom A] ; DW (perp A)
  | tri_init2 : forall B C A n i, SetU C -> mt i = true -> Permutation ((i, atom A)::C) B -> n |-F- B ; [] ; DW (perp A)
  | tri_one : forall B n, SetU B ->  n |-F- B ; [] ; DW One

  | tri_tensor : forall B C D BD M N MN F G n, Permutation MN (M++N) -> Permutation BD (B++C++D) -> SetU B ->
                                     SetL C -> SetL D ->
                                        (n |-F- B++C ; M ; DW F) ->
                                        (n |-F- B++D ; N ; DW G )->
                                        S n |-F- BD ; MN ; DW (MAnd F G)

  | tri_plus1 : forall B M F G n,
      n |-F- B ; M ; DW F -> S n |-F- B ; M ; DW (AOr F G)
  | tri_plus2 : forall B M F G n,
      n |-F- B ; M ; DW G -> S n |-F- B ; M ; DW (AOr F G)
  | tri_rel : forall B F L n,
      negativeFormula F -> n |-F- B ; L ; UP [F] ->  S n |-F- B ; L ; DW F
  | tri_top : forall B L M n,
      n |-F- B ; L ; UP (Top :: M)
  | tri_bot : forall B L M n,
      n |-F- B ; L ; UP M -> S n  |-F- B ; L ; UP (Bot :: M)
  | tri_par : forall B L M F G n,
      n |-F- B ; L ; UP (F::G::M) -> S n  |-F- B ; L ; UP((MOr F G) :: M)
  | tri_with : forall B L M F G n,
      (n |-F- B ; L ; UP (F :: M)) ->
      (n |-F- B ; L ; UP (G :: M)) -> S n|-F- B ; L ; UP ((AAnd F  G) :: M)
  | tri_quest : forall B L M F n i,
      n |-F- (i,F)::B ; L ; UP M -> S n  |-F- B ; L ; UP ((Quest i F) :: M)
  | tri_store : forall B L M F n,
      positiveLFormula  F-> n |-F- B ; F::L ; UP M -> S n |-F- B ; L ; UP (F::M)
  | tri_dec1 : forall B L L' F n,
      positiveFormula F -> Permutation (F::L') L -> n |-F- B ; L' ; DW F -> S n |-F- B ; L ; UP []
  | tri_dec2u : forall B L F n i,
     u i = true -> mt i = true -> ~IsPositiveAtom F -> In (i,F) B -> n |-F- B ; L ; DW F -> S n |-F- B ; L ; UP []
  | tri_dec2l : forall B B' L F n i,
     u i = false -> mt i = true -> ~IsPositiveAtom F -> Permutation ((i,F)::B') B -> n |-F- B' ; L ; DW F -> S n |-F- B ; L ; UP []
  | tri_dec3 : forall B L F n,
      theory F -> ~IsPositiveAtom F -> n |-F- B ; L ; DW F -> S n |-F- B ; L ; UP []
  | tri_ex  : forall B FX M t n,
      uniform_oo FX -> proper t -> n |-F- B; M ; DW (FX t) -> S n|-F- B; M ; DW (Some  FX)
  | tri_fx  : forall B L FX M n,
      uniform_oo FX -> (forall x, proper x -> n |-F- B ; L ; UP( (FX x) ::  M)) ->
      S n |-F- B ; L ; UP ((All FX) :: M)
  | tri_bangL : forall B F n,
     SetU B ->  n  |-F- B ; [] ; (UP [F]) -> S n  |-F- B ; [] ; DW (Bang loc F)
  | tri_bang : forall B F n i, i <> loc ->
     tri_bangK4 n B i [] [] (UP [F]) -> S n  |-F- B ; [] ; DW (Bang i F)
| tri_bangD : forall n B i,  tri_bangK4 n B i [] [] (UP [ ]) -> md i = true -> S n |-F- B ; [] ; UP []
     with
      tri_bangK4 : nat -> list TypedFormula -> subexp -> list TypedFormula -> list oo -> Arrow -> Prop :=
       | tri_copyK4 : forall b F n L M C B B' i, lt i b  -> m4 b = true ->
        Permutation ((b,F)::B') B -> tri_bangK4 n B' i (C++[(plust b,F)]) L (UP M) ->
                                          tri_bangK4 (S n) B i C L (UP M)
       | tri_copyUK : forall b F n L M C B B' i, lt i b  -> m4 b = false -> u b = true ->
        Permutation ((b,F)::B') B -> tri_bangK4 n B' i (C++[(loc,F)]) L (UP M) ->
                                          tri_bangK4 (S n) B i C L (UP M)
       | tri_copyLK : forall b F n L M C B B' i, lt i b  -> m4 b = false -> u b = false ->
        Permutation ((b,F)::B') B -> tri_bangK4 n B' i C L (UP (M++[F])) ->
                                          tri_bangK4 (S n) B i C L (UP M)
       | tri_exp : forall B C i L M n, SetU B -> (* NoLtX i B -> *)
                  n |-F- C; L; UP M -> tri_bangK4 (S n) B i C L (UP M)

  where " n '|-F-' B ';' L ';' X " := (seqN n B L X).

  (** Well formedness conditions for arrows. *)
  Definition isArrow (Ar:Arrow) : Prop :=
    match Ar with
    | UP l => isFormulaL l
    | DW F => isFormula F
    end.

  Reserved Notation " '|-f-' B ';' L ';' X " (at level 80).

  (** The same system without the height of the derivation *)
  Inductive seq:  list TypedFormula -> list oo -> Arrow -> Prop :=
  | tri_init1' : forall B A ,  SetU B ->  |-f- B ; [atom A] ; DW (perp A)
  | tri_init2' : forall B C A i, SetU C -> mt i = true -> Permutation ((i, atom A)::C) B -> |-f- B ; [] ; DW (perp A)

  | tri_one' : forall B, SetU B -> |-f- B ; [] ; DW One
  | tri_tensor' : forall M N MN B C D BD F G, Permutation MN (M++N) -> Permutation BD (B++C++D) -> SetU B ->
                                     SetL C -> SetL D ->
                                       |-f- B++C ; M ; DW F ->
                                        |-f- B++D ; N ; DW G ->
                                        |-f- BD ; MN ; DW (MAnd F G)
  | tri_plus1' : forall B M F G ,
      |-f- B ; M ; DW F -> |-f- B ; M ; DW (AOr F G)
  | tri_plus2' : forall B M F G,
      |-f- B ; M ; DW G -> |-f- B ; M ; DW (AOr F G)
  | tri_rel' : forall B F L,
      negativeFormula F -> |-f- B ; L ; UP [F] ->  |-f- B ; L ; DW F
  | tri_top' : forall B L M,
      |-f- B ; L ; UP (Top :: M)
  | tri_bot' : forall B L M,
      |-f- B ; L ; UP M -> |-f- B ; L ; UP (Bot :: M)
  | tri_par' : forall B L M F G,
      |-f- B ; L ; UP (F::G::M) -> |-f- B ; L ; UP((MOr F G) :: M)
  | tri_with' : forall B L M F G,
      |-f- B ; L ; UP (F :: M) ->
      |-f- B ; L ; UP (G :: M) -> |-f- B ; L ; UP ((AAnd F  G) :: M)
  | tri_quest' : forall B L M F i,
      |-f- (i,F)::B ; L ; UP M -> |-f- B ; L ; UP ((Quest i F) :: M)
  | tri_store' : forall B L M F,
      positiveLFormula  F-> |-f- B ; F::L; UP M -> |-f- B ; L ; UP (F::M)
  | tri_dec1' : forall B L L' F,
      positiveFormula F -> Permutation (F::L') L -> |-f- B ; L' ; DW F -> |-f- B ; L ; UP []
  | tri_dec2u' : forall B L F i,
     u i = true -> mt i = true -> ~IsPositiveAtom F -> In (i,F) B -> |-f- B ; L ; DW F -> |-f- B ; L ; UP []
  | tri_dec2l' : forall B B' L F i,
     u i = false -> mt i = true -> ~IsPositiveAtom F -> Permutation ((i,F)::B') B -> |-f- B' ; L ; DW F -> |-f- B ; L ; UP []

  | tri_dec3' : forall B L F ,
      theory F -> ~IsPositiveAtom F -> |-f- B ; L ; DW F -> |-f- B ; L ; UP []
  | tri_ex'  : forall B FX M t,
      uniform_oo FX -> proper t -> |-f- B; M ; DW (FX t) -> |-f- B; M ; DW (Some  FX)
  | tri_fx'  : forall B L FX M ,
      uniform_oo FX -> (forall x, proper x -> |-f- B ; L ; UP( (FX x) ::  M)) ->
      |-f- B ; L ; UP ((All FX) :: M)
 | tri_bangL' : forall B F,
    SetU B -> |-f- B ; [] ; (UP [F]) -> |-f- B ; [] ; DW (Bang loc F)

| tri_bang' : forall B F i, i <> loc ->
     tri_bangK4' B i [] [] (UP [F]) -> |-f- B ; [] ; DW (Bang i F)
| tri_bangD' : forall B i,  tri_bangK4' B i [] [] (UP []) -> md i = true -> |-f- B ; [] ; UP []
     with
      tri_bangK4' : list TypedFormula -> subexp -> list TypedFormula -> list oo -> Arrow -> Prop :=
       | tri_copyK4' : forall b F L M C B B' i, lt i b  -> m4 b = true ->
        Permutation ((b,F)::B') B-> tri_bangK4' B' i (C++[(plust b,F)]) L (UP M) ->
                                      tri_bangK4' B i C L (UP M)
       | tri_copyUK' : forall b F L M C B B' i, lt i b  -> m4 b = false -> u b = true ->
        Permutation ((b,F)::B') B -> tri_bangK4' B' i (C++[(loc,F)]) L (UP M) ->
                                      tri_bangK4' B i C L (UP M)
        | tri_copyLK' : forall b F L M C B B' i, lt i b  -> m4 b = false -> u b = false ->
        Permutation ((b,F)::B') B -> tri_bangK4' B' i C L (UP (M++[F])) ->
                                      tri_bangK4' B i C L (UP M)
       | tri_exp' : forall B C i L M , SetU B -> (* NoLtX i B -> *)
                  |-f- C; L; UP M -> tri_bangK4' B i C L (UP M)

  where "'|-f-' B ';' L ';' X " := (seq B L X).

End LLSequent .

Module FLLNotations .

Notation "n ⊢ B ';' L ⇕ X " := (seqN _ n B L X)  (at level 80).
Notation "n ⊢ B ';' L ⇓ F " := (seqN _ n B L (DW F))  (at level 80).
Notation "n ⊢ B ';' L ⇑ F " := (seqN _ n B L (UP F))  (at level 80).
Notation "⊢ B ';' L ⇕ X " := (seq _ B L X)  (at level 80).
Notation "⊢ B ';' L ⇓ F " := (seq _ B L (DW F))  (at level 80).
Notation "⊢ B ';' L ⇑ F " := (seq _ B L (UP F))  (at level 80).

End FLLNotations .

Global Hint Constructors seqN seq: core .


Section foo.
  Context (x := 1).
  Definition foo : x = 1 := eq_refl.
End foo.

Module Type Foo.
  Context (x := 1).
  Definition foo : x = 1 := eq_refl.
End Foo.

Set Universe Polymorphism.

Inductive unit := tt.
Inductive eq {A} (x y : A) : Type := eq_refl : eq x y.

Section bar.
  Context (x := tt).
  Definition bar : eq x tt := eq_refl _ _.
End bar.

Module Type Bar.
  Context (x := tt).
  Definition bar : eq x tt := eq_refl _ _.
End Bar.


(**
 More choice principles.

 This describes a choice principle that isn't given in [ChoiceFacts] yet.

 © 2017 Johannes Kloos

 This library requires Coq 8.7. *)
From Coq.Classes Require Import Equivalence Morphisms.
From Coq Require Import Utf8 Setoid ChoiceFacts.

(** This is in the standard library since 8.7. If you want to use 8.6, uncomment
    this definition. *)

(*
Definition SetoidFunctionalChoice_on A B :=
  forall R : A -> A -> Prop,
  forall T : A -> B -> Prop,
  Equivalence R ->
  (forall x x' y, R x x' -> T x y -> T x' y) ->
  (forall x, exists y, T x y) ->
  exists f : A -> B, forall x : A, T x (f x) /\
    (forall x' : A, R x x' -> f x = f x').
Notation SetoidFunctionalChoice := (forall A B, SetoidFunctionalChoice_on A B).
*)
(** * Reification principle. *)

(** This functional reification principle is missing from the standard library.
  It follows easily from existing principles, e.g., AC_fun_repr+AC!.
  But since AC_fun_setoid = AC! + AC_fun_repr, we just derive it from
  AC_fun_setoid. *)
Definition SetoidFunctionalRelReification_on A B :=
  forall R : A -> A -> Prop,
  forall S : B -> B -> Prop,
  forall T : A -> B -> Prop,
  Equivalence R ->
  Equivalence S ->
  (forall x x' y y', R x x' -> S y y' -> T x y -> T x' y') ->
  (forall x, exists y, T x y) ->
  (forall x y y', T x y -> T x y' -> S y y') ->
  exists f : A -> B,
    forall x : A, T x (f x) /\ (forall x' : A, R x x' -> S (f x) (f x')).

(** The reification principle follows from AC_fun_setoid. *)
Lemma setoid_fun_choice_imp_setoid_fun_rel_reification A B:
  SetoidFunctionalChoice_on A B -> SetoidFunctionalRelReification_on A B.
Proof.
  intros choice R S T Req Seq Tproper Tfull Tunique.
  destruct (choice R T) as [f Hf]; auto.
  { now intros * eqx; apply Tproper. }
  exists f.
  intros x; destruct (Hf x) as [x_good x_unique].
  split; trivial.
  now intros x' ->%x_unique.
Qed.

(** * Setoid relational choice.

  It generalizes [RelationalChoice_on] in that it provides choice on
  setoids, and is a weaker companion to [GeneralizedSetoidFunctionalChoice_on]
  from Coq trunk.
  *)

Definition GeneralizedSetoidRelationalChoice_on A B :=
  ∀ Ae Be
  (equA: Equivalence Ae) (equB: Equivalence Be)
  (R: A → B → Prop) (Rproper: Proper (Ae ==> Be ==> iff) R)
  (Rfull: ∀ x, ∃ y, R x y),
  ∃ (R': A → B → Prop),
  (∀ x y, R' x y → R x y) ∧
  Proper (Ae ==> Be ==> iff) R' ∧
  (∀ x, ∃ y, R' x y) ∧
  ∀ x y y', R' x y → R' x y' → Be y y'.

Notation GeneralizedSetoidRelationalChoice :=
  (∀ A B, GeneralizedSetoidRelationalChoice_on A B).

(** [GeneralizedSetoidRelationalChoice],
 follows from the standard library principle
 [SetoidFunctionalChoice]. *)

Lemma gen_setoid_fun_choice_imp_gen_setoid_rel_choice A B:
  SetoidFunctionalChoice_on A B →
  GeneralizedSetoidRelationalChoice_on A B.
Proof.
  intros choice Ae Be Aeequ Beequ R Rproper Rfull.
  destruct (choice Ae R _) as [f f_spec].
  - intros * eqx.
    now apply Rproper.
  - trivial.
  - exists (λ a b, Be (f a) b).
    split. { intros * <-; apply f_spec. }
    split. {
      intros a₁ a₂ eqa b₁ b₂ eqb.
      destruct (f_spec a₁) as [_ eqfa].
      rewrite (eqfa a₂ eqa).
      now rewrite eqb.
    }
    split.
    + now intro; exists (f x).
    + now intros * <- <-.
Qed.


Require Import stlcott.

Lemma canonical_forms : forall v t1 t2,
  is_value_of_expr(v) = true ->
  Jtype nil v (t_arrow t1 t2) ->
  exists x, exists t, exists e, v = e_abs x t e.
Proof.
  intros v t1 t2 Hval Htype. destruct v; simpl in Hval; inversion Hval.
    exists x. exists t. exists v. reflexivity.
Qed.


Require Import Coq.Program.Tactics.
Require Import ProofIrrelevance.

Section Moore.
  Record Moore :=
    { Q : Type;
      Sigma : Type;
      Y : Type;
      q0 : Q;
      delta : Sigma * Q -> Q;
      y : Q -> Y
    }.

  Record MooreMorphism (a b : Moore) :=
    { f_Q : (Q a) -> (Q b);
      f_Sigma : (Sigma a) -> (Sigma b);
      f_Y : (Y a) -> (Y b);
      pres_transition :
        forall sigma q,
          (delta b) (f_Sigma sigma, f_Q q) = f_Q ((delta a) (sigma, q));
      pres_outputs :
        forall q,
          f_Y ((y a) q) = (y b) (f_Q q);
      pres_init_state :
        f_Q (q0 a) = q0 b
    }.

  (** Moore machine morphisms compose. *)
  Program Definition MooreMorphism_composition
          {A B C : Moore}
          (map1 : MooreMorphism A B)
          (map2 : MooreMorphism B C) :
    MooreMorphism A C :=
    {| f_Q := fun a => (f_Q B C map2) ((f_Q A B map1) a);
       f_Sigma := fun a => (f_Sigma B C map2) ((f_Sigma A B map1) a);
       f_Y := fun a => (f_Y B C map2) ((f_Y A B map1) a);
    |}.
  Next Obligation.
  Proof.
    destruct map1, map2.
    simpl in *.
    rewrite pres_transition1.
    rewrite pres_transition0.
    reflexivity.
  Qed.
  Next Obligation.
    destruct map1, map2.
    simpl in *.
    rewrite pres_outputs0.
    rewrite pres_outputs1.
    reflexivity.
  Qed.
  Next Obligation.
    destruct map1, map2.
    simpl in *.
    rewrite pres_init_state0.
    rewrite pres_init_state1.
    reflexivity.
  Qed.

  (** Moore machine identity morphisms hold. *)
  Program Definition MooreMorphism_identity
          {A : Moore} :
    MooreMorphism A A :=
    {| f_Q := fun a => a;
       f_Sigma := fun a => a;
       f_Y := fun a => a
    |}.

  (** Equality of Moore morphisms, assuming proof irrelevance. *)
  Theorem MooreMorphism_eq : forall A B (N M : MooreMorphism A B),
      @f_Q A B N = @f_Q A B M ->
      @f_Sigma A B N = @f_Sigma A B M ->
      @f_Y A B N = @f_Y A B M ->
      N = M.
  Proof.
    intros.
    destruct N, M.
    simpl in *.
    subst.
    f_equal;
      apply proof_irrelevance.
  Qed.

  (** Composition of Moore morphism is associative. *)
  Program Definition MooreMorphism_assoc
          {A B C D : Moore}
          (f : MooreMorphism A B)
          (g : MooreMorphism B C)
          (h : MooreMorphism C D) :
    MooreMorphism_composition f (MooreMorphism_composition g h) =
    MooreMorphism_composition (MooreMorphism_composition f g) h.
  Proof.
    destruct f, g, h.
    simpl.
    apply MooreMorphism_eq.
    simpl.
    reflexivity.
    reflexivity.
    reflexivity.
  Qed.
End Moore.


Require Import MLTT2.Overture.

Definition ap {A B: Type} {FibA: Fibrant A} {FibB: Fibrant B} (f: A -> B) {x y: A} (p: x = y)
  : f x = f y
  := paths_rec x (fun y => f x = f y) idpath y p.

Arguments ap {A B}%type_scope {FibA FibB} f {x y} p%path_scope.

Definition apD {A: Type} {FibA: Fibrant A} {B: A -> Type} {FibB: FibrantF B}
           (f: forall a: A, B a) {x y: A} (p: x = y)
  : p # (f x) = f y
  := paths_ind x (fun y p => transport B p (f x) = f y) 1 y p.

Arguments apD {A%type_scope FibA B FibB} f {x y} p%path_scope : simpl nomatch.

Definition ap_pp {A B} {FibA: Fibrant A} {FibB: Fibrant B} (f : A -> B) {x y z : A} (p : x = y) (q : y = z) :
  ap f (p @ q) = (ap f p) @ (ap f q).
Proof.
  destruct_path p.
  destruct_path q.
  exact 1.
Defined.

Definition ap_V {A B} {FibA: Fibrant A} {FibB: Fibrant B} (f : A -> B) {x y : A} (p : x = y) :
  ap f (p^) = (ap f p)^.
Proof.
  destruct_path p; exact 1.
Defined.

Definition inv_pp {A} {FibA: Fibrant A} {x y z : A} (p : x = y) (q : y = z) :
  (p @ q)^ = q^ @ p^.
Proof.
  destruct_path p.
  destruct_path q.
  exact 1.
Defined.

Definition inv_V {A} {FibA: Fibrant A} {x y : A} (p : x = y) :
  p^^ = p.
Proof.
  destruct_path p; exact 1.
Defined.

Definition ap_compose {A B C} {FibA: Fibrant A} {FibB: Fibrant B} {FibC: Fibrant C} (f : A -> B) (g : B -> C) {x y : A} (p : x = y) :
  ap (g o f) p = ap g (ap f p).
Proof.
  destruct_path p; exact 1.
Defined.

Definition concat_p_pp {A} {FibA: Fibrant A} {x y z t : A} (p : x = y) (q : y = z) (r : z = t) :
  p @ (q @ r) = (p @ q) @ r.
Proof.
  destruct_path r.
  destruct_path q.
  destruct_path p.
  exact 1.
Defined.

Definition concat_pp_p {A} {FibA: Fibrant A} {x y z t : A} (p : x = y) (q : y = z) (r : z = t) :
  (p @ q) @ r = p @ (q @ r).
Proof.
  destruct_path r.
  destruct_path q.
  destruct_path p.
  exact 1.
Defined.

Definition concat_1p {A} {FibA: Fibrant A} {x y: A} (p: x = y)
  : 1 @ p = p.
Proof.
  destruct_path p.
  exact 1.
Defined.

Definition concat_p1 {A} {FibA: Fibrant A} {x y: A} (p: x = y)
  : p @ 1 = p.
Proof.
  destruct_path p.
  exact 1.
Defined.

Definition concat_pV {A} {FibA: Fibrant A} {x y : A} (p : x = y) :
  p @ p^ = 1
  := paths_ind x (fun y p => p @ p^ = 1) 1 _ _.

Definition concat_Vp {A} {FibA: Fibrant A} {x y : A} (p : x = y) :
  p^ @ p = 1
  := paths_ind x (fun y p => p^ @ p = 1) 1 _ _.

Definition moveR_Vp {A} {FibA: Fibrant A} {x y z : A} (p : x = z) (q : y = z) (r : x = y) :
  p = r @ q -> r^ @ p = q.
Proof.
  destruct_path r.
  intro h. exact (concat_1p _ @ h @ concat_1p _).
Defined.

Definition moveL_Vp {A} {FibA: Fibrant A} {x y z : A} (p : x = z) (q : y = z) (r : x = y) :
  r @ q = p -> q = r^ @ p.
Proof.
  destruct_path r.
  intro h. exact ((concat_1p _)^ @ h @ (concat_1p _)^).
Defined.

Definition moveR_M1 {A} {FibA: Fibrant A} {x y : A} (p q : x = y) :
  1 = p^ @ q -> p = q.
Proof.
  destruct_path p.
  intro h. exact (h @ (concat_1p _)).
Defined.

Definition concat_pA1 {A} {FibA: Fibrant A} {f : A -> A} (p : forall x, x = f x) {x y : A} (q : x = y) :
  (p x) @ (ap f q) =  q @ (p y)
    := paths_ind x (fun y q => (p x) @ (ap f q) = q @ (p y))
               (concat_p1 _ @ (concat_1p _)^) y q.

Definition path_sigma {A: Type} {FibA: Fibrant A}
           (P: A -> Type) {FibP: FibrantF P}
           {x x': A} {y: P x} {y': P x'}
           (p: x = x') (q: p # y = y')
  : (x; y) = (x'; y').
Proof.
  destruct_path p.
  destruct_path q.
  exact 1.
Defined.

Definition path_contr {A} {FibA: Fibrant A} {HA: Contr A} (x y : A)
  : x = y.
Proof.
  exact ((contr _ _ _)^ @ contr _ HA _).
Defined.

Definition transport_compose {A B} {FibA: Fibrant A} {FibB: Fibrant B}
           {x y: A} (P: B → Type) {FibP : FibrantF P}
           (f : A → B) (p : x = y) (z : P (f x))
  : transport (P o f) p z = transport P (ap f p) z.
Proof.
  destruct_path p.
  exact 1.
Defined.

Definition transport_const {A B} {FibA: Fibrant A} {FibB: Fibrant B}
           {x1 x2 : A} (p : x1 = x2) (y : B)
  : transport (fun x => B) p y = y.
Proof.
  refine (paths_ind x1 (fun x2 p => p # y = y) 1 x2 p).
Defined.

Definition transport_paths_r A {FibA: Fibrant A} {x y1 y2: A}
           (p : y1 = y2) (q : x = y1)
  : transport (λ y : A, x = y) p q = q @ p.
Proof.
  destruct_path p.
  destruct_path q.
  exact 1.
Defined.

Definition transport_paths_Fl {A B} {FibA: Fibrant A} {FibB: Fibrant B}
           (f: A → B) {x1 x2: A} {y: B} (p: x1 = x2) (q: f x1 = y)
  : transport (λ x : A, f x = y) p q = (ap f p)^ @ q.
Proof.
  destruct_path q.
  destruct_path p.
  exact 1.
Defined.

Definition transport_paths_Fr {A B} {FibA: Fibrant A} {FibB: Fibrant B}
           (f: A → B) {x1 x2: A} {y: B} (p: x1 = x2) (q: y = f x1)
  : transport (λ x : A, y = f x) p q = q @ ap f p.
Proof.
  destruct_path p. cbn.
  exact (concat_p1 _)^.
Defined.

Definition concat_Ep {A} {FibA: Fibrant A} {x y z : A} (e: x ≡ y) (p: y = z) : x = z
  := Etransport (λ u, u = z) e^E p.

Definition concat_EVp {A} {FibA: Fibrant A} {x y z : A} (e: y ≡ x) (p: y = z) : x = z
  := Etransport (λ u, u = z) e p.

Definition concat_pE {A} {FibA: Fibrant A} {x y z : A} (p: x = y) (e: y ≡ z) : x = z
  := Etransport (λ v, x = v) e p.

Definition concat_Ep_ETP {A} {FibA: Fibrant A} {x y z: A} (e: x ≡ y :> A) (p: y ≡ z)
  : concat_Ep e (Eq_to_paths p) ≡ Eq_to_paths (e E@ p).
Proof.
  destruct e; cbn. apply Eap, Eq_UIP.
Defined.

Definition concat_EVp_ETP {A} {FibA: Fibrant A} {x y z: A} (e: y ≡ x :> A) (p: y ≡ z)
  : concat_EVp e (Eq_to_paths p) ≡ Eq_to_paths (e^E E@ p).
Proof.
  destruct e; cbn. apply Eap, Eq_UIP.
Defined.

Definition concat_pE_ETP {A} {FibA: Fibrant A} {x y z: A} (p: x ≡ y) (e: y ≡ z)
  : concat_pE (Eq_to_paths p) e ≡ Eq_to_paths (p E@ e).
Proof.
  destruct e; cbn. apply Eap, Eq_UIP.
Defined.

Definition ap_concat_Ep {A B} {FibA: Fibrant A}  {FibB: Fibrant B} (f: A -> B)
           {x y z: A} (e: x ≡ y :> A) (p: y = z)
  : ap f (concat_Ep e p) ≡ concat_Ep (Eap f e) (ap f p).
Proof.
    now destruct e.
Defined.

Definition ap_concat_EVp {A B} {FibA: Fibrant A} {FibB: Fibrant B} (f: A -> B)
           {x y z: A} (e: y ≡ x) (p: y = z)
  : ap f (concat_EVp e p) ≡ concat_EVp (Eap f e) (ap f p).
Proof.
    now destruct e.
Defined.

Definition ap_concat_pE {A B} {FibA: Fibrant A} {FibB: Fibrant B} (f: A -> B)
           {x y z: A} (p: x = y) (e: y ≡ z)
  : ap f (concat_pE p e) ≡ concat_pE (ap f p) (Eap f e).
Proof.
    now destruct e.
Defined.

Definition Etransport_paths_FlFrE {A B} {FibB: Fibrant B} {f g: A -> B} {x1 x2: A} (p: x1 ≡ x2) (q: f x1 ≡ g x1)
  : Etransport (fun x => f x = g x) p (Eq_to_paths q) ≡ Eq_to_paths ((Eap f p^E) E@ q E@ (Eap g p)).
Proof.
  destruct p; simpl. apply Eap, Eq_UIP.
Defined.

(* Axiom ap_compose_strict : *)
(*   ∀ {A B C} {FibA: Fibrant A} {FibB: Fibrant B} {FibC: Fibrant C} *)
(*     (f: A → B) (g: B → C) {x y: A} (p: x = y), *)
(*     ap (g o f) p ≡ ap g (ap f p). *)


From mathcomp Require Import ssreflect ssrfun ssrbool ssrnat eqtype choice div .
From mathcomp Require Import seq finset fintype bigop order ssralg ssrnum finmap matrix interval.
From mathcomp Require Import all_real_closed.
From mathcomp Require Import
  boolp reals nngnum posnum classical_sets topology
  normedtype prodnormedzmodule derive reals landau forms.
Close Scope boolean_if_scope.
Require Import Program.
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Set Bullet Behavior "Strict Subproofs".

Import Order.TTheory GRing.Theory Num.Theory.
Open Scope complex_scope.
Open Scope classical_set_scope.
Open Scope ring_scope.

(** We first need to discuss restricting functions to a region*)
Section DomainRestrictions.
Record dom_restricted {U V: Type} (A : set U) := {
  f : U -> V
}.
Coercion f : dom_restricted >-> Funclass.

Context {U V : Type}.
Variable (A : set U).

Notation DR := (@dom_restricted U V A).

Local Definition explode (f : DR) :=
  [set g : DR | {in A, f =1 g} ].

Local Definition explode_set (X : set DR) :=
  \bigcup_(f in X) explode f.

Lemma explode_refl: forall f, explode f f.
Proof.
  rewrite /explode.
  by move => f /=.
Qed.

Lemma explodeE : forall f g,
  explode f g <-> {in A, f =1 g}.
Proof. done. Qed.

Lemma explode_trans : forall f g h,
  explode f g -> explode g h -> explode f h.
Proof.
  move => ? ? ? /explodeE L /explodeE R.
  apply/explodeE => ??.
  rewrite ?L ?R //=.
Qed.

Lemma explode_sym : forall f g,
  explode f g -> explode g f .
Proof.
  move => ? ? /explodeE L.
  apply/explodeE => ??.
  rewrite ?L //=.
Qed.

Lemma explode_setT : explode_set setT = setT.
Proof.
  rewrite /explode_set /= eqEsubset; split => f.
  - by move.
  - move => ?.
    econstructor.
    2: apply: explode_refl.
    eauto.
Qed.

Definition restricted (F : set (set DR)) :=
  [set Q | (exists P, F P /\ explode_set P `<=` Q)].

Global Instance restricted_filter F: Filter F -> Filter (restricted F).
Proof.
  move => FF. rewrite /restricted. constructor.
  - rewrite /=; exists setT; split.
    2: rewrite [x in x `<=` _]explode_setT.
    2: done.
    by apply filterE.
  - move => /= P Q [P' [? a]] [Q' [? b]].
    set R := [set f | P' f /\ (exists g, Q' g /\ {in A, f =1 g}) ].
    exists R.
    split.
    + apply: (filter_app _ _ _ (P := Q' `&` P')).
      2: by apply: (filterI).
      apply: filterE.
      move => g [??] /=.
      rewrite /R /=; split; first by [].
      by exists g.
    + move => f [g [gP [g' [g'Q W]]] /explodeE E].
        split; [apply: a| apply b];
        rewrite /explode_set => /=;
          first by (exists g; eauto).
        exists g'; first by eauto.
        rewrite explodeE => t tA.
        by apply: eq_trans; [symmetry; apply:W |apply:E].
  - move => P Q W /= [P' [W1 W2]].
    exists P'; split; first by [].
    apply: subset_trans.
    2: apply: W.
    exact W2.
Qed.

Canonical restricted_filter_on (F: filter_on DR) :=
  FilterType (restricted F) (restricted_filter _) .

Lemma restricted_filter_not_emtpy : forall (F: pfilter_on DR),
  ~ restricted F set0.
Proof.
  move => [F1 [N ?]] [P [M W]].
  have  Q: (P = set0).
  {
    apply: funext => f.
    apply: propext; split; last by [].
    move: W=> /(_ f) W L; apply: W.
    exists f; first by [].
    apply explode_refl.
  }
  have R: (set0 = xpredp0) by done.
  move: M => /=; rewrite Q R.
  done.
Qed.

Global Instance restricted_prop_filter F :
  ProperFilter F -> ProperFilter (restricted F).
Proof.
  move => [N ?]; constructor.
  2: apply: restricted_filter.
  move => W.
  rewrite /restricted in W.
  case: W => B [X W] .
  have: ( B = xpredp0).
  2: congruence.
  apply: funext => f.
  apply: propext; split; last by [].
  move: W=> /(_ f) W L; apply: W.
  exists f; first by [].
  apply explode_refl.
Qed.

Canonical restricted_pfilter_on (F: pfilter_on DR) :=
  PFilterType (restricted F) (@restricted_filter_not_emtpy _) .

Definition explode_pair ( fg : DR * DR) :=
  explode (fg.1) `*` explode (fg.2).

Definition explode_pairs ( X : set (DR * DR)) :=
  \bigcup_(f in X) explode_pair f.

Definition restrict_ent (E : set(set(DR * DR))) :=
  [set Q | (exists P, E P /\ explode_pairs P `<=` Q)].

End DomainRestrictions.

Notation "U |_ A => V" := (@dom_restricted U V A) (at level 0).

Definition foo := nat|_setT => nat.

Section RestrictionTopology.
Context {U : choiceType} {V : uniformType}.
Variable (A : set U).

Definition restricted_nbhs_filter (p : U -> V) :=
  restricted A [filter of p].

Definition restricted_ent := restrict_ent A (@fct_ent U V).

Lemma restricted_ent_explode : forall i,
  fct_ent i -> restricted_ent (explode_pairs A i).
Proof.
  move => i J.
  pose proof J as J'.
  move: J' => [j E L].
  exists (explode_pairs A i).
  split.
  apply: filterS.
  2: exact J.
  - move => [f g] I.
    rewrite /explode_pairs /explode_pair.
    exists (f,g); first by [].
    move => /=; split; apply: explode_refl.
  - move => [t1 t2] [[x1 x2] [[y1 y2] M]].
    rewrite /explode_pairs /= /explode_pair /setM /=.
    move => [/explodeE E1 /explodeE E2] [/explodeE E3 /explodeE E4].
    exists (y1,y2); first by [].
    rewrite /explode_pair /= /setM /=.
    split; apply/explodeE; move => t T;
      apply: eq_trans.
    + by apply: E1.
    + by apply: E3.
    + by apply: E2.
    + by apply: E4.
Qed.

Definition patch (f g : U -> V) :=
  (fun u =>
     if_expr (asbool (A u)) (g u) (f u)).
Lemma explode_patch : forall f g,
  explode A g (patch f g).
Proof.
  move => f g.
  apply/explodeE => u.
  rewrite /patch /in_mem /mem /= /in_set /=.
  move => -> //=.
Qed.

Lemma restricted_ent_eq :
  restricted_nbhs_filter = nbhs_ (restricted_ent).
Proof.
  apply:funext => f.
  rewrite eqEsubset; split.
  - move => P [Q [M N]].
    have : (nbhs f Q) by apply: M.
    rewrite nbhsP /nbhs_ /filter_from /= => /exists2P [I [[B L1] L2]].
    pose B' := [set fg : ((U -> V) * (U -> V)) | (forall t, B (fg.1 t, fg.2 t))].
    exists (explode_pairs A B').
    1: by apply: restricted_ent_explode; exists B.
    apply: subset_trans.
    2: apply: N.
    move => t /= W.
    exists (patch f t).
    2: apply explode_sym, explode_patch.
    apply: b => /=.
    apply: L2 => /= u.
    rewrite /patch.
    case uA : `[< A u >] => /=.
    2: apply entourage_refl; apply L1.
    move: W => [[f' t']].
    rewrite /B' /= => L [/= /explodeE W1 /explodeE W2].
    by rewrite -?W1 -?W2.
  - move => P [rI [I [? S] N]].
    exists [set y | I (f,y)]; split.
    1: by exists I.
    apply: subset_trans.
    2: apply: N.
    move => g [g' /= gI] E.
    apply S.
    exists (f,g').
    1: done.
    split => /=.
    1: apply explode_refl.
    done.
Qed.

Lemma restricted_ent_filter : Filter restricted_ent.
Proof.
  constructor.
  - exists setT; split.
    1: apply filterT.
    done.
  - move => P Q [P' [X1 X2]] [Q' [Y1 Y2]].
    exists (P' `&` Q').
    split.
    1: by apply: filterI.
    move => [f g] [/= [f' g'] [??] ?].
    split;[apply: X2 | apply: Y2];
      by exists (f', g').
  - move => P Q S [P' [X1 X2]].
    exists (P').
    split.
    1: done.
    apply: subset_trans; eauto.
Qed.

Program Definition restricted_uniformMixin := @UniformMixin
  (U -> V)
  restricted_nbhs_filter
  restricted_ent
  restricted_ent_filter
  _
  _
  _
  restricted_ent_eq
  .
Next Obligation.
  move => [f g /=] ->.
  case: H => [I [eI J]].
  apply J.
  exists (g, g).
  2: split => /=; apply explode_refl.
  by apply: entourage_refl.
Qed.
Next Obligation.
  case: H => [I [/fct_ent_inv eI J]].
  exists [set xy | I(xy.2, xy.1)].
  split.
  1: done.
  move => [f g] [[f' g'] /= gfI] [/= L R].
  apply: J.
  by exists (g',f').
Qed.
Next Obligation.
  case: H => [I [/fct_ent_split [J eJ] S1 S2]].
  move: eJ => [/=B eJ S3].
  pose B' := [set fg : ((U -> V) * (U -> V)) | (forall t, B (fg.1 t, fg.2 t))].
  exists (explode_pairs A B').
  1: by apply: restricted_ent_explode; exists B.
  apply: subset_trans.
  2: apply S2.
  move => [f h] /= [g [[f' g1']] X1 [/=? M1]] [[g2' h'] Y1 [/=M2 ?]].
  exists (patch g1' f', patch g1' h').
  2: split => /=; apply: explode_trans; eauto;
     apply explode_sym, explode_patch.
  apply S1 => /=.
  exists g1'; apply S3 => /= u;
  rewrite /patch /=;
  case uA : `[< A u >] => /=.
  2,4: by apply entourage_refl.
  1: apply: X1.
  rewrite ?M1 -?M2; eauto.
Qed.

Definition restricted_topologicalType_mixin :=
  topologyOfEntourageMixin restricted_uniformMixin.

Canonical restricted_fct_uniformType :=
  UniformType dom_restricted restricted_uniformMixin.

  case: H => P [[ X Y Z ] W].
  apply: W.
  exists p; last by apply: explode_refl.
  apply: Z => /=.
  apply fct_ent_refl; done.
Qed.
Next Obligation.
  case:H => P [X Y].
  have Z : fct_ent_split
  rewrite /restricted_nbhs_filter /restricted /=.
  eexists.
  split.
  2: { move => f.
  2: move => [g gP].
  2: eexists.

End DomainRestrictions.

Section RestrictedTopology.
Context {U : choiceType} {V : uniformType}.
Variable (A : set U).

Definition restricted_topologyType_mixin :=
  topologyOfFilterMixin.

(** We need to define the topology of compact convergence
    before we get started *)
Section CompactCongergence.
Variable (U : topologicalType) ( P : set (set U)) .
Section Topology.
Variable (V : topologicalType).

Definition fct_cnv_on_P_mixin :=
  @topologyOfSubbaseMixin
    _ (U -> V)
    [set MA  | open MA.2 /\  P MA.1 ]
    (fun MA =>
      [set g | {in (MA.1 : set U), forall t, (MA.2 (g t))}]
    )
.

Definition compact_cnv_topologicalType := Topological.Pack (
  (@Topological.Class _
      (Filtered.Class (Pointed.class _) _)
    fct_cnv_on_P_mixin)).

Local Notation TCC := compact_cnv_topologicalType.
Local Definition nbhs_TCC := @nbhs (U -> V) [filteredType TCC of TCC].

Lemma nbhs_TCC_alt : forall (F : set (set TCC)) (f:TCC),
  F --> f <-> forall K, P K ->
     .

End Topology.

Section Uniform.
Variable (V : uniformType).

Context (nonemptyP : nonempty P).
Context (intersectP : forall i j, P i /\ P j -> P (i `&` j)).
Print nonempty.
Definition cvg_on_P_ent :=
  @filter_from (set U * set (V * V)) ((U -> V) * (U -> V))
  [set AB | P AB.1 /\ entourage AB.2]
  (fun AB =>
    [set fg | {in AB.1, forall t, AB.2 (fg.1 t, fg.2 t)}]
  )
  .

Lemma compact_entourage_nbhs: nbhs_TCC (V:=V) = nbhs_ cvg_on_P_ent.
Proof.
  apply: funext => p.
  rewrite  nbhs_E /filter_from.
  rewrite /nbhs_TCC /nbhs /=.
  rewrite eqEsubset; split.
    rewrite nbhsP.
    apply (in_filter_from ((U -> V) * (U -> V)) _ cvg_on_P_ent).

  rewrite /nbhs_TCC /nbhs /=.
  Search "`<=`".

Program Definition compact_cvg_ent_mixin :=
  @Uniform.Mixin (U -> V) (@nbhs_TCC V) cvg_on_P_ent _ _ _ _ _.
Next Obligation.
Proof.
  apply: filter_from_filter.
  {  move: nonemptyP => [?]?.
     eexists (_,_); rewrite //=; split;
    [eauto | apply: entourageT].
  }
  move => [i1 i2] [j1 j2] /= [??] [??].
  exists ((i1 `&` j1), (i2 `&` j2)).
  split => /=.
  1: by apply: intersectP.
  1: by apply: filterI.
  rewrite /=.

Admitted.
Next Obligation.
Admitted.
Next Obligation.
Admitted.
Next Obligation.
Admitted.
Next Obligation.
Proof.

Lemma compact_cnv_limits : forall F (f: U -> V),
  F `=>` nbhs_TCC f <->
  true.

Definition locally_compact_cnv :=

Section Integrals.

Variable (R : realType) (V : normedModType R).

Definition C_1 {R:numFieldType} {V : normedModType R}
  (f : R^o -> V^o) := forall (z:R),
  { near (z:R^o), forall x, differentiable f x} /\
  { near (z:R^o), continuous (f^`() : R^o -> _)}.

Structure ContourIntegral := {
  integrate : R -> R -> (R^o -> V) -> V;

  linear : forall l r, linear (integrate l r);
  ftc : forall (l r :R) (f : R^o -> V),
    {in `]l,r[, C_1 f } ->
    integrate l r (f^`()) = f r - f l

}.

Section C1.
Open Scope type_scope.

Definition continuous_on
  {X Y : topologicalType} (U : set X) (f: X^o -> Y) :=
  (forall x, f @ (within U [filter of x]) --> f x).

Definition continuous_on_itv
  {R:rcfType} {V : topologicalType} (i : interval R)
  (f : R^o -> V^o) :=
  @continuous_on ([topologicalType of R^o]) _
    (itv_decompose i) f.

Inductive Piecewise_C_1 {R : realType} {V : normedModType R}
  (l r:R) (f : R^o -> V) : Prop :=
| OnePiece :
    {in `]l,r[, C_1 f } ->
    continuous_on_itv `[l,r] f ->
    Piecewise_C_1 l r f
| Combined : forall (c : R),
    Piecewise_C_1 l c f ->
    Piecewise_C_1 c r f ->
    Piecewise_C_1 l r f
.

    forall (i : interval R,  C_1  -> Piecewise P f.

End C1.

Section SubspaceContinuity.
Variable .

End SubspaceContinuity.
Section C_structures.
Set Printing Coercions.
Variable (R : realType).
(* This is R[i], as seen as a 1-R[i] dimension normed vector space*)
Definition C := R[i].
Definition as_R2 (z:C) := let: x +i* y := z in (x,y).

Section Holomorphic.
Context {V : normedModType C}.

Definition Holomorphic_on U {O:open U} (f : C^o -> V) :=
    {in U, forall z, derivable f 1 z}.
Program Definition CHolo_on U {O:open U} (f : C^o -> V) (z:C^o) :=
  Holomorphic_on (O:=O) f /\
  {in U, continuous (f^`() : C^o -> _) }.
End Holomorphic.

Section ComplexIntegrals.

Context {V : normedModType R}.

Record CIntegral := {
  path : R^o -> C^o;
  l_end : R^o;
  r_end : R^o;
  f : C^o -> V^o;

  lltr : l_end < r_end;
  cts_f : continuous_on
    (path @` itv_decompose `[l_end,r_end]) f;
  (* continuously differentiable on the open interval*)
  pathdiff : {in `]l_end,r_end[, C_1
    (as_R2 \o path : R^o -> R^o * R^o)  };
  (* continuous on the closed interval*)
  pathcts : continuous_on (X:=[topologicalType of R^o])
    (itv_decompose `[l_end, r_end]) path;
}.

Section