Require Export Arith.
Require Export projective_plane_inst.
Require Export Classical.
Require Export Ensembles.

Implicit Arguments  Included.
Implicit Arguments In.

Export AbstractProjectivePlane.
Export AbstractProjectivePlane'.
Module Export uniq := (uniqueness_axioms AbstractProjectivePlane).
Module Export decid := (decidability.decidability AbstractProjectivePlane).

(* flat property *)
Definition pset := Ensemble Point.

Definition pempty : pset := fun (x:Point) => False.
Definition pplane : pset := fun (x:Point) => True.
Definition psingleton (x:Point) : pset := fun (y:Point) => if (eq_point_dec x y) then True else False.
Definition pline (l:Line) : pset :=fun (x:Point) => (if incid_dec x l then True else False).

Definition flat (v:pset) : Prop :=
  forall A B:Point, v A -> v B -> A<>B ->
    forall l:Line, Incid A l -> Incid B l ->
      forall C:Point, Incid C l -> v C.

(* the empty set is a flat *)
Lemma fp_empty : flat (pempty).
unfold flat, pempty.
intros; tauto.
Qed.

(* the whole plane is a flat *)
Lemma fp_plane :  flat (pplane).
unfold flat, pplane.
tauto.
Qed.

(* singleton points are flats *)
Lemma fp_singleton : forall x:Point, flat (psingleton x).
intros X; unfold flat,psingleton.
intros A B.
elim (eq_point_dec X A).
elim (eq_point_dec X B).
intros HXB HXA Ht1 Ht2 HAB l HAl HBl C HCl.
elim (eq_point_dec X C).
tauto.
intros HCX.
subst A.
subst B.
apply HAB; trivial.
tauto.
elim (eq_point_dec X B).
tauto.
tauto.
Qed.

(* lines are flats *)
Lemma fp_line : forall l:Line, flat (pline l).
intros l.
unfold pline, flat.
intros A B.
elim (incid_dec A l).
elim (incid_dec B l).
intros HAl HBl Ht1 Ht2 HAB.
intros l0 HAl0 HBl0.
assert (l=l0).
apply (a1_unique A B l l0 HAB); assumption.
subst l0.
intros C HCl.
elim (incid_dec C l).
trivial.
intros Hf; apply Hf; assumption.
tauto.
tauto.
Qed.

(* characterization *)

(* decomposition requires excluded middle *)
Lemma set01 : forall v:pset, (exists x:Point, v(x)) \/ forall x:Point, ~v(x).
intros v.
elim (classic (exists x:Point, v(x))).
intros; left; intuition.
intros H; right.
intros x Hx.
apply H.
exists x.
assumption.
Qed.

Lemma set12 : forall v:pset, (exists x:Point, v(x)) ->
(exists a :Point, exists b:Point, a<>b/\v(a)/\v(b))\/(exists w:Point, v(w)/\forall p:Point, p<>w -> ~v(p)).
intros v H.
elim H; intros v1 Hv1; clear H.
elim (classic (forall p:Point, p<>v1 -> ~v(p))).
intros Hc.
right.
exists v1.
intuition.
intros Hc.
left.
exists v1.
apply not_all_not_ex.
intros H.
apply Hc.
intros p Hpv1.
generalize (H p).
intuition.
Qed.

(* either zero, one or at least 2 points in v *)

Lemma pset_decompose :
forall v:pset,
(forall x:Point, ~(v x))
\/(exists y:Point, v y /\ forall x:Point, x<>y -> ~v x)
\/(exists z :Point, exists t : Point, z <> t /\ v z /\ v t).
intros v.
elim (set01 v).
intros H.
elim (set12 v H).
intros H'.
right;right.
assumption.
intros H''.
right;left.
assumption.
intros H''.
left.
assumption.
Qed.

