From Coqprime Require Import PocklingtonRefl.
Local Open Scope positive_scope.

Lemma primo114:
  prime  2224424442783039323682545799822955619261761489->
  prime  157702795295546355891797783928828805431555932027233.
Proof.
intro H.
apply (Pocklington_refl
     (Ell_certif
      157702795295546355891797783928828805431555932027233
      70896
      ((2224424442783039323682545799822955619261761489,1)::nil)
      0
      2058000
      280
      4900)
     ((Proof_certif _ H) :: nil)).
native_cast_no_check (refl_equal true).
Time Qed.


Require Import Nat.
Require Import DBCircuits.
Require Import TypeChecking.
Require Import Denotation.
Require Import Composition.
Require Import VectorDef.
Require Import List.
Require Import QuantumLib.VectorStates.
Require Import QuantumLib.Measurement.
Require Import QuantumLib.Matrix.
Require Import QuantumLib.FTA.
Require Import Grover2QubitBasic.

Local Coercion Nat.b2n : bool >-> nat.

(*has to be declared anew*)
Variable f : nat -> bool.

Local Open Scope nat_scope.

(* since In goes to Prop, and existsb takes a variable f, it is simpler to just write this here *)
Fixpoint is_in (k:nat) (l:list nat) : bool :=
      match l with
      | nil => false
      | a::l => (k =? a) || is_in k l
      end.

Definition fs (l:list nat) : nat -> bool :=
  (fun g => match g with
         | 0 => is_in 0 l
         | 1 => is_in 1 l
         | 2 => is_in 2 l
         | 3 => is_in 3 l
         | _ => false
         end).

(* S gate is derived from the The "controlled phase gate" _R_ m with m = 2, so the rotation = Pi/2*)
Definition _S := _R_ (PI/2).

Local Close Scope nat_scope.

Local Open Scope circ_scope.

Definition better_oracle_0_1 : Box ( Qubit ⊗ Qubit ) ( Qubit ⊗ Qubit ) :=
  box_ (x, y) ⇒
    let_ x ← _S $ x;
    let_ (x,y) ← ctrl _Z $ (x,y);
    let_ x  ← _X $ x;
    (x,y).

Definition better_oracle_0_2 : Box ( Qubit ⊗ Qubit ) ( Qubit ⊗ Qubit ) :=
  box_ (x, y) ⇒
    let_ y ← _S $ y;
    let_ (x,y) ← ctrl _Z $ (x,y);
    let_ y ← _X $ y;
    (x,y).

Definition better_oracle_0_3 : Box ( Qubit ⊗ Qubit ) ( Qubit ⊗ Qubit ) :=
  box_ (x, y) ⇒
    let_ y ← _S $ y;
    let_ (x,y) ← ctrl _X $ (x,y);
    let_ (x,y) ← ctrl _Z $ (x,y);
    (x,y).

Definition better_oracle_1_2 : Box ( Qubit ⊗ Qubit ) ( Qubit ⊗ Qubit ) :=
  box_ (x, y) ⇒
    let_ y ← _S $ y;
    let_ (x,y) ← ctrl _X $ (x,y);
    let_ (x,y) ← ctrl _Z $ (x,y);
    let_ y ← _X $ y;
    (x,y).

Definition better_oracle_1_3 : Box ( Qubit ⊗ Qubit ) ( Qubit ⊗ Qubit ) :=
  box_ (x, y) ⇒
    let_ y ← _S $ y;
    let_ (x,y) ← ctrl _Z $ (x,y);
(x,y).

Definition better_oracle_2_3 : Box ( Qubit ⊗ Qubit ) ( Qubit ⊗ Qubit ) :=
  box_ (x, y) ⇒
    let_ x ← _S $ x;
    let_ (x,y) ← ctrl _Z $ (x,y);
    (x,y).

(* For all possible f-s other than no solution and all solutions *)
Definition small_grover_total (f: nat -> bool) : Box One (Qubit ⊗ Qubit) :=
  box_ () ⇒
    let_ x ← _H $ init0 $ ();
    let_ y ← _H $ init0 $ ();
match f 0%nat, f 1%nat, f 2%nat, f 3%nat with
  |true, false, false, false =>
        (let_ (x,y) ← small_oracle_0 $ (x,y);
        let_ (x,y) ← small_diffusion $ (x,y);
        (x,y))
  |false, true, false, false =>
        (let_ (x,y) ← small_oracle_1 $ (x,y);
        let_ (x,y) ← small_diffusion $ (x,y);
        (x,y))
  |false, false, true, false =>
        (let_ (x,y) ← small_oracle_2 $ (x,y);
        let_ (x,y) ← small_diffusion $ (x,y);
        (x,y))
  |false, false, false, true =>
        (let_ (x,y) ← small_oracle_3 $ (x,y);
        let_ (x,y) ← small_diffusion $ (x,y);
        (x,y))
  |true, true, false, false =>
       (let_ (x,y) ← better_oracle_0_1 $ (x,y);
        let_ (x,y) ← small_diffusion $ (x,y);
        (x,y))
  |true, false, true, false =>
        (let_ (x,y) ← better_oracle_0_2 $ (x,y);
        let_ (x,y) ← small_diffusion $ (x,y);
        (x,y))
  |true, false, false, true =>
       (let_ (x,y) ← better_oracle_0_3 $ (x,y);
        let_ (x,y) ← small_diffusion $ (x,y);
        (x,y))
  |false, true, true, false =>
        (let_ (x,y) ← better_oracle_1_2 $ (x,y);
        let_ (x,y) ← small_diffusion $ (x,y);
        (x,y))
  |false, true, false, true =>
       (let_ (x,y) ← better_oracle_1_3 $ (x,y);
        let_ (x,y) ← small_diffusion $ (x,y);
        (x,y))
  |false, false, true, true =>
       (let_ (x,y) ← better_oracle_2_3 $ (x,y);
        let_ (x,y) ← small_diffusion $ (x,y);
        (x,y))
(* For the below, a convenient truth is exploited; looking for any element but one is equivalent to looking for the one element that will not satify f;
   and since in this case (in an ideal world, of course), we know for sure that after one rotation we should have the answer to that and all other cases,
   if we turn these below cases into the equivalent problem of looking for the one for which f is false, we will therefore know that if we get a value
   that does not return true for f then it will be all other values that return true.
   This ends up both making things much cleaner (very difficult to implement the oracle without an ancilla in this case and then these cases would be rather different to the others),
   and the relevant lemma easier to write and prove.*)
  |true, true, true, false =>
     (let_ (x,y) ← small_oracle_3 $ (x,y);
      let_ (x,y) ← small_diffusion $ (x,y);
      (x,y))
  |true, true, false, true =>
      (let_ (x,y) ← small_oracle_2 $ (x,y);
       let_ (x,y) ← small_diffusion $ (x,y);
       (x,y))
  |false, true, true, true =>
      (let_ (x,y) ← small_oracle_0 $ (x,y);
       let_ (x,y) ← small_diffusion $ (x,y);
       (x,y))
  |true, false, true, true =>
      (let_ (x,y) ← small_oracle_1 $ (x,y);
       let_ (x,y) ← small_diffusion $ (x,y);
       (x,y))
  | _, _, _, _ => (x,y)

     end.

Lemma small_grover_total_WT : Typed_Box (small_grover_total f).
Proof. type_check. Qed.

Definition prob_partial_meas_matrix {m n} (ξ : Density (2^m)) (ρ : Density (2^(n+m))) : R :=
  fst (trace (Mmult ξ ρ)).

Ltac grover_2qubit_denote_to_nonzero_general :=
  intros;
  unfold fs;
  matrix_denote;
  solve_matrix;
  repeat rewrite Cexp_PI2;
  solve_matrix;
  C_field_simplify;
  Msimpl;
  simpl;
  solve_matrix;
  split.

(* well-typedness ensured by Coq Reals *)
Lemma prob_matrix_0 : denote (small_grover_total (fs [0%nat])) (I 1) = list2D_to_matrix ( [ [ C1 ; C0 ; C0 ; C0 ] ; [ C0 ; C0 ; C0 ; C0 ]  ; [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C0 ; C0 ; C0 ] ] ).
Proof.
  all: grover_2qubit_denote_to_nonzero_general.
    Local Close Scope circ_scope.
  apply Csqrt2_neq_0.
  grover_nonzero_begin.
  grover_nonzero_end.
  apply sqrt_sqrt;
  intuition.
Qed.

Lemma ptob_matrix_1 : denote (small_grover_total  (fs [1%nat])) (I 1) = list2D_to_matrix ( [ [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C1 ; C0 ; C0 ]  ; [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C0 ; C0 ; C0 ] ] ) .
Proof.
  grover_2qubit_denote_to_nonzero_general.
  Local Close Scope circ_scope.
  apply Csqrt2_neq_0.
  grover_nonzero_begin.
  grover_nonzero_end.
  apply sqrt_sqrt;
  intuition.
Qed.

Lemma prob_matrix_2: denote (small_grover_total (fs [2%nat])) (I 1) = list2D_to_matrix ( [ [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C0 ; C0 ; C0 ]  ; [ C0 ; C0 ; C1 ; C0 ] ; [ C0 ; C0 ; C0 ; C0 ] ] ).
Proof.
  grover_2qubit_denote_to_nonzero_general.
  Local Close Scope circ_scope.
  apply Csqrt2_neq_0.
  grover_nonzero_begin.
  grover_nonzero_end.
  apply sqrt_sqrt;
  intuition.
Qed.

Lemma prob_matrix_3 : denote (small_grover_total (fs [3%nat])) (I 1) = list2D_to_matrix ( [ [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C0 ; C0 ; C0 ]  ; [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C0 ; C0 ; C1 ] ] ).
Proof.
  grover_2qubit_denote_to_nonzero_general.
  Local Close Scope circ_scope.
  apply Csqrt2_neq_0.
  grover_nonzero_begin.
  grover_nonzero_end.
  apply sqrt_sqrt;
  intuition.
Qed.

(*For the below, we are really only concerned with the Trace, and the values relevant to it (M i j such that i = j).
  The other values are a result of how the gate applications work out, but not relevant to the main lemma below.
  Be reminded that these separate lemmas are not necessary, the relevant part of their meaning is encapsulated in the main lemma,
  however, they make that lemma much quicker itself to prove, and also a lot neater (since it is already quite long). *)
Lemma prob_matrix_1_2 : denote (small_grover_total (fs ([1%nat;2%nat]))) (I 1) = list2D_to_matrix ( [ [ C0; C0 ; C0 ; C0 ] ; [ C0 ; (RtoC 0.5) ; (0.5 * Ci)%C ; C0 ]  ; [ C0 ; (-0.5 * Ci)%C ; (RtoC 0.5) ; C0 ] ; [ C0 ; C0 ; C0 ; C0] ] ).
  matrix_denote.
  solve_matrix.
  all: repeat rewrite Cexp_PI2.
  all: solve_matrix.
  all: C_field_simplify; solve_matrix; replace (R1 + R1)%R with 2%R; replace (R0 + R0)%R with 0%R.
  2,3,4,6,7,8, 10,11,12,14,15,16: intuition.
  Local Close Scope circ_scope.
  all: split; try apply Csqrt2_neq_0;
  grover_nonzero_begin;
  try grover_nonzero_end;
  apply sqrt_sqrt;
  intuition.
Qed.

Lemma prob_matrix_0_3 : denote (small_grover_total (fs ([0%nat;3%nat]))) (I 1) = list2D_to_matrix ( [ [ (RtoC 0.5); C0 ; C0 ;  (0.5 * Ci)%C] ; [ C0 ;C0  ; C0 ; C0 ]  ; [ C0 ; C0 ; C0 ; C0 ] ; [ (-0.5 * Ci)%C ; C0 ; C0 ; (RtoC 0.5)] ] ).
  matrix_denote.
  solve_matrix.
  all: repeat rewrite Cexp_PI2.
  all:  solve_matrix.
  all: C_field_simplify; solve_matrix; replace (R1 + R1)%R with 2%R; replace (R0 + R0)%R with 0%R.
  2,3,4,6,7,8, 10,11,12,14,15,16: intuition.
  Local Close Scope circ_scope.
  all: split; try apply Csqrt2_neq_0;
  grover_nonzero_begin;
  try grover_nonzero_end;
  apply sqrt_sqrt;
  intuition.
Qed.

Lemma prob_matrix_0_1 : denote (small_grover_total (fs ([0%nat;1%nat]))) (I 1) = list2D_to_matrix ( [ [ (RtoC 0.5); (-0.5 * Ci)%C ; C0 ; C0] ; [ (0.5 * Ci)%C ;(RtoC 0.5) ; C0 ; C0 ]  ; [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C0 ; C0 ; C0] ] ) .
  matrix_denote.
  solve_matrix.
  all: repeat rewrite Cexp_PI2.
  all:  solve_matrix.
  all: C_field_simplify; solve_matrix; replace (R1 + R1)%R with 2%R; replace (R0 + R0)%R with 0%R.
  2,3,4,6,7,8, 10,11,12,14,15,16: intuition.
  Local Close Scope circ_scope.
  all: split; try apply Csqrt2_neq_0;
  grover_nonzero_begin;
  try grover_nonzero_end;
  apply sqrt_sqrt;
  intuition.
Qed.

Lemma prob_matrix_0_2 : denote (small_grover_total (fs ([0%nat;2%nat]))) (I 1) = list2D_to_matrix ( [ [ (RtoC 0.5); C0 ; (-0.5 * Ci)%C ; C0] ; [ C0 ; C0 ; C0 ; C0 ]  ; [ (0.5 * Ci)%C; C0 ; (RtoC 0.5) ; C0 ] ; [ C0 ; C0 ; C0 ; C0] ] ).
  matrix_denote.
  solve_matrix.
  all: repeat rewrite Cexp_PI2.
  all:  solve_matrix.
  all: C_field_simplify; solve_matrix; replace (R1 + R1)%R with 2%R; replace (R0 + R0)%R with 0%R.
  2,3,4,6,7,8, 10,11,12,14,15,16: intuition.
  Local Close Scope circ_scope.
  all: split; try apply Csqrt2_neq_0;
  grover_nonzero_begin;
  try grover_nonzero_end;
  apply sqrt_sqrt;
  intuition.
Qed.

