(* 5 Topological Concepts *)

Require Export Number.

(* 5.1 Topological Spaces *)
Definition Topology X cT := cT ⊂ cP(X) ∧
  X ∈ cT ∧ ∅ ∈ cT ∧ (∀ A B, A ∈ cT → B ∈ cT → A ∩ B ∈ cT) ∧
  (∀ cT1, cT1 ⊂ cT → ∪cT1 ∈ cT).

Fact TopologyP : ∀ X cT, Ensemble X → Topology X cT →
  ∀ cT1, ⦿ cT1 → Finite cT1 → cT1 ⊂ cT → ⋂cT1 ∈ cT.
Proof.
  intros * Hxe Htp * Hne [n [Hn He]] Hs. apply eqnumSymm in He as [f].
  apply bijection_is_func in H; andH. apply MapMapR1 in H.
  edestruct MarFamUIEq as [_ Hp]. split; eauto.
  apply Mapping6 in H; subst; auto. rewrite <- Hp; clear Hp.
  generalize dependent f. generalize dependent cT1.
  ω_induction n; intros * Hne Hs * Hf Hi Hr.
  - destruct Hne as [A Ha], Hi as [_ Hi]. rewrite <- Hr in Ha. apply Hi in
      Ha. destruct Ha as [[x Ha] _]. apply Hf in Ha. cprod Ha; exfalso0.
  - assert (Hki : k ∈ k⁺). ens. assert (Hke : f[k] ∈ cT1).
    eapply ValueP1; eauto. assert (Hks : k ⁺ - [k] = k).
    { AppE. smH. AppC H0. orH; auto. sing H0. apply SingNE in H1; auto.
      elim H1; auto. smG. AppCG; Ens. apply SingNI; auto. intro.
      subst. apply RegAxP in H0; auto. } DC (k = ∅).
    { subst k; apply Hs. assert (MarkFamI f ∅ ⁺ = f[∅]).
      { AppE. AppC H0; apply H0; ens. AppCG; Ens. intros; AppC H1. orH.
      exfalso0. sing H1. } rewrite H0. eapply ValueP1; eens. }
    apply Mapping5 in Hf as Hfd. apply MapMapR in Hf as Hff.
    assert (Hfb : bijection f k⁺ cT1). apply bijection_is_func; auto.
    assert (Hp : ∀ x, x ∈ k⁺ → x ≠ k → f[x] ≠ f[k]).
    { intros. AppC H1. orH; [|sing H1].
      assert ([x,f[x]] ∈ f ∧ [k,f[k]] ∈ f). andG; eapply ValueP; eauto.
      AppCG; Ens. andH. intro. rewrite H5 in H3. assert (x = k).
      eapply Hi; eauto. rewrite Hr; auto. auto. }
    pose proof (bijection_sm_point _ _ _ _ Hfb Hki Hp) as Hfb'.
    set (f-[[k,f[k]]]) as f'. assert (MarkFamI f k⁺ = MarkFamI f' k∩f[k]).
    { apply IncAsym; intros x Hx; AssE x; AppCG.
      - AppC Hx. andG; [|apply Hx; ens]. AppCG; intros. AppCG; intros.
        AppC H3. AppC H3; andH. eapply ValueP2 in H3; eauto;
        [|AppCG; Ens]. subst; apply Hx; AppCG; Ens.
      - inH. intros. AppC H4; orH; [|sing H4]. DC (γ = k).
        subst; apply RegAxP in H4; elim H4. AppC H2.
        assert ([γ,f[γ]] ∈ f ∧ [k,f[k]] ∈ f).
        { andG; eapply ValueP; eauto. AppCG; Ens. }
        destruct H6 as [Hgc Hkc]. assert (Ensemble f[γ] ∧ Ensemble f[k]).
        { AssE [γ,f[γ]]; AssE [k,f[k]]. apply OrdEns2 in H6.
          apply OrdEns2 in H7; auto. } destruct H6 as [Hgb Hkb].
        apply H2 in H4 as Hg. AppC Hg. apply Hg. AppCG. AppCG; andG; Ens.
        apply SingNI; ens. intro. apply ordEq in H6; andH; Ens. }
    rewrite H1. apply Htp; [|apply Hs; eapply ValueP1; eens].
    apply bijection_is_func in Hfb'; andH. apply MapMapR1 in H2.
    rewrite Hks in H2. apply (IH (cT1 - [f[k]])); auto;
    [|intros A Ha; smH; auto]. destruct Hne as [A Ha]. rewrite <- Hr in Ha.
    exists f[∅]. smG. eapply ValueP1; eens. apply SingNI; Ens. intro.
    assert ([∅,f[∅]] ∈ f ∧ [k,f[k]] ∈ f). andG; eapply ValueP; eens.
    andH. rewrite H5 in H6. assert (k = ∅).
    eapply Hi; revgoals; eauto. rewrite Hr; auto. auto.
Qed.

Definition inDiscrete X := [X] ⋃ [∅].
Definition Discrete X := cP(X).

Example inDiscreteT : ∀ X, Ensemble X → Topology X (inDiscrete X).
Proof.
  intros. unfold inDiscrete. repeat split; intros.
  intros x Hx; unH; sing H0; ens. AppCG; ens. apply EmptySub.
  AppCG; ens. AppCG; ens. apply IntSinEm; auto. apply EleUSinEm; auto.
Qed.

Example DiscreteT : ∀ X, Ensemble X → Topology X (Discrete X).
Proof.
  intros. unfold Discrete; repeat split; ens; intros.
  apply PowerI; auto; apply EmptySub. pow H0; pow H1. AppCG.
  apply InterEns; eens. intros x Hx; inH; auto.
  AppCG. eens. intros x Hx; eleU Hx; apply H0 in H2; pow H2.
Qed.

(* 5.2 Neighborhoods and neighborhood system *)
Definition TNeigh x U X cT := Topology X cT ∧ x ∈ X ∧ U ⊂ X ∧
  ∃ V, V ∈ cT ∧ x ∈ V ∧ V ⊂ U.
Definition TNeighS x X cT := \{λ U, TNeigh x U X cT\}.
Definition TONeigh x U X cT := TNeigh x U X cT ∧ x ∈ U ∧ U ∈ cT.

Lemma TNeighP : ∀ x U X cT,
  Topology X cT → x ∈ U → U ∈ cT → TNeigh x U X cT.
Proof.
  intros. assert (U ⊂ X). apply H in H1; pow H1.
  red; andG; auto. exists U; andG; ens.
Qed.

Lemma TNeighP1 : ∀ x U X cT,
  Ensemble X → TNeigh x U X cT ↔ U ∈ TNeighS x X cT.
Proof. split; intros. AppCG. eapply SubAxP; eauto. apply H0. AppC H0. Qed.

Definition EleUx x U cT := ∪\{λ V, x ∈ U ∧ V ∈ cT ∧ x ∈ V ∧ V ⊂ U \}.

Lemma Le_NeFa : ∀ U, U = ∪(\{λ t, ∃ x, x ∈ U ∧ t = [x]\}).
Proof.
  intro. AppE; AssE x. AppCG. exists [x]. andG; ens. AppCG; ens.
  eleU H. AppC H1; destruct H1; andH. subst. sing H; Ens.
Qed.

Fact Neighbor_F : ∀ U X cT, Ensemble X → Topology X cT → U ⊂ X →
  (U ∈ cT ↔ ∀ x, x ∈ U → U ∈ TNeighS x X cT).
Proof.
  intros * Hxe Ht Hs. split; intros Hp.
  - intros. apply TNeighP1, TNeighP; auto.
  - DC (U = ∅). subst; apply Ht. set (∪(\{λ t, ∃ x, x ∈ U ∧
      t = EleUx x U cT\})) as Hmi.
    assert (H1 : ∪(\{λ t, ∃ x, x ∈ U ∧ t = [x]\}) ⊂ Hmi).
    { intros z Hz; eleU Hz. AppC H1; destruct H1; andH. subst.
      sing H0; Ens. apply Hp in H1 as Hu. AppC Hu. AppCG; Ens.
      exists (EleUx x0 U cT). andG. AppCG; Ens. destruct Hu as
        [_ [_ [_ [V [Hv []]]]]]. exists V. andG; auto. AppCG; Ens. AppCG.
      apply (SubAxP U); eens. intros z Hz. eleU Hz. AppC H2; andH; auto. }
    rewrite <- Le_NeFa in H1. assert (H2 : Hmi ⊂ U).
    { intros z Hz. eleU Hz. AppC H2; destruct H2; andH.
      subst. eleU H0; AppC H3; andH; auto. } assert (U = Hmi). eens.
    rewrite H0. apply Ht; intros V Hv. AppC Hv; destruct Hv; andH.
    subst V. apply Ht. intros z Hz; AppC Hz; tauto.
Qed.

Fact Neighbors_Fa : ∀ x X cT, Ensemble X → Topology X cT → x ∈ X →
  ∀ U V, U ∈ TNeighS x X cT → V ∈ TNeighS x X cT →
  U ∩ V ∈ TNeighS x X cT.
Proof.
  intros * Hxe Ht Hx * Hu Hv.
  apply TNeighP1 in Hu as [_ [_ [Hux [U0 [Ho1 []]]]]]; auto.
  apply TNeighP1 in Hv as [_ [_ [Hvx [V0 [Ho2 []]]]]]; auto.
  apply TNeighP1; auto. red; andG; auto. intros z Hz; inH; auto.
  exists (U0 ∩ V0). andG; ens. apply Ht; auto. intros z Hz; inH; ens.
Qed.

Fact Neighbors_Fb : ∀ x X cT, Ensemble X → Topology X cT → x ∈ X →
  ∀ U V, U ∈ TNeighS x X cT → V ⊂ X → U ⊂ V → V ∈ TNeighS x X cT.
Proof.
  intros * Hxe Ht Hx * Hu Hv Huv.
  apply TNeighP1 in Hu as [_ [_ [Hux [U0 [Ho1 []]]]]]; auto.
  apply TNeighP1; auto. red; andG; auto. exists U0; andG; eens.
Qed.

Fact Neighbors_Fc : ∀ x X cT, Ensemble X → Topology X cT → x ∈ X →
  ∀ U, U ∈ TNeighS x X cT → ∃ V, V ∈ TNeighS x X cT ∧ V ⊂ U ∧
  (∀ y, y ∈ V → V ∈ TNeighS y X cT).
Proof.
  intros. apply TNeighP1 in H2 as [_[_[Hu [V [Ho []]]]]]; auto. exists V.
  andG; auto. apply TNeighP1, TNeighP; auto. apply Neighbor_F; eens.
Qed.

(* 5.3 Derived, Closed, Closure *)
Definition Cluster x A X cT := Topology X cT ∧ A ⊂ X ∧ x ∈ X ∧
  ∀ U, TNeigh x U X cT → U ∩ (A - [x]) ≠ ∅.
Definition Derived A X cT := \{λ x, Cluster x A X cT\}.

Lemma DerivedP : ∀ A X cT, Derived A X cT ⊂ X.
Proof. intros * x Hx. AppC Hx. apply Hx. Qed.

Lemma DerivedP1 : ∀ x A X cT, Cluster x A X cT ↔ x ∈ Derived A X cT.
Proof. split; intros. AppCG; exists X; apply H. AppC H. Qed.

Lemma DerivedP2 : ∀ x A X cT, Topology X cT → A ⊂ X → x ∈ X →
  x ∉ Derived A X cT → ∃ U, TNeigh x U X cT ∧ U ∩ (A - [x]) = ∅.
Proof.
  intros * Ht Hs Hx Hp. DC (∃ U, TNeigh x U X cT ∧ U ∩ (A - [x]) = ∅).
  auto. elim Hp; apply DerivedP1; red; andG; eauto.
Qed.

Fact Derived_Fa : ∀ A B X cT,
  B ⊂ X → A ⊂ B → Derived A X cT ⊂ Derived B X cT.
Proof.
  intros * Hb Hs x Hx. apply DerivedP1 in Hx. red in Hx; andH.
  apply DerivedP1. red; andG; auto. intros U Hu. apply H2 in Hu.
  apply EmptyNE in Hu as [y]. inH; smH.
  apply EmptyNE. exists y; inG; smG; auto.
Qed.