(* either v is included in w or there exists p in v and not in w *)
Lemma included_or_not : forall v w: pset,
(forall p:Point, v(p) -> w(p))\/(exists p:Point, v(p)/\~ w(p)).
intros v w.
elim (classic (forall p : Point, v p -> w p)).
intros; left; intuition.
intros;right.
apply not_all_not_ex.
intros H'.
apply H.
intros p Hvp.
elim  (not_and_or (v p) (~ w p) (H' p)).
intros H2; cut False.
intros Hf; elim Hf.
apply H2; assumption.
intros Hnotnot.
elim (classic (w p)).
intuition.
intros Hmagic.
elim (Hnotnot Hmagic).
Qed.

(* "en dim 2, les seuls plats sont : l'ensemble vide, les points (singletons), les droites (d:M | Incid M d) et le plan entier" *)

Lemma characterization : forall v:pset, flat v ->
(forall x:Point, (v x)<->(pempty x))
\/ (exists y:Point, forall x:Point, ((v x) <-> ((psingleton y) x)))
\/   (exists l:Line, forall x:Point, ((v x) <-> ((pline l) x)))
\/ (forall x:Point, (v x) <-> (pplane x)).
intros v Hflat.
unfold flat in Hflat.
elim (pset_decompose v).
(* empty set *)
intros Hempty.
left.
unfold pempty.
intros x; split.
apply Hempty.
intuition.
intros Helim; elim Helim.
(* singleton *)
intros Hsingleton.
right; left.
elim Hsingleton.
intros wit [Hwit1 Hwit2].
unfold psingleton.
exists wit.
intros x; split.
generalize Hwit1 Hwit2; case (eq_point_dec wit x).
intros Hwitx; subst wit.
intuition.
intros Hwitx Hvwit Hforall Hvx0.
assert (x <> wit) by intuition.
exact (Hwit2 x H Hvx0).
generalize Hwit1 Hwit2; case (eq_point_dec wit x).
intros H; subst x.
intuition.
intuition.
clear Helim; intros Hatleast2.
(* at least 2 elements *)
elim Hatleast2; intros A H'; elim H'; clear H'.
intros B.
(* a line *)
intros [ HnAB [HvA HvB]].
elim (a1_exist A B).
intros l [ HAl HBl ].
(* at least 2 points in v : all on the same line or one outside of this line *)
elim (included_or_not v (fun p => Incid p l)).
(* every single point belongs to l *)
intros H.
right;right;left.
exists l.
unfold pline.
intros x; elim (incid_dec x l).
intros Hxl.
split.
intuition.
intros Htrue.
eapply Hflat with (A:=A) (B:=B) (l:=l); assumption.
intros Hnxl.
split.
intros Hvx.
elim (Hnxl (H x Hvx)).
intros Hf; elim Hf.
(* one pt of v does not belong to l *)
intros H.
elim H; intros q [Hvq Hiq].
right;right;right.
intros x; unfold pplane.
split.
intuition.
intros Htrue.
elim (incid_dec x l).
intros Hxl.
eapply Hflat with (A:=A) (B:=B) (l:=l); intuition.
intros Hxl.
elim (a1_exist q x).
intros l' [Hql' Hxl'].
elim (a2_exist l l').
intros I (HI1, HI2).
assert (HvI : v(I)).
apply Hflat with (A:=A) (B:=B) (l:=l); intuition.
elim (eq_point_dec I q).
intros HIq.
subst q.
assert (Hf:False).
apply Hiq; assumption.
elim Hf.
intros HIq.
apply Hflat with (A:=I) (B:=q) (l:=l'); intuition.
Qed.


Require Import rt.util.all.
Require Import rt.analysis.global.basic.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.

    (* As input for each iteration of the algorithm, we consider pairs
       of tasks and computed response-time bounds. *)
    Let task_with_response_time := (sporadic_task * time)%type.

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

    (* 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 tsk
                                                R_prev t)
                    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 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: seq 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: seq 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) /\
            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 ->
          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 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 tsk rt_bounds
                     (per_task_rta tsk rt_bounds (max_steps tsk))) 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 is sorted by unique priorities, ... *)
      Hypothesis H_task_set_is_sorted: sorted higher_priority ts.
      Hypothesis H_task_set_has_unique_priorities:
        FP_is_antisymmetric_over_task_set higher_priority ts.

      (* ...the priority order is transitive, ...*)
      Hypothesis H_priority_transitive: FP_is_transitive 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.

      (* We prove that higher-priority tasks have smaller index. *)
      Lemma fp_claimed_bounds_hp_tasks_have_smaller_index :
        forall hp_idx idx,
          hp_idx < size ts ->
          idx < size ts ->
          hp_idx != idx ->
          higher_priority (TASK hp_idx) (TASK idx) ->
          hp_idx < idx.
      Proof.
        unfold TASK; clear TASK.
        rename ts into ts'; destruct ts' as [ts UNIQ]; simpl in *.
        intros hp_idx idx LThp LT NEQ HP.
        rewrite ltn_neqAle; apply/andP; split; first by done.
        by apply sorted_rel_implies_le_idx with (leT := higher_priority) (s := ts) (x0 := elem).
      Qed.

    End HighPriorityTasks.

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

      (* Consider any list of higher-priority tasks. *)
      Variable ts_hp: list 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.
        rewrite [\sum_(_ <- _ | true) _]big_seq_cond.
        rewrite leq_add2l leq_div2r //.
        apply leq_sum; move => i /andP [IN _].
        destruct i as [i R].
        have GE_COST := fp_claimed_bounds_ge_cost ts_hp rt_bounds i R SOME IN.
        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 task_cost task_period i R x1); first by apply geq_minl.
          exploit (VALID i); [by rewrite mem_rcons in_cons IN' orbT | ins; des].
          by apply W_monotonic; try (by done); 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, it remains as a fixed point. *)
      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 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.

      (* Assume that the task set is totally ordered by unique priorities,
         and that the priority order is transitive. *)
      Hypothesis H_task_set_is_sorted: sorted higher_priority ts.
      Hypothesis H_task_set_has_unique_priorities:
        FP_is_antisymmetric_over_task_set higher_priority ts.
      Hypothesis H_priority_is_total:
        FP_is_total_over_task_set higher_priority ts.
      Hypothesis H_priority_transitive: FP_is_transitive higher_priority.

      (* 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, arrives_in arr_seq j -> job_task j \in ts.

      (* ...jobs have valid parameters,...*)
      Hypothesis H_valid_job_parameters:
        forall j,
          arrives_in arr_seq j ->
          valid_sporadic_job task_cost task_deadline job_cost job_deadline job_task j.

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

      (* Then, consider any schedule of this arrival sequence such that... *)
      Variable sched: schedule Job num_cpus.
      Hypothesis H_at_least_one_cpu: num_cpus > 0.
      Hypothesis H_jobs_come_from_arrival_sequence:
        jobs_come_from_arrival_sequence sched arr_seq.

      (* ...jobs only execute after they arrived and no longer
         than their execution costs. *)
      Hypothesis H_jobs_must_arrive_to_execute:
        jobs_must_arrive_to_execute job_arrival 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 respects the FP policy. *)
      Hypothesis H_work_conserving: work_conserving job_arrival job_cost arr_seq sched.
      Hypothesis H_respects_FP_policy:
        respects_FP_policy job_arrival job_cost job_task arr_seq sched higher_priority.

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

      (* 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: assume 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 R.
      Proof.
        rename H_valid_job_parameters into JOBPARAMS, H_valid_task_parameters into TASKPARAMS.
        unfold valid_sporadic_taskset in *.
        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) (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 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) (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)
              (higher_eq_priority := higher_priority); try (by done).
        {
          cut (NTH idx \in hp_bounds = true); [intros IN | by apply mem_nth].
          by rewrite set_mem -UNZIP; apply/mapP; exists (TASK idx, RESP idx); rewrite PAIR.
        }
        {
          intros hp_tsk IN INTERF.
          exists (RESP (index hp_tsk ts)).
          move: (IN) => INDEX; apply nth_index with (x0 := tsk) in INDEX.
          rewrite -{1}[hp_tsk]INDEX -SUBST; last by rewrite SIZE index_mem.
          assert (UNIQ: uniq hp_bounds).
          {
            apply map_uniq with (f := fst); unfold unzip1 in *; rewrite UNZIP.
            by destruct ts.
          }
          rewrite -filter_idx_lt_take //.
          {
            rewrite PAIR mem_filter; apply/andP; split;
              last by apply mem_nth; rewrite SIZE index_mem.
            {
              rewrite /NTH index_uniq; [| by rewrite SIZE index_mem | by done ].
              {
                move: INTERF => /andP [HP NEQ].
                apply fp_claimed_bounds_hp_tasks_have_smaller_index with
                  (ts := ts) (elem := tsk) (hp_bounds := hp_bounds);
                  try (by done);
                  [by rewrite index_mem | by rewrite -SIZE | | by rewrite INDEX -SUBST].
                apply/eqP; intro BUG; subst idx.
                rewrite SUBST -{1}INDEX in NEQ;
                  first by rewrite eq_refl in NEQ.
                by rewrite SIZE index_mem INDEX.
              }
            }
          }
        }
        {
          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);
            [by apply fp_claimed_bounds_take; try (by apply ltnW) | | by rewrite -REC ].
          rewrite SUBST // -take_nth -?SIZE //.
          by intros i IN; eapply TASKPARAMS, mem_take, IN.
        }
      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 in *.
        rename H_valid_job_parameters into JOBPARAMS.
        move => tsk INtsk j ARRj 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 set_mem -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 EX j ARRj); [by done | 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 + R)); last first.
        {
          unfold valid_sporadic_taskset, is_valid_sporadic_task in *.
          apply extend_sum; rewrite // leq_add2l.
          specialize (JOBPARAMS j ARRj); des; rewrite JOBPARAMS1.
          by rewrite 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, arrives_in arr_seq j -> no_deadline_missed_by_job j.
      Proof.
        intros j ARRj.
        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); try (by done).
        by apply H_all_jobs_from_taskset.
      Qed.

    End MainProof.

  End Analysis.

End ResponseTimeIterationFP.


Require Import Lists.List Lists.ListSet Arith.

Definition D := nat.
Definition D_eq_dec := eq_nat_dec.

Inductive DFA :
  set D -> set D -> D -> set (D*D*D) -> set D -> Type :=
| aDFA : forall (Q:set D) (Sigma:set D) (q0:D) (delta:set (D*D*D)) (F:set D),
    set_In q0 Q ->
    (forall qi a qj,
        set_In (qi,a,qj) delta ->
        (set_In qi Q /\ set_In a Sigma /\ set_In qj Q)) ->
    (forall qi a qj qk,
        set_In (qi,a,qj) delta ->
        set_In (qi,a,qk) delta ->
        qj = qk) ->
    (forall qf,
        set_In qf F ->
        set_In qf Q) ->
    (forall qi s,
        set_In qi Q ->
        set_In s Sigma ->
        { qj | set_In (qi, s, qj) delta }) ->
    DFA Q Sigma q0 delta F.
Hint Constructors DFA.

Definition Binary := set_add D_eq_dec 0 (set_add D_eq_dec 1 (@empty_set D)).

Inductive DFA_step Q Sigma q0 delta F (d:DFA Q Sigma q0 delta F) : D -> D -> D -> Prop :=
| aDFA_step : forall qi a qj,
    set_In (qi, a, qj) delta ->
    DFA_step Q Sigma q0 delta F d qi a qj.
Hint Constructors DFA_step.

Theorem DFA_step_fun:
  forall Q Sigma q0 delta F (d:DFA Q Sigma q0 delta F),
  forall qi a qj qk,
    DFA_step Q Sigma q0 delta F d qi a qj ->
    DFA_step Q Sigma q0 delta F d qi a qk ->
    qj = qk.
Proof.
  intros. rename H into DSj. rename H0 into DSk.
  destruct DSj as [qi a qj INj].
  destruct DSk as [qi a qk INk].
  destruct d as [Q Sigma q0 delta F INq0 INdelta FUNdelta INF delta_dec].
  eapply FUNdelta.
  apply INj.
  apply INk.
Qed.

Theorem DFA_step_dec:
  forall Q Sigma q0 delta F (d:DFA Q Sigma q0 delta F),
  forall qi a,
    set_In qi Q ->
    set_In a Sigma ->
    { qj | DFA_step Q Sigma q0 delta F d qi a qj /\ set_In qj Q }.