Lemma prob_matrix_2_3 : denote (small_grover_total (fs ([2%nat;3%nat]))) (I 1) = list2D_to_matrix ( [ [ C0 ; C0 ; C0 ; C0 ] ;  [ C0 ; C0 ; C0 ; C0 ]  ; [ C0 ; C0 ; (RtoC 0.5);  (-0.5 * Ci)%C ] ; [ C0; C0 ; (0.5 * Ci)%C ; (RtoC 0.5)] ] ).
  matrix_denote.
  solve_matrix.
  all: repeat rewrite Cexp_PI2.
  all:  solve_matrix.
  all: C_field_simplify; solve_matrix; replace (R1 + R1)%R with 2%R; replace (R0 + R0)%R with 0%R.
  2,3,4,6,7,8, 10,11,12,14,15,16: intuition.
  Local Close Scope circ_scope.
  all: split; try apply Csqrt2_neq_0;
  grover_nonzero_begin;
  try grover_nonzero_end;
  apply sqrt_sqrt;
  intuition.
Qed.

Lemma prob_matrix_1_3 : denote (small_grover_total (fs ([1%nat;3%nat]))) (I 1) = list2D_to_matrix ( [ [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; (RtoC 0.5); C0 ; (-0.5 * Ci)%C ] ; [ C0 ; C0 ; C0 ; C0 ]  ; [ C0; (0.5 * Ci)%C; C0 ; (RtoC 0.5)] ] ).
  matrix_denote.
  solve_matrix.
  all: repeat rewrite Cexp_PI2.
  all:  solve_matrix.
  all: C_field_simplify; solve_matrix; replace (R1 + R1)%R with 2%R; replace (R0 + R0)%R with 0%R.
  2,3,4,6,7,8, 10,11,12,14,15,16: intuition.
  Local Close Scope circ_scope.
  all: split; try apply Csqrt2_neq_0;
  grover_nonzero_begin;
  try grover_nonzero_end;
  apply sqrt_sqrt;
  intuition.
Qed.

Lemma prob_matrix_1_2_3: denote (small_grover_total (fs [1%nat; 2%nat; 3%nat])) (I 1) = list2D_to_matrix ( [ [ C1 ; C0 ; C0 ; C0 ] ; [ C0 ; C0 ; C0 ; C0 ]  ; [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C0 ; C0 ; C0 ] ] ).
Proof.
  grover_2qubit_denote_to_nonzero_general.
  Local Close Scope circ_scope.
  apply Csqrt2_neq_0.
  grover_nonzero_begin.
  grover_nonzero_end.
  apply sqrt_sqrt;
  intuition.
Qed.

Lemma prob_matrix_0_2_3 : denote (small_grover_total  (fs [0%nat; 2%nat; 3%nat])) (I 1) = list2D_to_matrix ( [ [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C1 ; C0 ; C0 ]  ; [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C0 ; C0 ; C0 ] ] ).
Proof.
  grover_2qubit_denote_to_nonzero_general.
  Local Close Scope circ_scope.
  apply Csqrt2_neq_0.
  grover_nonzero_begin.
  grover_nonzero_end.
  apply sqrt_sqrt;
  intuition.
Qed.

Lemma prob_matrix_0_1_3: denote (small_grover_total (fs [0%nat; 1%nat; 3%nat])) (I 1) = list2D_to_matrix ( [ [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C0 ; C0 ; C0 ]  ; [ C0 ; C0 ; C1 ; C0 ] ; [ C0 ; C0 ; C0 ; C0 ] ] ).
Proof.
  grover_2qubit_denote_to_nonzero_general.
  Local Close Scope circ_scope.
  apply Csqrt2_neq_0.
  grover_nonzero_begin.
  grover_nonzero_end.
  apply sqrt_sqrt;
  intuition.
Qed.

Lemma prob_matrix_0_1_2 : denote (small_grover_total (fs [0%nat; 1%nat; 2%nat])) (I 1) =  list2D_to_matrix ( [ [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C0 ; C0 ; C0 ]  ; [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C0 ; C0 ; C1 ] ] ).
Proof.
  grover_2qubit_denote_to_nonzero_general.
  Local Close Scope circ_scope.
  apply Csqrt2_neq_0.
  grover_nonzero_begin.
  grover_nonzero_end.
  apply sqrt_sqrt;
  intuition.
Qed.

Local Close Scope nat_scope.

(*counts the number of solutions for a given f, taken from SQIR*)
Fixpoint count (f : nat -> bool) a b : nat :=
  match b with
  | O => O
  | S b' => (f (a + b') + count f a b')%nat
  end.

Definition k := count f 0 (4).
Definition θ := asin (√ (INR k / 4)).

(*so as not to have to construct the relevant matrices to use as observablees from outer products of basis-vectors; dpericated, because an explicit definition is easier do deal with in the proof *)
Definition basis_matrix (n:nat) (k:nat) : Matrix n n :=
  (fun i j => if (i =? k)%nat && (j =? k)%nat then C1 else C0).

(*explicitness, although it looks worse, is a lot easier to deal with below due to the non-dimension-preserving nature of the basid definition here below*)
Definition basis_matrix_4 (k:nat) : Matrix 4 4 :=
  match k with
  | 0%nat => list2D_to_matrix ( [ [ C1 ; C0 ; C0 ; C0 ] ; [ C0 ; C0 ; C0 ; C0 ]  ; [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C0 ; C0 ; C0 ] ] )
  | 1%nat => list2D_to_matrix ( [ [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C1 ; C0 ; C0 ]  ; [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C0 ; C0 ; C0 ] ] )
  | 2%nat => list2D_to_matrix ( [ [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C0 ; C0 ; C0 ]  ; [ C0 ; C0 ; C1 ; C0 ] ; [ C0 ; C0 ; C0 ; C0 ] ] )
  | 3%nat => list2D_to_matrix ( [ [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C0 ; C0 ; C0 ]  ; [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C0 ; C0 ; C1 ] ] )
  | _ => basis_matrix 4 k (* let the absract definition deal with it; will be a Zero 4 *)
  end.

Require Import sin_asin_rules.

Ltac three_true_solution_prep :=
  unfold Rsum, sum_f_R0;
  unfold count;
  simpl;
  replace (1+1+1+1)%R with 4%R by ring;
  replace (1+1+1)%R with 3%R by ring;
  rewrite sqrt_div;
  intuition;
  rewrite asin34;
  replace (3 * (PI / 3))%R with PI%R.

Local Close Scope circ_scope.
Local Open Scope R_scope.
Ltac three_true_solution_trig :=
  unfold Rdiv;
  rewrite Rmult_comm;
  rewrite Rmult_assoc;
 (* unfortunately, separate goals have to be created with replace, and then proven, because coq would not recognize a rewrite
    (either locally or in Ltac) nor would it allow replace with by, both above and below *)
  replace (/ 3 * 3) with (3 * / 3);
  replace (3 * / 3) with 1.

Local Close Scope R_scope.

Ltac three_true_solution_end :=
  rewrite Rmult_1_r;
  rewrite sin_PI;
  unfold prob_partial_meas_matrix;
  solve_matrix;
  ring.

Local Open Scope nat_scope.
Definition f_list : list (nat->bool) :=
  [ (fs [0]) ; (fs [1]) ; (fs [2]) ; (fs [3]) ; (fs [0;1]) ; (fs [0;2]) ; (fs [0;3]) ; (fs [1;2]) ; (fs [1;3]) ; (fs [2;3]); (fs [0;1;2]) ; (fs [0;1;3]) ;(fs [0;2;3]); (fs [1;2;3]) ].
Local Close Scope nat_scope.

(* There is no way of proving this triviality without significant hassle due to how reals are set up in coq; so I will have it here as an axiom; the truth of it is obvious *)
Axiom two_times_point_five_eq_1 :  (0.5 + 0.5)%R = 1%R.

Lemma small_grover_general_correct_prob_simpl : forall g, In g f_list ->
    Rsum 4 (fun z => if g z
              then (@prob_partial_meas_matrix 2 0
    (basis_matrix_4 z)
    (denote (small_grover_total g) (I 1))) else 0)
               = if ((count g 0 4) <? 3)%nat then 1 else 0.
Proof.
  intros.
  unfold count.
  induction H. symmetry in H. rewrite H.
  2:  destruct H. 2: symmetry in H. 2: rewrite H.
  3:  destruct H. 3: symmetry in H. 3: rewrite H.
  4:  destruct H. 4: symmetry in H. 4: rewrite H.
  5:  destruct H. 5: symmetry in H. 5: rewrite H.
  6:  destruct H. 6: symmetry in H. 6: rewrite H.
  7:  destruct H. 7: symmetry in H. 7: rewrite H.
  8:  destruct H. 8: symmetry in H. 8: rewrite H.
  9:  destruct H. 9: symmetry in H. 9: rewrite H.
  10:  destruct H. 10: symmetry in H. 10: rewrite H.
  11:  destruct H. 11: symmetry in H. 11: rewrite H.
  12:  destruct H. 12: symmetry in H. 12: rewrite H.
  13:  destruct H. 13: symmetry in H. 13: rewrite H.
  14:  destruct H. 14: symmetry in H. 14: rewrite H.
  15:  destruct H.
    (* unfortunately, rewrite does not find the relevant section in the subgoal to do the below automatically, even though that is why the lemmas are reversed in this file *)
  1: replace ((⟦ small_grover_total (fs [0%nat]) ⟧) (I 1)) with (list2D_to_matrix ( [ [ C1 ; C0 ; C0 ; C0 ] ; [ C0 ; C0; C0 ; C0 ]  ; [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C0 ; C0 ; C0 ] ])).
  2: symmetry; apply prob_matrix_0.
  2: replace ((⟦ small_grover_total (fs [1%nat]) ⟧) (I 1)) with (list2D_to_matrix ( [ [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C1; C0 ; C0 ]  ; [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C0 ; C0 ; C0 ] ])).
  3: symmetry; apply ptob_matrix_1.
  3: replace ((⟦ small_grover_total (fs [2%nat]) ⟧) (I 1)) with (list2D_to_matrix ( [ [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C0; C0 ; C0 ]  ; [ C0 ; C0 ; C1 ; C0 ] ; [ C0 ; C0 ; C0 ; C0 ] ])).
  4: symmetry; apply prob_matrix_2.
  4: replace ((⟦ small_grover_total (fs [3%nat]) ⟧) (I 1)) with (list2D_to_matrix ( [ [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C0 ; C0 ; C0 ]  ; [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C0 ; C0 ; C1 ] ])).
  5: symmetry; apply prob_matrix_3.
  1,2,3,4 :  unfold Rsum, sum_f_R0; simpl; unfold prob_partial_meas_matrix; solve_matrix.
  1,2,3,4: unfold Rminus;  rewrite Rmult_1_l; repeat rewrite Rplus_0_r; repeat rewrite Rplus_0_l; repeat rewrite Rmult_0_l; repeat rewrite Rmult_0_r.
  1,2,3,4: replace (- 0)%R with 0%R. 2,4,6,8: intuition.
  1,2,3,4: repeat rewrite Rplus_0_r; repeat rewrite Rplus_0_l.
  5: replace ((⟦ small_grover_total (fs [0%nat; 1%nat]) ⟧) (I 1)) with (list2D_to_matrix ( [ [ (RtoC 0.5); ((-0.5)%R * Ci)%C ; C0 ; C0] ; [(0.5%R * Ci)%C ;(RtoC 0.5) ; C0 ; C0 ]  ; [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C0 ; C0 ; C0] ] ) ).
  6: symmetry. 6: apply prob_matrix_0_1.
  6: replace ((⟦ small_grover_total (fs [0%nat; 2%nat]) ⟧) (I 1)) with (list2D_to_matrix ( [ [ (RtoC 0.5); C0 ; ((-0.5)%R * Ci)%C ; C0] ; [ C0 ; C0 ; C0 ; C0 ]  ; [ (0.5%R * Ci)%C ; C0 ; (RtoC 0.5) ; C0 ] ; [ C0 ; C0 ; C0 ; C0] ] ) ).
  7: symmetry; apply prob_matrix_0_2.
  7: replace ((⟦ small_grover_total (fs [0%nat; 3%nat]) ⟧) (I 1)) with (list2D_to_matrix ( [ [ (RtoC 0.5); C0 ; C0 ; (0.5%R * Ci)%C] ; [ C0 ;C0  ; C0 ; C0 ]  ; [ C0 ; C0 ; C0 ; C0 ] ; [ ((-0.5)%R * Ci)%C ; C0 ; C0 ; (RtoC 0.5)] ] ) ).
  8: symmetry; apply prob_matrix_0_3.
  8: replace ((⟦ small_grover_total (fs [1%nat; 2%nat]) ⟧) (I 1)) with (list2D_to_matrix ( [ [ C0; C0 ; C0 ; C0 ] ; [ C0 ; (RtoC 0.5) ; (0.5%R * Ci)%C ; C0 ]  ; [ C0 ; ((-0.5)%R * Ci)%C ; (RtoC 0.5) ; C0 ] ; [ C0 ; C0 ; C0 ; C0] ] ) ).
  9: symmetry; apply prob_matrix_1_2.
  9: replace ((⟦ small_grover_total (fs [1%nat; 3%nat]) ⟧) (I 1)) with (list2D_to_matrix ( [ [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; (RtoC 0.5); C0 ; ((-0.5)%R * Ci)%C] ; [ C0 ; C0 ; C0 ; C0 ]  ; [ C0; (0.5%R * Ci)%C ; C0 ; (RtoC 0.5)] ] ) ).
  10: symmetry; apply prob_matrix_1_3.
  10: replace ((⟦ small_grover_total (fs [2%nat; 3%nat]) ⟧) (I 1)) with (list2D_to_matrix ( [ [ C0 ; C0 ; C0 ; C0 ] ;  [ C0 ; C0 ; C0 ; C0 ]  ; [ C0 ; C0 ; (RtoC 0.5);  ((-0.5)%R * Ci)%C ] ; [ C0; C0 ; (0.5%R * Ci)%C ; (RtoC 0.5)] ] ) ).
  11: symmetry; apply prob_matrix_2_3.
  5,6,7,8,9,10 :  unfold Rsum, sum_f_R0; simpl; unfold prob_partial_meas_matrix; solve_matrix.
  5,6,7,8,9,10: unfold Rminus;  rewrite Rmult_1_l; repeat rewrite Rplus_0_r; repeat rewrite Rplus_0_l; repeat rewrite Rmult_0_l; repeat rewrite Rmult_0_r.
  5,6,7,8,9,10: replace (- 0)%R with 0%R. 6,8,10,12,14,16: intuition.
  5,6,7,8,9,10: repeat rewrite Rplus_0_r; repeat rewrite Rplus_0_l.
  11: replace ((⟦ small_grover_total (fs [0%nat; 1%nat; 2%nat]) ⟧) (I 1)) with (list2D_to_matrix ( [ [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C0; C0 ; C0 ]  ; [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C0 ; C0 ; C1 ] ])).
  12: symmetry; apply prob_matrix_0_1_2.
  12: replace ((⟦ small_grover_total (fs [0%nat; 1%nat; 3%nat]) ⟧) (I 1)) with (list2D_to_matrix ( [ [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C0; C0 ; C0 ]  ; [ C0 ; C0 ; C1 ; C0 ] ; [ C0 ; C0 ; C0 ; C0 ] ])).
  13: symmetry; apply prob_matrix_0_1_3.
  13: replace ((⟦ small_grover_total (fs [0%nat; 2%nat; 3%nat]) ⟧) (I 1)) with (list2D_to_matrix ( [ [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C1; C0 ; C0 ]  ; [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C0 ; C0 ; C0 ] ])).
  14: symmetry; apply prob_matrix_0_2_3.
  14: replace ((⟦ small_grover_total (fs [1%nat; 2%nat; 3%nat]) ⟧) (I 1)) with (list2D_to_matrix ( [ [ C1 ; C0 ; C0 ; C0 ] ; [ C0 ; C0 ; C0 ; C0 ]  ; [ C0 ; C0 ; C0 ; C0 ] ; [ C0 ; C0 ; C0 ; C0 ] ])).
  15: symmetry; apply prob_matrix_1_2_3.
  Local Close Scope circ_scope.
  Local Open Scope R_scope.
  11,12,13,14 :  unfold Rsum, sum_f_R0; simpl; unfold prob_partial_meas_matrix; solve_matrix.
  11,12,13,14: unfold Rminus;  rewrite Rmult_1_l; repeat rewrite Rplus_0_r; repeat rewrite Rplus_0_l; repeat rewrite Rmult_0_l; repeat rewrite Rmult_0_r.
  11,12,13,14: replace (- 0)%R with 0%R. 6,8,10,12,14,16: intuition.
  11,12,13,14: repeat rewrite Rplus_0_r; repeat rewrite Rplus_0_l.
  all: intuition.
  all: apply two_times_point_five_eq_1.