Fact Derived_Fb : ∀ A B X cT, Ensemble X → A ⊂ X → B ⊂ X →
  Derived (A ⋃ B) X cT = Derived A X cT ⋃ Derived B X cT.
Proof.
  intros * Hxe Ha Hb. apply IncAsym.
  - intros x Hx. pose proof Hx as Hx'. apply DerivedP1 in Hx as
      [Ht [_ [Hx _]]]. DC (x ∈ Derived A X cT ⋃ Derived B X cT); auto.
    apply UnionNE in H; andH. apply DerivedP2 in H as [U [Hun Hu]];
    apply DerivedP2 in H0 as [V [Hvn Hv]]; auto.
    assert (x ∉ Derived (A ⋃ B) X cT).
    { intro. apply DerivedP1 in H as [_ [_ [_ Hp]]]. set (U ∩ V) as D.
      assert (D ∈ TNeighS x X cT). apply Neighbors_Fa; auto;
      apply TNeighP1; auto. apply TNeighP1, Hp in H; auto.
      assert (D ∩ (A ⋃ B) - [x] = ∅).
      { assert ((A ⋃ B) - [x] = A - [x] ⋃ B - [x]). AppE. smH; unH; ens.
        unH; smH; smG; ens. rewrite H0, DistribuLI. AppE; [|exfalso0].
        rewrite <- Hu, <- (EmptyU (U ∩ A - [x])), <- Hv.
        unH;inH;smH;AppC H1; andH; [unG|apply UnionI']; inG; smG; auto. }
       auto. } tauto.
  - assert (Derived A X cT ⊂ Derived (A ⋃ B) X cT ∧
      Derived B X cT ⊂ Derived (A ⋃ B) X cT).
    { andG; apply Derived_Fa; intros x Hx; unH; ens. }
    andH; intros x Hx; unH; auto.
Qed.

Fact Derived_Fc : ∀ A X cT, Ensemble X → A ⊂ X →
  Derived (Derived A X cT) X cT ⊂ A ⋃ Derived A X cT.
Proof.
  intros * Hxe Ha x Hx. pose proof Hx as Hx'. apply DerivedP1 in Hx as
    [Ht [_ [Hx _]]]. DC (x ∈ A ⋃ Derived A X cT); auto. exfalso.
  apply UnionNE in H as [Hxa Hxd]. apply DerivedP2 in Hxd as
    [U [Hun Hue]]; auto. apply TNeighP1 in Hun as Hun'; auto.
  apply Neighbors_Fc in Hun' as [V [Hvn [Hvu Hp]]]; auto.
  apply Neighbor_F in Hp as Hp'; auto; [|apply TNeighP1 in Hvn; auto;
  eapply IncTran; eauto; apply Hun]. assert (V ∩ A - [x] = ∅).
  { AppE; [|exfalso0]. rewrite <- Hue. inH; smH. inG; smG; auto. }
  assert (V ∩ A = ∅). { eapply InterEqEmI; revgoals; eauto; Ens. }
  assert (∀ y, y ∈ V → y ∉ A).
  { intros * Hy H1. assert (y ∈ V ∩ A); ens. rewrite H0 in H2. exfalso0. }
  assert (∀ y, y ∈ V → V ∩ A - [y] = ∅).
  { intros. AppE; [|exfalso0]. inH; smH. apply H1 in H3; tauto. }
  assert (∀ y, y ∈ V → y ∉ Derived A X cT).
  { intros * Hy H3. apply H2 in Hy as Hyp. apply DerivedP1 in H3.
    apply Hp, TNeighP1, H3 in Hy; auto. }
  assert (V ∩ Derived A X cT - [x] = ∅).
  { AppE; [|exfalso0]. inH; smH. exfalso. apply H3 in H4; auto. }
  apply DerivedP1 in Hx' as [_ [_ [_ Hx']]].
  AppC Hvn. apply Hx' in Hvn; auto.
Qed.

Definition Closed A X cT := Topology X cT ∧ A ⊂ X ∧ Derived A X cT ⊂ A.

Fact Closed_F1 : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →
  Closed A X cT ↔ X - A ∈ cT.
Proof.
  intros * Hxe Ht Hs. pose proof (SetminSubI A X). split; intros Hp.
  - eapply Neighbor_F; eauto. intros. smH. assert (x ∉ Derived A X cT).
    { intro. apply Hp in H2; tauto. } apply DerivedP2 in H2 as
      [U [Hun Hue]]; auto. apply InterEqEmI in Hue; Ens.
    apply TNeighP1; auto. red; andG; auto. destruct Hun as
      [_ [_ [Hu [V [Hv [Hxv Hvu]]]]]]. exists V. andG; auto.
    eapply IncTran; eauto. intros z Hz. smG; auto. intro.
    assert (z ∈ U ∩ A); ens. rewrite Hue in H3; exfalso0.
  - red; andG; auto. intros x Hx. DC (x ∈ A); auto. exfalso.
    assert (x ∈ X - A). { AppC Hx. smG; auto. apply Hx. }
    eapply Neighbor_F, TNeighP1 in H1; eauto. pose proof Hx.
    apply DerivedP1 in Hx as [_ [_ [_ Hx]]]. apply Hx in H1.
    assert (X-A ∩ A-[x] = ∅). AppE; [|exfalso0]; inH; smH; tauto. auto.
Qed.

Corollary Co_ClFa1 : ∀ A X cT,
  Ensemble X → Topology X cT → A ⊂ X → A ∈ cT → Closed (X - A) X cT.
Proof.
  intros. apply Closed_F1; auto.
  apply SetminSubI. rewrite TwoCompl; auto.
Qed.

Definition TcF X cT := \{λ U, U ⊂ X ∧ X - U ∈ cT\}.

Fact cFP : ∀ X cT, TcF X cT ⊂ cP(X).
Proof. intros * U Hu. AppCG; Ens. AppC Hu; tauto. Qed.

Fact Closed_F2a : ∀ X cT, Ensemble X → Topology X cT →
  X ∈ TcF X cT ∧ ∅ ∈ TcF X cT.
Proof.
  intros. andG; AppCG; ens; andG; ens;
  [rewrite SetminId|apply EmptySub|rewrite SetminEm]; apply H0.
Qed.

Fact Closed_F2b : ∀ cF1 X cT, Ensemble X → Topology X cT →
  cF1 ≠ ∅ → cF1 ⊂ TcF X cT → ⋂cF1 ∈ TcF X cT.
Proof.
  intros * Hxe Ht Hne Hs. set \{λ A, A ⊂ X ∧ X - A ∈ cF1\} as cT1.
  assert (HcT : cT1 ⊂ cT).
  { intros A Ha. AppC Ha; andH. apply Hs in H0. AppC H0; andH.
    rewrite TwoCompl in H1; auto. }
  apply Ht in HcT. assert (H1 : (X - ∪cT1) ∈ TcF X cT).
  { AppCG; ens. andG. apply SetminSubI. rewrite TwoCompl; auto.
    apply Ht in HcT; pow HcT. }
  assert (H2 : (X - ∪(AAr X cF1)) = X - ∪cT1).
  { AppE; smH; smG; auto; intro; elim H0; eleU H2.
    - AppC H3; andH. AppCG; Ens. exists (X - (X - x0)). andG.
      rewrite TwoCompl; auto. AppCG; ens.
    - pose proof H3; AppC H3; destruct H3 as [T []]. AppCG; Ens.
      exists x0. andG; auto. AppCG; Ens. subst; rewrite TwoCompl.
      andG; auto. apply SetminSubI. apply Hs in H3; AppC H3; tauto. }
  rewrite DeMorganUI in H2; try apply AArP; auto.
  assert (⋂ cF1 = ⋂ AAr X (AAr X cF1)).
  { AppE; AssE x; AppC H; AppCG; intros.
    - AppC H3; destruct H3 as [B [Hb Heq]]. AppC Hb; destruct Hb as
        [C [Hc Heq1]]. subst. rewrite TwoCompl; auto.
      apply Hs in Hc. AppC Hc; tauto.
    - apply H. AppCG; Ens. exists (X - y). pose proof H3; apply Hs in H3.
      AppC H3; andH. rewrite TwoCompl; auto. andG; auto. AppCG;Ens. }
  rewrite H, H2; auto.
Qed.

Definition Closure A X cT := A ⋃ Derived A X cT.

Lemma ClosureP : ∀ A X cT, A ⊂ X → Closure A X cT ⊂ X.
Proof.
  intros * Ha x Hx. AppC Hx; orH; auto. apply DerivedP in H; auto.
Qed.

Fact Closure_Fa : ∀ A B X cT, Ensemble X → Topology X cT →
  A ⊂ X → B ⊂ X → Closure (A ⋃ B) X cT = Closure A X cT ⋃ Closure B X cT.
Proof.
  intros * Hxe Ht Ha Hb. unfold Closure. rewrite Derived_Fb,
    AssocU, (CommuU B), <- AssocU,
    <- AssocU, AssocU, (CommuU _ B); auto.
Qed.

Fact Closure_Fb : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →
  Closure (Closure A X cT) X cT = Closure A X cT.
Proof.
  intros * He Ht Hs. unfold Closure at 2. rewrite Closure_Fa; auto;
  [|apply DerivedP]. unfold Closure. rewrite AssocU,
    <- (AssocU (Derived A X cT) _ _), IdemU,
    <- AssocU, UnionSub; auto. apply Derived_Fc; auto.
Qed.

Fact Re1_CloClo : ∀ A X cT, Topology X cT → A ⊂ X →
  Closed A X cT ↔ A = Closure A X cT.
Proof.
  intros * Ht Hs. split.
  - intros [_ [_ Hp]]. unfold Closure. AppE; [|unH]; ens.
  - intros. red; andG; auto. rewrite H at 2; intros z HZ; AppCG; Ens.
Qed.

Fact Re2_CloClo : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →
  Closed (Closure A X cT) X cT.
Proof.
  intros * Hxe Ht Hs. apply Re1_CloClo; auto.
  apply ClosureP; auto. rewrite Closure_Fb; auto.
Qed.

Lemma Le_Re3CC : ∀ A B X cT, Topology X cT →
  A ⊂ B → Closed B X cT → Closure A X cT ⊂ B.
Proof.
  intros * Ht Hab Hb z Hz. AppC Hz; orH; auto.
  eapply Derived_Fa in H; eauto; apply Hb; auto.
Qed.

Fact Re3_CloClo : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →
  Closure A X cT = ⋂\{λ B, B ∈ TcF X cT ∧ A ⊂ B \}.
Proof.
  intros * Hxe Ht Hs. set (\{λ B, B ∈ TcF X cT ∧ A ⊂ B\}) as cB.
  assert (A ⊂ ⋂cB ∧ ⋂cB ∈ TcF X cT).
  { andG. intros x Hx. AppCG; Ens. intros B Hb. AppC Hb; andH; auto.
    apply Closed_F2b; auto. apply EmptyNE. exists X; AppCG; andG;
    auto. apply Closed_F2a; auto. intros B Hb; AppC Hb; tauto. }
  destruct H as [Ha Hb]. apply IncAsym.
  - AppC Hb; andH. apply Closed_F1 in H0; auto. apply Le_Re3CC; auto.
  - intros z Hz. AppC Hz. assert (Closure A X cT ∈ cB).
    { eapply ClosureP in Hs as Hc; eauto. AppCG; andG; eens.
      AppCG; andG; eens. apply Closed_F1, Re2_CloClo; auto.
      intros x Hx. AppCG; Ens. } auto.
Qed.

(* 5.4 Interior, External, Boundary *)
Definition Interiorp x A X cT := TNeigh x A X cT.
Definition Interior A X cT := \{λ x, Interiorp x A X cT \}.
Definition External A X cT := Interior (X - A) X cT.

Lemma InteriorP : ∀ A X cT, Interior A X cT ⊂ X.
Proof.
  unfold Interior, Interiorp, TNeigh.
  intros * z Hz. AppC Hz. andH. destruct H2; andH; auto.
Qed.

Fact Interior_F1a : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →
  Interior A X cT = X - (Closure (X - A) X cT).