Proof.
  intros. rename H into INqi. rename H0 into INa.
  destruct d as [Q Sigma q0 delta F INq0 INdelta FUNdelta INF delta_dec].
  destruct (delta_dec qi a INqi INa) as [qj INqj].
  exists qj.
  split; auto.
  apply INdelta in INqj.
  destruct INqj as [INqi2 INqj]; destruct INqj; auto.
Qed.

Inductive DFA_steps Q Sigma q0 delta F (d:DFA Q Sigma q0 delta F) : D -> list D -> D -> Prop :=
| aDFA_steps_mt : forall qi,
    DFA_steps Q Sigma q0 delta F d qi nil qi
| aDFA_steps_cons : forall qi a qj aa qk,
    DFA_step  Q Sigma q0 delta F d qi a qj ->
    DFA_steps Q Sigma q0 delta F d qj aa qk ->
    DFA_steps Q Sigma q0 delta F d qi (cons a aa) qk.
Hint Constructors DFA_steps.

Theorem DFA_steps_fun:
  forall Q Sigma q0 delta F (d:DFA Q Sigma q0 delta F),
  forall qi w qj qk,
    DFA_steps Q Sigma q0 delta F d qi w qj ->
    DFA_steps Q Sigma q0 delta F d qi w qk ->
    qj = qk.
Proof.
  intros Q Sigma q0 delta F d.
  intros qi w. generalize w qi. clear w qi.
  induction w as [|a aa]; intros qi qj qk DS1 DS2.
  - inversion DS1. subst.
    inversion DS2. subst.
    auto.
  - inversion DS1. subst.
    inversion DS2. subst.
    rewrite (DFA_step_fun Q Sigma q0 delta F d qi a qj0 qj1 H2 H3) in *.
    apply (IHaa qj1); auto.
Qed.

Definition all_In (D:Set) (s:set D) (l:list D) :=
  forall (a:D), In a l -> set_In a s.
Hint Unfold all_In.

Lemma all_In_eq :
  forall D Sigma a aa,
    all_In D Sigma (a :: aa) ->
    set_In a Sigma.
Proof.
  intros D Sigma a aa AI.
  apply AI. apply in_eq.
Qed.
Hint Resolve all_In_eq.

Lemma all_In_cons :
  forall D Sigma a aa,
    all_In D Sigma (a :: aa) ->
    all_In D Sigma aa.
Proof.
  intros D Sigma a aa AI.
  intros x INx.
  apply AI. apply in_cons.
  auto.
Qed.
Hint Resolve all_In_cons.

Theorem DFA_steps_dec:
  forall Q Sigma q0 delta F (d:DFA Q Sigma q0 delta F),
  forall qi aa,
    set_In qi Q ->
    all_In D Sigma aa ->
    { qj | DFA_steps Q Sigma q0 delta F d qi aa qj /\ set_In qj Q }.
Proof.
  intros. generalize aa qi H H0.
  clear aa qi H H0.
  induction aa as [|a aa]; intros qi INqi INaa.
  exists qi. auto.
  destruct (DFA_step_dec Q Sigma q0 delta F d qi a) as [qj [DS INqj]]; auto.
  eauto.
  destruct d as [Q Sigma q0 delta F INq0 INdelta FUNdelta INF delta_dec].
  destruct (IHaa qj INqj) as [qk [DSS INqk]].
  eauto.
  exists qk.
  split; auto.
  econstructor.
  apply DS.
  apply DSS.
Qed.

Inductive DFA_member Q Sigma q0 delta F (d:DFA Q Sigma q0 delta F) : list D -> Prop :=
| aDFA_mem : forall w qa,
    set_In qa F ->
    DFA_steps Q Sigma q0 delta F d q0 w qa ->
    DFA_member Q Sigma q0 delta F d w.
Hint Constructors DFA_member.

Theorem DFA_member_dec:
  forall Q Sigma q0 delta F (d:DFA Q Sigma q0 delta F),
  forall w,
    all_In D Sigma w ->
    { DFA_member Q Sigma q0 delta F d w } + { ~ DFA_member Q Sigma q0 delta F d w }.
Proof.
  intros. rename H into Aw.
  destruct (DFA_steps_dec Q Sigma q0 delta F d q0 w) as [qa [DSS INqj]]; auto.
  destruct d as [Q Sigma q0 delta F INq0 INdelta FUNdelta INF delta_dec].
  auto.
  destruct (set_In_dec D_eq_dec qa F) as [INa | NINa].
  left. econstructor.
  apply INa. auto.
  right. intros DM.
  destruct DM as [w qa2 NINa2 DSS2].
  rewrite (DFA_steps_fun Q Sigma q0 delta F d q0 w qa qa2 DSS DSS2) in *.
  apply NINa. auto.
Qed.


Require Import List SetoidClass.
Require Import Omega.

Require Import Util.

Set Implicit Arguments.