Qed.


(*************************************************************)
(*   Copyright Dominique Larchey-Wendling [*]                 *)
(*                                                            *)
(*                             [*] Affiliation LORIA -- CNRS  *)
(*************************************************************)
(*      This file is distributed under the terms of the       *)
(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)
(*************************************************************)

Require Import List Permutation.

From Undecidability.ILL
  Require Import IMSELL.

From Undecidability.Shared.Libs.DLW
  Require Import utils pos vec.

Set Implicit Arguments.

(* * Intuionistic Multiplicative Linear Logic with several exponentials and modabilities *)

Local Infix "~p" := (@Permutation _) (at level 70).
Local Notation "X ⊆ Y" := (forall a, X a -> Y a : Prop) (at level 70).
Local Infix "∊" := In (at level 70).

Local Reserved Notation "'⟦' A '⟧'" (at level 1, format "⟦ A ⟧").

Section IMSELL.

  Variable bang : Type.

  Notation "£ A" := (@imsell_var _ _ A) (at level 1).
  Notation "‼ l" := (@imsell_lban nat bang l).

  Fact imsell_lban_perm Σ Γ : Σ ~p Γ -> ‼Σ ~p ‼Γ.
  Proof. apply Permutation_map. Qed.

  Variable (bang_le : bang -> bang -> Prop) (bang_U : bang -> Prop).

  Infix "≤" := bang_le (at level 70).
  Notation U := bang_U.

  Notation "u ≼ l" := (forall '(v,A), (v,A) ∊ l -> u ≤ v) (at level 70).
  Notation "Γ ⊢ A" := (@S_imsell nat _ bang_le bang_U Γ A) (at level 70).

  Fact S_imsell_weak Γ Δ B : Forall (fun '(u,_) => U u) Γ -> Δ ⊢ B -> ‼Γ++Δ ⊢ B.
  Proof.
    intros H1 H2; revert H1.
    induction 1 as [ | (u,A) Γ H1 IH1 ]; simpl; auto.
    apply in_imsell_weak; auto.
  Qed.

  Fact S_imsell_gen_weak u Γ Δ B : U u -> Δ ⊢ B -> map (fun A => ![u]A) Γ++Δ ⊢ B.
  Proof.
    intros H1 H2.
    replace (map (fun A => ![u]A) Γ) with (‼ (map (fun A => (u,A)) Γ)).
    + apply S_imsell_weak; auto.
      apply Forall_forall.
      intros ?; rewrite in_map_iff.
      intros (? & <- & ?); auto.
    + unfold imsell_lban; rewrite map_map; auto.
  Qed.

  Fact S_imsell_cntr Γ Δ B : Forall (fun '(u,_) => U u) Γ -> ‼Γ++‼Γ++Δ ⊢ B -> ‼Γ++Δ ⊢ B.
  Proof.
    intros H; revert H Δ.
    induction 1 as [ | (u,A) Γ H1 H2 IH2 ]; simpl; auto; intros Δ H.
    apply in_imsell_cntr; auto.
    apply in_imsell_perm with (‼Γ ++ (![u]A::![u]A::Δ)).
    + apply Permutation_sym.
      do 2 apply Permutation_cons_app; auto.
    + apply IH2.
      revert H; apply in_imsell_perm.
      rewrite app_assoc.
      apply Permutation_cons_app.
      rewrite <- app_assoc.
      apply Permutation_app; auto.
      apply Permutation_cons_app; auto.
  Qed.

  Theorem S_imsell_extract Γ u A B : ![u]A ∊ Γ -> U u -> Γ ⊢ B <-> ![u]A::Γ ⊢ B.
  Proof.
    intros H1 H2; split.
    + apply in_imsell_weak; auto.
    + intros H3.
      apply In_perm in H1 as (Δ & H1).
      apply in_imsell_perm with (1 := H1).
      apply in_imsell_cntr; auto.
      apply in_imsell_perm with (2 := H3).
      apply perm_skip, Permutation_sym; auto.
  Qed.

(*

  Theorem S_imsell_weak_cntr' Σ Γ u A B : (u,A) ∊ Σ -> U u -> ‼Σ++Γ ⊢ B <-> ![u]A::‼Σ++Γ ⊢ B.
  Proof.
    intros H1 H2; apply S_imsell_extract; auto.
    apply in_app_iff; left.
    apply in_map_iff.
    exists (u,A); auto.
  Qed.

*)

  Section Trivial_Phase_semantics.

    (* We only consider the monoids nat^n *)

    Variables (n : nat) (s : nat -> vec nat n -> Prop).

    Notation "⦳" := vec_zero.
    Notation ø := vec_nil.

    Definition imsell_tps_mult (X Y : _ -> Prop) (x : vec _ n) := exists a b, x = vec_plus a b /\ X a /\ Y b.
    Definition imsell_tps_imp (X Y : _ -> Prop) (v : vec _ n) := forall x, X x -> Y (vec_plus x v).

    Infix "⊛" := imsell_tps_mult (at level 65, right associativity).
    Infix "-⊛" := imsell_tps_imp (at level 65, right associativity).

    Fact imsell_tps_imp_zero X Y : (X -⊛ Y) ⦳ <-> X ⊆ Y.
    Proof.
      split.
      + intros ? ? ?; rewrite <- vec_zero_plus, vec_plus_comm; auto.
      + intros ? ?; rewrite vec_plus_comm, vec_zero_plus; auto.
    Qed.

    Variable (K : bang -> vec nat n -> Prop).

    Hypothesis HK_antitone : forall p q, p ≤ q -> K q ⊆ K p.
    Hypothesis HK_unit0 : forall m, K m ⦳.
    Hypothesis HK_plus  : forall m, K m ⊛ K m ⊆ K m.
    Hypothesis HK_unit1 : forall u, U u -> forall x, K u x -> x = ⦳.

    Fact imsell_tps_mult_mono (X1 X2 Y1 Y2 : _ -> Prop) :
              X1 ⊆ X2 -> Y1 ⊆ Y2 -> X1⊛Y1 ⊆ X2⊛Y2.
    Proof.
      intros H1 H2 x (y & z & H3 & H4 & H5); subst.
      exists y, z; auto.
    Qed.

    Fixpoint imsell_tps (A : imsell_form nat bang) x : Prop :=
      match A with
        | £ X   => s X x
        | ![m]A => ⟦A⟧ x /\ K m x
        | A⊸B   => (⟦A⟧-⊛⟦B⟧) x
      end
    where "⟦ A ⟧" := (imsell_tps A).

    Fact imsell_tps_bang_zero m A : ⟦![m]A⟧ ⦳ <-> ⟦A⟧ ⦳.
    Proof. simpl; split; auto; tauto. Qed.

    Fact imsell_tps_bang_U u A : U u -> (forall v, ⟦![u]A⟧ v <-> v = ⦳) <-> ⟦A⟧ ⦳.
    Proof.
      intros Hu; split.
      + intros H; rewrite <- imsell_tps_bang_zero, H; auto.
      + intros H v; split; simpl.
        * intros (_ & H1); revert H1; eauto.
        * intros ->; auto.
    Qed.

    Reserved Notation "⟪ Γ ⟫" (at level 1, format "⟪ Γ ⟫").

    Fixpoint imsell_tps_list Γ :=
      match Γ with
        | nil  => eq ⦳
        | A::Γ => ⟦A⟧⊛⟪Γ⟫
      end
    where "⟪ Γ ⟫" := (imsell_tps_list Γ).

    Fact imsell_tps_app Γ Δ x : ⟪Γ++Δ⟫ x <-> (⟪Γ⟫⊛⟪Δ⟫) x.
    Proof.
      revert Γ Δ x; intros Ga De.
      induction Ga as [ | A Ga IH ]; intros x; simpl; split; intros Hx.
      + exists vec_zero, x; simpl; rew vec.
      + destruct Hx as (? & ? & ? & ? & ?); subst; auto; rewrite vec_zero_plus; auto.
      + destruct Hx as (y & z & H1 & H2 & H3).
        apply IH in H3.
        destruct H3 as (c & d & H4 & H5 & H6).
        exists (vec_plus y c), d; split.
        * subst; apply vec_plus_assoc.
        * split; auto.
        exists y, c; auto.
      + destruct Hx as (y & d & ? & (z & g & ? & ? & ?) & ?).
        exists z, (vec_plus g d); split.
        * subst; symmetry; apply vec_plus_assoc.
        * split; auto.
          apply IH.
          exists g, d; auto.
    Qed.

    Fact imsell_tps_perm Γ Δ : Γ ~p Δ -> ⟪Γ⟫ ⊆ ⟪Δ⟫.
    Proof.
      induction 1 as [ | A Ga De H IH | A B Ga | ]; simpl; auto.
      + intros x (y & z & H1 & H2 & H3).
        exists y, z; repeat split; auto.
      + intros x (y & z & H1 & H2 & c & d & H3 & H4 & H5).
        exists c, (vec_plus y d); split.
        * subst; rewrite (vec_plus_comm c), vec_plus_assoc, (vec_plus_comm c); auto.
        * split; auto.
          exists y, d; auto.
    Qed.

    Fact imsell_tps_list_zero Γ : (forall A, A ∊ Γ -> ⟦A⟧ ⦳) -> ⟪Γ⟫ ⦳.
    Proof.
      induction Γ as [ | A Γ IH ]; simpl; auto; intros H.
      exists ⦳, ⦳; msplit 2; auto; now rewrite vec_zero_plus.
    Qed.

    Definition imsell_sequent_tps Γ A := ⟪Γ⟫ -⊛ ⟦A⟧.

    Notation "'[<' Γ '|-' A '>]'" := (imsell_sequent_tps Γ A) (at level 1, format "[<  Γ  |-  A  >]").

    Fact imsell_sequent_tps_mono Γ A B :
           ⟦A⟧ ⊆ ⟦B⟧ -> [< Γ |- A >] ⊆ [< Γ |- B >].
    Proof.
      intros H x; simpl; unfold imsell_sequent_tps.
      intros H1 ? H2; apply H, H1; auto.
    Qed.

    Fact imsell_perm_tps Γ Δ : Γ ~p Δ -> forall A, [< Γ |- A >] ⊆ [< Δ |- A >].
    Proof.
      intros H1 B x; unfold imsell_sequent_tps.
      intros H2 ? H3; apply H2; revert H3.
      apply imsell_tps_perm, Permutation_sym; auto.
    Qed.

    Fact imsell_sequent_tps_eq Γ A : [< Γ |- A >] ⦳ <-> ⟪Γ⟫ ⊆ ⟦A⟧.
    Proof.
      split.
      * intros H x Hx.
        rewrite <- vec_zero_plus, vec_plus_comm.
        apply (H x); trivial.
      * intros H x Hx.
        rewrite vec_plus_comm, vec_zero_plus; auto.
    Qed.

   Fact imsell_tps_lbang m Γ : m ≼ Γ -> ⟪‼Γ⟫ ⊆ K m.
    Proof.
      induction Γ as [ | (v,A) Γ IH ]; simpl; intros H1 x.
      + intros <-; auto.
      + intros (y & z & -> & (G1 & G2) & G3).
        apply HK_plus; exists y, z; msplit 2; auto.
        * revert G2; apply HK_antitone; auto.
          apply (H1 (v,A)); auto.
        * revert G3; apply IH.
          intros (w,B) ?; apply (H1 (_,B)); auto.
    Qed.

    Theorem imsell_tps_sound Γ A : Γ ⊢ A -> [< Γ |- A >] ⦳.
    Proof.
      induction 1 as [ A
                     | Γ Δ A H1 H2 IH2
                     | Γ Δ A B C H1 IH1 H2 IH2
                     | Γ A B H1 IH1
                     | Γ m A B H1 IH1
                     | Γ m A H1 H2 IH2
                     | Γ u A B H1 H2 IH2
                     | Γ u A B H1 H2 IH2
                     ]; unfold imsell_sequent_tps in * |- *.

      + intros x; simpl; intros (y & z & H1 & H2 & H3); subst; eq goal H2.
        f_equal; do 2 rewrite vec_plus_comm, vec_zero_plus; auto.

      + revert IH2; apply imsell_perm_tps; auto.

      + intros x (y & z & H3 & H4 & H5); simpl.
        apply IH2.
        apply imsell_tps_app in H5 as (g & d & H5 & H6 & H7).
        simpl in H4; apply IH1, H4 in H6.
        exists (vec_plus y g), d; repeat split; auto.
        * subst; apply vec_plus_assoc.
        * eq goal H6; f_equal; rew vec.

      + simpl; intros y Hy x Hx.
        rewrite vec_plus_assoc.
        apply IH1.
        exists x, y; repeat split; auto.

      + intros x (y & z & H2 & H3 & H4).
        apply IH1; exists y, z; repeat split; auto.
        apply H3.

      + intros x Hx; split.
        * apply IH2; auto.
        * rew vec.
          revert Hx; apply imsell_tps_lbang; auto.

      + intros x (y & z & -> & H3 & H4); rew vec.
        apply proj2, HK_unit1 in H3; auto; subst.
        rewrite vec_plus_comm.
        now apply IH2.

      + intros x (y & z & G2 & G3 & G4).
        apply IH2.
        exists y, z; repeat (split; auto).
        exists y, z; repeat (split; auto).
        apply proj2, HK_unit1 in G3; auto.
        subst; rew vec; auto.
    Qed.

  End Trivial_Phase_semantics.

End IMSELL.


Require Import rt.util.all.
Require Import rt.model.arrival.basic.task rt.model.priority rt.model.arrival.basic.task_arrival.
Require Import rt.model.schedule.global.workload rt.model.schedule.global.schedulability
               rt.model.schedule.global.response_time.
Require Import rt.model.schedule.global.jitter.job rt.model.schedule.global.jitter.schedule
               rt.model.schedule.global.jitter.platform rt.model.schedule.global.jitter.interference
               rt.model.schedule.global.jitter.constrained_deadlines.
Require Import rt.analysis.global.jitter.workload_bound
               rt.analysis.global.jitter.interference_bound_edf.
From mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq fintype bigop div path.

Module ResponseTimeAnalysisEDFJitter.

  Export JobWithJitter SporadicTaskset ScheduleOfSporadicTaskWithJitter Workload
         Schedulability ResponseTime Priority TaskArrival WorkloadBoundJitter
         InterferenceBoundEDFJitter Platform Interference ConstrainedDeadlines.

  (* In this section, we prove that any fixed point in Bertogna and
     Cirinei's RTA for EDF scheduling modified to account for jitter
     yields a safe response-time bound. This is an extension of the
     analysis found in Chapter 17.1.2 of Baruah et al.'s book
     Multiprocessor Scheduling for Real-time Systems. *)
  Section ResponseTimeBound.

    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.

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

    (* Assume any job arrival sequence... *)
    Context {arr_seq: arrival_sequence Job}.

    (* ... in which jobs arrive sporadically and have valid parameters.
       Note: the jitter of a valid job is bounded by the jitter of its task. *)
    Hypothesis H_sporadic_tasks:
      sporadic_task_model task_period job_arrival job_task arr_seq.
    Hypothesis H_valid_job_parameters:
      forall j,
        arrives_in arr_seq j ->
        valid_sporadic_job_with_jitter task_cost task_deadline task_jitter job_cost
                                                 job_deadline job_task job_jitter j.

    (* Assume that we have a task set where all tasks have valid
       parameters and constrained deadlines, ... *)
    Variable ts: taskset_of sporadic_task.
    Hypothesis H_valid_task_parameters:
      valid_sporadic_taskset task_cost task_period task_deadline ts.
    Hypothesis H_constrained_deadlines:
      forall tsk, tsk \in ts -> task_deadline tsk <= task_period tsk.

    (* ... and that all jobs in the arrival sequence come from the task set. *)
    Hypothesis H_all_jobs_from_taskset:
      forall j,
        arrives_in arr_seq j ->
        job_task j \in ts.

    (* Next, consider any schedule such that...*)
    Variable num_cpus: nat.
    Variable sched: schedule Job num_cpus.
    Hypothesis H_jobs_come_from_arrival_sequence:
      jobs_come_from_arrival_sequence sched arr_seq.

    (* ...jobs are sequential, do not execute before the
       jitter has passed and nor longer than their execution costs. *)
    Hypothesis H_sequential_jobs: sequential_jobs sched.
    Hypothesis H_execute_after_jitter:
      jobs_execute_after_jitter job_arrival job_jitter sched.
    Hypothesis H_completed_jobs_dont_execute:
      completed_jobs_dont_execute job_cost sched.

    (* Assume that there exists at least one processor. *)
    Hypothesis H_at_least_one_cpu: num_cpus > 0.

    (* Assume that the schedule is a work-conserving EDF schedule. *)
    Hypothesis H_work_conserving: work_conserving job_arrival job_cost job_jitter arr_seq sched.
    Hypothesis H_edf_policy: respects_JLFP_policy job_arrival job_cost job_jitter arr_seq sched
                                                  (EDF job_arrival job_deadline).

    (* Let's define some local names to avoid passing many parameters. *)
    Let no_deadline_is_missed_by_tsk (tsk: sporadic_task) :=
      task_misses_no_deadline job_arrival job_cost job_deadline job_task arr_seq sched tsk.
    Let response_time_bounded_by (tsk: sporadic_task) :=
      is_response_time_bound_of_task job_arrival job_cost job_task arr_seq sched tsk.

    (* Next we consider the response-time recurrence.
       Assume that a response-time bound R is known...  *)
    Let task_with_response_time := (sporadic_task * time)%type.
    Variable rt_bounds: seq task_with_response_time.

    (* ...for any task in the task set, ... *)
    Hypothesis H_rt_bounds_contains_all_tasks: unzip1 rt_bounds = ts.

    (* Also, assume that R is a fixed-point of the response-time recurrence, ... *)
    Let I (tsk: sporadic_task) (delta: time) :=
      total_interference_bound_edf task_cost task_period task_deadline task_jitter tsk rt_bounds delta.
    Hypothesis H_response_time_is_fixed_point :
      forall tsk R,
        (tsk, R) \in rt_bounds ->
        R = task_cost tsk + div_floor (I tsk R) num_cpus.

    (* ..., and R is no larger than the deadline. *)
    Hypothesis H_tasks_miss_no_deadlines:
      forall tsk R,
        (tsk, R) \in rt_bounds ->
        task_jitter tsk + R <= task_deadline tsk.

    (* In order to prove that R is a response-time bound, we first provide some lemmas. *)
    Section Lemmas.

      (* Let (tsk, R) be any task to be analyzed, with its response-time bound R. *)
      Variable tsk: sporadic_task.
      Variable R: time.
      Hypothesis H_tsk_R_in_rt_bounds: (tsk, R) \in rt_bounds.

      (* Consider any job j of tsk. *)
      Variable j: Job.
      Hypothesis H_j_arrives: arrives_in arr_seq j.
      Hypothesis H_job_of_tsk: job_task j = tsk.

      (* Let t1 be the first point in time where j can actually be scheduled. *)
      Let t1 := job_arrival j + job_jitter j.

      (* Assume that job j did not complete on time, ... *)
      Hypothesis H_j_not_completed: ~~ completed job_cost sched j (t1 + R).

      (* ...and that it is the first job not to satisfy its response-time bound. *)
      Hypothesis H_all_previous_jobs_completed_on_time :
        forall j_other tsk_other R_other,
          arrives_in arr_seq j_other ->
          job_task j_other = tsk_other ->
          (tsk_other, R_other) \in rt_bounds ->
          job_arrival j_other + task_jitter tsk_other + R_other < job_arrival j + task_jitter tsk + R ->
          completed job_cost sched j_other (job_arrival j_other + task_jitter tsk_other + R_other).

      (* Let's call x the interference incurred by job j due to tsk_other, ...*)
      Let x (tsk_other: sporadic_task) :=
        task_interference job_arrival job_cost job_task job_jitter sched j tsk_other t1 (t1 + R).

      (* and X the total interference incurred by job j due to any task. *)
      Let X := total_interference job_arrival job_cost job_jitter sched j t1 (t1 + R).

      (* Recall Bertogna and Cirinei's workload bound ... *)
      Let workload_bound (tsk_other: sporadic_task) (R_other: time) :=
        W_jitter task_cost task_period task_jitter tsk_other R_other R.

      (*... and the EDF-specific bound, ... *)
      Let edf_specific_bound (tsk_other: sporadic_task) (R_other: time) :=
        edf_specific_interference_bound task_cost task_period task_deadline task_jitter tsk tsk_other R_other.

      (* ... which combined form the interference bound. *)
      Let interference_bound (tsk_other: sporadic_task) (R_other: time) :=
        interference_bound_edf task_cost task_period task_deadline task_jitter tsk R (tsk_other, R_other).

      (* Based on the definition of a different task, ... *)
      Let other_task := different_task tsk.

      (* ...let other_tasks denote the set of tasks that are different from tsk. *)
      Let other_tasks :=
        [seq tsk_other <- ts | other_task tsk_other].

      (* Now we establish results the interfering tasks. *)
      Section LemmasAboutInterferingTasks.

        (* Let (tsk_other, R_other) be any pair of higher-priority task and
           response-time bound computed in previous iterations. *)
        Variable tsk_other: sporadic_task.
        Variable R_other: time.
        Hypothesis H_response_time_of_tsk_other: (tsk_other, R_other) \in rt_bounds.

        (* Note that tsk_other is in task set ts ...*)
        Lemma bertogna_edf_tsk_other_in_ts: tsk_other \in ts.
        Proof.
          by rewrite set_mem -H_rt_bounds_contains_all_tasks; apply/mapP; exists (tsk_other, R_other).
        Qed.

        (* Also, R_other is larger than the cost of tsk_other. *)
        Lemma bertogna_edf_R_other_ge_cost :
          R_other >= task_cost tsk_other.
        Proof.
          by rewrite [R_other](H_response_time_is_fixed_point tsk_other);
            first by apply leq_addr.
        Qed.

        (* Since tsk_other cannot interfere more than it executes, we show that
           the interference caused by tsk_other is no larger than workload bound W. *)
        Lemma bertogna_edf_workload_bounds_interference :
          x tsk_other <= workload_bound tsk_other R_other.
        Proof.
          unfold valid_sporadic_job in *.
          rename H_all_previous_jobs_completed_on_time into BEFOREok,
                 H_valid_job_parameters into PARAMS,
                 H_valid_task_parameters into TASK_PARAMS,
                 H_constrained_deadlines into RESTR,
                 H_tasks_miss_no_deadlines into NOMISS.
          unfold x, task_interference, valid_sporadic_job_with_jitter, valid_sporadic_job in *.
          have INts := bertogna_edf_tsk_other_in_ts.
          apply leq_trans with (n := workload job_task sched tsk_other t1 (t1 + R));
            first by apply task_interference_le_workload.
          have BOUND := workload_bounded_by_W task_cost task_period task_deadline task_jitter
            job_arrival job_cost job_task job_deadline job_jitter arr_seq _ sched.
          apply BOUND; try (by done); last 2 first;
            [ by apply NOMISS |
            | by ins; apply TASK_PARAMS
            | by apply RESTR
            | by apply bertogna_edf_R_other_ge_cost].
          {
            intros j0 ARR0 JOB0 LT0; apply BEFOREok; try (by done).
            unfold t1 in *.
            apply leq_trans with (n := job_arrival j + job_jitter j + R); first by done.
            rewrite leq_add2r leq_add2l.
            specialize (PARAMS j H_j_arrives); des.
            rewrite -H_job_of_tsk; apply PARAMS0.
          }
        Qed.

        (* Recall that the edf-specific interference bound also holds. *)
        Lemma bertogna_edf_specific_bound_holds :
          x tsk_other <= edf_specific_bound tsk_other R_other.
        Proof.
          by apply interference_bound_edf_bounds_interference with (job_deadline0 := job_deadline)
                   (arr_seq0 := arr_seq) (ts0 := ts); try (by done);
          [  by apply bertogna_edf_tsk_other_in_ts
          |  by apply H_tasks_miss_no_deadlines
          |  by apply leq_trans with (n := task_jitter tsk + R);
               [apply leq_addl | by apply H_tasks_miss_no_deadlines]
          |  by ins; apply H_all_previous_jobs_completed_on_time with (tsk_other := tsk_other)].
        Qed.

      End LemmasAboutInterferingTasks.

      (* Next we prove some lemmas that help to derive a contradiction.*)
      Section DerivingContradiction.

        (* 0) Since job j did not complete by its response time bound, it follows that
              the total interference X >= R - e_k + 1. *)
        Lemma bertogna_edf_too_much_interference : X >= R - task_cost tsk + 1.
        Proof.
          rename H_completed_jobs_dont_execute into COMP,
                 H_valid_job_parameters into PARAMS, H_response_time_is_fixed_point into REC,
                 H_job_of_tsk into JOBtsk, H_j_not_completed into NOTCOMP.
          unfold completed, valid_sporadic_job_with_jitter, valid_sporadic_job in *.
          unfold X, total_interference; rewrite addn1.
          rewrite -(ltn_add2r (task_cost tsk)).
          rewrite subh1; last by rewrite [R](REC tsk) // leq_addr.
          rewrite -addnBA // subnn addn0.
          move: (NOTCOMP) => /negP NOTCOMP'.
          rewrite neq_ltn in NOTCOMP.
          move: NOTCOMP => /orP [LT | BUG]; last first.
          {
            exfalso; rewrite ltnNge in BUG; move: BUG => /negP BUG; apply BUG.
            by apply cumulative_service_le_job_cost.
          }
          apply leq_ltn_trans with (n := (\sum_(t1 <= t < t1 + R)
                                       backlogged job_arrival job_cost job_jitter sched j t) +
                                     service sched j (t1 + R)); last first.
          {
            rewrite -addn1 -addnA leq_add2l addn1.
            apply leq_trans with (n := job_cost j); first by done.
            by specialize (PARAMS j H_j_arrives); des; rewrite -JOBtsk.
          }
          unfold service.
          rewrite -> big_cat_nat with (n := t1) (m := 0); rewrite ?leq_addr // /=.
          rewrite (cumulative_service_before_jitter_zero job_arrival job_jitter) // add0n.
          rewrite -big_split /=.
          apply leq_trans with (n := \sum_(t1 <= i < t1 + R) 1);
            first by simpl_sum_const; rewrite addKn.
          apply leq_sum_nat; move => i /andP [GEi LTi] _.
          destruct (backlogged job_arrival job_cost job_jitter sched j i) eqn:BACK;
            first by rewrite -addn1 addnC; apply leq_add.
          apply negbT in BACK.
          rewrite add0n lt0n -not_scheduled_no_service negbK.
          rewrite /backlogged negb_and negbK in BACK.
          move: BACK => /orP [/negP NOTPENDING | SCHED]; last by done.
          exfalso; apply NOTPENDING; unfold pending; apply/andP; split; first by done.
          apply/negP; red; intro BUG; apply NOTCOMP'.
          by apply completion_monotonic with (t := i); try (by done); apply ltnW.
        Qed.

      (* 1) Next, we prove that during the scheduling window of j, any job that is
            scheduled while j is backlogged comes from a different task.
            This follows from the fact that j is the first job not to complete
            by its response-time bound, so previous jobs of j's task must have
            completed by their periods and cannot be pending. *)
        Lemma bertogna_edf_interference_by_different_tasks :
          forall t j_other,
            t1 <= t < t1 + R ->
            backlogged job_arrival job_cost job_jitter sched j t ->
            scheduled sched j_other t ->
            job_task j_other != tsk.
        Proof.
          rename H_all_jobs_from_taskset into FROMTS,
                 H_valid_task_parameters into PARAMS,
                 H_valid_job_parameters into JOBPARAMS,
                 H_job_of_tsk into JOBtsk, H_sporadic_tasks into SPO,
                 H_work_conserving into WORK,
                 H_tsk_R_in_rt_bounds into INbounds,
                 H_all_previous_jobs_completed_on_time into BEFOREok,
                 H_tasks_miss_no_deadlines into NOMISS,
                 H_constrained_deadlines into CONSTR.
          unfold valid_sporadic_job_with_jitter, valid_sporadic_job in *.
          move => t j_other /andP [LEt GEt] BACK SCHED.
          apply/eqP; red; intro SAMEtsk.
          move: SCHED => /existsP [cpu SCHED].
          have SCHED': scheduled sched j_other t by apply/existsP; exists cpu.
          clear SCHED; rename SCHED' into SCHED.
          have ARRother: arrives_in arr_seq j_other.
            by apply (H_jobs_come_from_arrival_sequence j_other t).
          move: (SCHED) => PENDING.
          apply scheduled_implies_pending with (job_cost0 := job_cost) (job_jitter0 := job_jitter)
            (job_arrival0 := job_arrival) in PENDING; try (by done).
          destruct (ltnP (job_arrival j_other) (job_arrival j)) as [BEFOREother | BEFOREj].
          {
            move: (BEFOREother) => LT; rewrite -(ltn_add2r R) in LT.
            exploit (BEFOREok j_other tsk R ARRother SAMEtsk INbounds).
            {
              rewrite -addnA [_ + R]addnC addnA -[(_ + _) + R]addnA [_ tsk + R]addnC addnA.
              by rewrite ltn_add2r.
            }
            intros COMP.
            move: PENDING => /andP [_ /negP NOTCOMP]; apply NOTCOMP.
            apply completion_monotonic with (t0 := job_arrival j_other + task_jitter tsk + R);
              try by done.
            apply leq_trans with (n := job_arrival j);
              last by apply leq_trans with (n := t1); [by apply leq_addr | by done].
            apply leq_trans with (n := job_arrival j_other + task_period tsk).
            {
              rewrite -addnA leq_add2l.
              by apply leq_trans with (n := task_deadline tsk);
                [by apply NOMISS | by apply CONSTR; rewrite -JOBtsk FROMTS].
            }
            rewrite -SAMEtsk; apply SPO; [ | by done | by done| by rewrite JOBtsk | by apply ltnW].
            by red; intro EQ; subst; rewrite ltnn in BEFOREother.
          }
          {
            move: PENDING => /andP [ARRIVED _].
            exploit (SPO j j_other); try (by done); [ | by rewrite SAMEtsk | ]; last first.
            {
              apply/negP; rewrite -ltnNge JOBtsk.
              apply leq_trans with (n := job_arrival j + task_deadline tsk);
                last by rewrite leq_add2l; apply CONSTR; rewrite -JOBtsk FROMTS.
              apply leq_trans with (n := job_arrival j + task_jitter tsk + R);
                last by rewrite -addnA leq_add2l; apply NOMISS.
              apply leq_trans with (n := t1 + R); last first.
              {
                rewrite leq_add2r leq_add2l -JOBtsk.
                by specialize (JOBPARAMS j H_j_arrives); des.
              }
              apply leq_ltn_trans with (n := job_arrival j_other + job_jitter j_other);
                first by apply leq_addr.
              by apply leq_ltn_trans with (n := t).
            }
            by intros EQtsk; subst j_other; rewrite /backlogged SCHED andbF in BACK.
          }
        Qed.

      (* 2) In order to use the lemmas in constrained_deadlines.v, we show that
            all jobs released before the end of the interval complete by their
            periods. This follows trivially from the hypothesis that all jobs
            before (t1 + R) complete by their response-time bounds.
            With this lemma, we can conclude that during job j's scheduling
            window there cannot be multiple pending jobs of each task.*)
        Lemma bertogna_edf_all_previous_jobs_complete_by_their_period:
          forall t j0,
            t < t1 + R ->
            arrives_in arr_seq j0 ->
            job_arrival j0 + task_period (job_task j0) <= t ->
            completed job_cost sched j0
               (job_arrival j0 + task_period (job_task j0)).
        Proof.
          rename H_valid_job_parameters into JOBPARAMS,
                 H_rt_bounds_contains_all_tasks into UNZIP,
                 H_job_of_tsk into JOBtsk,
                 H_constrained_deadlines into CONSTR,
                 H_tasks_miss_no_deadlines into NOMISS,
                 H_all_jobs_from_taskset into FROMTS,
                 H_all_previous_jobs_completed_on_time into BEFOREok.
          unfold valid_sporadic_job_with_jitter, valid_sporadic_job in *.
          intros t j0 LEt ARR0 LE.
          cut ((job_task j0) \in unzip1 rt_bounds = true); last by rewrite UNZIP FROMTS.
          move => /mapP [p IN EQ]; destruct p as [tsk' R0]; simpl in *; subst tsk'.
          apply completion_monotonic with (t0 := job_arrival j0 +
                                        task_jitter (job_task j0) + R0); first by done.
          {
            rewrite -addnA leq_add2l.
            apply leq_trans with (n := task_deadline (job_task j0));
              [by apply NOMISS | by apply CONSTR; rewrite FROMTS].
          }
          apply BEFOREok with (tsk_other := (job_task j0)); try by done.
          apply leq_ltn_trans with (n := t); last first.
          {
            apply leq_trans with (n := t1 + R); first by done.
            rewrite leq_add2r leq_add2l -JOBtsk.
            by specialize (JOBPARAMS j H_j_arrives); des.
          }
          apply leq_trans with (n := job_arrival j0 + task_period (job_task j0)); last by done.
          by rewrite -addnA leq_add2l; apply leq_trans with (n := task_deadline (job_task j0));
            [by apply NOMISS | apply CONSTR; rewrite FROMTS].
        Qed.

        (* Let's define a predicate to identify the other tasks that are scheduled. *)
        Let other_scheduled_task (t: time) (tsk_other: sporadic_task) :=
          task_is_scheduled job_task sched tsk_other t &&
          other_task tsk_other.

        (* 3) Now we prove that, at all times that j is backlogged, the number
              of tasks other than tsk that are scheduled is exactly the number
              of processors in the system. This is required to prove lemma (4). *)
        Lemma bertogna_edf_all_cpus_are_busy:
          forall t,
            t1 <= t < t1 + R ->
            backlogged job_arrival job_cost job_jitter sched j t ->
            count (other_scheduled_task t) ts = num_cpus.
        Proof.
          rename H_all_jobs_from_taskset into FROMTS,
                 H_valid_task_parameters into PARAMS,
                 H_valid_job_parameters into JOBPARAMS,
                 H_job_of_tsk into JOBtsk, H_jobs_come_from_arrival_sequence into FROMSEQ,
                 H_sporadic_tasks into SPO,
                 H_tsk_R_in_rt_bounds into INbounds,
                 H_all_previous_jobs_completed_on_time into BEFOREok,
                 H_tasks_miss_no_deadlines into NOMISS,
                 H_rt_bounds_contains_all_tasks into UNZIP,
                 H_constrained_deadlines into RESTR,
                 H_work_conserving into WORK.
          unfold x, X, total_interference, task_interference,
                 valid_sporadic_job_with_jitter, valid_sporadic_job in *.
          move => t /andP [LEt LTt] BACK.
          have PLAT := platform_cpus_busy_with_interfering_tasks task_cost task_period task_deadline
            job_arrival job_cost job_task job_jitter arr_seq sched FROMSEQ WORK.
          apply PLAT with (j := j); try (by done);
            [by apply PARAMS; rewrite -JOBtsk; apply FROMTS | clear PLAT].
          intros j0 tsk0 ARR0 TSK0 LE.
          cut (tsk0 \in unzip1 rt_bounds = true); last by rewrite UNZIP -TSK0 FROMTS //.
          move => /mapP [p IN EQ]; destruct p as [tsk' R0]; simpl in *; subst tsk'.
          apply completion_monotonic with (t0 := job_arrival j0 + task_jitter tsk0 + R0); try (by done).
          {
            rewrite -addnA leq_add2l TSK0.
            apply leq_trans with (n := task_deadline tsk0); first by apply NOMISS.
            by apply RESTR; rewrite -TSK0 FROMTS.
          }
          {
            apply BEFOREok with (tsk_other := tsk0); try (by done).
            apply leq_trans with (n := t1 + R);
              last by rewrite leq_add2r leq_add2l -JOBtsk; specialize (JOBPARAMS j H_j_arrives); des.
            apply leq_ltn_trans with (n := t); last by done.
            apply leq_trans with (n := job_arrival j0 + task_period tsk0); last by done.
            rewrite -addnA leq_add2l.
            apply leq_trans with (n := task_deadline tsk0); first by apply NOMISS.
            by apply RESTR; rewrite -TSK0; apply FROMTS.
          }
        Qed.

      (* 4) Next, we prove that the sum of the interference of each task is equal
          to the total interference multiplied by the number of processors. This
          holds because interference only occurs when all processors are busy.
          With this lemma we can relate per-task interference with the total
          interference incurred by j (backlogged time). *)
        Lemma bertogna_edf_interference_on_all_cpus :
          \sum_(tsk_k <- other_tasks) x tsk_k = X * num_cpus.
        Proof.
          have DIFFTASK := bertogna_edf_interference_by_different_tasks.
          rename H_all_jobs_from_taskset into FROMTS, H_valid_task_parameters into PARAMS,
                 H_job_of_tsk into JOBtsk, H_sporadic_tasks into SPO,
                 H_work_conserving into WORK, H_jobs_come_from_arrival_sequence into FROMSEQ,
                 H_tsk_R_in_rt_bounds into INbounds,
                 H_all_previous_jobs_completed_on_time into BEFOREok,
                 H_tasks_miss_no_deadlines into NOMISS, H_rt_bounds_contains_all_tasks into UNZIP,
                 H_constrained_deadlines into CONSTR.
          unfold sporadic_task_model in *.
          unfold x, X, total_interference, task_interference.
          rewrite -big_mkcond -exchange_big big_distrl /= mul1n.
          rewrite [\sum_(_ <= _ < _ | backlogged _ _ _ _ _ _) _]big_mkcond.
          apply eq_big_nat; move => t /andP [GEt LTt].
          destruct (backlogged job_arrival job_cost job_jitter sched j t) eqn:BACK;
            last by rewrite big1 //; ins; rewrite big1.
          rewrite big_mkcond /=.
          rewrite exchange_big /=.
          apply eq_trans with (y := \sum_(cpu < num_cpus) 1); last by simpl_sum_const.
          apply eq_bigr; intros cpu _.
          move: (WORK j t H_j_arrives BACK cpu) => [j_other /eqP SCHED]; unfold scheduled_on in *.
          have ARRother: arrives_in arr_seq j_other.
            by apply (FROMSEQ j_other t); apply/existsP; exists cpu; apply/eqP.
          rewrite (bigD1_seq (job_task j_other)) /=; last by rewrite filter_uniq; destruct ts.
          {
            rewrite (eq_bigr (fun i => 0));
              last by intros i DIFF; rewrite /task_scheduled_on SCHED;apply/eqP;rewrite eqb0 eq_sym.
            simpl_sum_const; apply/eqP; rewrite eqb1.
            by unfold task_scheduled_on; rewrite SCHED.
          }
          rewrite mem_filter; apply/andP; split; last by apply FROMTS.
          apply DIFFTASK with (t := t); [by auto | by done |].
          by apply/existsP; exists cpu; apply/eqP.
        Qed.

        (* Before stating the next lemma, let (num_tasks_exceeding delta) be the
           number of interfering tasks whose interference x is larger than delta. *)
        Let num_tasks_exceeding delta := count (fun i => x i >= delta) (other_tasks).

        (* 5) Now we prove that, for any delta, if (num_task_exceeding delta > 0), then the
              cumulative interference caused by the complementary set of interfering tasks fills
              the remaining, not-completely-full (num_cpus - num_tasks_exceeding delta)
              processors. *)
        Lemma bertogna_edf_interference_in_non_full_processors :
          forall delta,
            0 < num_tasks_exceeding delta < num_cpus ->
            \sum_(i <- other_tasks | x i < delta) x i >= delta * (num_cpus - num_tasks_exceeding delta).
        Proof.
          have COMP := bertogna_edf_all_previous_jobs_complete_by_their_period.
          have INV := bertogna_edf_all_cpus_are_busy.
          rename H_all_jobs_from_taskset into FROMTS, H_valid_task_parameters into PARAMS,
                 H_job_of_tsk into JOBtsk, H_sporadic_tasks into SPO,
                 H_tsk_R_in_rt_bounds into INbounds, H_jobs_come_from_arrival_sequence into FROMSEQ,
                 H_all_previous_jobs_completed_on_time into BEFOREok,
                 H_tasks_miss_no_deadlines into NOMISS,
                 H_constrained_deadlines into CONSTR, H_sequential_jobs into SEQ.
          unfold sporadic_task_model in *.
          move => delta /andP [HAS LT].
          rewrite -has_count in HAS.

          set some_interference_A := fun t =>
            has (fun tsk_k => backlogged job_arrival job_cost job_jitter sched j t &&
                              (x tsk_k >= delta) &&
                              task_is_scheduled job_task sched tsk_k t) other_tasks.
          set total_interference_B := fun t =>
              backlogged job_arrival job_cost job_jitter sched j t *
              count (fun tsk_k => (x tsk_k < delta) &&
                    task_is_scheduled job_task sched tsk_k t) other_tasks.

          apply leq_trans with ((\sum_(t1 <= t < t1 + R)
                                some_interference_A t) * (num_cpus - num_tasks_exceeding delta)).
          {
            rewrite leq_mul2r; apply/orP; right.
            move: HAS => /hasP HAS; destruct HAS as [tsk_a INa LEa].
            apply leq_trans with (n := x tsk_a); first by apply LEa.
            unfold x, task_interference, some_interference_A.
            apply leq_sum_nat; move => t /andP [GEt LTt] _.
            destruct (backlogged job_arrival job_cost job_jitter sched j t) eqn:BACK;
              last by rewrite (eq_bigr (fun x => 0)); [by simpl_sum_const | by ins].
            destruct ([exists cpu, task_scheduled_on job_task sched tsk_a cpu t]) eqn:SCHED;
              last first.
            {
              apply negbT in SCHED; rewrite negb_exists in SCHED; move: SCHED => /forallP ALL.
              rewrite (eq_bigr (fun x => 0)); first by simpl_sum_const.
              by intros cpu _; specialize (ALL cpu); apply negbTE in ALL; rewrite ALL.
            }
            move: SCHED => /existsP [cpu SCHED].
            apply leq_trans with (n := 1); last first.
            {
              rewrite lt0b; apply/hasP; exists tsk_a; first by done.
              by rewrite LEa 2!andTb; apply/existsP; exists cpu.
            }
            rewrite (bigD1 cpu) /= // SCHED.
            rewrite (eq_bigr (fun x => 0)); first by simpl_sum_const; rewrite leq_b1.
            intros cpu' DIFF.
            apply/eqP; rewrite eqb0; apply/negP.
            intros SCHED'.
            move: DIFF => /negP DIFF; apply DIFF; apply/eqP.
            unfold task_scheduled_on in *.
            destruct (sched cpu t) as [j1|] eqn:SCHED1; last by done.
            destruct (sched cpu' t) as [j2|] eqn:SCHED2; last by done.
            move: SCHED SCHED' => /eqP JOB /eqP JOB'.
            subst tsk_a; symmetry in JOB'.
            have ARR1: arrives_in arr_seq j1.
              by apply (FROMSEQ j1 t); apply/existsP; exists cpu; apply/eqP.
            have ARR2: arrives_in arr_seq j2.
              by apply (FROMSEQ j2 t); apply/existsP; exists cpu'; apply/eqP.
            assert (PENDING1: pending job_arrival job_cost job_jitter sched j1 t).
            {
              apply scheduled_implies_pending; try by done.
              by apply/existsP; exists cpu; apply/eqP.
            }
            assert (PENDING2: pending job_arrival job_cost job_jitter sched j2 t).
            {
              apply scheduled_implies_pending; try by done.
              by apply/existsP; exists cpu'; apply/eqP.
            }
            assert (BUG: j1 = j2).
            {
              apply platform_at_most_one_pending_job_of_each_task with (task_cost0 := task_cost)
               (job_jitter0 := job_jitter) (task_period0 := task_period) (job_cost0 := job_cost)
               (task_deadline0 := task_deadline) (tsk0 := tsk) (job_task0 := job_task)
               (sched0 := sched) (job_arrival0 := job_arrival) (arr_seq0 := arr_seq)
               (j0 := j) (t0 := t);
              rewrite ?JOBtsk ?SAMEtsk //; first by apply PARAMS; rewrite -JOBtsk FROMTS.
              by intros j0 tsk0 ARR0 TSK0 LE; apply (COMP t); rewrite ?TSK0.
            }
            by subst j2; apply SEQ with (j := j1) (t := t).
          }

          apply leq_trans with (\sum_(t1 <= t < t1 + R) total_interference_B t).
          {
            rewrite big_distrl /=.
            apply leq_sum_nat; move => t LEt _.
            unfold some_interference_A, total_interference_B.
            destruct (backlogged job_arrival job_cost job_jitter sched j t) eqn:BACK;
              [rewrite mul1n /= | by rewrite has_pred0 //].

            destruct (has (fun tsk_k : sporadic_task => (delta <= x tsk_k) &&
                       task_is_scheduled job_task sched tsk_k t) other_tasks) eqn:HAS';
              last by done.
            rewrite mul1n; move: HAS => /hasP [tsk_k INk LEk].
            unfold num_tasks_exceeding.
            apply leq_trans with (n := num_cpus -
                         count (fun i => (x i >= delta) &&
                            task_is_scheduled job_task sched i t) other_tasks).
            {
              apply leq_sub2l.
              rewrite -2!sum1_count big_mkcond /=.
              rewrite [\sum_(_ <- _ | _ <= _)_]big_mkcond /=.
              apply leq_sum; intros i _.
              by destruct (task_is_scheduled job_task sched i t);
                [by rewrite andbT | by rewrite andbF].
            }
            rewrite -count_filter -[count _ other_tasks]count_filter.
            eapply leq_trans with (n := count (predC (fun tsk => delta <= x tsk)) _);
              last by apply eq_leq, eq_in_count; red; ins; rewrite ltnNge.
            rewrite leq_subLR count_predC size_filter.
            by apply leq_trans with (n := count (other_scheduled_task t) ts);
              [by rewrite INV | by rewrite count_filter].
          }
          {
            unfold x at 2, total_interference_B.
            rewrite exchange_big /=; apply leq_sum; intros t _.
            destruct (backlogged job_arrival job_cost job_jitter sched j t) eqn:BACK; last by ins.
            rewrite mul1n -sum1_count.
            rewrite big_mkcond [\sum_(i <- other_tasks | _ < _) _]big_mkcond /=.
            apply leq_sum_seq; move => tsk_k IN _.
            destruct (x tsk_k < delta); [rewrite andTb | by rewrite andFb].
            destruct (task_is_scheduled job_task sched tsk_k t) eqn:SCHED; last by done.
            move: SCHED => /existsP [cpu SCHED].
            by rewrite (bigD1 cpu) /= // SCHED.
          }
        Qed.

        (* 6) Based on lemma (5), we prove that, for any interval delta, if the sum of per-task
              interference exceeds (delta * num_cpus), the same applies for the
              sum of the minimum of the interference and delta. *)
        Lemma bertogna_edf_minimum_exceeds_interference :
          forall delta,
            \sum_(tsk_k <- other_tasks) x tsk_k >= delta * num_cpus ->
               \sum_(tsk_k <- other_tasks) minn (x tsk_k) delta >=
               delta * num_cpus.
        Proof.
          intros delta SUMLESS.
          set more_interf := fun tsk_k => x tsk_k >= delta.
          rewrite [\sum_(_ <- _) minn _ _](bigID more_interf) /=.
          unfold more_interf, minn.
          rewrite [\sum_(_ <- _ | delta <= _)_](eq_bigr (fun i => delta));
            last by intros i COND; rewrite leqNgt in COND; destruct (delta > x i).
          rewrite [\sum_(_ <- _ | ~~_)_](eq_big (fun i => x i < delta)
                                                (fun i => x i));
            [| by red; ins; rewrite ltnNge
             | by intros i COND; rewrite -ltnNge in COND; rewrite COND].

          (* Case 1: num_tasks_exceeding = 0 *)
          destruct (~~ has (fun i => delta <= x i) other_tasks) eqn:HASa.
          {
            rewrite [\sum_(_ <- _ | _ <= _) _]big_hasC; last by apply HASa.
            rewrite big_seq_cond; move: HASa => /hasPn HASa.
            rewrite add0n (eq_bigl (fun i => (i \in other_tasks) && true));
              last by red; intros tsk_k; destruct (tsk_k \in other_tasks) eqn:INk;
                [by rewrite andTb ltnNge; apply HASa | by rewrite andFb].
            by rewrite -big_seq_cond.
          } apply negbFE in HASa.

          (* Case 2: num_tasks_exceeding >= num_cpus *)
          destruct (num_tasks_exceeding delta >= num_cpus) eqn:CARD.
          {
            apply leq_trans with (delta * num_tasks_exceeding delta);
              first by rewrite leq_mul2l; apply/orP; right.
            unfold num_tasks_exceeding; rewrite -sum1_count big_distrr /=.
            rewrite -[\sum_(_ <- _ | _) _]addn0.
            by apply leq_add; [by apply leq_sum; ins; rewrite muln1|by ins].
          } apply negbT in CARD; rewrite -ltnNge in CARD.

          (* Case 3: num_tasks_exceeding < num_cpus *)
          rewrite big_const_seq iter_addn addn0; fold num_tasks_exceeding.
          apply leq_trans with (n := delta * num_tasks_exceeding delta +
                                     delta * (num_cpus - num_tasks_exceeding delta));
            first by rewrite -mulnDr subnKC //; apply ltnW.
          rewrite leq_add2l; apply bertogna_edf_interference_in_non_full_processors.
          by apply/andP; split; first by rewrite -has_count.
        Qed.

        (* 7) Next, using lemmas (0), (4) and (6) we prove that the reduction-based
              interference bound is not enough to cover the sum of the minima over all tasks
              (artifact of the proof by contradiction). *)
        Lemma bertogna_edf_sum_exceeds_total_interference:
          \sum_((tsk_other, R_other) <- rt_bounds | other_task tsk_other)
            minn (x tsk_other) (R - task_cost tsk + 1) > I tsk R.
        Proof.
          have GE_COST := bertogna_edf_R_other_ge_cost.
          have EXCEEDS := bertogna_edf_minimum_exceeds_interference.
          have ALLBUSY := bertogna_edf_interference_on_all_cpus.
          have TOOMUCH := bertogna_edf_too_much_interference.
          rename H_rt_bounds_contains_all_tasks into UNZIP,
            H_response_time_is_fixed_point into REC.
          apply leq_trans with (n := \sum_(tsk_other <- other_tasks) minn (x tsk_other) (R - task_cost tsk + 1));
            last first.
          {
            rewrite (eq_bigr (fun i => minn (x (fst i)) (R - task_cost tsk + 1)));
              last by ins; destruct i.
            move: UNZIP => UNZIP.
            assert (FILTER: filter other_task (unzip1 rt_bounds) =
                            filter other_task ts).
              by f_equal.
            unfold other_tasks; rewrite -FILTER; clear FILTER.
            rewrite -[\sum_(_ <- rt_bounds | _)_]big_filter.
            assert (SUBST: [seq i <- rt_bounds
                             | let '(tsk_other, _) := i in other_task tsk_other] =
                           [seq i <- rt_bounds | other_task (fst i)]).
            {
              by apply eq_filter; red; intro i; destruct i.
            } rewrite SUBST; clear SUBST.
            have MAP := big_map (fun x => fst x) (fun i => true) (fun i => minn (x i) (R - task_cost tsk + 1)).
            by rewrite -MAP; apply eq_leq; f_equal; rewrite filter_map.
          }

          apply ltn_div_trunc with (d := num_cpus); first by apply H_at_least_one_cpu.
          rewrite -(ltn_add2l (task_cost tsk)) -REC; last by done.
          rewrite -addn1 -leq_subLR.
          rewrite -[R + 1 - _]subh1; last by apply GE_COST.
          rewrite leq_divRL; last by apply H_at_least_one_cpu.
          apply EXCEEDS.
          apply leq_trans with (n := X * num_cpus); last by rewrite ALLBUSY.
          by rewrite leq_mul2r; apply/orP; right; apply TOOMUCH.
        Qed.

        (* 8) After concluding that the sum of the minima exceeds (R - e_i + 1),
              we prove that there exists a tuple (tsk_k, R_k) that satisfies
              min (x_k, R - e_i + 1) > min (W_k, I_edf, R - e_i + 1).
              This implies that either x_k > W_k or x_k > I_edf, which is a contradiction,
              since both W_k and I_edf are valid task interference bounds. *)
        Lemma bertogna_edf_exists_task_that_exceeds_bound :
          exists tsk_other R_other,
            (tsk_other, R_other) \in rt_bounds /\
            (minn (x tsk_other) (R - task_cost tsk + 1) > interference_bound tsk_other R_other).
        Proof.
          have SUM := bertogna_edf_sum_exceeds_total_interference.
          have BOUND := bertogna_edf_workload_bounds_interference.
          have EDFBOUND := bertogna_edf_specific_bound_holds.
          rename H_rt_bounds_contains_all_tasks into UNZIP.
          assert (HAS: has (fun tup : task_with_response_time =>
                              let (tsk_other, R_other) := tup in
                              (tsk_other \in ts) && other_task tsk_other &&
                                (minn (x tsk_other) (R - task_cost tsk + 1)  >
                                interference_bound tsk_other R_other))
                           rt_bounds).
          {
            apply/negP; unfold not; intro NOTHAS.
            move: NOTHAS => /negP /hasPn ALL.
            rewrite -[_ < _]negbK in SUM.
            move: SUM => /negP SUM; apply SUM; rewrite -leqNgt.
            unfold I, total_interference_bound_edf.
            rewrite big_seq_cond [\sum_(_ <- _ | let _ := _ in _)_]big_seq_cond.
            apply leq_sum; move => tsk_k /andP [INBOUNDSk INTERFk]; destruct tsk_k as [tsk_k R_k].
            specialize (ALL (tsk_k, R_k) INBOUNDSk).
            unfold interference_bound_edf; simpl in *.
            rewrite leq_min; apply/andP; split.
            {
              unfold interference_bound; rewrite leq_min; apply/andP; split;
                last by rewrite geq_minr.
              by apply leq_trans with (n := x tsk_k);
                [by rewrite geq_minl | by apply BOUND].
            }
            {
              apply leq_trans with (n := x tsk_k); first by rewrite geq_minl.
              by apply EDFBOUND.
            }
          }
          move: HAS => /hasP HAS; destruct HAS as [[tsk_k R_k] HPk MIN].
          move: MIN => /andP [/andP [INts INTERFk] MINk].
          by exists tsk_k, R_k; repeat split.
        Qed.

      End DerivingContradiction.

    End Lemmas.

    Section MainProof.

      (* Let (tsk, R) be any task to be analyzed, with its response-time bound R. *)
      Variable tsk: sporadic_task.
      Variable R: time.
      Hypothesis H_tsk_R_in_rt_bounds: (tsk, R) \in rt_bounds.

      (* Using the lemmas above, we prove that R bounds the response time of task tsk. *)
      Theorem bertogna_cirinei_response_time_bound_edf :
        response_time_bounded_by tsk (task_jitter tsk + R).
      Proof.
        have EXISTS := bertogna_edf_exists_task_that_exceeds_bound.
        have BASICBOUND := bertogna_edf_workload_bounds_interference.
        have EDFBOUND := bertogna_edf_specific_bound_holds.
        rename H_valid_job_parameters into JOBPARAMS.
        unfold valid_sporadic_job_with_jitter, valid_sporadic_job in *.
        intros j ARRj JOBtsk.

        rewrite addnA.
        (* First, rewrite the claim in terms of the *absolute* response-time bound (arrival + R) *)
        remember (job_arrival j + task_jitter tsk + R) as ctime.

        revert H_tsk_R_in_rt_bounds.
        generalize dependent R; generalize dependent tsk; generalize dependent j.

        (* Now, we apply strong induction on the absolute response-time bound. *)
        induction ctime as [ctime IH] using strong_ind.

        intros j ARRj tsk' JOBtsk R' EQc INbounds; subst ctime.

        (* First, let's simplify the induction hypothesis. *)
        assert (BEFOREok: forall j0 tsk R0,
                                 arrives_in arr_seq j0 ->
                                 job_task j0 = tsk ->
                               (tsk, R0) \in rt_bounds ->
                               job_arrival j0 + task_jitter tsk + R0 < job_arrival j + task_jitter tsk' + R' ->
                               service sched j0 (job_arrival j0 + task_jitter tsk + R0) == job_cost j0).
        {
            by ins; apply IH with (tsk := tsk0) (R := R0).
        }
        clear IH.

        (* The proof follows by contradiction. Assume that job j does not complete by its
           response-time bound. By the induction hypothesis, all jobs with absolute
           response-time bound t < (job_arrival j + R) have correct response-time bounds. *)
        destruct (completed job_cost sched j (job_arrival j + job_jitter j + R')) eqn:NOTCOMP.
        {
          apply completion_monotonic with (t := job_arrival j + job_jitter j + R'); try (by done).
          rewrite leq_add2r leq_add2l.
          specialize (JOBPARAMS j ARRj); des.
          by rewrite -JOBtsk; apply JOBPARAMS0.
        }
        apply negbT in NOTCOMP; exfalso.

        (* Next, we derive a contradiction using the previous lemmas. *)
        exploit (EXISTS tsk' R' INbounds j ARRj JOBtsk NOTCOMP).
        {
          by ins; apply IH with (tsk := tsk_other) (R := R_other).
        }
        intro EX; destruct EX as [tsk_other [R_other [HP LTmin]]].
        unfold interference_bound_edf, interference_bound_generic in LTmin.
        rewrite minnAC in LTmin; apply min_lt_same in LTmin.
        specialize (BASICBOUND tsk' R' j ARRj JOBtsk BEFOREok tsk_other R_other HP).
        specialize (EDFBOUND tsk' R' INbounds j ARRj JOBtsk BEFOREok tsk_other R_other HP).
        unfold minn in LTmin; clear -LTmin HP BASICBOUND EDFBOUND tsk; desf.
        {
          by apply (leq_ltn_trans BASICBOUND) in LTmin; rewrite ltnn in LTmin.
        }
        {
          by apply (leq_ltn_trans EDFBOUND) in LTmin; rewrite ltnn in LTmin.
        }
      Qed.

    End MainProof.

  End ResponseTimeBound.

End ResponseTimeAnalysisEDFJitter.


Require Import Arith.
Require Import Program.
Require Import Compare_dec.

Require Import Axioms.
Require Import TypeSyntax.

Set Implicit Arguments.

Inductive ty_environment : nat -> Type :=
| ty_nil  : ty_environment 0
| ty_cons : forall i, Set -> ty_environment i -> ty_environment (S i).

Notation "A ;: e" := (ty_cons A e) (at level 61, right associativity).

Definition lookup : forall j i, j < i -> ty_environment i -> Set.
fix 1. intros. destruct j.
 destruct X.
  elimtype False. inversion H.
  apply P.
 destruct X.
  elimtype False. inversion H.
  apply (lookup j i).
   apply lt_S_n. apply H.
   apply X.
Defined.

Definition lookup_var : forall g, variable g -> ty_environment g -> Set.
intros g v e. destruct v as [g i l]. apply (lookup l e).
Defined.

Inductive rel_environment : forall n, ty_environment n -> ty_environment n -> Type :=
| rel_nil  : rel_environment ty_nil ty_nil
| rel_cons : forall (n:nat) (A B:Set) (env1 env2:ty_environment n),
  (A -> B -> Prop) ->
  rel_environment env1 env2 ->
  rel_environment (A;:env1) (B;:env2).

Notation "R ;; re" := (rel_cons R re) (at level 61, right associativity).

Definition rel_lookup : forall i g (l : le (S i) g) e1 e2, rel_environment e1 e2 ->
   lookup l e1 -> lookup l e2 -> Prop.
induction i; intros.
 destruct X.
  elimtype False. inversion l.
  simpl in *. apply P; assumption.
 destruct X.
  elimtype False. inversion l.
  simpl in *. refine (IHi _ _ _ _ X H H0).
Defined.

Definition rel_lookup_var : forall g (v : variable g) e1 e2, rel_environment e1 e2 ->
  lookup_var v e1 -> lookup_var v e2 -> Prop.
intros. destruct v as [g i l]. eapply rel_lookup.
 apply X. apply H. apply H0.
Defined.

Definition diagonal : forall (g:nat) (e:ty_environment g), rel_environment e e.
intros. induction e.
 constructor.
 constructor.
  exact (@eq P).
  assumption.
Defined.

Definition ty_sem_rel (g:nat) (t:type g) :
  { ty_sem : ty_environment g -> Set
  & forall (e1 e2 : ty_environment g), rel_environment e1 e2 -> ty_sem e1 -> ty_sem e2 -> Prop }.
induction t.
 (* ty_var *)
 exists (fun e => lookup_var v e).
 intros e1 e2 re x1 x2.
 exact (rel_lookup_var v re x1 x2).
 (* ty_arr *)
 exists (fun e => (projT1 IHt1) e -> (projT1 IHt2) e).
 intros e1 e2 R f1 f2.
 exact (forall (x1 : projT1 IHt1 e1) (x2 : projT1 IHt1 e2), projT2 IHt1 e1 e2 R x1 x2 ->
                                                            projT2 IHt2 e1 e2 R (f1 x1) (f2 x2)).
 (* ty_forall *)
 exists (fun e => { x : forall (A:Set), (projT1 IHt) (A;:e)
                  | forall (A1 A2 : Set) (R : A1 -> A2 -> Prop),
                        (projT2 IHt) (A1;:e) (A2;:e) (R;;diagonal e) (x A1) (x A2) }).
 intros e1 e2 re x1 x2.
 exact (forall (A1 A2 : Set) (R : A1 -> A2 -> Prop),
           projT2 IHt (A1;:e1) (A2;:e2) (R;;re) (projT1 x1 A1) (projT1 x2 A2)).
Defined.

Definition ty_sem (g:nat) (e:ty_environment g) (t:type g) : Set.
apply (projT1 (ty_sem_rel t) e).
Defined.

Definition ty_rel (g:nat) (e1 e2:ty_environment g) (re:rel_environment e1 e2) (t:type g) :
   ty_sem e1 t -> ty_sem e2 t -> Prop.
unfold ty_sem.
intros.
apply (projT2 (ty_sem_rel t) e1 e2 re H H0).
Defined.

Lemma rel_lookup_diagonal : forall g (e:ty_environment g) i (l:le (S i) g) x y,
  rel_lookup l (diagonal e) x y <-> x = y.
induction e; intros; simpl in *.
 inversion l.
 destruct i0; simpl.
  reflexivity.
  apply IHe.
Save.

Lemma rel_lookup_var_diagonal : forall g (e : ty_environment g) (v : variable g) x y,
  rel_lookup_var v (diagonal e) x y <-> x = y.
intros. destruct v as [g i l]. simpl. apply rel_lookup_diagonal.
Save.

Lemma rel_diagonal : forall g (e:ty_environment g) ty x y, ty_rel (diagonal e) ty x y <-> x = y.
unfold ty_rel. unfold ty_sem. induction ty; simpl; intros.
 (* ty_var *)
 apply rel_lookup_var_diagonal.
 (* ty_arr *)
 split; intros.
  ext z. rewrite <- IHty2. apply H. rewrite IHty1. reflexivity.
  rewrite IHty2. rewrite IHty1 in H0. subst. reflexivity.
 (* ty_forall *)
 destruct x as [x x_rel]. destruct y as [y y_rel]. simpl in *.
 split; intros.
  apply sig_eq. simpl. ext A. rewrite <- IHty. apply H.
  inversion H. subst. apply x_rel.
Save.


Require Export PredMonad.Reflection.OrderedType.
Require Export PredMonad.Reflection.OrderedContext.
Require Export PredMonad.Reflection.OExpr_typed.

(***
 *** The monad typeclass
 ***)

Class MonadOps M `{OTypeF M} : Type :=
  { returnM : forall {A} `{OType A}, A -o> M A _ _;
    bindM : forall {A B} `{OType A} `{OType B},
        M A _ _ -o> (A -o> M B _ _) -o> M B _ _ }.

Class Monad M `{MonadOps M} : Prop :=
  {
    monad_return_bind :
      forall A B `{OType A} `{OType B} (f: A -o> M B _ _) x,
        bindM @o@ (returnM @o@ x) @o@ f =o= f @o@ x;

    monad_bind_return :
      forall A `{OType A} m prp,
        bindM @o@ m @o@ (ofun (fun x => returnM @o@ x) (prp:=prp)) =o= m;

    monad_assoc :
      forall A B C `{OType A} `{OType B} `{OType C}
             m (f: A -o> M B _ _) (g: B -o> M C _ _) prp,
        bindM @o@ (bindM @o@ m @o@ f) @o@ g
        =o=
        bindM @o@ m @o@ (ofun (fun x => bindM @o@ (f @o@ x) @o@ g) (prp:=prp));
  }.

(* Helpful bind notation *)
Notation "'do' x <- m1 ; m2" :=
  (bindM @o@ m1 @o@ (ofun (fun x => m2))) (at level 60, right associativity).

(***
 *** The Monad Laws for OExprs
 ***)

(* Return-bind law for OExprs *)
Lemma monad_return_bind_OExpr
      {ctx} `{ValidCtx ctx} `{Monad} {A B} `{OType A} `{OType B}
      (f: OExpr ctx (A -o> M B _ _)) (x: OExpr ctx A)
      {validF: ValidOExpr f} {validX: ValidOExpr x} :
  App (App (Embed bindM) (App (Embed returnM) x)) f
  =e= (App f x).
Proof.
  apply unquote_eq. intro. apply monad_return_bind.
Qed.

(* Bind-return law for OExprs *)
Lemma monad_bind_return_OExpr
      {ctx} `{ValidCtx ctx} `{Monad} {A} `{OType A} (m: OExpr ctx (M A _ _))
      {validM: ValidOExpr m} :
  App (App (Embed bindM) m) (Lam (App (Embed returnM) (Var OVar_0))) =e= m.
Proof.
  apply unquote_eq. intro. apply monad_bind_return.
Qed.

(* Associativity law for OExprs *)
Lemma monad_assoc_OExpr
      {ctx} `{ValidCtx ctx} `{Monad} {A B C} `{OType A} `{OType B} `{OType C}
      m (f: OExpr ctx (A -o> M B _ _)) (g: OExpr ctx (B -o> M C _ _))
      {validM: @ValidOExpr ctx (M A _ _) _ m}
      {validF: ValidOExpr f} {validG: ValidOExpr g} :
  App (App (Embed bindM) (App (App (Embed bindM) m) f)) g =e=
  App (App (Embed bindM) m)
      (Lam (App (App (Embed bindM)
                     (App (weakenOExpr 0 A f) (Var OVar_0)))
                (weakenOExpr 0 A g))).
Proof.
  apply unquote_eq. intro. simpl. apply monad_assoc.
Qed.

(* Add the monad laws to the OT rewrite set *)
Hint Rewrite @monad_return_bind_OExpr @monad_bind_return_OExpr
     @monad_assoc_OExpr : osimpl.

(***
 *** The Identity Monad
 ***)

Definition Identity A `{OType A} := A.

Instance OTRelationF_Identity : OTRelationF Identity :=
  fun _ R _ => R.

Instance OTypeF_Identity : OTypeF Identity :=
  fun _ _ ot => ot.

Instance IdMonad_MonadOps : MonadOps Identity :=
  { returnM := fun A _ _ => ofun (fun x => x);
    bindM := fun A B _ _ _ _ =>
               ofun (fun m => ofun (fun (f:A -o> B) => f @o@ m)) }.

Instance IdMonad : Monad Identity.
Proof.
  econstructor; intros; simpl; reflexivity.
Qed.


(* --------------------------------------------------------------------
 * Copyright (c) - 2006--2012 - IMDEA Software Institute
 * Copyright (c) - 2006--2012 - Inria
 * Copyright (c) - 2006--2012 - Microsoft Coprporation
 *
 * Distributed under the terms of the CeCILL-B-V1 license
 * -------------------------------------------------------------------- *)

(*************************************************************)
(*      This file is distributed under the terms of the      *)
(*      GNU Lesser General Public License Version 2.1        *)
(*************************************************************)
(*    Benjamin.Gregoire@inria.fr Laurent.Thery@inria.fr      *)
(*************************************************************)

(**********************************************************************
     ZCAux.v

     Auxillary functions & Theorems
 **********************************************************************)

Require Import ArithRing.
Require Export ZArith Zpow_facts.
Require Export Znumtheory.
Require Export Tactic.

Theorem Zdivide_div_prime_le_square:  forall x, 1 < x -> ~prime x -> exists p, prime p /\ (p | x) /\ p * p <= x.
intros x Hx; generalize Hx; pattern x; apply Z_lt_induction; auto with zarith.
clear x Hx; intros x Rec H H1.
case (not_prime_divide x); auto.
intros x1 ((H2, H3), H4); case (prime_dec x1); intros H5.
case (Zle_or_lt (x1 * x1) x); intros H6.
exists x1; auto.
case H4; clear H4; intros x2 H4; subst.
assert (Hx2: x2 <= x1).
case (Zle_or_lt x2 x1); auto; intros H8; contradict H6; apply Zle_not_lt.
apply Zmult_le_compat_r; auto with zarith.
case (prime_dec x2); intros H7.
exists x2; repeat (split; auto with zarith).
apply Zmult_le_compat_l; auto with zarith.
apply Zle_trans with 2%Z; try apply prime_ge_2; auto with zarith.
case (Zle_or_lt 0 x2); intros H8.
case Zle_lt_or_eq with (1 := H8); auto with zarith; clear H8; intros H8; subst; auto with zarith.
case (Zle_lt_or_eq 1 x2); auto with zarith; clear H8; intros H8; subst; auto with zarith.
case (Rec x2); try split; auto with zarith.
intros x3 (H9, (H10, H11)).
exists x3; repeat (split; auto with zarith).
contradict H; apply Zle_not_lt; auto with zarith.
apply Zle_trans with (0 * x1);  auto with zarith.
case (Rec x1); try split; auto with zarith.
intros x3 (H9, (H10, H11)).
exists x3; repeat (split; auto with zarith).
apply Zdivide_trans with x1; auto with zarith.
Qed.

Theorem Zmult_interval: forall p q, 0 < p * q  -> 1 < p -> 0 < q < p * q.
intros p q H1 H2; assert (0 < q).
case (Zle_or_lt q 0); auto; intros H3; contradict H1; apply Zle_not_lt.
rewrite <- (Zmult_0_r p).
apply Zmult_le_compat_l; auto with zarith.
split; auto.
pattern q at 1; rewrite <- (Zmult_1_l q).
apply Zmult_lt_compat_r; auto with zarith.
Qed.

Theorem prime_induction: forall (P: Z -> Prop), P 0 -> P 1 -> (forall p q, prime p -> P q -> P (p * q)) -> forall p, 0 <= p -> P p.
intros P H H1 H2 p Hp.
generalize Hp; pattern p; apply Z_lt_induction; auto; clear p Hp.
intros p Rec Hp.
case Zle_lt_or_eq with (1 := Hp); clear Hp; intros Hp; subst; auto.
case (Zle_lt_or_eq  1 p); auto with zarith; clear Hp; intros Hp; subst; auto.
case (prime_dec p); intros H3.
rewrite <- (Zmult_1_r p); apply H2; auto.
 case (Zdivide_div_prime_le_square p); auto.
intros q (Hq1, ((q2, Hq2), Hq3)); subst.
case (Zmult_interval q q2).
rewrite Zmult_comm; apply Zlt_trans with 1; auto with zarith.
apply Zlt_le_trans with 2; auto with zarith; apply prime_ge_2; auto.
intros H4 H5; rewrite Zmult_comm; apply H2; auto.
apply Rec; try split; auto with zarith.
rewrite Zmult_comm; auto.
Qed.

Theorem div_power_max: forall p q, 1 < p -> 0 < q -> exists n, 0 <= n /\ (p ^n | q)  /\ ~(p ^(1 + n) | q).
intros p q H1 H2; generalize H2; pattern q; apply Z_lt_induction; auto with zarith; clear q H2.
intros q Rec H2.
case (Zdivide_dec p q); intros H3.
case (Zdivide_Zdiv_lt_pos p q); auto with zarith; intros H4 H5.
case (Rec (Zdiv q p)); auto with zarith.
intros n (Ha1, (Ha2, Ha3)); exists (n + 1); split; auto with zarith; split.
case Ha2; intros q1 Hq; exists q1.
rewrite Zpower_exp; try rewrite Zpower_1_r; auto with zarith.
rewrite  Zmult_assoc; rewrite <- Hq.
rewrite Zmult_comm; apply Zdivide_Zdiv_eq; auto with zarith.
intros (q1, Hu); case Ha3; exists q1.
apply Zmult_reg_r with p; auto with zarith.
rewrite (Zmult_comm (q / p)); rewrite <- Zdivide_Zdiv_eq; auto with zarith.
apply trans_equal with (1 := Hu); repeat rewrite Zpower_exp; try rewrite Zpower_exp_1; auto with zarith.
ring.
exists 0; repeat split; try rewrite Zpower_1_r; try rewrite Zpower_exp_0; auto with zarith.
Qed.

Theorem prime_div_induction:
  forall (P: Z -> Prop) n,
    0 < n ->
    (P 1) ->
    (forall p i, prime p -> 0 <= i -> (p^i | n) -> P (p^i)) ->
    (forall p q, rel_prime p q -> P p -> P q -> P (p * q)) ->
   forall m, 0 <= m -> (m | n) -> P m.
intros P n P1 Hn H H1 m Hm.
generalize Hm; pattern m; apply Z_lt_induction; auto; clear m Hm.
intros m Rec Hm H2.
case (prime_dec m); intros Hm1.
rewrite <- Zpower_1_r; apply H; auto with zarith.
rewrite Zpower_1_r; auto.
case Zle_lt_or_eq with (1 := Hm); clear Hm; intros Hm; subst.
2: contradict P1; case H2; intros; subst; auto with zarith.
case (Zle_lt_or_eq 1 m); auto with zarith; clear Hm; intros Hm; subst; auto.
case Zdivide_div_prime_le_square with m; auto.
intros p (Hp1, (Hp2, Hp3)).
case (div_power_max p m); auto with zarith.
generalize (prime_ge_2 p Hp1); auto with zarith.
intros i (Hi, (Hi1, Hi2)).
case Zle_lt_or_eq with (1 := Hi); clear Hi; intros Hi.
assert (Hpi: 0 < p ^ i).
apply Zpower_gt_0; auto with zarith.
apply Zlt_le_trans with 2; try apply prime_ge_2; auto with zarith.
rewrite (Z_div_exact_2 m (p ^ i)); auto with zarith.
apply H1; auto with zarith.
apply rel_prime_sym; apply rel_prime_Zpower_r; auto.
apply rel_prime_sym.
apply prime_rel_prime; auto.
contradict Hi2.
case Hi1; intros; subst.
rewrite Z_div_mult in Hi2; auto with zarith.
case Hi2; intros q0 Hq0; subst.
exists q0; rewrite Zpower_exp; try rewrite Zpower_1_r; auto with zarith.
apply H; auto with zarith.
apply Zdivide_trans with (1 := Hi1); auto.
apply Rec; auto with zarith.
split; auto with zarith.
apply Z_div_pos; auto with zarith.
apply Z_div_lt; auto with zarith.
apply Zle_ge; apply Zle_trans with p.
apply prime_ge_2; auto.
pattern p at 1; rewrite <- Zpower_1_r; apply Zpower_le_monotone; auto with zarith.
apply Zlt_le_trans with 2; try apply prime_ge_2; auto with zarith.
apply Z_div_pos; auto with zarith.
apply Zdivide_trans with (2 := H2); auto.
exists (p ^ i); apply Z_div_exact_2; auto with zarith.
apply Zdivide_mod; auto with zarith.
apply Zdivide_mod; auto with zarith.
case Hi2; rewrite <- Hi; rewrite Zplus_0_r; rewrite Zpower_1_r; auto.
Qed.

Theorem prime_div_Zpower_prime: forall n p q, 0 <= n -> prime p -> prime q -> (p | q ^ n) -> p = q.
intros n p q Hp Hq; generalize p q Hq; pattern n; apply natlike_ind; auto; clear n p q Hp Hq.
intros  p q Hp Hq; rewrite Zpower_0_r.
intros (r, H); subst.
case (Zmult_interval p r); auto; try rewrite Zmult_comm.
rewrite <- H; auto with zarith.
apply Zlt_le_trans with 2; try apply prime_ge_2; auto with zarith.
rewrite <- H; intros H1 H2; contradict H2; auto with zarith.
intros n1 H Rec p q Hp Hq; try rewrite Zpower_Zsucc; auto with zarith; intros H1.
case prime_mult with (2 := H1); auto.
intros H2; apply prime_div_prime; auto.
Qed.

Definition Zmodd  a b :=
match a with
| Z0 => 0
| Zpos a' =>
    match b with
    | Z0 => 0
    | Zpos _ => Zmod_POS a' b
    | Zneg b' =>
        let r := Zmod_POS a' (Zpos b') in
        match r  with Z0 =>  0 |  _  =>   b + r end
    end
| Zneg a' =>
    match b with
    | Z0 => 0
    | Zpos _ =>
        let r := Zmod_POS a' b in
        match r with Z0 =>  0 | _  =>  b - r end
    | Zneg b' => - (Zmod_POS a' (Zpos b'))
    end
end.

Theorem Zmodd_correct: forall a b, Zmodd a b = Zmod a b.
intros a b; unfold Zmod; case a; simpl; auto.
intros p; case b; simpl; auto.
intros p1; refine (Zmod_POS_correct _ _); auto.
intros p1; rewrite Zmod_POS_correct; auto.
case (Zdiv_eucl_POS p (Zpos p1)); simpl; intros z1 z2; case z2; auto.
intros p; case b; simpl; auto.
intros p1; rewrite Zmod_POS_correct; auto.
case (Zdiv_eucl_POS p (Zpos p1)); simpl; intros z1 z2; case z2; auto.
intros p1; rewrite Zmod_POS_correct; simpl; auto.
case (Zdiv_eucl_POS p (Zpos p1)); auto.
Qed.

Theorem prime_divide_prime_eq:
 forall p1 p2, prime p1 -> prime p2 -> Zdivide p1 p2 ->  p1 = p2.
intros p1 p2 Hp1 Hp2 Hp3.
assert (Ha: 1 < p1).
inversion Hp1; auto.
assert (Ha1: 1 < p2).
inversion Hp2; auto.
case (Zle_lt_or_eq p1 p2); auto with zarith.
apply Zdivide_le; auto with zarith.
intros Hp4.
case (prime_div_prime p1 p2); auto with zarith.
Qed.

Theorem Zdivide_Zpower: forall n m, 0 < n -> (forall p i, prime p -> 0 < i -> (p^i | n) -> (p^i | m)) -> (n | m).
intros n m Hn; generalize m Hn; pattern n; apply prime_induction; auto with zarith; clear n m Hn.
intros m H1; contradict H1; auto with zarith.
intros p q H Rec m H1 H2.
assert (H3: (p | m)).
rewrite <- (Zpower_1_r p); apply H2; auto with zarith; rewrite Zpower_1_r; apply Zdivide_factor_r.
case (Zmult_interval p q); auto.
apply Zlt_le_trans with 2; auto with zarith; apply prime_ge_2; auto.
case H3; intros k Hk; subst.
intros Hq Hq1.
rewrite (Zmult_comm k); apply Zmult_divide_compat_l.
apply Rec; auto.
intros p1 i Hp1 Hp2 Hp3.
case (Z_eq_dec p p1); intros Hpp1; subst.
case (H2 p1 (Zsucc i)); auto with zarith.
rewrite Zpower_Zsucc; try apply Zmult_divide_compat_l; auto with zarith.
intros q2 Hq2; exists q2.
apply Zmult_reg_r with p1.
contradict H; subst; apply not_prime_0.
rewrite Hq2; rewrite Zpower_Zsucc; try ring; auto with zarith.
apply Gauss with p.
rewrite Zmult_comm; apply H2; auto.
apply Zdivide_trans with (1:= Hp3).
apply Zdivide_factor_l.
apply rel_prime_sym; apply rel_prime_Zpower_r; auto.
apply prime_rel_prime; auto.
contradict Hpp1; apply prime_divide_prime_eq; auto.
Qed.

Theorem prime_divide_Zpower_Zdiv: forall m a p i, 0 <= i -> prime p -> (m | a) -> ~(m | (a/p)) -> (p^i | a) -> (p^i | m).
intros m a p i Hi Hp (k, Hk) H (l, Hl); subst.
case (Zle_lt_or_eq 0 i); auto with arith; intros Hi1; subst.
assert (Hp0: 0 < p).
apply Zlt_le_trans with 2; auto with zarith; apply prime_ge_2; auto.
case (Zdivide_dec p k); intros H1.
case H1; intros k' H2; subst.
case H; replace (k' * p * m) with ((k' * m) * p); try ring; rewrite Z_div_mult; auto with zarith.
apply Gauss with k.
exists l; rewrite Hl; ring.
apply rel_prime_sym; apply rel_prime_Zpower_r; auto.
apply rel_prime_sym; apply prime_rel_prime; auto.
rewrite Zpower_0_r; apply Zone_divide.
Qed.

Theorem Zle_square_mult: forall a b, 0 <= a <= b -> a * a <= b * b.
intros a b (H1, H2); apply Zle_trans with (a * b); auto with zarith.
Qed.

Theorem Zlt_square_mult_inv: forall a b, 0 <= a -> 0 <= b -> a * a < b * b -> a < b.
intros a b H1 H2 H3; case (Zle_or_lt b a); auto; intros H4; apply Zmult_lt_reg_r with a;
   contradict H3; apply Zle_not_lt; apply Zle_square_mult; auto.
Qed.

Theorem Zmod_closeby_eq: forall a b n,  0 <= a -> 0 <= b < n -> a - b < n -> a mod n = b -> a = b.
intros a b n H H1 H2 H3.
case (Zle_or_lt 0 (a - b)); intros H4.
case Zle_lt_or_eq with (1 := H4); clear H4; intros H4; auto with zarith.
contradict H2; apply Zle_not_lt; apply Zdivide_le; auto with zarith.
apply Zmod_divide_minus; auto with zarith.
rewrite <- (Zmod_small a n); try split; auto with zarith.
Qed.

Theorem Zpow_mod_pos_Zpower_pos_correct: forall a m n, 0 < n -> Zpow_mod_pos a m n = (Zpower_pos a m) mod n.
intros a m; elim m; simpl; auto.
intros p Rec n H1; rewrite xI_succ_xO; rewrite Pplus_one_succ_r; rewrite <- Pplus_diag; auto.
repeat rewrite Zpower_pos_is_exp; auto.
repeat rewrite Rec; auto.
replace (Zpower_pos a 1) with a; auto.
2: unfold Zpower_pos; simpl; auto with zarith.
repeat rewrite (fun x => (Zmult_mod x a)); auto.
rewrite  (Zmult_mod  (Zpower_pos a p)); auto.
case (Zpower_pos a p mod n); auto.
intros p Rec n H1; rewrite <- Pplus_diag; auto.
repeat rewrite Zpower_pos_is_exp; auto.
repeat rewrite Rec; auto.
rewrite  (Zmult_mod  (Zpower_pos a p)); auto.
case (Zpower_pos a p mod n); auto.
unfold Zpower_pos; simpl; rewrite Zmult_1_r; auto with zarith.
Qed.

Theorem Zpow_mod_Zpower_correct: forall a m n, 1 < n -> 0 <= m -> Zpow_mod a m n = (a ^ m) mod n.
intros a m n; case m; simpl.
intros; apply sym_equal; apply Zmod_small; auto with zarith.
intros; apply Zpow_mod_pos_Zpower_pos_correct; auto with zarith.
intros p H H1; case H1; auto.
Qed.