Proof.
  intros * Hxe Ht Hs. apply IncAsym; intros x Hx.
  - AppC Hx. assert (Hx' := Hx).
    destruct Hx as [_ [Hx [_ [V [Hv [Hxv Hva]]]]]]. apply Hva in Hxv.
    AppCG; andG; Ens. intro. AppC H; orH. smH; auto. apply DerivedP1 in H.
    apply H in Hx'. elim Hx'. AppE. inH; smH; tauto. exfalso0.
  - smH. apply UnionNE in H0 as [Hxi Hc]. apply DerivedP2 in Hc as
      [V [Hnv Hc]]; auto; [|apply SetminSubI]. apply InterEqEmI in Hc; Ens.
    apply InterSetmin in Hc; [|apply Hnv]. AppCG; Ens.
    eapply TNeighP1, Neighbors_Fb; eauto. apply TNeighP1; auto.
Qed.

Fact Interior_F1b : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →
  Closure A X cT = X - (Interior (X - A) X cT).
Proof.
  intros * Hxe Ht Hs. pose proof (SetminSubI A X) as Hc.
  eapply Interior_F1a in Hc; eauto. erewrite TwoCompl in Hc; auto.
  apply (SetminEq _ _ X) in Hc. erewrite TwoCompl in Hc; auto.
  apply ClosureP; auto.
Qed.

Fact Interior_F2 : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →
  Interior (Interior A X cT) X cT = Interior A X cT.
Proof.
  intros *Hxe Ht Ha. pose proof SetminSubI A X as Ha'.
  rewrite Interior_F1a, Interior_F1a, TwoCompl, Closure_Fb;
  auto. apply ClosureP; auto. apply InteriorP.
Qed.

Fact Re1_OpeInt : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →
  A ∈ cT ↔ A = Interior A X cT.
Proof.
  intros * Hxe Ht Ha. pose proof SetminSubI A X as Hc. split; intros Hp.
  - eapply Co_ClFa1 in Hp as Hp'; eauto.
    apply Re1_CloClo, (SetminEq _ _ X) in Hp'; auto.
    rewrite TwoCompl in Hp'; auto. rewrite Interior_F1a; auto.
  - rewrite Interior_F1a in Hp; auto. apply (SetminEq _ _ X) in Hp.
    rewrite TwoCompl in Hp; [|apply ClosureP]; auto.
    apply Re1_CloClo, Closed_F1 in Hp; auto.
    rewrite TwoCompl in Hp; auto.
Qed.

Fact Re2_OpeInt : ∀ A X cT,
  Ensemble X → Topology X cT → A ⊂ X → Interior A X cT ∈ cT.
Proof.
  intros * Hxe Ht Ha. eapply Re1_OpeInt; eauto.
  apply InteriorP. symmetry; apply Interior_F2; auto.
Qed.

Fact Re3_OpeInt : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →
  Interior A X cT = ∪\{λ B, B ∈ cT ∧ B ⊂ A\}.
Proof.
  intros * Hxe Ht Ha. pose proof SetminSubI A X as Ha'.
  rewrite Interior_F1a, Re3_CloClo, DeMorganIU; auto. AppE; eleU H.
  - AppC H0; destruct H0 as [r [Hr Hb]]. subst. AppC Hr; andH. AppC H0.
    andH. AppCG; Ens. exists (X - r). andG; auto. AppCG; Ens. andG; auto.
    eapply SetminSub2 in H1. rewrite TwoCompl in H1; auto.
  - AppC H0; destruct H0 as [Hb Hs]. AppCG; Ens. exists x0. andG; auto.
    AppCG; Ens. exists (X - x0). rewrite TwoCompl; eens. andG; auto.
    assert (X - x0 ⊂ X). apply SetminSubI. AppCG; eens.
    andG; [|apply SetminSub2; auto]. AppCG; andG; eens.
    rewrite TwoCompl; eens.
Qed.

Definition Boundp x A X cT := Topology X cT ∧ A ⊂ X ∧ x ∈ X ∧
  ∀ U, TNeigh x U X cT → U ∩ A ≠ ∅ ∧ U ∩ X - A ≠ ∅.
Definition Bound A X cT := \{λ x, Boundp x A X cT\}.

Fact Re1_ClInBo : ∀ A X cT, Topology X cT → A ⊂ X →
  Bound A X cT = Closure A X cT ∩ Closure (X - A) X cT.
Proof.
  intros * Ht Ha. pose proof SetminSubI A X as Ha'. AppE.
  - AppC H. red in H; andH. AppCG; Ens. andG; AppCG; Ens;
    [DC (x ∈ A); auto|DC (x ∈ X - A); auto]; right; apply DerivedP1;
    red; andG; auto; intros; [apply H2 in H4 as [Hl _]|
    apply H2 in H4 as [_ Hl]]; intro; elim Hl; eapply InterEqEmI; Ens.
  - inH. AppCG; Ens. red; andG; auto. eapply ClosureP; eauto. intros.
    AppC H; AppC H0; orH; [smH; tauto|apply DerivedP1 in H|
    apply DerivedP1 in H0|].
    + andG. apply H in H1; intro; elim H1; apply InterEqEmE; auto.
      destruct H1 as [_ [_ [_ [V [_ [Hv Hvu]]]]]]. intro.
      assert (x ∈ U ∩ X - A); ens. rewrite H1 in H2; exfalso0.
    + andG; [|apply H0 in H1; intro; elim H1; apply InterEqEmE; auto].
      destruct H1 as [_ [_ [_ [V [_ [Hv Hvu]]]]]]. intro.
      assert (x ∈ U ∩ A); ens. rewrite H1 in H2; exfalso0.
    + apply DerivedP1 in H; apply DerivedP1 in H0. andG; [apply H in H1|
      apply H0 in H1]; intro; elim H1; apply InterEqEmE; auto.
Qed.

Fact Re2_ClInBo : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →
  Closure A X cT ∩ Closure (X - A) X cT =
  X - (Interior A X cT ⋃ Interior (X - A) X cT).
Proof.
  intros * Hxe Ht Ha. rewrite Interior_F1b, Interior_F1b,
    TwoCompl, <- UnionCompl, CommuU;
  try apply InteriorP; auto. apply SetminSubI.
Qed.

Fact Re3_ClInBo : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →
  X - (Interior A X cT ⋃ Interior (X - A) X cT) = Bound (X - A) X cT.
Proof.
  intros * Hxe Ht Ha. rewrite Re1_ClInBo, TwoCompl,
    CommuI, Re2_ClInBo; auto. apply SetminSubI.
Qed.

Corollary BoundP : ∀ A X cT, Topology X cT → A ⊂ X →
  Closure A X cT = A ⋃ Bound A X cT.
Proof.
  intros. rewrite Re1_ClInBo, DistribuLU, IncU; auto;
  [|intros x Hx; unfold Closure; ens]. assert (A ⋃ Closure (X-A) X cT = X).
  { AppE. unH; auto. AppC H1; orH. smH; auto. AppC H1; apply H1.
    DC (x ∈ A); ens. apply UnionI'; unfold Closure; ens. }
  rewrite H1, IncI; [|apply ClosureP]; auto.
Qed.

(* 5.5 Base, *)
Definition Base cB X cT := Topology X cT ∧ cB ⊂ cT ∧
  ∀ U, U ∈ cT → ∃ cB1, cB1 ⊂ cB ∧ U = ∪cB1.
Definition SubBase cS X cT := Topology X cT ∧ cS ⊂ cT ∧
  Base (\{λ U, ∃ cN, ⦿ cN ∧ Finite cN ∧ cN ⊂ cS ∧ U = ⋂cN\}) X cT.

Fact BaseP : ∀ X cT, Topology X cT → Base cT X cT.
Proof.
  split; andG; ens. intros. exists [U]. andG. intros z Hz.
  sing Hz; Ens. rewrite EleUSin; Ens.
Qed.

Fact NeFiSuP1 : ∀ cS,
  cS ⊂ \{λ U, ∃ cN, ⦿ cN ∧ Finite cN ∧ cN ⊂ cS ∧ U = ⋂cN\}.
Proof.
  intros * U Hu; AssE U. AppCG. exists [U]. andG. exists U; ens.
  apply sin_finite; auto. intros x Hx; sing Hx. rewrite EleISin; auto.
Qed.


Fixpoint mod2 n :=
  match n with
  | 0 => 0
  | S n' => match mod2 n' with 0 => 1 | S _ => 0 end
  end.

Definition task := forall n, mod2 n = mod2 (n * n).


(** This file axiomatizes the needed definitions and properties of the Lebesgue
integral. It ignores all issues of measurability, but otherwise attempts to
only axiomatize well-known results in analysis and measure theory. *)

Require Import Utf8.
Require Import Coq.Classes.Morphisms.
Require Import Coq.Relations.Relations.

Require Import RRR.Util.Option.
Require Import RRR.Util.Misc.
Require Import RRR.Lebesgue.Ennr.

Local Open Scope program_scope.
Local Open Scope ennr_scope.

(** * Definitions *)

(** Using [bool] instead of [Prop] for the definition of an event is a little
unusual, but allows us to define an indicator function that produces real
numbers (which are in the [Set] universe). It's very possible there are other
solutions to this problem, such as using [excluded_middle_informative]. *)
Definition Event X := X → bool.
Definition Meas A := (Event A → R⁺).

(** [ifte] is a function version of "if then else" which allows tactics like
f_equal can deal with it more easily. *)
Definition ifte {X} (a : bool) (b c : X) := if a then b else c.
Definition indicator {X} (b : Event X) : X → R⁺ := fun x => ifte (b x) 1 0.

Definition full_event {X} : Event X := const true.

Definition bool_of_dec {X Y} : sumbool X Y → bool :=
  fun xy => if xy then true else false.

(** * Axioms of integration *)

(** Assume that integration exists for all (non-negative) functions. *)
Parameter integrate : ∀ {A}, (A → R⁺) → Meas A → R⁺.
Notation "∫" := (integrate).

(** Assume the general form of linearity for integration. *)
Axiom integration_linear :
∀ {A} (μ : Meas A) (s0 s1 : R⁺) (f0 f1 : A → R⁺),
s0 * ∫ f0 μ + s1 * ∫ f1 μ = ∫ (fun x => s0 * f0 x + s1 * f1 x) μ.

(** Axiomatize the Lebesgue measure restricted to non-negative reals.
 Throw in ∞ too -- but it's just one point so it has no mass. *)
Parameter lebesgue_pos_measure : Meas R⁺.
Parameter lebesgue_measure : Meas R.
Axiom lebesgue_measure_full_event : ∞ = lebesgue_measure full_event.

(** Assume lebesgue([0, r]) = r *)
Axiom lebesgue_pos_measure_interval :
∀ (r : R⁺),
lebesgue_pos_measure (fun x => bool_of_dec (ennr_gt_dec r x)) = r.

(** Assume that Lebesgue integration can be expressed as a Riemann integral
of the "layer cake" function. (Leib and Loss, 1997).

Despite the promise in the name to relate Lebesgue and Riemann integrals, it
is phrased here as a relation just between Lebesgue and Lebesgue. Since the
Lebesuge integral is defined strictly more often than and always agrees with
the Riemann integral, this is still a valid assumption.

This assumption turns out to be very useful for proving equalities of
integrals between measure-isomorphic domains. It also can provide a way to
deal with integration by non-axiomatized measures, e.g., pushfowards.
*)
Axiom riemann_def_of_lebesgue_integration :
∀ {X} μ (f : X → R⁺),
∫ f μ =
∫ (fun r => μ (fun x => bool_of_dec (ennr_gt_dec (f x) r)))
  lebesgue_pos_measure.

(** This assumption is usually presented as the first step in the definition
of the Lebesgue integral. *)
Axiom integration_of_indicator :
∀ {A} (μ : Meas A) (ev : Event A), ∫ (indicator ev) μ = μ ev.

(** Define convenient, Haskelly syntax for working with Markov kernels as a
monad in the spirit of Giry (1980) and Panangaden (1999). For lack of a
better name, let's call the SRel+ because we're removing the subprobability
restriction from SRel. *)
Definition meas_bind {A B} (μ : Meas A) (f : A → Meas B) : Meas B :=
fun eB => ∫ (fun a => f a eB) μ.
Infix ">>=" := meas_bind (at level 20).

(** This is the associativity law for SRel+. Panangaden proved this for
subprobabilities, but his proof makes no use of that restriction, and is
therefore just as good of a proof in this instance. *)
Axiom meas_bind_assoc :
∀ {A B C} (μ : Meas A) (f : A → Meas B) (g : B → Meas C),
(μ >>= f) >>= g = μ >>= (fun a => f a >>= g).

(** Axiomatize σ-finiteness. *)
Parameter σ_finite : ∀ {A}, Meas A → Prop.

(** An actual definition of σ-finiteness here would be more challenging than
rewarding, so we instead simply state the σ-finiteness results that we will be using.
*)
Axiom leb_pos_is_σ_finite : σ_finite lebesgue_pos_measure.
Axiom leb_is_σ_finite : σ_finite lebesgue_measure.

(* Hint Resolve leb_pos_is_σ_finite leb_is_σ_finite. *)

(** We axiomitize Tonelli's theorem for all combinations of the two measures
listed above. *)
Axiom tonelli :
∀ {X Y} (f : X → Y → R⁺) (μx : Meas X) (μy : Meas Y),
σ_finite μx →
σ_finite μy →
∫ (fun x => ∫ (fun y => f x y) μy) μx =
∫ (fun y => ∫ (fun x => f x y) μx) μy.

(** * Consequences of the axioms *)

(** ** Measure combinators *)

Definition empty_meas X : Meas X := fun x => 0.
Arguments empty_meas {X} _ /.

Definition dirac {A} (a : A) : Meas A := fun ev => indicator ev a.
Arguments dirac {_} _ _ /.

Definition preimage {A B} (f : A → B) : (B → bool) → (A → bool) :=
fun eB a => eB (f a).
Arguments preimage {_ _} _ _ _ /.

Definition pushforward {A B} (μ : Meas A) (f : A → B) : Meas B :=
  μ ∘ preimage f.

(** Convert emptiness in an option to emptiness in a measure. *)
Definition option_meas {A} (oμ : option (Meas A)) : Meas A :=
fromOption empty_meas oμ.

Definition meas_option {A} (μo : Meas (option A)) : Meas A :=
fun ev => μo (
  fun oa =>
    match oa with
    | Some x => ev x
    | _ => false
    end
).

(** Two ways to reweight a [Meas A].
[unif_score_meas] reweights the entire measure by a constant.
[score_meas] reweights dependent on each element in [A].
*)
Definition unif_score_meas {X} (s : R⁺) (μ : Meas X) : Meas X :=
fun A => μ A * s.
Arguments unif_score_meas {_} _ _ _ /.

Definition score_meas {X} (w : X → R⁺) (μ : Meas X) : Meas X :=
  μ >>= (fun x A => w x * indicator A x).

(** ** Lemmas about integration *)

(** Tactic for showing [∫ f dμ = ∫ g dμ] by pointwise equality of [f] and [g]. *)
Ltac integrand_extensionality x :=
match goal with
| [ |- _ = _ :> R⁺ ] => idtac
| [ |- _ = _ :> Meas _ ] => let A := fresh "A" in extensionality A
| [ |- _ = _ :> _ → R⁺ ] => let A := fresh "A" in extensionality A
end;
refine (f_equal2 ∫ _ eq_refl);
extensionality x.

(** Derive some more immediately useful forms of linearity. *)

Lemma integration_linear_plus:
  ∀ {A} (μ : Meas A) (f0 f1 : A → R⁺),
    ∫ f0 μ + ∫ f1 μ = ∫ (fun x => f0 x + f1 x) μ.
Proof.
  intros.
  replace (∫ f0 μ + ∫ f1 μ) with (1 * ∫ f0 μ + 1 * ∫ f1 μ) by ring.
  rewrite integration_linear.
  integrand_extensionality x.
  ring.
Qed.

Axiom integration_linear_minus:
∀ {A} (μ : Meas A) (f0 f1 : A → R⁺),
(∀ a, f1 a ≤ f0 a) →
∫ f0 μ - ∫ f1 μ = ∫ (fun x => f0 x - f1 x) μ.

Lemma integration_linear_mult_r
{A} (μ : Meas A) (r : R⁺) (f : A → R⁺) :
∫ (fun x => f x * r) μ =
∫ f μ * r.
Proof.
replace (∫ f μ * r) with (r * ∫ f μ + 0 * ∫ f μ) by ring.
rewrite integration_linear.
integrand_extensionality x.
ring.
Qed.

Lemma integration_linear_mult_l
{A} (μ : Meas A) (r : R⁺) (f : A → R⁺) :
∫ (fun x => r * f x) μ =
r * ∫ f μ.
Proof.
setoid_rewrite ennr_mul_comm.
apply integration_linear_mult_r.
Qed.

Lemma integration_linear_in_meas_l
{A} (r : R⁺) (μ : Meas A) (f : A → R⁺) :
∫ f (fun ev => r * μ ev) =
r * ∫ f μ.
Proof.
setoid_rewrite riemann_def_of_lebesgue_integration.
rewrite <- integration_linear_mult_l.
reflexivity.
Qed.

Lemma integration_linear_in_meas_r
{A} (r : R⁺) (μ : Meas A) (f : A → R⁺) :
∫ f (fun ev => μ ev * r) =
∫ f μ * r.
Proof.
setoid_rewrite riemann_def_of_lebesgue_integration.
rewrite <- integration_linear_mult_r.
reflexivity.
Qed.

Lemma integration_of_const
{X} (r : R⁺) (f : X → R⁺) (μ : Meas X) :
(∀ x, f x = r) → ∫ f μ = r * μ full_event.
Proof.
intros.
replace f with (fun x => f x * 1) by (extensionality t; ring).
setoid_rewrite H.
rewrite integration_linear_mult_l.
replace (fun _ => 1) with (@indicator X full_event) by reflexivity.
rewrite integration_of_indicator.
ring.
Qed.

Lemma integration_of_0
{A} (μ : Meas A) : ∫ (fun _ => 0) μ = 0.
Proof.
replace 0 with (0 * 0) by ring.
rewrite integration_linear_mult_r.
ring.
Qed.

(** Lemmas about inequality *)
Axiom integrand_extensionality_lt :
∀ {A} (μ : Meas A) (f1 f2 : A → R⁺),
(∀ a, f1 a < f2 a) →
∫ f1 μ < ∫ f2 μ.

Axiom integrand_extensionality_le :
∀ {A} (μ : Meas A) (f1 f2 : A → R⁺),
(∀ a, f1 a ≤ f2 a) →
∫ f1 μ ≤ ∫ f2 μ.

Axiom integrand_extensionality_le_meas :
∀ {A} (μ1 μ2 : Meas A) (f1 f2 : A → R⁺),
(∀ a, f1 a ≤ f2 a) →
(∀ A, μ1 A ≤ μ2 A) →
∫ f1 μ1 ≤ ∫ f2 μ2.

(** Some lemmas about integrating by the new measures *)
Lemma integration_of_pushforward
{A B} (f : A → B) (g : B → R⁺) (μ : Meas A) :
∫ (g ∘ f) μ = ∫ g (pushforward μ f).
Proof.
setoid_rewrite riemann_def_of_lebesgue_integration.
unfold pushforward, preimage, compose.
trivial.
Qed.

Lemma integration_wrt_dirac
{A} (a : A) (f : A → R⁺) :
∫ f (dirac a) = f a.
Proof.
setoid_rewrite riemann_def_of_lebesgue_integration.
unfold dirac.
setoid_rewrite integration_of_indicator.
rewrite lebesgue_pos_measure_interval.
reflexivity.
Qed.

Lemma integration_wrt_empty
{A} (f : A → R⁺) :
∫ f empty_meas = 0.
Proof.
setoid_rewrite riemann_def_of_lebesgue_integration.
unfold empty_meas.
rewrite integration_of_0.
reflexivity.
Qed.

Axiom integration_wrt_score_meas : ∀ X (f w : X → R⁺) (μ : Meas X),
∫ f (score_meas w μ) = ∫ (λ x, f x * w x) μ.
(* Requires Radon–Nikodym to find the pushforward *)

Lemma bind_meas_option {A B} μ (f : A → Meas B) :
meas_option μ >>= f =
μ >>= (fun x ev => option0 (flip f ev <$> x)).
Proof.
intros.
extensionality ev.
setoid_rewrite riemann_def_of_lebesgue_integration.
integrand_extensionality t.
unfold meas_option.
f_equal.
extensionality x.
destruct x; cbn; auto.
destruct ennr_gt_dec; auto.
contradict e.
destruct t; cbn; auto.
apply RIneq.Rle_not_lt.
auto.
Qed.

(** The remaining two monad laws for SRel+ *)

Lemma meas_id_left {A B} a (f : A → Meas B) :
(dirac a >>= f) = f a.
Proof.
extensionality ev.
unfold ">>=".
rewrite integration_wrt_dirac.
reflexivity.
Qed.

Lemma meas_id_right {A} (μ : Meas A) :
(μ >>= dirac) = μ.
Proof.
extensionality ev.
unfold ">>=", dirac.
apply integration_of_indicator.
Qed.

Definition meas_join {A} (μ : Meas (Meas A)) : Meas A :=
μ >>= (fun x => x).

Definition kernel A B := A → Meas B.

(** * Measures that may be safely interchanged *)

(** Tonelli's theorem will be too restricted to be of immediate use in
dealing with some of our measures. We will need to prove that a wider class
of measures than just σ-finite ones can be involved in an integral
interchange. *)
Class interchangeable {A B} (μa : Meas A) (μb : Meas B) : Prop :=
  interchange :
  ∀ {C} (f : A → B → Meas C),
  μa >>= (fun a => μb >>= (fun b => f a b)) =
  μb >>= (fun b => μa >>= (fun a => f a b))
.

(** [interchangeable] is a symmetric relation. Unfortunately we can't use the
[Symmetry] typeclass because it's a relation between different types. *)
Definition interchangeable_sym {A B} (μa : Meas A) (μb : Meas B) :
interchangeable μa μb → interchangeable μb μa.
Proof.
repeat intro.
symmetry.
apply H.
Qed.

Instance σ_finite_is_interchangeable {A B} (μa : Meas A) (μb : Meas B) :
σ_finite μa →
σ_finite μb →
interchangeable μa μb.
Proof.
repeat intro.
extensionality ec.
unfold ">>=".
apply tonelli ; auto.
Qed.

Instance score_meas_interchangeable {X} (μX : Meas X) (w : X → R⁺) :
∀ {Y} (μy : Meas Y),
interchangeable μX μy →
interchangeable (score_meas w μX) μy.
Proof.
repeat intro.
unfold score_meas.
setoid_rewrite meas_bind_assoc.
rewrite <- H ; clear H.
unfold ">>=".
extensionality eC.
integrand_extensionality x.
setoid_rewrite integration_linear_in_meas_l.
setoid_rewrite integration_linear_mult_l.
f_equal.
fold (dirac x).
setoid_rewrite integration_wrt_dirac.
reflexivity.
Qed.

Instance pushforward_interchangeable
{X Y} (μ : Meas X) (f : X → Y)
{Z} (μz : Meas Z) :
interchangeable μ μz →
interchangeable (pushforward μ f) μz.
Proof.
intros H ? g.
unfold ">>=".
setoid_rewrite <- (integration_of_pushforward f).
unfold compose.
change (
  (λ ev, ∫ (λ x, ∫ (λ z : Z, (g ∘ f) x z ev) μz) μ) =
  (λ ev, ∫ (λ z, ∫ (λ x : X, (g ∘ f) x z ev) μ) μz)
).
apply H.
Qed.

Instance meas_option_interchangeable
{X} (μ : Meas (option X))
{Y} (μy : Meas Y) :
interchangeable μ μy →
interchangeable (meas_option μ) μy.
Proof.
intros H ? f.
setoid_rewrite bind_meas_option.
rewrite <- H.
integrand_extensionality ox.
destruct ox; cbn; auto.
setoid_rewrite integration_of_0.
trivial.
Qed.

Lemma bind_interchangeable
{X Y} (μ : Meas X) (f : X → Meas Y)
{Z} (μz : Meas Z) :
interchangeable μ μz →
(∀ x, interchangeable (f x) μz) →
interchangeable (μ >>= f) μz.
Proof.
intros H1 H2 ? g.
repeat intro.
setoid_rewrite meas_bind_assoc.
rewrite <- H1.
setoid_rewrite H2.
reflexivity.
Qed.

(** ** Other lemmas *)

Lemma coarsening
{X} (M : Event X → Event X → Prop)
(μ₁ μ₂ : Meas X)
(f₁ f₂ : X → R⁺) :
(∀ A₁ A₂, M A₁ A₂ → μ₁ A₁ = μ₂ A₂) →
(∀ (B : Event R⁺), M (preimage f₁ B) (preimage f₂ B)) →
∫ f₁ μ₁ = ∫ f₂ μ₂.
Proof.
intros Hμ Hf.
setoid_rewrite riemann_def_of_lebesgue_integration.
integrand_extensionality t.
apply Hμ.
unfold preimage in Hf.
apply Hf with (B := λ r, bool_of_dec (ennr_gt_dec r t)).
Qed.

Axiom integration_wrt_redundant_var : ∀ X
(f : option (nat * X) → R⁺) (g : option X → R⁺)
(μ : Meas (option (nat * X))) (ν : Meas (option X)),
f None = g None →
(∀ n x, f (Some (n, x)) = g (Some x)) →
(∀ X, μ (λ y, match y with
  | Some (_, x) => X (Some x)
  | None => X None
  end) = ν X) →
∫ f μ = ∫ g ν.

(** Monotone Convergence Theorem *)

Axiom interchange_sup_integration :
∀ X (f : X → nat → R⁺) (μ : Meas X),
(∀ x, monotone (f x)) →
sup (λ n, ∫ (λ x, f x n) μ) = ∫ (λ x, sup (f x)) μ.

Axiom interchange_sup_integration_meas :
∀ X (f : X → nat → R⁺) (μ : nat → Meas X),
(∀ x, monotone (f x)) →
(∀ X, monotone (λ n, μ n X)) →
sup (λ n, ∫ (λ x, f x n) (μ n)) = ∫ (λ x, sup (f x)) (λ X, sup (λ n, μ n X)).

Axiom interchange_inf_integration :
∀ X (f : X → nat → R⁺) (μ : Meas X),
(∀ x, antitone (f x)) →
inf (λ n, ∫ (λ x, f x n) μ) = ∫ (λ x, inf (f x)) μ.

Axiom interchange_inf_integration_meas :
∀ X (f : X → nat → R⁺) (μ : nat → Meas X),
(∀ x, antitone (f x)) →
(∀ X, antitone (λ n, μ n X)) →
inf (λ n, ∫ (λ x, f x n) (μ n)) = ∫ (λ x, inf (f x)) (λ X, inf (λ n, μ n X)).

(* left open, right closed interval *)
Axiom Rinterval_dec' : ∀ (a b r : R), {(a < r ∧ r ≤ b)%R} + {¬ (a < r ∧ r ≤ b)%R}.

Axiom integral_over_intervals : ∀ (a b c : R) (e : R → R⁺) (H : (a ≤ b ≤ c)%R),
    ∫ (λ r : R, e r * (if Rinterval_dec a c r then 1 else 0)) lebesgue_measure
    = ∫ (λ r : R, e r * (if Rinterval_dec a b r then 1 else 0)) lebesgue_measure
      + ∫ (λ r : R, e r * (if Rinterval_dec' b c r then 1 else 0)) lebesgue_measure.

Axiom lebesgue_measure_of_inverval : ∀ (a b : R) (H : (0 <= b - a)%R),
    ∫ (λ x : R, if Rinterval_dec a b x then 1 else 0) lebesgue_measure
    = finite (b - a) H.

Axiom lebesgue_measure_of_inverval' : ∀ (a b : R) (H : (0 <= b - a)%R),
    ∫ (λ x : R, if Rinterval_dec' a b x then 1 else 0) lebesgue_measure
    = finite (b - a) H.


Require Import rt.util.all.
Require Import rt.analysis.jitter.bertogna_fp_theory.
From mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq fintype bigop div path.

Module ResponseTimeIterationFP.

  Import ResponseTimeAnalysisFP.

  (* In this section, we define the algorithm of Bertogna and Cirinei's
     response-time analysis for FP scheduling. *)
  Section Analysis.

    Context {sporadic_task: eqType}.
    Variable task_cost: sporadic_task -> time.
    Variable task_period: sporadic_task -> time.
    Variable task_deadline: sporadic_task -> time.
    Variable task_jitter: sporadic_task -> time.

    (* During the iterations of the algorithm, we pass around pairs
       of tasks and computed response-time bounds. *)
    Let task_with_response_time := (sporadic_task * time)%type.

    Context {Job: eqType}.
    Variable job_cost: Job -> time.
    Variable job_deadline: Job -> time.
    Variable job_task: Job -> sporadic_task.
    Variable job_jitter: Job -> time.

    (* Consider a platform with num_cpus processors, ... *)
    Variable num_cpus: nat.

    (* ..., and priorities based on an FP policy. *)
    Variable higher_priority: FP_policy sporadic_task.

    (* Next we define the fixed-point iteration for computing
       Bertogna's response-time bound of a task set. *)

    (* First, given a sequence of pairs R_prev = <..., (tsk_hp, R_hp)> of
       response-time bounds for the higher-priority tasks, we define an
       iteration that computes the response-time bound of the current task:

           R_tsk (0) = task_cost tsk
           R_tsk (step + 1) =  f (R step),

       where f is the response-time recurrence, step is the number of iterations,
       and R_tsk (0) is the initial state. *)
    Definition per_task_rta (tsk: sporadic_task)
                            (R_prev: seq task_with_response_time) (step: nat) :=
      iter step
        (fun t => task_cost tsk +
                  div_floor
                    (total_interference_bound_fp task_cost task_period task_jitter tsk
                                                R_prev t higher_priority)
                    num_cpus)
        (task_cost tsk).

    (* To ensure that the iteration converges, we will apply per_task_rta
       a "sufficient" number of times: task_deadline tsk - task_cost tsk + 1.
       This corresponds to the time complexity of the iteration. *)
    Definition max_steps (tsk: sporadic_task) := task_deadline tsk - task_cost tsk + 1.

    (* Next we compute the response-time bounds for the entire task set.
       Since high-priority tasks may not be schedulable, we allow the
       computation to fail.
       Thus, given the response-time bound of previous tasks, we either
       (a) append the computed response-time bound (tsk, R) of the current task
           to the list of pairs, or,
       (b) return None if the response-time analysis failed. *)
    Definition fp_bound_of_task hp_pairs tsk :=
      if hp_pairs is Some rt_bounds then
        let R := per_task_rta tsk rt_bounds (max_steps tsk) in
          if task_jitter tsk + R <= task_deadline tsk then
            Some (rcons rt_bounds (tsk, R))
          else None
      else None.

    (* The response-time analysis for a given task set is defined
       as a left-fold (reduce) based on the function above.
       This either returns a list of task and response-time bounds, or None. *)
    Definition fp_claimed_bounds (ts: taskset_of sporadic_task) :=
      foldl fp_bound_of_task (Some [::]) ts.

    (* The schedulability test simply checks if we got a list of
       response-time bounds (i.e., if the computation did not fail). *)
    Definition fp_schedulable (ts: taskset_of sporadic_task) :=
      fp_claimed_bounds ts != None.

    (* In the following section, we prove several helper lemmas about the
       list of response-time bounds. The results seem trivial, but must be proven
       nonetheless since the list of response-time bounds is computed with
       a specific algorithm and there are no lemmas in the library for that. *)
    Section SimpleLemmas.

      (* First, we show that the first component of the computed list is the set of tasks. *)
      Lemma fp_claimed_bounds_unzip :
        forall ts hp_bounds,
          fp_claimed_bounds ts = Some hp_bounds ->
          unzip1 hp_bounds = ts.
      Proof.
        unfold fp_claimed_bounds in *; intros ts.
        induction ts using last_ind; first by destruct hp_bounds.
        {
          intros hp_bounds SOME.
          destruct (lastP hp_bounds) as [| hp_bounds'].
          {
            rewrite -cats1 foldl_cat /= in SOME.
            unfold fp_bound_of_task at 1 in SOME; simpl in *; desf.
            by destruct l.
          }
          rewrite -cats1 foldl_cat /= in SOME.
          unfold fp_bound_of_task at 1 in SOME; simpl in *; desf.
          move: H0 => /eqP EQSEQ.
          rewrite eqseq_rcons in EQSEQ.
          move: EQSEQ => /andP [/eqP SUBST /eqP EQSEQ]; subst.
          unfold unzip1; rewrite map_rcons; f_equal.
          by apply IHts.
        }
      Qed.

      (* Next, we show that some properties of the analysis are preserved for the
         prefixes of the list: (a) the tasks do not change, (b) R <= deadline,
         (c) R is computed using the response-time equation, ... *)
      Lemma fp_claimed_bounds_rcons :
        forall ts' hp_bounds tsk1 tsk2 R,
          (fp_claimed_bounds (rcons ts' tsk1) = Some (rcons hp_bounds (tsk2, R)) ->
           (fp_claimed_bounds ts' = Some hp_bounds /\
            tsk1 = tsk2 /\
            R = per_task_rta tsk1 hp_bounds (max_steps tsk1) /\
            task_jitter tsk1 + R <= task_deadline tsk1)).
      Proof.
        intros ts hp_bounds tsk tsk' R.
        rewrite -cats1.
        unfold fp_claimed_bounds in *.
        rewrite foldl_cat /=.
        unfold fp_bound_of_task at 1; simpl; desf.
        intros EQ; inversion EQ; move: EQ H0 => _ /eqP EQ.
        rewrite eqseq_rcons in EQ.
        move: EQ => /andP [/eqP EQ /eqP RESP].
        by inversion RESP; repeat split; subst.
      Qed.

      (* ..., which implies that any prefix of the computation is the computation
         of the prefix. *)
      Lemma fp_claimed_bounds_take :
        forall ts hp_bounds i,
          fp_claimed_bounds ts = Some hp_bounds ->
          i <= size hp_bounds ->
          fp_claimed_bounds (take i ts) = Some (take i hp_bounds).
      Proof.
        intros ts hp_bounds i SOME LTi.
        have UNZIP := fp_claimed_bounds_unzip ts hp_bounds SOME.
        rewrite <- UNZIP in *.
        rewrite -[hp_bounds]take_size /unzip1 map_take in SOME.
        fold (unzip1 hp_bounds) in *; clear UNZIP.
        rewrite leq_eqVlt in LTi.
        move: LTi => /orP [/eqP EQ | LTi]; first by subst.
        remember (size hp_bounds) as len; apply eq_leq in Heqlen.
        induction len; first by rewrite ltn0 in LTi.
        {
          assert (TAKElen: fp_claimed_bounds (take len (unzip1 (hp_bounds))) =
                             Some (take len (hp_bounds))).
          {
            assert (exists p, p \in hp_bounds).
            {
              destruct hp_bounds; first by rewrite ltn0 in Heqlen.
              by exists t; rewrite in_cons eq_refl orTb.
            } destruct H as [[tsk R] _].
             rewrite (take_nth tsk) in SOME; last by rewrite size_map.
            rewrite (take_nth (tsk,R)) in SOME; last by done.
            destruct (nth (tsk, R) hp_bounds len) as [tsk_len R_len].
            by apply fp_claimed_bounds_rcons in SOME; des.
          }
          rewrite ltnS leq_eqVlt in LTi.
          move: LTi => /orP [/eqP EQ | LESS]; first by subst.
          apply ltnW in Heqlen.
          by specialize (IHlen Heqlen TAKElen LESS).
        }
      Qed.

      (* If the analysis suceeds, the computed response-time bounds are no larger
         than the deadlines... *)
      Lemma fp_claimed_bounds_le_deadline :
        forall ts' rt_bounds tsk R,
          fp_claimed_bounds ts' = Some rt_bounds ->
          (tsk, R) \in rt_bounds ->
          task_jitter tsk + R <= task_deadline tsk.
      Proof.
        intros ts; induction ts as [| ts' tsk_lst] using last_ind.
        {
          intros rt_bounds tsk R SOME IN.
          by inversion SOME; subst; rewrite in_nil in IN.
        }
        {
          intros rt_bounds tsk_i R SOME IN.
          destruct (lastP rt_bounds) as [|rt_bounds (tsk_lst', R_lst)];
            first by rewrite in_nil in IN.
          rewrite mem_rcons in_cons in IN; move: IN => /orP IN.
          destruct IN as [LAST | FRONT].
          {
            move: LAST => /eqP LAST.
            rewrite -cats1 in SOME.
            unfold fp_claimed_bounds in *.
            rewrite foldl_cat /= in SOME.
            unfold fp_bound_of_task in SOME.
            desf; rename H0 into EQ.
            move: EQ => /eqP EQ.
            rewrite eqseq_rcons in EQ.
            move: EQ => /andP [_ /eqP EQ].
            inversion EQ; subst.
            by apply Heq0.
          }
          {
            apply IHts with (rt_bounds := rt_bounds); last by ins.
            by apply fp_claimed_bounds_rcons in SOME; des.
          }
        }
      Qed.

      (* ... and the computed response-time bounds are no smaller
         than the task costs. *)
      Lemma fp_claimed_bounds_ge_cost :
        forall ts' rt_bounds tsk R,
          fp_claimed_bounds ts' = Some rt_bounds ->
          (tsk, R) \in rt_bounds ->
          R >= task_cost tsk.
      Proof.
        intros ts; induction ts as [| ts' tsk_lst] using last_ind.
        {
          intros rt_bounds tsk R SOME IN.
          by inversion SOME; subst; rewrite in_nil in IN.
        }
        {
          intros rt_bounds tsk_i R SOME IN.
          destruct (lastP rt_bounds) as [|rt_bounds (tsk_lst', R_lst)];
            first by rewrite in_nil in IN.
          rewrite mem_rcons in_cons in IN; move: IN => /orP IN.
          destruct IN as [LAST | FRONT].
          {
            move: LAST => /eqP LAST.
            rewrite -cats1 in SOME.
            unfold fp_claimed_bounds in *.
            rewrite foldl_cat /= in SOME.
            unfold fp_bound_of_task in SOME.
            desf; rename H0 into EQ.
            move: EQ => /eqP EQ.
            rewrite eqseq_rcons in EQ.
            move: EQ => /andP [_ /eqP EQ].
            inversion EQ; subst.
            by destruct (max_steps tsk_lst');
              [by apply leqnn | by apply leq_addr].
          }
          {
            apply IHts with (rt_bounds := rt_bounds); last by ins.
            by apply fp_claimed_bounds_rcons in SOME; des.
          }
        }
      Qed.

      (* Short lemma about unfolding the iteration one step. *)
      Lemma per_task_rta_fold :
        forall tsk rt_bounds,
          task_cost tsk +
           div_floor (total_interference_bound_fp task_cost task_period task_jitter tsk rt_bounds
                     (per_task_rta tsk rt_bounds (max_steps tsk)) higher_priority) num_cpus
          = per_task_rta tsk rt_bounds (max_steps tsk).+1.
      Proof.
          by done.
      Qed.

    End SimpleLemmas.

    (* In this section, we prove that if the task set is sorted by priority,
       the tasks in fp_claimed_bounds are interfering tasks.  *)
    Section HighPriorityTasks.

      (* Consider a list of previous tasks and a task tsk to be analyzed. *)
      Variable ts: taskset_of sporadic_task.

      (* Assume that the task set doesn't contain duplicates and is sorted by priority, ... *)
      Hypothesis H_task_set_is_a_set: uniq ts.
      Hypothesis H_task_set_is_sorted: sorted higher_priority ts.

      (* ...the priority order is strict (<), ...*)
      Hypothesis H_priority_irreflexive: irreflexive higher_priority.
      Hypothesis H_priority_transitive: transitive higher_priority.
      Hypothesis H_priority_antissymetric: antisymmetric higher_priority.

      (* ... and that the response-time analysis succeeds. *)
      Variable hp_bounds: seq task_with_response_time.
      Variable R: time.
      Hypothesis H_analysis_succeeds: fp_claimed_bounds ts = Some hp_bounds.

      (* Let's refer to tasks by index. *)
      Variable elem: sporadic_task.
      Let TASK := nth elem ts.

      (* Then, the tasks in the prefix of fp_claimed_bounds are exactly interfering tasks
         under FP scheduling.*)
      Lemma fp_claimed_bounds_interf:
        forall idx,
          idx < size ts ->
          [seq tsk_hp <- ts | fp_can_interfere_with higher_priority (TASK idx) tsk_hp] = take idx ts.
      Proof.
        rename H_task_set_is_sorted into SORT,
               H_task_set_is_a_set into UNIQ,
               H_priority_antissymetric into ANTI,
               H_priority_irreflexive into IRR.
        induction idx.
        {
          intros LT.
          destruct ts as [| tsk0 ts']; [by done | simpl in SORT].
          unfold fp_can_interfere_with; rewrite /= eq_refl andbF.
          apply eq_trans with (y := filter pred0 ts');
            last by apply filter_pred0.
          apply eq_in_filter; red; intros x INx; rewrite /TASK /=.
          destruct (x != tsk0) eqn:SAME; rewrite ?andbT ?andbF //.
          apply negbTE; apply/negP; unfold not; intro HP.
          move: SAME => /eqP SAME; apply SAME; clear SAME.
          apply ANTI; apply/andP; split; first by done.
          apply order_path_min in SORT; last by done.
          by move: SORT => /allP SORT; apply SORT.
        }
        {
          intros LT.
          generalize LT; intro LT'; apply ltSnm in LT.
          feed IHidx; first by done.
          rewrite -filter_idx_le_takeS //.
          apply eq_in_filter; red; intros x INx.
          unfold fp_can_interfere_with.
          generalize INx; intro SUBST; apply nth_index with (x0 := elem) in SUBST.
          rewrite -SUBST; clear SUBST.
          rewrite index_uniq; [ | by rewrite index_mem | by done].
          apply/idP/idP.
          {
            move => /andP [HP DIFF].
            unfold TASK in *.
            apply sorted_uniq_rel_implies_le_idx in HP; try (by done);
              last by rewrite index_mem.
            by rewrite leq_eqVlt in HP; move: HP => /orP [/eqP SAME | LESS];
                first by rewrite SAME eq_refl in DIFF.
          }
          {
            intros LEidx; apply/andP; split;
              first by apply sorted_lt_idx_implies_rel.
            apply/eqP; red; intro BUG.
            eapply f_equal with (f := fun x => index x ts) in BUG.
            rewrite nth_index in BUG; last by done.
            rewrite BUG in LEidx.
            by rewrite index_uniq // ltnn in LEidx.
          }
        }
      Qed.

    End HighPriorityTasks.

    (* In this section, we show that the fixed-point iteration converges. *)
    Section Convergence.

      (* Consider any set of higher-priority tasks. *)
      Variable ts_hp: taskset_of sporadic_task.

      (* Assume that the response-time analysis succeeds for the higher-priority tasks. *)
      Variable rt_bounds: seq task_with_response_time.
      Hypothesis H_test_succeeds: fp_claimed_bounds ts_hp = Some rt_bounds.

      (* Consider any task tsk to be analyzed, ... *)
      Variable tsk: sporadic_task.

      (* ... and assume all tasks have valid parameters. *)
      Hypothesis H_valid_task_parameters:
        valid_sporadic_taskset task_cost task_period task_deadline (rcons ts_hp tsk).

      (* To simplify, let f denote the fixed-point iteration. *)
      Let f := per_task_rta tsk rt_bounds.

      (* Assume that f (max_steps tsk) is no larger than the deadline. *)
      Hypothesis H_no_larger_than_deadline: f (max_steps tsk) <= task_deadline tsk.

      (* First, we show that f is monotonically increasing. *)
      Lemma bertogna_fp_comp_f_monotonic :
        forall x1 x2, x1 <= x2 -> f x1 <= f x2.
      Proof.
        unfold valid_sporadic_taskset, is_valid_sporadic_task in *.
        rename H_test_succeeds into SOME,
               H_valid_task_parameters into VALID.
        intros x1 x2 LEx; unfold f, per_task_rta.
        apply fun_mon_iter_mon; [by ins | by ins; apply leq_addr |].
        clear LEx x1 x2; intros x1 x2 LEx.
        unfold div_floor, total_interference_bound_fp.
        rewrite big_seq_cond [\sum_(i <- _ | let '(tsk_other, _) := i in
                                 _ && (tsk_other != tsk))_]big_seq_cond.
        rewrite leq_add2l leq_div2r // leq_sum //.

        intros i; destruct (i \in rt_bounds) eqn:HP; last by rewrite andFb.
        destruct i as [i R]; intros _.
        unfold fp_claimed_bounds in SOME.
        have GE_COST := (fp_claimed_bounds_ge_cost ts_hp rt_bounds i R SOME).
        have UNZIP := fp_claimed_bounds_unzip ts_hp rt_bounds SOME.
        assert (IN: i \in ts_hp).
        {
          by rewrite -UNZIP; apply/mapP; exists (i,R).
        }
        unfold interference_bound_generic; simpl.
        rewrite leq_min; apply/andP; split.
        {
          apply leq_trans with (n := W_jitter task_cost task_period task_jitter i R x1);
            first by apply geq_minl.
          exploit (VALID i); first by rewrite mem_rcons in_cons; apply/orP; right.
          by ins; des; apply W_monotonic; try (by ins); apply GE_COST.
        }
        {
          apply leq_trans with (n := x1 - task_cost tsk + 1); first by apply geq_minr.
          by rewrite leq_add2r leq_sub2r //.
        }
      Qed.

      (* If the iteration converged at an earlier step, then it remains stable. *)
      Lemma bertogna_fp_comp_f_converges_early :
        (exists k, k <= max_steps tsk /\ f k = f k.+1) ->
        f (max_steps tsk) = f (max_steps tsk).+1.
      Proof.
        by intros EX; des; apply iter_fix with (k := k).
      Qed.

      (* Else, we derive a contradiction. *)
      Section DerivingContradiction.

        (* Assume instead that the iteration continued to diverge. *)
        Hypothesis H_keeps_diverging:
          forall k,
            k <= max_steps tsk -> f k != f k.+1.

        (* By monotonicity, it follows that the value always increases. *)
        Lemma bertogna_fp_comp_f_increases :
          forall k,
            k <= max_steps tsk ->
            f k < f k.+1.
        Proof.
          intros k LT.
          rewrite ltn_neqAle; apply/andP; split.
            by apply H_keeps_diverging.
            by apply bertogna_fp_comp_f_monotonic, leqnSn.
        Qed.

        (* In the end, the response-time bound must exceed the deadline. Contradiction! *)
        Lemma bertogna_fp_comp_rt_grows_too_much :
          forall k,
            k <= max_steps tsk ->
            f k > k + task_cost tsk - 1.
        Proof.
          have INC := bertogna_fp_comp_f_increases.
          rename H_valid_task_parameters into TASK_PARAMS.
          unfold valid_sporadic_taskset, is_valid_sporadic_task in *; des.
          exploit (TASK_PARAMS tsk);
            [by rewrite mem_rcons in_cons eq_refl orTb | intro PARAMS; des].
          induction k.
          {
            intros _; rewrite add0n -addn1 subh1;
              first by rewrite -addnBA // subnn addn0 /= leqnn.
            by apply PARAMS.
          }
          {
            intros LT.
            specialize (IHk (ltnW LT)).
            apply leq_ltn_trans with (n := f k);
              last by apply INC, ltnW.
            rewrite -addn1 -addnA [1 + _]addnC addnA -addnBA // subnn addn0.
            rewrite -(ltn_add2r 1) in IHk.
            rewrite subh1 in IHk;
              last by apply leq_trans with (n := task_cost tsk);
                [by apply PARAMS | by apply leq_addl].
            by rewrite -addnBA // subnn addn0 addn1 ltnS in IHk.
          }
        Qed.

      End DerivingContradiction.

      (* Using the lemmas above, we prove the convergence of the iteration after max_steps. *)
      Lemma per_task_rta_converges:
        f (max_steps tsk) = f (max_steps tsk).+1.
      Proof.
        have TOOMUCH := bertogna_fp_comp_rt_grows_too_much.
        have INC := bertogna_fp_comp_f_increases.
        rename H_no_larger_than_deadline into LE,
               H_valid_task_parameters into TASK_PARAMS.
        unfold valid_sporadic_taskset, is_valid_sporadic_task in *; des.

        (* Either f converges by the deadline or not. *)
        destruct ([exists k in 'I_(max_steps tsk).+1, f k == f k.+1]) eqn:EX.
        {
          move: EX => /exists_inP EX; destruct EX as [k _ ITERk].
          apply bertogna_fp_comp_f_converges_early.
          by exists k; split; [by rewrite -ltnS; apply ltn_ord | by apply/eqP].
        }

        (* If not, then we reach a contradiction *)
        apply negbT in EX; rewrite negb_exists_in in EX.
        move: EX => /forall_inP EX.
        rewrite leqNgt in LE; move: LE => /negP LE.
        exfalso; apply LE.

        assert (DIFF: forall k : nat, k <= max_steps tsk -> f k != f k.+1).
        {
          intros k LEk; rewrite -ltnS in LEk.
          by exploit (EX (Ordinal LEk)); [by done | intro DIFF; apply DIFF].
        }
        exploit TOOMUCH; [by apply DIFF | by apply leq_addr |].
        exploit (TASK_PARAMS tsk);
          [by rewrite mem_rcons in_cons eq_refl orTb | intro PARAMS; des].
        rewrite subh1; last by apply PARAMS2.
        rewrite -addnBA // subnn addn0 subn1 prednK //.
        intros LT; apply (leq_ltn_trans LT).
        by rewrite /max_steps [_ - _ + 1]addn1; apply INC, leq_addr.
      Qed.

    End Convergence.

    Section MainProof.

      (* Consider a task set ts. *)
      Variable ts: taskset_of sporadic_task.

      (* Assume that higher_eq_priority is a total strict order (<).
         TODO: it doesn't have to be total over the entire domain, but
         only within the task set.
         But to weaken the hypothesis, we need to re-prove some lemmas
         from ssreflect. *)
      Hypothesis H_irreflexive: irreflexive higher_priority.
      Hypothesis H_transitive: transitive higher_priority.
      Hypothesis H_unique_priorities: antisymmetric higher_priority.
      Hypothesis H_total: total higher_priority.

      (* Assume the task set has no duplicates, ... *)
      Hypothesis H_ts_is_a_set: uniq ts.

      (* ...all tasks have valid parameters, ... *)
      Hypothesis H_valid_task_parameters:
        valid_sporadic_taskset task_cost task_period task_deadline ts.

      (* ...constrained deadlines, ...*)
      Hypothesis H_constrained_deadlines:
        forall tsk, tsk \in ts -> task_deadline tsk <= task_period tsk.

      (* ...and tasks are ordered by increasing priorities. *)
      Hypothesis H_sorted_ts: sorted higher_priority ts.

      (* Next, consider any arrival sequence such that...*)
      Context {arr_seq: arrival_sequence Job}.

     (* ...all jobs come from task set ts, ...*)
      Hypothesis H_all_jobs_from_taskset:
        forall (j: JobIn arr_seq), job_task j \in ts.

      (* ...they have valid parameters,...*)
      Hypothesis H_valid_job_parameters:
        forall (j: JobIn arr_seq),
          valid_sporadic_job_with_jitter task_cost task_deadline task_jitter job_cost
                                                   job_deadline job_task job_jitter j.

      (* ... and satisfy the sporadic task model.*)
      Hypothesis H_sporadic_tasks:
        sporadic_task_model task_period arr_seq job_task.

      (* Then, consider any platform with at least one CPU such that...*)
      Variable sched: schedule num_cpus arr_seq.
      Hypothesis H_at_least_one_cpu :
        num_cpus > 0.

      (* ...jobs only execute after jitter and no longer than their execution costs. *)
      Hypothesis H_jobs_must_arrive_to_execute:
        jobs_execute_after_jitter job_jitter sched.
      Hypothesis H_completed_jobs_dont_execute:
        completed_jobs_dont_execute job_cost sched.

      (* Also assume that jobs are sequential (as required by the workload bound). *)
      Hypothesis H_sequential_jobs: sequential_jobs sched.

      (* Assume that the scheduler is work-conserving and enforces the FP policy. *)
      Hypothesis H_work_conserving: work_conserving job_cost job_jitter sched.
      Hypothesis H_enforces_FP_policy:
        enforces_FP_policy job_cost job_task job_jitter sched higher_priority.

      Let no_deadline_missed_by_task (tsk: sporadic_task) :=
        task_misses_no_deadline job_cost job_deadline job_task sched tsk.
      Let no_deadline_missed_by_job :=
        job_misses_no_deadline job_cost job_deadline sched.
      Let response_time_bounded_by (tsk: sporadic_task) :=
        is_response_time_bound_of_task job_cost job_task tsk sched.

      (* In the following theorem, we prove that any response-time bound contained
         in fp_claimed_bounds is safe. The proof follows by induction on the task set:

           Induction hypothesis: all higher-priority tasks have safe response-time bounds.
           Inductive step: We prove that the response-time bound of the current task is safe.

         Note that the inductive step is a direct application of the main Theorem from
         bertogna_fp_theory.v. *)
      Theorem fp_analysis_yields_response_time_bounds :
        forall tsk R,
          (tsk, R) \In fp_claimed_bounds ts ->
          response_time_bounded_by tsk (task_jitter tsk + R).
      Proof.
        rename H_valid_job_parameters into JOBPARAMS, H_valid_task_parameters into TASKPARAMS,
               H_constrained_deadlines into RESTR, H_completed_jobs_dont_execute into COMP,
               H_jobs_must_arrive_to_execute into MUSTARRIVE, H_sorted_ts into SORT,
               H_unique_priorities into UNIQ,
               H_all_jobs_from_taskset into ALLJOBS.
        intros tsk R MATCH.
        assert (SOME: exists hp_bounds, fp_claimed_bounds ts = Some hp_bounds /\
                                        (tsk, R) \in hp_bounds).
        {
          destruct (fp_claimed_bounds ts); last by done.
          by exists l; split.
        } clear MATCH; des; rename SOME0 into IN.

        have UNZIP := fp_claimed_bounds_unzip ts hp_bounds SOME.

        set elem := (tsk,R).
        move: IN => /(nthP elem) [idx LTidx EQ].
        set NTH := fun k => nth elem hp_bounds k.
        set TASK := fun k => (NTH k).1.
        set RESP := fun k => (NTH k).2.
        cut (response_time_bounded_by (TASK idx) (task_jitter (TASK idx) + RESP idx));
          first by unfold TASK, RESP, NTH; rewrite EQ.
        clear EQ.

        assert (PAIR: forall idx, (TASK idx, RESP idx) = NTH idx).
        {
          by intros i; unfold TASK, RESP; destruct (NTH i).
        }

        assert (SUBST: forall i, i < size hp_bounds -> TASK i = nth tsk ts i).
        {
          by intros i LTi; rewrite /TASK /NTH -UNZIP (nth_map elem) //.
        }

        assert (SIZE: size hp_bounds = size ts).
        {
          by rewrite -UNZIP size_map.
        }

        induction idx as [idx IH'] using strong_ind.

        assert (IH: forall tsk_hp R_hp, (tsk_hp, R_hp) \in take idx hp_bounds -> response_time_bounded_by tsk_hp (task_jitter tsk_hp + R_hp)).
        {
          intros tsk_hp R_hp INhp.
          move: INhp => /(nthP elem) [k LTk EQ].
          rewrite size_take LTidx in LTk.
          rewrite nth_take in EQ; last by done.
          cut (response_time_bounded_by (TASK k) (task_jitter (TASK k) + RESP k));
            first by unfold TASK, RESP, NTH; rewrite EQ.
          by apply IH'; try (by done); apply (ltn_trans LTk).
        } clear IH'.

        unfold response_time_bounded_by in *.

        exploit (fp_claimed_bounds_rcons (take idx ts) (take idx hp_bounds) (TASK idx) (TASK idx) (RESP idx)).
        {
          by rewrite PAIR SUBST // -2?take_nth -?SIZE // (fp_claimed_bounds_take _ hp_bounds).
        }
        intros [_ [_ [REC DL]]].

        apply bertogna_cirinei_response_time_bound_fp with
              (task_cost0 := task_cost) (task_period0 := task_period)
              (task_deadline0 := task_deadline) (job_deadline0 := job_deadline) (tsk0 := (TASK idx))
              (job_task0 := job_task) (ts0 := ts) (hp_bounds0 := take idx hp_bounds)
              (job_jitter0 := job_jitter) (higher_eq_priority := higher_priority); try (by done).
        {
          cut (NTH idx \in hp_bounds = true);
            [intros IN | by apply mem_nth].
          by rewrite -UNZIP; apply/mapP; exists (TASK idx, RESP idx); rewrite PAIR.
        }
        {
          unfold unzip1 in *; rewrite map_take UNZIP SUBST //.
          by apply fp_claimed_bounds_interf with (hp_bounds := hp_bounds); rewrite -?SIZE.
        }
        {
          intros hp_tsk R_hp IN; apply mem_take in IN.
          by apply fp_claimed_bounds_ge_cost with (ts' := ts) (rt_bounds := hp_bounds).
        }
        {
          intros hp_tsk R_hp IN; apply mem_take in IN.
          by apply fp_claimed_bounds_le_deadline with (ts' := ts) (rt_bounds := hp_bounds).
        }
        {
          rewrite REC per_task_rta_fold.
          apply per_task_rta_converges with (ts_hp := take idx ts);
            first by apply fp_claimed_bounds_take; try (by apply ltnW).
          {
            rewrite SUBST // -take_nth -?SIZE //.
            by intros i IN; eapply TASKPARAMS, mem_take, IN.
          }
          {
            rewrite -REC.
            by apply leq_trans with (n := task_jitter (TASK idx) + RESP idx); first by apply leq_addl.
          }
        }
      Qed.

      (* Therefore, if the schedulability test suceeds, ...*)
      Hypothesis H_test_succeeds: fp_schedulable ts.

      (*..., no task misses its deadline. *)
      Theorem taskset_schedulable_by_fp_rta :
        forall tsk, tsk \in ts -> no_deadline_missed_by_task tsk.
      Proof.
        have RLIST := (fp_analysis_yields_response_time_bounds).
        have UNZIP := (fp_claimed_bounds_unzip ts).
        have DL := (fp_claimed_bounds_le_deadline ts).
        unfold no_deadline_missed_by_task, task_misses_no_deadline,
               job_misses_no_deadline, completed,
               fp_schedulable,
               valid_sporadic_job_with_jitter, valid_sporadic_job in *.
        rename H_valid_job_parameters into JOBPARAMS.
        move => tsk INtsk j JOBtsk.
        destruct (fp_claimed_bounds ts) as [rt_bounds |]; last by ins.
        feed (UNZIP rt_bounds); first by done.
        assert (EX: exists R, (tsk, R) \in rt_bounds).
        {
          rewrite -UNZIP in INtsk; move: INtsk => /mapP EX.
          by destruct EX as [p]; destruct p as [tsk' R]; simpl in *; subst tsk'; exists R.
        } des.
        exploit (RLIST tsk R); [by ins | by apply JOBtsk | intro COMPLETED].
        exploit (DL rt_bounds tsk R); [by ins | by ins | clear DL; intro DL].

        rewrite eqn_leq; apply/andP; split; first by apply cumulative_service_le_job_cost.
        apply leq_trans with (n := service sched j (job_arrival j + (task_jitter tsk + R))); last first.
        {
          unfold valid_sporadic_taskset, is_valid_sporadic_task in *.
          apply extend_sum; rewrite // leq_add2l.
          by specialize (JOBPARAMS j); des; rewrite JOBPARAMS2 JOBtsk.
        }
        rewrite leq_eqVlt; apply/orP; left; rewrite eq_sym.
        by apply COMPLETED.
      Qed.

      (* For completeness, since all jobs of the arrival sequence
         are spawned by the task set, we also conclude that no job in
         the schedule misses its deadline. *)
      Theorem jobs_schedulable_by_fp_rta :
        forall (j: JobIn arr_seq), no_deadline_missed_by_job j.
      Proof.
        intros j.
        have SCHED := taskset_schedulable_by_fp_rta.
        unfold no_deadline_missed_by_task, task_misses_no_deadline in *.
        apply SCHED with (tsk := job_task j); last by done.
        by apply H_all_jobs_from_taskset.
      Qed.

    End MainProof.

  End Analysis.

End ResponseTimeIterationFP.


Require Import ZArith AltErgo Classical.
Open Scope Z_scope.

Section Einstein.
  Notation is_house h := (h = 1 \/ h = 2 \/ h = 3).

  (* Colors *)
  Variable color : Type.
  Variables Blue White Red : color.
  Notation is_color c := (c = Blue \/ c = White \/ c = Red).
  Hypothesis color_discr : Blue <> White /\ Blue <> Red /\ White <> Red.

  (* Persons *)
  Variable person : Type.
  Variables Professor Engineer Scientist : person.
  Notation is_person p := (p = Professor \/ p = Engineer \/ p = Scientist).
  Hypothesis person_discr : Professor <> Engineer /\ Engineer <> Scientist
    /\ Scientist <> Professor.

  (* OS *)
  Variable system : Type.
  Variables Ubuntu MacOS Suse : system.
  Notation is_system s := (s = Ubuntu \/ s = MacOS \/ s = Suse).
  Hypothesis system_discr : Ubuntu <> MacOS /\ MacOS <> Suse /\ Suse <> Ubuntu.

  (* Owner *)
  Variable owner_of : Z -> person.
  Variable house_of : person -> Z.
  Hypothesis owner_house :
    owner_of (house_of Professor) = Professor /\
    owner_of (house_of Engineer) = Engineer /\
    owner_of (house_of Scientist) = Scientist.
  Hypothesis owner_is_person :
    is_person (owner_of 1) /\
    is_person (owner_of 2) /\
    is_person (owner_of 3).
  Hypothesis house_owner :
    house_of (owner_of 1) = 1 /\
    house_of (owner_of 2) = 2 /\
    house_of (owner_of 3) = 3.
  Hypothesis house_is_house :
    is_house (house_of Professor) /\
    is_house (house_of Engineer) /\
    is_house (house_of Scientist).

  (* Color *)
  Variable color_of : Z -> color.
  Variable color_to : color -> Z.
  Hypothesis color_1 :
    color_of (color_to Blue) = Blue /\
    color_of (color_to White) = White /\
    color_of (color_to Red) = Red.
  Hypothesis color_is_color :
    is_color (color_of 1) /\
    is_color (color_of 2) /\
    is_color (color_of 3).
  Hypothesis color_2 :
    color_to (color_of 1) = 1 /\
    color_to (color_of 2) = 2 /\
    color_to (color_of 3) = 3.
  Hypothesis color_is_house :
    is_house (color_to Blue) /\
    is_house (color_to White) /\
    is_house (color_to Red).

  (* User *)
  Variable user_of : system -> person.
  Variable system_of : person -> system.
  Hypothesis user_system :
    user_of (system_of Professor) = Professor /\
    user_of (system_of Engineer) = Engineer /\
    user_of (system_of Scientist) = Scientist.
  Hypothesis user_is_user :
    is_person (user_of Ubuntu) /\
    is_person (user_of MacOS) /\
    is_person (user_of Suse).
  Hypothesis system_user :
    system_of (user_of Ubuntu) = Ubuntu /\
    system_of (user_of MacOS) = MacOS /\
    system_of (user_of Suse) = Suse.
  Hypothesis system_is_system :
    is_system (system_of Professor) /\
    is_system (system_of Engineer) /\
    is_system (system_of Scientist).

  (* * Hints
     - The Professor lives in a blue house.
     - The Engineer uses Suse.
     - The Scientist lives to the right of the person using Mac/OS.
     - The first house is not white.
     - The person in the red house uses Ubuntu.

     --> Francais n'utilise pas Suse, ni Ubuntu, donc MacOS
     --> Serbe utilise Ubuntu, donc habite dans la maison rouge
     --> L'allemand vit dans la blanche car le français occupe la bleue
     --> Le français est à gauche du serbe, donc 1 ou 2, mais pas 1 car bleu
     --> Le français est 2, le serbe 3 et l'allemand 1.
     *)
  Hypothesis H1 : color_of (house_of Professor) = Blue.
  Hypothesis H2 : system_of Engineer = Suse.
  Hypothesis H3 : house_of Scientist = 1 + house_of (user_of MacOS).
  Hypothesis H4 : color_of 1 <> White.
  Hypothesis H5 : system_of (owner_of (color_to Red)) = Ubuntu.

  (** manually *)
  Lemma M1: system_of Professor <> Suse.
  Proof.
    intro abs.
    rewrite <- H2 in abs.
    apply (proj1 person_discr).
    rewrite <- (proj1 user_system),
      <- (proj1 (proj2 user_system)), abs; reflexivity.
  Qed.
  Lemma M2: system_of Professor <> Ubuntu.
  Proof.
    intro abs.
    rewrite <- H5 in abs.
    assert (L : owner_of (color_to Red) = Professor).
    match goal with | abs: ?L = ?R |- _ =>
      assert (Z : user_of L = user_of R) by (rewrite abs; reflexivity)
    end.
    rewrite (proj1 user_system) in Z.
    assert (is_house (color_to Red)) by
      (destruct (proj2 (proj2 color_is_house)) as [H | [H | H]];
        rewrite H; clear; tauto).
    assert (L' : is_person (owner_of (color_to Red))).
    revert owner_is_person; destruct H as [H | [H | H]];
      rewrite H; clear; tauto.
    clear H; destruct L' as [H | [H | H]]; auto; rewrite H in Z.
    rewrite (proj1 (proj2 user_system)) in Z.
    revert Z; revert person_discr; clear; tauto.
    rewrite (proj2 (proj2 user_system)) in Z.
    revert Z; revert person_discr; clear; intuition congruence.
    clear abs.
    contradiction (proj1 (proj2 color_discr)).
    rewrite <- H1, <- L.
    destruct (proj2 (proj2 color_is_house)) as [H | [H | H]]; rewrite H.
    rewrite (proj1 house_owner), <- H, (proj2 (proj2 color_1)); auto.
    rewrite (proj1 (proj2 house_owner)), <- H, (proj2 (proj2 color_1)); auto.
    rewrite (proj2 (proj2 house_owner)), <- H, (proj2 (proj2 color_1)); auto.
  Qed.
  Lemma M3: system_of Professor = MacOS.
  Proof.
    destruct (proj1 system_is_system) as [Z | [Z | Z]]; auto.
    contradiction (M2 Z).
    contradiction (M1 Z).
  Qed.
  Lemma M4 : system_of Engineer = Suse.
  Proof.
    assumption.
  Qed.
  Lemma M5 : system_of Scientist = Ubuntu.
  Proof.
    destruct (proj2 (proj2 system_is_system)) as [Z | [Z | Z]]; auto.
    generalize M3;
      revert person_discr user_system Z; clear; intuition congruence.
    generalize M4;
      revert person_discr user_system Z; clear; intuition congruence.
  Qed.

  (** auto *)
  Lemma A1:
    system_of Professor = MacOS /\
    system_of Scientist = Ubuntu /\
    system_of Engineer = Suse
    /\
    house_of Professor = 1 /\
    house_of Engineer = 3 /\
    house_of Scientist = 2
    /\
    color_of 1 = Blue /\
    color_of 2 = Red /\
    color_of 3 = White.
  Proof.
    Time vergo.
  Time Qed.
  Size A1.

End Einstein.


Require Import util.
Require Import Coq.omega.Omega.
Require Import Coq.Bool.Bool.
Require Import Coq.Arith.Arith.
Require Import Coq.Arith.EqNat.
Require Import Coq.Lists.List.
Require Import language.
Require Import semantic.
Require Import state.
Require Import assertionV.
Require Import assertionB.
Import ListNotations.

Definition assertionG := state -> Prop.

Definition pairG (assV: assertionV) (assB: assertionB) : assertionG :=
    fun st:state =>
        (assV st) /\ (assB st).

Notation " '[[' p '&' q ']]' " :=
  (pairG p q) (at level 75).

Definition empG : assertionG := [[ empV & empB ]].

Definition s_conjG (p q: assertionG) : assertionG :=
  fun (s: state) => p s /\ q s.
Notation "p '/G\' q" := (s_conjG p q) (at level 75).

Definition s_disjG (p q: assertionG) : assertionG :=
  fun (s: state) => p s \/ q s.
Notation "p '\G/' q" := (s_disjG p q) (at level 78).

Definition s_impG (p q: assertionG) : assertionG :=
  fun (s: state) => p s -> q s.
Notation "p '--G>' q" := (s_impG p q) (at level 85).

Definition strongerThanG (p q: assertionG) : Prop :=
  forall s: state, s_impG p q s.
Notation "p '==G>' q" := (strongerThanG p q) (at level 90).


Require Export SO_syntax.
Require Import List.

(* Returns a list of preds that in l2 but not l1 (relative complement). *)
Fixpoint list_rel_compl (l2 l1 : list predicate) : list predicate :=
  match l2 with
  | nil => nil
  | cons P l2' => if in_predicate_dec P l1 then list_rel_compl l2' l1
                  else cons P (list_rel_compl l2' l1)
  end.

Lemma list_rel_compl_nil : forall l,
  list_rel_compl l nil = l.
Proof.
  induction l. auto. simpl.
  rewrite IHl. destruct (in_predicate_dec a nil); firstorder.
Qed.

Lemma list_rel_compl_contains : forall l2 l1,
  (forall P, In P l2 -> In P l1 ) ->
  list_rel_compl l2 l1 = nil.
Proof.
  induction l2; intros l1 H.
    reflexivity.

    simpl in *.
    destruct (in_predicate_dec a l1) as [H1 | H1].
    apply IHl2. intros P H2. apply H. auto.
    firstorder.
Qed.

Lemma list_rel_compl_refl : forall l,
  list_rel_compl l l = nil.
Proof.
  intros l.
  apply list_rel_compl_contains.
  intros P H.
  assumption.
Qed.

Lemma list_rel_compl_cons_cons : forall l l2 P,
  list_rel_compl  l2 (cons P (cons P l)) = list_rel_compl  l2 (cons P l).
Proof.
  intros l l2. revert l.
  induction l2; intros l P. auto.
  simpl. destruct (in_predicate_dec a (P :: P :: l)) as [H1 | H1];
  destruct (in_predicate_dec a (P :: l)) as [H2 | H2].
  apply IHl2.
  simpl in *. destruct H1. firstorder.
  destruct H; firstorder.
  simpl in H2. destruct H2.  subst. firstorder.
  firstorder. rewrite IHl2. auto.
Qed.

Lemma list_rel_compl_is_in_f : forall l1 l2 P,
  ~ In P l1 ->
  list_rel_compl (cons P l2) l1 = cons P (list_rel_compl l2 l1).
Proof.
  intros l1 l2 P Hin. simpl. destruct (in_predicate_dec P l1); firstorder.
Qed.

Lemma is_in_pred_l_list_rel_compl : forall l2 l1,
  incl (list_rel_compl l2 l1) l2.
Proof.
  induction l2; intros l1; simpl in *. firstorder.
  destruct (in_predicate_dec a l1);[|
  apply incl_cons; firstorder];
  apply incl_tl; auto.
Qed.

Lemma list_rel_compl_app : forall l1 l2 l,
  list_rel_compl (app l1 l2) l =
  app (list_rel_compl l1 l) (list_rel_compl l2 l).
Proof.
  induction l1; intros l2 l. auto.
  simpl. destruct (in_predicate_dec a l). apply IHl1.
  simpl. rewrite IHl1. auto.
Qed.

Lemma want12 : forall l1 l2 P,
  In P l1 -> ~ In P l2 ->  In P (list_rel_compl l1 l2).
Proof.
  induction l1; intros l2 P H1 H2. contradiction.
  simpl in *.  destruct (predicate_dec a P). subst.
  subst. rewrite in_predicate_dec_r; auto.
  simpl. firstorder.  destruct H1. firstorder.
  destruct (in_predicate_dec a l2); [|simpl; right];
    apply IHl1; auto.
Qed.

Lemma want11 : forall l1 l2 l P,
In P (list_rel_compl l1 l) /\ In P l2 -> In P (list_rel_compl l2 l).
Proof.
  induction l1; intros l2 l P [H1 H2]. contradiction.
  simpl in *. destruct (in_predicate_dec a l). apply IHl1; auto.
  simpl in H1. destruct H1. subst. apply want12; auto.
  apply IHl1; auto.
Qed.