Section NDL.
  Variable A : Type.
  Context `{DA : Decidable A}.

  Record NDL :=
    {
      elems :> list A;
      nodup : NoDup elems
    }.
  Hint Resolve nodup.

  Definition nd_In x (xs: NDL) := In x (elems xs).
  Lemma nd_In_In : forall x xs, nd_In x xs <-> In x xs.
  Proof.
    intros.
    reflexivity.
  Qed.

  Definition same_set (xs ys : NDL) : Prop := forall x,
      nd_In x xs <-> nd_In x ys.

  Global Program Instance NDL_Setoid : Setoid NDL := {| equiv := same_set |}.
  Next Obligation.
    constructor; autounfold; unfold same_set.
    - reflexivity.
    - intros xs ys H.
      intro x.
      now symmetry.
    - intros xs ys zs.
      intros Hxy Hyz.
      intro x.
      now rewrite Hxy.
  Qed.

  Global Instance nd_in_proper :
    Proper (eq ==> equiv  ==> equiv) nd_In.
  Proof.
    simpl.
    intros x x' Heqx xs xs' Heqxs'.
    unfold same_set in *.
    subst.
    unfold nd_In in *.
    rewrite Heqxs'.
    reflexivity.
  Qed.

  Definition nd_included (xs ys : NDL) : Prop :=
    forall x, nd_In x xs -> nd_In x ys.

  Global Instance nd_included_proper :
    Proper (equiv ==> equiv ==> equiv) nd_included.
  Proof.
    simpl.
    intros xs xs' Heqxs ys ys' Heqys.
    unfold nd_included.
    intuition.
    - specialize (H x).
      rewrite Heqxs, Heqys in H.
      auto.
    - specialize (H x).
      rewrite <- Heqxs, <- Heqys in H.
      auto.
  Qed.

  Definition NDL_iff (P : A -> Prop) (xs : NDL) := forall x, nd_In x xs <-> P x.

  Definition count (xs : NDL) : nat := length (elems xs).
  Lemma nd_count_length : forall xs, count xs = length xs.
  Proof.
    reflexivity.
  Qed.

  Global Instance count_proper : Proper (equiv ==> eq) count.
  Proof.
    simpl.
    intros [xs NDxs] [ys NDys].
    unfold count.
    unfold same_set.
    unfold nd_In.
    simpl.
    revert ys NDys.
    induction NDxs.
    - intros.
      destruct ys; auto.
      specialize (H a).
      simpl in H.
      tauto.
    - intros ys Hys HIn.
      simpl in *.
      assert (In x ys) as HInx. {
        rewrite <- HIn.
        auto.
      }
      apply in_split in HInx.
      destruct HInx as (yl & yr & Heqys). subst.
      simpl.
      specialize (IHNDxs (yl ++ yr)).
      rewrite app_length in *.
      simpl.
      rewrite IHNDxs; auto.
      + apply NoDup_remove in Hys.
        tauto.
      + intro y.
        specialize (HIn y).
        split; intro HIny.
        * intuition; subst; try tauto.
          rewrite in_app_iff in *.
          simpl in *.
          intuition.
          now subst.
        * assert (x <> y) as HNe. {
            intro.
            subst.
            now apply NoDup_remove in Hys.
          }
          rewrite in_app_iff in *.
          simpl in *.
          tauto.
  Qed.

  Program Definition nd_add (x : A) (xs : NDL) : NDL :=
    if In_dec x xs
    then xs
    else {| elems := cons x xs |}.
  Next Obligation.
    now constructor.
  Qed.

  Lemma nodup_app :
    forall (xs ys : list A),
      NoDup xs -> NoDup ys -> (forall x, In x xs -> ~In x ys) ->
      NoDup (xs ++ ys).
  Proof.
      intros xs ys Hxs Hys Hnin.
      induction xs.
      - now simpl.
      - simpl.
        constructor.
        + rewrite in_app_iff.
          intros [HInx | HIny].
          * now inversion Hxs.
          * apply (Hnin a); simpl; auto.
        + apply IHxs.
          * now inversion Hxs.
          * intros x HInx.
            apply Hnin.
            simpl. auto.
  Qed.
  Hint Resolve nodup_app.

  Lemma nd_add_in : forall x xs a, nd_In a (nd_add x xs) <-> x = a \/ nd_In a xs.
  Proof.
    intros.
    unfold nd_add.
    destruct In_dec.
    - intuition. subst. auto.
    - simpl.
      reflexivity.
  Qed.

  Global Instance nd_add_proper : Proper (eq ==> equiv ==> equiv) nd_add.
  Proof.
    simpl.
    intros x y Hxy xs ys Heqv.
    subst.
    unfold same_set in *.
    intro z.
    repeat rewrite nd_add_in.
    rewrite Heqv.
    reflexivity.
  Qed.

  Lemma nodup_filter : forall f (xs : list A), NoDup xs -> NoDup (filter f xs).
  Proof.
    intros f xs H.
    induction xs; simpl; auto.
    inversion H. subst. intuition.
    destruct (f a); simpl; auto.
    constructor; auto.
    rewrite filter_In.
    tauto.
  Qed.
  Hint Resolve nodup_filter.

  Lemma filter_length : forall f (xs : list A), length (filter f xs) <= length xs.
  Proof.
    intros.
    induction xs; simpl; auto.
    destruct (f a); simpl; auto.
    omega.
  Qed.

  Program Definition nd_filter (f : A -> bool) (xs : NDL) : NDL :=
    {| elems := filter f xs |}.
  Lemma nd_filter_in : forall f xs x,
      nd_In x (nd_filter f xs) <-> nd_In x xs /\ f x = true.
  Proof.
    intros.
    unfold nd_In, nd_filter.
    simpl.
    apply filter_In.
  Qed.

  Global Instance nd_filter_propre : Proper (eq ==> equiv ==> equiv) nd_filter.
  Proof.
    simpl.
    intros f f' Heqf xs xs' Heqxs.
    subst.
    intro x.
    repeat rewrite nd_filter_in.
    rewrite Heqxs.
    reflexivity.
  Qed.

  Program Definition nd_intersection (xs ys : NDL) : NDL :=
    nd_filter (fun x => if In_dec x ys then true else false) xs.

  Lemma nd_intersection_in : forall xs ys a, nd_In a (nd_intersection xs ys) <->
                                             nd_In a xs /\ nd_In a ys.
  Proof.
    intros.
    cbn.
    rewrite filter_In.
    destruct In_dec; try tauto.
    intuition.
  Qed.

  Global Instance nd_intersection_proper :
    Proper (equiv ==> equiv ==> equiv) nd_intersection.
  Proof.
    simpl.
    intros xs xs' Heqx ys ys' Heqy.
    intro x.
    repeat rewrite nd_intersection_in.
    rewrite Heqx, Heqy.
    reflexivity.
  Qed.

  Lemma nd_intersection_comm :
    forall xs ys, nd_intersection xs ys == nd_intersection ys xs.
  Proof.
    intros.
    intro x.
    repeat rewrite nd_intersection_in.
    tauto.
  Qed.

  Lemma nd_intersection_included :
    forall xs ys, nd_included xs ys ->
                  nd_intersection xs ys == xs.
  Proof.
    intros.
    intro x.
    rewrite nd_intersection_in.
    specialize (H x).
    intuition.
  Qed.

  Program Definition nd_diff (xs ys : NDL) : NDL :=
    nd_filter (fun x => if In_dec x ys then false else true) xs.

  Lemma nd_diff_in : forall xs ys a, nd_In a (nd_diff xs ys) <->
                                             nd_In a xs /\ ~nd_In a ys.
  Proof.
    intros.
    cbn.
    rewrite filter_In.
    destruct In_dec; try tauto.
    intuition.
  Qed.

  Global Instance nd_diff_proper :
    Proper (equiv ==> equiv ==> equiv) nd_diff.
  Proof.
    simpl.
    intros xs xs' Heqx ys ys' Heqy.
    intro x.
    repeat rewrite nd_diff_in.
    rewrite Heqx, Heqy.
    reflexivity.
  Qed.

  Lemma nd_diff_count : forall xs ys,
      count (nd_diff xs ys) = count xs - count (nd_intersection xs ys).
  Proof.
    intros.
    unfold count.
    destruct xs as [xs xs_prf].
    cbn.
    clear xs_prf.
    induction xs as [| x xs]; auto.
    simpl filter.
    destruct In_dec; auto.
    simpl length.
    rewrite IHxs.
    rewrite Nat.sub_succ_l; auto.
    apply filter_length.
  Qed.

  Program Definition nd_union (xs ys : NDL) : NDL :=
    {| elems :=
         nd_diff xs ys ++ ys
    |}.
  Next Obligation.
    apply nodup_app; auto.
    intro x.
    rewrite filter_In.
    destruct In_dec; try tauto.
    now destruct 1.
  Qed.

  Lemma nd_union_in : forall xs ys a, nd_In a (nd_union xs ys) <-> nd_In a xs \/ nd_In a ys.
  Proof.
    intros.
    unfold nd_union.
    simpl.
    unfold nd_In. simpl.
    rewrite in_app_iff, filter_In.
    intuition.
    destruct In_dec; tauto.
  Qed.

  Global Instance nd_union_proper :
    Proper (equiv ==> equiv ==> equiv) nd_union.
  Proof.
    simpl.
    intros xs xs' Heqx ys ys' Heqy.
    intro x.
    repeat rewrite nd_union_in.
    rewrite Heqx, Heqy.
    reflexivity.
  Qed.

  Lemma nd_union_count: forall xs ys,
      count (nd_union xs ys) =
      count xs + count ys - count (nd_intersection xs ys).
  Proof.
    intros.
    replace (count (nd_union xs ys)) with (count (nd_diff xs ys) + count ys).
    - rewrite nd_diff_count.
      rewrite Nat.add_sub_swap; auto.
      apply filter_length.
    - unfold nd_union, count.
      simpl.
      rewrite app_length.
      reflexivity.
  Qed.

  Program Definition empty : NDL := {| elems := nil |}.
  Next Obligation.
    constructor.
  Qed.

  Lemma empty_in : forall x, ~In x empty.
  Proof.
    intros.
    now simpl.
  Qed.

  Lemma count_0_empty : forall xs, count xs = 0 <-> xs == empty.
  Proof.
    intros.
    split; intro H.
    - destruct xs as [xs Hnd].
      unfold count in *.
      destruct xs as [| x xs]; simpl in *; try discriminate.
      unfold same_set, nd_In. simpl.
      tauto.
    - rewrite H.
      reflexivity.
  Qed.

  Fixpoint nd_union_many (xss : list NDL) : NDL :=
    match xss with
    | nil => empty
    | xs :: xss' => nd_union xs (nd_union_many xss')
    end.

  Lemma nd_union_many_in :
    forall xss a, nd_In a (nd_union_many xss) <-> (exists xs, In xs xss /\ nd_In a xs).
  Proof.
    induction xss as [| xs xss].
    - simpl.
      intros.
      intuition.
      now destruct H.
    - intro a.
      simpl.
      rewrite nd_union_in.
      rewrite IHxss.
      split.
      + intros [HIn | [xs' Hxs']].
        * exists xs.
          tauto.
        * exists xs'.
          tauto.
      + intros [xs' Hxs'].
        destruct Hxs' as [[Heq | HIn] HIna].
        * subst.
          auto.
        * eauto.
  Qed.

End NDL.
Arguments empty {A}.


Require Export Adjoint.UnitCounit NaturalTransformation.Equality.
Require Import Common.

Set Implicit Arguments.
Generalizable All Variables.
Set Asymmetric Patterns.
Set Universe Polymorphism.

Local Open Scope morphism_scope.
Local Open Scope natural_transformation_scope.

Section Adjunctions_Equal.
  Context `{Funext}.

  Variable C : PreCategory.
  Variable D : PreCategory.
  Variable F : Functor C D.
  Variable G : Functor D C.

  Local Open Scope equiv_scope.

  Notation Adjunction_sigT :=
    { η : NaturalTransformation 1 (G ∘ F)
    | { ε : NaturalTransformation (F ∘ G) 1
      | { equ1 : forall Y : C, (ε (F Y) ∘ F ₁ (η Y))%morphism = 1%morphism
        | forall X : D, (G ₁ (ε X) ∘ η (G X))%morphism = 1%morphism }}}.

  Lemma Adjunction_sig
  : Adjunction_sigT <~> (F ⊣ G).
  Proof.
    issig (@Build_AdjunctionUnitCounit _ _ F G)
          (@Adjunction_Unit _ _ F G)
          (@Adjunction_Counit _ _ F G)
          (@Adjunction_UnitCounitEquation1 _ _ F G)
          (@Adjunction_UnitCounitEquation2 _ _ F G).
  Defined.

  Global Instance trunc_adjunction : IsHSet (F ⊣ G).
  Proof.
    eapply trunc_equiv'; [ exact Adjunction_sig | ].
    typeclasses eauto.
  Qed.

  Lemma Adjunction_eq' (A A' : F ⊣ G)
  : Adjunction_Unit A = Adjunction_Unit A'
    -> Adjunction_Counit A = Adjunction_Counit A'
    -> A = A'.
  Proof.
    intros.
    destruct A, A'; simpl in *.
    path_induction.
    f_ap;
      exact (center _).
  Qed.

  Lemma Adjunction_eq (A A' : F ⊣ G)
  : ComponentsOf (Adjunction_Unit A) == ComponentsOf (Adjunction_Unit A')
    -> ComponentsOf (Adjunction_Counit A) == ComponentsOf (Adjunction_Counit A')
    -> A = A'.
  Proof.
    intros.
    apply Adjunction_eq';
    apply NaturalTransformation_eq;
    assumption.
  Qed.

  (** In fact, it suffices to show that either the units are equal, or
      the counits are euqal, by the UMP of the (co)unit.  And if we
      are working in a [Category], rather than a [PreCategory], then
      [Adjunction] is, in fact, an hProp, because the (co)unit is
      unique up to unique isomorphism.

      TODO: Formalize this. *)
End Adjunctions_Equal.

Ltac adjunction_eq :=
  repeat match goal with
           | _ => intro
           | _ => apply Adjunction_eq; simpl
         end.


Require Import GeoCoq.Axioms.parallel_postulates.
Require Import GeoCoq.Tarski_dev.Annexes.saccheri.
Require Import GeoCoq.Tarski_dev.Ch12_parallel.

Section similar_rah.

Context `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.

(**
This is an adaptation of the proof of Martin's Theorem 23.6.
It is more complicated because Martin use the properties of the deflect of a triangle,
which are difficult to handle in our formalization.
*)

Lemma similar__rah_aux : forall A B C D E F,
  ~ Col A B C -> CongA A B C D E F -> CongA B C A E F D -> CongA C A B F D E ->
  LeA B C A A B C -> Lt D E A B -> postulate_of_right_saccheri_quadrilaterals.
Proof.
  intros A B C D E F HNCol HCongaB HCongaC HCongaA Hlea Hlt.
  assert_diffs.
  destruct (segment_construction_3 A B D E) as [G []]; auto.
  rename H into HFD.
  destruct (segment_construction_3 A C D F) as [H []]; auto.
  apply (cong2_lt__lt _ _ _ _ A G A B) in Hlt; Cong.
  assert(Bet A G B) by (apply (l6_13_1); Le; apply l6_6; auto).
  assert(B <> G) by (intro; subst; destruct Hlt; Cong).
  assert(HCongaA' : CongA C A B H A G) by (apply out2__conga; apply l6_6; auto).
  destruct(l11_49 F D E H A G) as [_ [HConga1 HConga2]]; Cong.
    apply (conga_trans _ _ _ C A B); CongA.
  apply (conga_trans _ _ _ _ _ _ A G H) in HCongaB; auto.
  apply (conga_trans _ _ _ _ _ _ G H A) in HCongaC; CongA.
  clear dependent D; clear dependent E; clear dependent F.
  rename HCongaA' into HCongaA.

  assert(HNCol1 : ~ Col A G H) by (apply (ncol_conga_ncol A B C); auto).
  assert(HNCol2 : ~ Col B G H) by (intro; apply HNCol1; ColR).
  assert(Par_strict G H B C).
  { apply (par_not_col_strict _ _ _ _ B); Col.
    apply par_symmetry.
    apply (l12_22_b _ _ _ _ A); CongA.
    apply out_one_side; auto.
  }
  assert(HNCol3 : ~ Col G H C) by (apply (par_strict_not_col_4 _ _ B); auto).
  assert(HNCol4 : ~ Col B C G) by (apply (par_strict_not_col_3 _ H); auto).
  assert(HNCol5 : ~ Col H B C) by (apply (par_strict_not_col_2 G); auto).
  assert_diffs.
  assert(Out C H A).
  { apply (col_one_side_out _ B); Col.
    apply invert_one_side.
    apply (one_side_transitivity _ _ _ G).
      apply l12_6; Par.
      apply out_one_side; Col; apply bet_out; Between.
  }
  assert(Bet A H C) by (apply out2__bet; apply l6_6; auto).
  assert(SAMS B G H H C B).
  { apply (sams_chara _ _ _ _ _ _ A); Between.
    apply (l11_30 B C A A B C); auto; apply conga_right_comm; auto.
    apply out2__conga; [apply out_trivial|]; auto.
  }
  assert(CongA A G H G B C).
    apply (l11_10 A G H A B C); try (apply out_trivial); CongA; apply bet_out; Between.
  assert(CongA G H A B C H).
    apply (l11_10 G H A B C A); try (apply out_trivial); CongA.
  assert(SAMS B G H C B G) by (apply (conga2_sams__sams B G H H G A); CongA; SumA).
  assert(SAMS C H G B C H) by (apply (conga2_sams__sams C H G G H A); CongA; SumA).
  destruct(ex_suma B C G C G B) as [I [J [K]]]; auto.
  destruct(ex_suma H C G C G H) as [L [M [N]]]; auto.
  suma.assert_diffs.
  destruct(ex_suma I J K G B C) as [O [P [Q]]]; auto.
  destruct(ex_suma L M N G H C) as [R [S [T]]]; auto.
  destruct(ex_suma I J K L M N) as [U [V [W]]]; auto.
  suma.assert_diffs.
  assert(HInter : SAMS I J K L M N /\ SumA H G B B C H U V W).
  { assert(TS G C B H).
    { apply invert_two_sides, l9_31; Side.
      apply (col_one_side _ A); Col.
      apply invert_one_side; apply out_one_side; try (apply l6_6); Col.
    }
    assert(SAMS H G B B C G).
    { apply (sams_lea2__sams _ _ _ _ _ _ H G B B C H); try (apply lea_refl); SumA.
      apply inangle__lea.
      apply os_ts__inangle; Side.
    }
    destruct(ex_suma B C G H G B) as [X [Y [Z]]]; auto.
    assert(SumA B G C C G H H G B) by SumA.
    assert(SAMS B G C C G H).
    { apply os_ts__sams; trivial.
      apply (col_one_side _ A); Col.
      apply invert_one_side, out_one_side; Col.
    }
    assert(SAMS I J K C G H) by (apply (sams_assoc B C G C G B _ _ _ _ _ _ H G B); SumA).
    assert(SumA I J K C G H X Y Z) by (apply (suma_assoc B C G C G B _ _ _ _ _ _ _ _ _ H G B); SumA).
    assert(SAMS B C G H C G) by (apply sams_right_comm, os_ts__sams; Side).
    assert(SumA B C G H C G H C B) by SumA.
    split.
    - assert(SAMS X Y Z H C G) by (apply (sams_assoc H G B B C G _ _ _ _ _ _ H C B); SumA).
      apply (sams_assoc _ _ _ C G H H C G X Y Z); SumA.
    - assert(SumA X Y Z H C G U V W) by (apply (suma_assoc I J K C G H _ _ _ _ _ _ _ _ _ L M N); SumA).
      apply (suma_assoc _ _ _ B C G H C G _ _ _ X Y Z); SumA.
  }
  destruct HInter.

  elim(saccheri_s_three_hypotheses).
  - intro aah.
    exfalso.
    apply(nlta U V W).
    apply (sams_lta2_suma2__lta I J K L M N _ _ _ H G B B C H); SumA.
    { destruct (t22_14__sams_nbet aah C G B I J K O P Q) as [HIsi HNBet]; Col.
      apply (sams_lea_lta789_suma2__lta123 _ _ _ G B C O P Q _ _ _ G B C A G B); Lea.
        split; Lea; intro; apply HNBet; apply (bet_conga__bet A G B); CongA.
        apply (conga3_suma__suma B G H H G A A G B); CongA; SumA.
    }
    destruct (t22_14__sams_nbet aah C G H L M N R S T) as [HIsi HNBet]; Col.
    apply (sams_lea_lta789_suma2__lta123 _ _ _ G H C R S T _ _ _ G H C A H C); Lea.
      split; Lea; intro; apply HNBet; apply (bet_conga__bet A H C); CongA.
      apply (conga3_suma__suma A H G G H C A H C); CongA; SumA.

  - intro HUn.
    destruct HUn as [|oah]; auto.
    exfalso.
    apply(nlta U V W).
    apply (sams_lta2_suma2__lta H G B B C H _ _ _ I J K L M N); SumA; apply nlea__lta; auto; intro.
    { apply (t22_14__nsams oah C G B I J K); Col.
      apply (sams_lea2__sams _ _ _ _ _ _ H G B G B C); Lea; SumA.
    }
    apply (t22_14__nsams oah C G H L M N); Col.
    apply (sams_lea2__sams _ _ _ _ _ _ B C H G H C); Lea; SumA.
Qed.

Lemma similar__rah : postulate_of_existence_of_similar_triangles -> postulate_of_right_saccheri_quadrilaterals.
Proof.
  intro similar.
  destruct similar as [A [B [C [D [E [F]]]]]].
  spliter.
  assert_diffs.
  elim (lea_total B C A A B C); auto; intro; [elim (le_cases D E A B)|elim (le_cases D F A C)].
  - intro.
    apply (similar__rah_aux A B C D E F); auto.
    split; Cong.

  - intro.
    apply (similar__rah_aux D E F A B C); CongA.
      apply (ncol_conga_ncol A B C); auto.
      apply (l11_30 B C A A B C); auto.
      split; auto.

  - intro.
    apply (similar__rah_aux A C B D F E); Col; CongA.
      apply lea_comm; trivial.
    split; auto; intro; destruct(l11_50_1 A C B D F E); Col; CongA; Cong.

  - intro.
    apply (similar__rah_aux D F E A C B); CongA.
      apply (ncol_conga_ncol A C B); Col; CongA.
      apply (l11_30 A B C B C A); CongA.
      split; auto; intro; destruct(l11_50_1 A C B D F E); Col; CongA; Cong.
Qed.

End similar_rah.


Load LFindLoad.
From lfind Require Import LFind.
Unset Printing Notations.
Set Printing Implicit.

Inductive natural : Type := Succ : natural -> natural |  Zero : natural.

Inductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.

Inductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.

Inductive Pair : Type := mkpair : natural -> natural -> Pair
with Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.

Fixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) : natural
           := match plus_arg0, plus_arg1 with
              | Zero, n => n
              | Succ n, m => Succ (plus n m)
              end.

Fixpoint even (even_arg0 : natural) : bool
           := match even_arg0 with
              | Zero => true
              | Succ n => negb (even n)
              end.

Lemma lem: forall m n, even (plus m n) = negb (even (plus m (Succ n))).
Proof.
induction m.
  - intros. simpl. rewrite <- IHm. reflexivity.
  - intros. simpl. unfold negb. destruct (even n). reflexivity. reflexivity.
Qed.

Lemma lem2: forall n, plus n Zero = n.
Proof.
induction n.
  - simpl. rewrite IHn. reflexivity.
  - reflexivity.
Qed.

(* An alternaturale proof strategy is to prove that plus is commutative as a helper lemma,
and then this theorem can be proven without induction. *)

Theorem theorem0 : forall (x : natural) (y : natural), eq (even (plus x y)) (even (plus y x)).
Proof.
induction x.
- intros.  simpl.  rewrite IHx. lfind.  unfold negb.
Admitted.


(* Sampling an element from a finite cyclic group *)
Require Import Crypto.
Require Export GroupTheory.
Require Import RndNat.
Require Import ProgramLogic.

Local Open Scope group_scope.

Definition RndGrpElem`{FCG : FiniteCyclicGroup}{eqd : EqDec GroupElement} :=
    n <-$ [0 .. order);
    ret (g^n).

Section RndGrpElem.

  Context`{FCG : FiniteCyclicGroup}.
  Hypothesis GroupElement_EqDec : EqDec GroupElement.

  Theorem RndGrpElem_wf : well_formed_comp RndGrpElem.

    unfold RndGrpElem.
    wftac.

  Qed.

  Theorem groupExp_closed : forall k,
    In (g^k) (getSupport RndGrpElem).

    intuition.
    erewrite groupExp_mod.
    simpl.
    eapply in_getUnique.
    eapply in_flatten.
    econstructor.
    split.
    eapply in_map_iff.
    econstructor.
    split.
    eauto.
    eapply filter_In.
    split.
    eapply in_getUnique.
    eapply in_flatten.
    econstructor.
    split.
    eapply in_map_iff.
    econstructor.
    split.
    eapply eq_refl.
    eapply in_getAllBvectors.
    simpl.
    left.
    eapply eq_refl.
    Focus 2.
    rewrite bvToNat_natToBv_inverse.
    simpl.
    left.
    eapply eq_refl.
    eapply lognat_monotonic.
    eapply modNat_lt.
    rewrite bvToNat_natToBv_inverse.
    unfold ltNatBool.
    destruct (lt_dec (modNat k order) order); trivial.
    exfalso.
    eapply n.
    eapply modNat_lt.
    eapply lognat_monotonic.
    eapply modNat_lt.

    apply g_generator.
  Qed.

  Theorem RndGrpElem_uniform : forall x y,
    evalDist RndGrpElem x == evalDist RndGrpElem y.

    intuition.
    unfold RndGrpElem.

    eapply (evalDist_iso
              (fun z => (modNat (z + (modNatAddInverse (groupLog g y) order) + (groupLog g x))) order)
              (fun z => (modNat (z + (groupLog g y) + (modNatAddInverse (groupLog g x) order)) order))); intuition.

    rewrite <- plus_assoc.
    rewrite <- modNat_plus.
    assert ((x0 + groupLog g y + modNatAddInverse (groupLog g x) order +
      (modNatAddInverse (groupLog g y) order + groupLog g x)) =
    ((groupLog g y + modNatAddInverse (groupLog g y) order) +
      (groupLog g x + modNatAddInverse (groupLog g x) order +
      x0)))%nat.
    omega.
    rewrite H0.
    rewrite modNat_plus.
    rewrite modNatAddInverse_correct.
    rewrite plus_0_l.
    rewrite modNat_plus.
    rewrite modNatAddInverse_correct.
    rewrite plus_0_l.
    eapply modNat_eq.
    eapply RndNat_support_lt.
    trivial.

    rewrite <- plus_assoc.
    rewrite <- modNat_plus.
    assert ((x0 + modNatAddInverse (groupLog g y) order + groupLog g x +
      (groupLog g y + modNatAddInverse (groupLog g x) order)) =
    (groupLog g x + modNatAddInverse (groupLog g x) order +
      (groupLog g y + modNatAddInverse (groupLog g y) order + x0)))%nat.
    omega.
    rewrite H0.
    rewrite modNat_plus.
    rewrite modNatAddInverse_correct.
    rewrite plus_0_l.
    rewrite modNat_plus.
    rewrite modNatAddInverse_correct.
    rewrite plus_0_l.
    eapply modNat_eq.
    eapply RndNat_support_lt.
    trivial.

    eapply in_getSupport_RndNat.
    eapply modNat_lt.

    eapply RndNat_uniform.
    eapply modNat_lt.

    eapply RndNat_support_lt.
    trivial.

    subst.
    rewrite <- groupExp_mod.
    simpl.
    destruct (EqDec_dec GroupElement_EqDec (groupExp g x0) y); subst.
    rewrite groupExp_mod.
    rewrite modNat_plus.
    rewrite modNatAddInverse_correct_gen.
    rewrite plus_0_l.
    rewrite <- groupExp_mod.
    rewrite group_cyclic.
    destruct (EqDec_dec GroupElement_EqDec x x).
    intuition.
    congruence.
    apply g_generator.
    apply g_generator.

    symmetry.
    eapply groupLog_correct.
    apply g_generator.
    apply g_generator.

    destruct (EqDec_dec GroupElement_EqDec
         (groupExp g (x0 + modNatAddInverse (groupLog g y) order + groupLog g x)) x); intuition.
    exfalso.
    eapply n.
    rewrite groupExp_plus in e.
    rewrite group_cyclic in e.
    eapply ident_l_unique in e.
    rewrite <- (@groupIdent _ _ _ _ _ _ _ _ FCG g) in e.
    eapply groupExp_eq in e.
    rewrite (@modNat_eq order 0) in e.
    eapply modNatAddInverse_sum_0 in e.
    rewrite groupExp_mod.
    rewrite e.
    rewrite <- groupExp_mod.
    rewrite group_cyclic.
    trivial.
    apply g_generator.
    apply g_generator.
    apply g_generator.

    eapply posnat_pos.

    apply g_generator.
    apply g_generator.
    apply g_generator.
    apply g_generator.
  Qed.

  Theorem RndGrpElem_spec :
    forall x y,
      comp_spec (fun a b => a = x <-> b = y) RndGrpElem RndGrpElem.

    intuition.
    eapply eq_impl_comp_spec; eauto using RndGrpElem_wf.
    eapply RndGrpElem_uniform.

  Qed.

End RndGrpElem.

Notation "'RndG'" := (RndGrpElem)
  (right associativity, at level 75) : comp_scope.


Require Import GeoCoq.Axioms.parallel_postulates.
Require Import GeoCoq.Tarski_dev.Ch12_parallel.

Section playfair_alternate_interior_angles.

Context `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.

Lemma playfair__alternate_interior :  playfair_s_postulate -> alternate_interior_angles_postulate.
Proof.
intros playfair A B C D Hts HPar.
assert(~ Col B A C) by (destruct Hts; auto).
assert(HD' := ex_conga_ts B A C A C B).
destruct HD' as [D' []]; Col.
apply (conga_trans _ _ _ D' C A).
CongA.
assert_diffs.
apply (out_conga D C A D C A); try (apply out_trivial); CongA.
apply (col_one_side_out _ A).
assert (HP := playfair A B C D C D' C).
destruct HP; Col.
apply l12_21_b; CongA; Side.
apply invert_one_side; exists B; split; Side.
Qed.

End playfair_alternate_interior_angles.


(* -*- mode: coq; mode: visual-line -*- *)
(** Representation of cardinals, see Chapter 10 of the HoTT book. *)
Require Import HoTT.Basics HoTT.Types HoTT.HSet HoTT.TruncType.
Require Import UnivalenceImpliesFunext.
Require Import HoTT.Classes.interfaces.abstract_algebra.
Require Import HoTT.Truncations.

(** ** Definitions and operations *)

Definition Card := Trunc 0 hSet.

Definition sum_card (a b : Card) : Card.
Proof.
  strip_truncations.
  refine (tr (BuildhSet (a + b))).
Defined.

Definition prod_card (a b : Card) : Card.
Proof.
  strip_truncations.
  refine (tr (BuildhSet (a * b))).
Defined.

Definition exp_card `{Funext} (b a : Card) : Card.
Proof.
  strip_truncations.
  refine (tr (BuildhSet (b -> a))).
Defined.

Definition leq_card `{Univalence} : Card -> Card -> hProp.
Proof.
  refine (Trunc_rec (fun a => _)).
  refine (Trunc_rec (fun b => _)).
  refine (hexists (fun (i : a -> b) => isinj i)).
Defined.

(** ** Properties *)
Section contents.
  Context `{Univalence}.

  Global Instance plus_card : Plus Card := sum_card.
  Global Instance mult_card : Mult Card := prod_card.
  Global Instance zero_card : Zero Card := tr (BuildhSet Empty).
  Global Instance one_card : One Card := tr (BuildhSet Unit).
  Global Instance le_card : Le Card := leq_card.

  (* Reduce an algebraic equation to an equivalence *)
  Local Ltac reduce :=
    repeat (intros ?); strip_truncations; cbn; f_ap; apply path_hset.

  (* Simplify an equation by unfolding all the definitions apart from
  the actual operations. *)
  Local Ltac simpl_ops :=
    cbv-[plus_card mult_card zero_card one_card].

  (** We only make the instances of upper classes global, since the
  other instances will be project anyway. *)

  (** *** [Card] is a semi-ring *)
  Instance associative_sum : Associative plus_card.
  Proof. reduce. symmetry. apply equiv_sum_assoc. Defined.

  Instance rightid_sum : RightIdentity plus_card zero_card.
  Proof. reduce. apply sum_empty_r. Defined.

  Instance commutative_sum : Commutative plus_card.
  Proof. reduce. apply equiv_sum_symm. Defined.

  Instance associative_prod : Associative mult_card.
  Proof. reduce. apply equiv_prod_assoc. Defined.

  Instance rightid_prod : RightIdentity mult_card one_card.
  Proof. reduce. apply prod_unit_r. Defined.

  Instance commutative_prod : Commutative mult_card.
  Proof. reduce. apply equiv_prod_symm. Defined.

  Instance leftdistributive_card : LeftDistribute mult_card plus_card.
  Proof. reduce. apply sum_distrib_l. Defined.

  Instance leftabsorb_card : LeftAbsorb mult_card zero_card.
  Proof. reduce. apply prod_empty_l. Defined.

  Global Instance issemiring_card : IsSemiRing Card.
  Proof.
    repeat split; try apply _.
    - repeat intro. simpl_ops.
      rewrite (commutativity zero_card _).
      apply rightid_sum.
    - repeat intro. simpl_ops.
      rewrite (commutativity one_card _).
      apply rightid_prod.
  Defined.

  (** *** Properties of exponentiation *)
  Lemma exp_zero_card (a : Card) : exp_card 0 a = 1.
  Proof. simpl_ops. reduce. symmetry. apply equiv_empty_rec. Defined.

  Lemma exp_card_one (a : Card) : exp_card a 1 = 1.
  Proof. simpl_ops. reduce. symmetry. apply equiv_unit_coind. Defined.

  Lemma exp_one_card (a : Card) : exp_card 1 a = a.
  Proof. reduce. symmetry. apply equiv_unit_rec. Defined.

  Lemma exp_card_sum_mult (a b c : Card) :
    exp_card (b + c) a = (exp_card b a) * (exp_card c a).
  Proof. reduce. symmetry. apply equiv_sum_distributive. Defined.

  Lemma exp_mult_card_exp (a b c : Card) :
    exp_card (b * c) a = exp_card c (exp_card b a).
  Proof.
    rewrite (@commutativity _ _ (.*.) _ b c).
    reduce. symmetry. apply equiv_uncurry.
  Defined.

  Lemma exp_card_mult_mult (a b c : Card) :
    exp_card c (a * b) = (exp_card c a) * (exp_card c b).
  Proof. reduce. symmetry. apply equiv_prod_coind. Defined.

  (** *** Properties of ≤ *)
  Instance reflexive_card : Reflexive leq_card.
  Proof.
    intro x. strip_truncations.
    apply tr. exists idmap. refine (fun _ _ => idmap).
  Defined.

  Instance transitive_card : Transitive leq_card.
  Proof.
    intros a b c. strip_truncations.
    intros Hab Hbc. strip_truncations.
    destruct Hab as [iab Hab].
    destruct Hbc as [ibc Hbc].
    apply tr. exists (ibc ∘ iab).
    intros x y Hxy.
    apply Hab. apply Hbc. apply Hxy.
  Defined.

  Global Instance preorder_card : PreOrder le_card.
  Proof. split; apply _. Defined.

End contents.


(* This file is generated by Why3's Coq driver *)
(* Beware! Only edit allowed sections below    *)
Require Import BuiltIn.
Require Reals.R_sqrt.
Require BuiltIn.
Require real.Real.
Require real.Square.

(* Why3 assumption *)
Definition dot (x1:R) (x2:R) (y1:R) (y2:R): R :=
  ((x1 * y1)%R + (x2 * y2)%R)%R.

(* Why3 assumption *)
Definition norm2 (x1:R) (x2:R): R :=
  ((Reals.RIneq.Rsqr x1) + (Reals.RIneq.Rsqr x2))%R.

Axiom norm2_pos : forall (x1:R) (x2:R), (0%R <= (norm2 x1 x2))%R.

Axiom Lagrange : forall (a1:R) (a2:R) (b1:R) (b2:R), (((norm2 a1
  a2) * (norm2 b1 b2))%R = ((Reals.RIneq.Rsqr (dot a1 a2 b1
  b2)) + (Reals.RIneq.Rsqr ((a1 * b2)%R - (a2 * b1)%R)%R))%R).

Axiom CauchySchwarz_aux : forall (x1:R) (x2:R) (y1:R) (y2:R),
  ((Reals.RIneq.Rsqr (dot x1 x2 y1 y2)) <= ((norm2 x1 x2) * (norm2 y1
  y2))%R)%R.

(* Why3 assumption *)
Definition norm (x1:R) (x2:R): R := (Reals.R_sqrt.sqrt (norm2 x1 x2)).

Axiom norm_pos : forall (x1:R) (x2:R), (0%R <= (norm x1 x2))%R.

Axiom sqr_le_sqrt : forall (x:R) (y:R), ((Reals.RIneq.Rsqr x) <= y)%R ->
  (x <= (Reals.R_sqrt.sqrt y))%R.

Require Import Why3.
Ltac ae := why3 "Alt-Ergo,0.99.1," timelimit 3.

(* Why3 goal *)
Theorem CauchySchwarz : forall (x1:R) (x2:R) (y1:R) (y2:R), ((dot x1 x2 y1
  y2) <= ((norm x1 x2) * (norm y1 y2))%R)%R.
(* Why3 intros x1 x2 y1 y2. *)
intros x1 x2 y1 y2.
unfold norm.
rewrite <- R_sqrt.sqrt_mult.
apply sqr_le_sqrt.
ae.
ae.
ae.
Qed.


From CP Require Export operations.
From Coq Require Import Lists.List.
Require Import PeanoNat.
Import ListNotations.

(*
s1 ->+ s2 b(X) | a(X)
s2 b(XY1) ->+ s3 | a(X)
*)

(*
original numbers: a(X)
min: b(Y)
*)

Definition a1 := a @num 3.
Definition a2 := a @num 7.
Definition a3 := a @num 6.
Definition a4 := a @num 8.

Definition cPsys1 := cP_sys (s 1) [a1;a2;a3;a4].

Definition MakeB (t1: g_term) : g_term :=
  match t1 with
  | a @num x1 => b @num x1
  | _ => Atom e
  end.

Definition Rule1 (sys:cPsystem_conf) : cPsystem_conf :=
  match sys with
   | cP_sys (s 1) terms => NewConf (s 2) ((map MakeB terms) ++ terms)
   | _ => sys
  end.

(*
Definition Rule1 (sys:cPsystem_conf) : cPsystem_conf :=
  match sys with
   | cP_sys (s 1) terms => NewConfSorted (s 2) (map MakeB terms) nil sys
   | _ => sys
  end.
*)

Fixpoint BNotGreater (m1: g_multiset) (t1: g_term) : bool :=
  match t1, m1 with
   | b @num x1, a @num x2 :: t2 =>
    if x1 <=? x2 then (BNotGreater t2 t1) else false
   | _, _ :: t3 => BNotGreater t3 t1
   | _, _ => true
  end.

Definition Rule2 (sys:cPsystem_conf) : cPsystem_conf :=
  match sys with
   | cP_sys (s 2) terms => NewConf (s 3) (filter (BNotGreater terms) terms)
   | _ => sys
  end.

(*
Definition Rule2 (sys:cPsystem_conf) : cPsystem_conf :=
  match sys with
   | cP_sys (s 2) terms => NewConfSorted (s 3) (BFilter (BNotGreater terms) terms) terms sys
   | _ => sys
  end.
*)

Definition cPsys2 := Rule1 cPsys1.
Definition cPsys3 := Rule2 cPsys2.
Compute cPsys1.
Compute cPsys2.
Compute cPsys3.

Lemma SystemHaltsAfterTwoSteps: forall (sys: cPsystem_conf),
SystemIsTerminatedRS (Rule2 (Rule1 sys)) [Rule1; Rule2].
Proof. unfold SystemIsTerminatedRS. unfold ApplyARuleset.
destruct sys. destruct s1.
repeat (destruct n; try reflexivity; try discriminate). Qed.

Definition GetB (sys:cPsystem_conf) : nat :=
  match sys with
  | cP_sys (s 3) (b @num b1 :: _) => b1
  | _ => 1024
  end.

Lemma LETrivial1: forall (x1: nat), x1 <=? x1 = true.
Proof. induction x1; try reflexivity. compute. compute in IHx1.
rewrite IHx1. reflexivity. Qed.

Lemma LETrivial2: forall (x1 x2: nat), (S x1 <=? S x2) = (x1 <=? x2).
Proof. simpl. reflexivity. Qed.

Lemma LETrivial3: forall (x1 x2: nat), (x1 <=? x2) = false -> (x2 <=? x1) = true.
Proof. induction x1, x2; try reflexivity. discriminate. simpl. apply IHx1. Qed.

Lemma MinTrivial1: forall (x1 x2: nat), ((x1 <=? x2) = true) -> (x1 = min x1 x2).
Proof. induction x1, x2; try reflexivity; try discriminate. intros. simpl. apply IHx1 in H.
rewrite <- H. reflexivity. Qed.

Lemma SystemCorrect: forall (x1 x2: nat),
GetB (Rule2 (Rule1 (cP_sys (s 1) [a @num x1; a @num x2]))) = min x1 x2.
Proof. intros. destruct (x1 <=? x2) eqn: e1; try simpl.
try rewrite LETrivial1; try rewrite LETrivial2; try rewrite e1.
apply MinTrivial1 in e1. rewrite <- e1. reflexivity.
destruct (x2 <=? x1) eqn: e2; try simpl.
repeat(try rewrite LETrivial1; try rewrite LETrivial2;
try rewrite e1; try rewrite e2). rewrite Nat.min_comm. apply MinTrivial1 in e2.
rewrite <- e2. reflexivity. rewrite LETrivial3 in e1. discriminate e1.
rewrite e2. reflexivity. Qed.

Lemma S3IsATermination: forall (sys: cPsystem_conf), SystemState sys = s 3 ->
SystemIsTerminatedRS sys [Rule1; Rule2].
Proof. unfold SystemIsTerminatedRS. unfold ApplyARuleset.
destruct sys. destruct s1.
repeat (destruct n; try reflexivity; try discriminate). Qed.


From AlphaPearl Require Import Util.PlfTactics.
From Coq Require Import ssreflect.
From mathcomp Require Import ssrnat.

Set Asymmetric Patterns.
Set Bullet Behavior "Strict Subproofs".
Set Implicit Arguments.
Unset Printing Implicit Defensive.

Lemma maxn_either :
  forall m n,
    maxn m n = m \/ maxn m n = n.
Proof.
  intros.
  gen n. induction m; intros.
  - right. rewrite max0n //.
  - destruct n; auto.
    rewrite maxnSS.
    destruct (IHm n) as [IHm'|IHm']; auto.
Qed.

Lemma maxn_max :
  forall m n,
    Nat.max m n = maxn m n.
Proof.
  intros.
  gen n. induction m; intros; destruct n; auto.
  rewrite /= IHm maxnSS //.
Qed.