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

Module ResponseTimeAnalysisEDF.

  Export Job SporadicTaskset ScheduleOfSporadicTask Workload Schedulability ResponseTime
         Priority TaskArrival WorkloadBound InterferenceBoundEDF
         Interference Platform Affinity ConstrainedDeadlines.

  (* In this section, we prove that any fixed point in the APA-reduction of
     Bertogna and Cirinei's RTA for EDF scheduling is a safe response-time bound.
     This result corresponds to Lemma 10 in the revised version of the APA paper:
     http://www.mpi-sws.org/~bbb/papers/pdf/ecrts13a-rev1.pdf *)
  Section ResponseTimeBound.

    Context {sporadic_task: eqType}.
    Variable task_cost: sporadic_task -> time.
    Variable task_period: sporadic_task -> time.
    Variable task_deadline: 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.

    (* Assume any job arrival sequence... *)
    Variable arr_seq: arrival_sequence Job.

    (* ... in which jobs arrive sporadically and have valid parameters. *)
    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 task_cost task_deadline job_cost job_deadline job_task j.

    (* Consider a task set ts 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 assume 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.

    (* Also assume that every task has a non-empty processor affinity alpha. *)
    Context {num_cpus: nat}.
    Variable alpha: task_affinity sporadic_task num_cpus.

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

    (* ...jobs are sequential and do not execute before their
       arrival times nor longer than their execution costs. *)
    Hypothesis H_sequential_jobs: sequential_jobs sched.
    Hypothesis H_jobs_must_arrive_to_execute: jobs_must_arrive_to_execute job_arrival sched.
    Hypothesis H_completed_jobs_dont_execute: completed_jobs_dont_execute job_cost sched.

    (* Assume that the schedule is an work-conserving APA schedule that
       respects EDF priorities. *)
    Hypothesis H_respects_affinity: respects_affinity job_task sched alpha.
    Hypothesis H_work_conserving: apa_work_conserving job_arrival job_cost job_task arr_seq
                                                      sched alpha.
    Hypothesis H_edf_policy:
      respects_JLFP_policy_under_weak_APA job_arrival job_cost job_task arr_seq
                                          sched alpha (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.

    (* Now we consider the response-time recurrence. In the computation of
       the response-time bound, we assume that each task under analysis has
       a non-empty subaffinity alpha'.
       Note that the notation #|...| expresses the cardinality of the set. *)
    Variable alpha': task_affinity sporadic_task num_cpus.
    Hypothesis H_affinity_subset: forall tsk, tsk \in ts -> is_subaffinity (alpha' tsk) (alpha tsk).
    Hypothesis H_at_least_one_cpu : forall tsk, tsk \in ts -> #|alpha' tsk| > 0.

    (* 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.

    (* ... where R is a fixed-point of the response-time recurrence (with
           alpha' as the reduced affinity mask), ... *)
    Let I (tsk: sporadic_task) (delta: time) :=
      total_interference_bound_edf task_cost task_period task_deadline alpha
                                   tsk (alpha' 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) #|alpha' tsk|.

    (* ..., and R is no larger than the deadline. *)
    Hypothesis H_tasks_miss_no_deadlines:
      forall tsk R,
        (tsk, R) \in rt_bounds -> 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.

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

      (* ... and that 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 + R_other < job_arrival j + R ->
          completed job_cost sched j_other (job_arrival j_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 sched alpha j
                          tsk_other (job_arrival j) (job_arrival j + R).

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

      (* Recall Bertogna and Cirinei's workload bound ... *)
      Let workload_bound (tsk_other: sporadic_task) (R_other: time) :=
        W task_cost task_period 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 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 tsk R (tsk_other, R_other).

      (* Based on the definition of a different task in subaffinity alpha', ... *)
      Let other_task_in alpha' := different_task_in alpha tsk alpha'.

      (* ...let (other_tasks_in alpha') denote the set of tasks that are different from tsk
         and that can be scheduled on subaffinity alpha'. *)
      Let other_tasks_in alpha' :=
        [seq tsk_other <- ts | other_task_in (alpha' tsk) 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 the task set, ...*)
        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.

        (* ... and 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.
          have INts := bertogna_edf_tsk_other_in_ts.
          apply leq_trans with (n := workload job_task sched tsk_other
                                         (job_arrival j) (job_arrival j + R));
            first by apply task_interference_le_workload.
          by apply workload_bounded_by_W with (task_deadline0 := task_deadline)
             (job_arrival0 := job_arrival) (arr_seq0 := arr_seq)
             (job_cost0 := job_cost) (job_deadline0 := job_deadline); try (by ins); last 2 first;
            [ by apply bertogna_edf_R_other_ge_cost
            | by ins; apply NOMISS
            | by ins; apply TASK_PARAMS
            | by ins; apply RESTR
            | by ins; apply BEFOREok with (tsk_other := tsk_other)].
        Qed.

        (* Recall that the edf-specific interference bound also holds for tsk_other. *)
        Lemma bertogna_edf_specific_bound_holds :
          x tsk_other <= edf_specific_bound tsk_other R_other.
        Proof.
          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 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 exceeds  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 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 -ltnNge in NOTCOMP.
        apply leq_ltn_trans with (n := (\sum_(job_arrival j <= t < job_arrival j + R)
                                     backlogged job_arrival job_cost sched j t) +
                                   service sched j (job_arrival j + 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 service_before_arrival_eq_service_during //.
        rewrite -big_split /=.
        apply leq_trans with (n := \sum_(job_arrival j <= i < job_arrival j + R) 1);
          first by rewrite big_const_nat iter_addn mul1n addn0 addKn.
        rewrite big_nat_cond [\sum_(_ <= _ < _ | true) _]big_nat_cond.
        apply leq_sum; move => i /andP [/andP [GEi LTi] _].
        destruct (backlogged job_arrival job_cost 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,
          job_arrival j <= t < job_arrival j + R ->
          arrives_in arr_seq j_other ->
          backlogged job_arrival job_cost 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_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 RESTR.
        move => t j_other /andP [LEt GEt] ARRother BACK SCHED.
        apply/eqP; red; intro SAMEtsk.
        move: SCHED => /existsP [cpu SCHED].
        assert (SCHED': scheduled sched j_other t).
          by apply/existsP; exists cpu.
        clear SCHED; rename SCHED' into SCHED.
        move: (SCHED) => PENDING.
        apply scheduled_implies_pending with (job_arrival0 := job_arrival) (job_cost0 := job_cost)
           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.
          specialize (BEFOREok j_other tsk R ARRother SAMEtsk INbounds LT).
          move: PENDING => /andP [_ /negP NOTCOMP]; apply NOTCOMP.
          apply completion_monotonic with (t0 := job_arrival j_other + R); try (by done).
          apply leq_trans with (n := job_arrival j); last by done.
          apply leq_trans with (n := job_arrival j_other + task_deadline tsk);
            first by rewrite leq_add2l; apply NOMISS.
          apply leq_trans with (n := job_arrival j_other + task_period tsk);
            first by rewrite leq_add2l; apply RESTR; rewrite -JOBtsk FROMTS.
          rewrite -SAMEtsk; apply SPO; try (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.
            apply leq_ltn_trans with (n := t); first by done.
            apply leq_trans with (n := job_arrival j + R); first by done.
            by rewrite leq_add2l; apply leq_trans with (n := task_deadline tsk);
              [by apply NOMISS | by rewrite JOBtsk RESTR // -JOBtsk FROMTS].
          }
          by red; intros EQtsk; subst; 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 (job_arrival j + 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,
          arrives_in arr_seq j0 ->
          t < job_arrival j + R ->
          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_rt_bounds_contains_all_tasks into UNZIP,
               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.
        intros t j0 ARR0 LEt 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 + R0).
        {
          rewrite 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 by done.
        apply leq_trans with (n := job_arrival j0 + task_period (job_task j0)); last by done.
        by rewrite leq_add2l; apply leq_trans with (n := task_deadline (job_task j0));
          [by apply NOMISS | apply CONSTR; rewrite FROMTS].
      Qed.

      (* 3) Next, we prove that the sum of the interference of each task is equal to the
            total interference multiplied by the number of processors in tsk's *actual*
            affinity. This holds because interference only occurs when all processors in
            the affinity are busy.
            With this lemma we can relate per-task interference with the total interference
            incurred by j (backlogged time). *)
      Lemma bertogna_edf_all_cpus_in_affinity_busy :
        \sum_(tsk_k <- other_tasks_in alpha) x tsk_k = X * #|alpha tsk|.
      Proof.
        have DIFFTASK := bertogna_edf_interference_by_different_tasks.
        rename H_all_jobs_from_taskset into FROMTS,
               H_valid_task_parameters into PARAMS, H_jobs_come_from_arrival_sequence into FROMSEQ,
               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_rt_bounds_contains_all_tasks into UNZIP,
               H_constrained_deadlines into RESTR,
               H_respects_affinity into APA.
        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 sched j t) eqn:BACK; last first.
        {
          rewrite (eq_bigr (fun i => 0));
            first by rewrite big_const_seq iter_addn mul0n addn0.
          by intros i _; rewrite (eq_bigr (fun i => 0));
            first by rewrite big_const_seq iter_addn mul0n addn0.
        }
        rewrite big_mkcond /=.
        rewrite exchange_big /=.
        apply eq_trans with (y := \sum_(cpu < num_cpus | cpu \in alpha tsk) 1);
          last by rewrite sum1_card.
        rewrite [\sum_(_ < _ | _) 1]big_mkcond /=.
        apply eq_bigr; intros cpu _.
        unfold can_execute_on in *.
        destruct (cpu \in alpha (job_task j)) eqn:ALPHA; rewrite -?JOBtsk ALPHA;
          last by rewrite big_filter (eq_bigr (fun x => 0));
            [by simpl_sum_const | by ins].
        move: (WORK j t H_j_arrives BACK cpu ALPHA) => [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.
          rewrite big_const_seq iter_addn mul0n 2!addn0; apply/eqP; rewrite eqb1.
          by unfold task_scheduled_on; rewrite SCHED.
        }
        rewrite mem_filter; apply/andP; split; last by apply FROMTS.
        unfold different_task_in, affinity_intersects.
        apply/andP; split; last first.
        {
          apply/existsP; exists cpu; rewrite -JOBtsk ALPHA andTb.
          by apply APA with (t := t); apply/eqP.
        }
        apply DIFFTASK with (t := t); try (by done); first by auto.
        by apply/existsP; exists cpu; apply/eqP.
      Qed.

      (* 4) Recall that the reduction-based analysis considers only the interfering tasks
            within subaffinity (alpha' tsk), as opposed to (alpha tsk). Therefore, we must
            reason about the task interference wihin (alpha' tsk).
            We begin by showing that the cumulative interference within (alpha' tsk) is at
            least the total interference multiplied by the number of processors in (alpha' tsk). *)
      Lemma bertogna_edf_all_cpus_in_subaffinity_busy :
        \sum_(tsk_k <- other_tasks_in alpha') x tsk_k >= X * #|alpha' tsk|.
      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_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_respects_affinity into APA, H_affinity_subset into SUB.
        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 leq_sum_nat; move => t /andP [GEt LTt] _.
        destruct (backlogged job_arrival job_cost sched j t) eqn:BACK; last first.
        {
          rewrite (eq_bigr (fun i => 0));
            first by rewrite big_const_seq iter_addn mul0n addn0.
          by intros i _; rewrite (eq_bigr (fun i => 0));
            first by rewrite big_const_seq iter_addn mul0n addn0.
        }
        rewrite big_mkcond /=.
        rewrite exchange_big /=.
        apply leq_trans with (n := \sum_(cpu < num_cpus | cpu \in alpha' tsk) 1);
          first by rewrite sum1_card.
        rewrite [\sum_(_ < _ | _) 1]big_mkcond /=.
        apply leq_sum; intros cpu _.
        unfold can_execute_on in *.
        destruct (cpu \in alpha' (job_task j)) eqn:ALPHA'; rewrite -?JOBtsk ALPHA';
          last by done.
        feed (SUB (job_task j)); first by apply FROMTS.
        specialize (SUB cpu ALPHA').
        move: (WORK j t H_j_arrives BACK cpu SUB) => [j_other /eqP SCHED]; unfold scheduled_on in *.
        have ARRother: arrives_in arr_seq j_other.
          by apply (H_jobs_come_from_arrival_sequence j_other t); apply/existsP; exists cpu; apply/eqP.
        rewrite (bigD1_seq (job_task j_other)) /=; last by apply filter_uniq; destruct ts.
        {
          by rewrite {1}/task_scheduled_on SUB SCHED eq_refl andTb.
        }
        {
          rewrite mem_filter; apply/andP; split; last by apply FROMTS.
          apply/andP; split; last first.
          {
            apply/existsP; exists cpu; apply/andP; split; first by rewrite -JOBtsk.
            by apply APA with (t := t); apply/eqP.
          }
          apply DIFFTASK with (t := t); try (by done); first by auto.
          by apply/existsP; exists cpu; apply/eqP.
        }
      Qed.

      (* Let's define a predicate for whether a task is scheduled on (alpha tsk). *)
      Let scheduled_on_alpha_tsk := fun t tsk_k =>
        task_scheduled_on_affinity job_task sched (alpha tsk) tsk_k t.

      (* 5) Now we prove that, at all times that j is backlogged, the number
            of tasks whose affinity intersects (alpha' tsk) that are in fact
            scheduled on (alpha' tsk) is at least the size of (alpha' tsk).
            This is required to prove lemma (6). *)
      Lemma bertogna_edf_alpha'_is_full:
        forall t,
          job_arrival j <= t < job_arrival j + R ->
          backlogged job_arrival job_cost sched j t ->
          count (scheduled_on_alpha_tsk t) (other_tasks_in alpha') >= #|alpha' tsk|.
      Proof.
        have COMP := bertogna_edf_all_previous_jobs_complete_by_their_period.
        rename H_work_conserving into WORK, H_respects_affinity into APA,
               H_affinity_subset into SUB, H_job_of_tsk into JOBtsk,
               H_all_jobs_from_taskset into FROMTS, H_jobs_come_from_arrival_sequence into FROMSEQ,
               H_valid_task_parameters into PARAMS,
               H_sequential_jobs into SEQ.
        move => t /andP [GEt LTt] BACK.
        move: WORK  => WORK.
        specialize (WORK j t H_j_arrives BACK).
        rewrite -size_filter.
        apply leq_trans with (n := size (alpha' tsk));
          first by apply card_size.
        apply leq_trans with (n := size (pmap (fun cpu => sched cpu t) (enum (alpha' tsk)))).
        {
          rewrite size_pmap -size_filter.
          apply uniq_leq_size; first by destruct (alpha' tsk).
          intros cpu IN.
          rewrite mem_filter; apply/andP; split; last by rewrite mem_enum.
          feed (WORK cpu); first by apply SUB; rewrite ?FROMTS ?JOBtsk.
          by move: WORK => [j_other /eqP SCHED]; rewrite SCHED.
        }
        {
          apply leq_trans with (n := size (map (fun j => job_task j) (pmap (fun cpu => sched cpu t) (enum (alpha' tsk)))));
            first by rewrite size_map.
          apply uniq_leq_size.
          {
            rewrite map_inj_in_uniq.
            {
              apply pmap_inj_in_uniq; last by apply enum_uniq.
              intros cpu1 cpu2 IN1 IN2 SCHED2.
              destruct (sched cpu1 t) as [j0|] eqn:SCHED1; symmetry in SCHED2;
                first by apply SEQ with (j := j0) (t := t).
              rewrite 2!mem_enum in IN1 IN2.
              exploit (WORK cpu1); first by apply SUB; rewrite ?FROMTS ?JOBtsk.
              by move => [j_other SCHED]; rewrite /scheduled_on SCHED1 in SCHED.
            }
            {
              intros j1 j2 SCHED1 SCHED2 SAMEtsk.
              rewrite 2!mem_pmap in SCHED1 SCHED2.
              move: SCHED1 SCHED2 => /mapP [cpu1 IN1 SCHED1] /mapP [cpu2 IN2 SCHED2].
              have ARR1: arrives_in arr_seq j1.
                by apply (FROMSEQ j1 t); apply/existsP; exists cpu1; apply/eqP.
              have ARR2: arrives_in arr_seq j2.
                by apply (FROMSEQ j2 t); apply/existsP; exists cpu2; apply/eqP.
              assert (PENDING1: pending job_arrival job_cost sched j1 t).
              {
                apply scheduled_implies_pending; try by done.
                by apply/existsP; exists cpu1; rewrite /scheduled_on -SCHED1.
              }
              assert (SCHED2': pending job_arrival job_cost sched j2 t).
              {
                apply scheduled_implies_pending; try by done.
                by apply/existsP; exists cpu2; rewrite /scheduled_on -SCHED2.
              }
              apply platform_at_most_one_pending_job_of_each_task with (task_cost0 := task_cost)
              (task_period0 := task_period) (task_deadline0 := task_deadline) (tsk0 := tsk)
              (job_cost0 := job_cost) (job_task0 := job_task) (sched0 := sched) (j0 := j) (t0 := t)
              (job_arrival0 := job_arrival) (arr_seq0 := arr_seq);
                rewrite ?JOBtsk ?SAMEtsk //; first by apply PARAMS; rewrite -JOBtsk FROMTS.
              intros j0 tsk0 ARR0 TSK0 LE.
              by apply (COMP t); rewrite ?TSK0.
            }
          }
          {
            move => tsk' /mapP [j' IN EQtsk'].
            rewrite mem_pmap in IN.
            move: IN => /mapP [cpu INcpu SCHED'].
            rewrite mem_enum in INcpu.
            rewrite mem_filter; apply/andP; split.
            {
              apply/existsP; exists cpu; apply/andP; split;
                 first by apply SUB; rewrite -?JOBtsk ?FROMTS ?JOBtsk.
              by rewrite /task_scheduled_on -SCHED' EQtsk'.
            }
            have ARR': arrives_in arr_seq j'.
              by apply (FROMSEQ j' t); apply/existsP; exists cpu; apply/eqP.
            rewrite EQtsk' mem_filter; apply/andP; split; last by apply FROMTS.
            apply/andP; split; last first.
            {
              apply/existsP; exists cpu; apply/andP; split; first by done.
              by apply APA with (t := t); rewrite /scheduled_on SCHED'.
            }
            {
              apply/eqP; intro SAMEtsk.
              move: BACK => /andP [PENDING NOTSCHED].
              assert (SCHEDULED': scheduled sched j' t).
              {
                by apply/existsP; exists cpu; rewrite /scheduled_on -SCHED'.
              }
              move: (SCHEDULED') => PENDING'.
              apply scheduled_implies_pending with (job_cost0 := job_cost) (job_arrival0:=job_arrival)
                in PENDING'; try by done.
              assert (BUG: j = j').
              {
                apply platform_at_most_one_pending_job_of_each_task with (task_cost0 := task_cost)
                (task_period0 := task_period) (task_deadline0 := task_deadline) (tsk0 := tsk)
                (job_cost0 := job_cost) (job_task0 := job_task) (sched0 := sched) (j0 := j) (t0 := t)
                (job_arrival0 := job_arrival) (arr_seq0 := arr_seq);
                  rewrite ?JOBtsk ?SAMEtsk //; first by apply PARAMS; rewrite -JOBtsk FROMTS.
                intros j0 tsk0 ARR0 TSK0 LE.
                by apply (COMP t); rewrite ?TSK0.
              }
              by rewrite BUG SCHEDULED' in NOTSCHED.
            }
          }
        }
      Qed.

      (* Before stating the next lemma, let (num_tasks_exceeding delta) be the
         number of interfering tasks that can execute on (alpha' tsk) whose
         interference x is larger than delta. *)
      Let num_tasks_exceeding delta := count (fun i => x i >= delta) (other_tasks_in alpha').

      (* 6) 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 (#|alpha' tsk| - num_tasks_exceeding delta)
            processors. *)
      Lemma bertogna_edf_interference_in_non_full_processors :
        forall delta,
          0 < num_tasks_exceeding delta < #|alpha' tsk| ->
          \sum_(i <- other_tasks_in alpha' | x i < delta) x i >= delta * (#|alpha' tsk| - num_tasks_exceeding delta).
      Proof.
        have COMP := bertogna_edf_all_previous_jobs_complete_by_their_period.
        have ATMOST := platform_at_most_one_pending_job_of_each_task.
        have INV := bertogna_edf_alpha'_is_full.
        rename H_all_jobs_from_taskset into FROMTS,
               H_valid_task_parameters into PARAMS,
               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_constrained_deadlines into RESTR,
               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 sched j t &&
                            (x tsk_k >= delta) &&
                            scheduled_on_alpha_tsk t tsk_k)
            (other_tasks_in alpha').
        set total_interference_B := fun t =>
            backlogged job_arrival job_cost sched j t *
            count (fun tsk_k => (x tsk_k < delta) &&
                  scheduled_on_alpha_tsk t tsk_k) (other_tasks_in alpha').

        apply leq_trans with ((\sum_(job_arrival j <= t < job_arrival j + R)
                              some_interference_A t) * (#|alpha' tsk| - 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 sched j t) eqn:BACK;
            last by rewrite (eq_bigr (fun x => 0)); [by simpl_sum_const | by ins].
          destruct ([exists cpu, can_execute_on alpha (job_task j) 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 /andP [CAN SCHED]].
          apply leq_trans with (n := 1); last first.
          {
            rewrite lt0b; apply/hasP; exists tsk_a; first by done.
            rewrite LEa 2!andTb; apply/existsP; exists cpu.
            by apply/andP; split; first by rewrite -JOBtsk.
          }
          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.
          move => /andP [ALPHA' 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'.
          assert (BUG: j1 = j2).
          {
            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 sched j1 t).
            {
              apply scheduled_implies_pending; try by done.
              by apply/existsP; exists cpu; rewrite /scheduled_on -SCHED1.
            }
            assert (SCHED2': pending job_arrival job_cost sched j2 t).
            {
              apply scheduled_implies_pending; try by done.
              by apply/existsP; exists cpu'; rewrite /scheduled_on -SCHED2.
            }
            apply platform_at_most_one_pending_job_of_each_task with (task_cost0 := task_cost)
              (task_period0 := task_period) (task_deadline0 := task_deadline) (tsk0 := tsk)
              (job_cost0 := job_cost) (job_task0 := job_task) (sched0 := sched) (j0 := j) (t0 := t)
              (job_arrival0 := job_arrival) (arr_seq0 := arr_seq);
              rewrite ?JOBtsk ?SAMEtsk //; first by apply PARAMS; rewrite -JOBtsk FROMTS.
            intros j0 tsk0 ARR0 TSK0 LE.
            by apply (COMP t); rewrite ?TSK0.
          }
          by subst j2; apply SEQ with (j := j1) (t := t).
        }

        apply leq_trans with (\sum_(job_arrival j <= t < job_arrival j + 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 sched j t) eqn:BACK;
            [rewrite mul1n /= | by rewrite has_pred0 //].

          destruct (has (fun tsk_k : sporadic_task => (delta <= x tsk_k) &&
                     scheduled_on_alpha_tsk t tsk_k) (other_tasks_in alpha')) eqn:HAS';
            last by done.
          rewrite mul1n; move: HAS => /hasP [tsk_k INk LEk].
          unfold num_tasks_exceeding.
          apply leq_trans with (n := #|alpha' tsk| -
                       count (fun i => (x i >= delta) &&
                          scheduled_on_alpha_tsk t i) (other_tasks_in alpha')).
          {
            apply leq_sub2l.
            rewrite -2!sum1_count big_mkcond /=.
            rewrite [\sum_(_ <- _ | _ <= _)_]big_mkcond /=.
            apply leq_sum; intros i _.
            by destruct (scheduled_on_alpha_tsk t i);
              [by rewrite andbT | by rewrite andbF].
          }
          rewrite -count_filter -[count _ (other_tasks_in _)]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.
          move: INV => INV. by apply (INV t).
        }
        {
          unfold x at 2, total_interference_B.
          rewrite exchange_big /=; apply leq_sum; intros t _.
          destruct (backlogged job_arrival job_cost sched j t) eqn:BACK; last by ins.
          rewrite mul1n -sum1_count.
          rewrite big_mkcond [\sum_(i <- other_tasks_in alpha' | _ < _) _]big_mkcond /=.
          apply leq_sum_seq; move => tsk_k IN _.
          destruct (x tsk_k < delta); [rewrite andTb | by rewrite andFb].
          destruct (scheduled_on_alpha_tsk t tsk_k) eqn:SCHED; last by done.
          move: SCHED => /existsP [cpu /andP [ALPHA SCHED]].
          rewrite (bigD1 cpu) /= // JOBtsk SCHED andbT.
          by rewrite /can_execute_on ALPHA.
        }
      Qed.

      (* 7) Based on lemma (6), we prove that, for any interval delta, if the sum of per-task
            interference exceeds (delta * |alpha' tsk|), 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_in alpha') x tsk_k >= delta * #|alpha' tsk| ->
             \sum_(tsk_k <- other_tasks_in alpha') minn (x tsk_k) delta >=
             delta * #|alpha' tsk|.
      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_in alpha')) 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_in alpha') && true));
            last by red; intros tsk_k; destruct (tsk_k \in other_tasks_in alpha') 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 >= #|alpha' tsk| *)
        destruct (num_tasks_exceeding delta >= #|alpha' tsk|) 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 < #|alpha' tsk| *)
        rewrite big_const_seq iter_addn addn0; fold num_tasks_exceeding.
        apply leq_trans with (n := delta * num_tasks_exceeding delta +
                                   delta * (#|alpha' tsk| - num_tasks_exceeding delta));
          first by rewrite -mulnDr subnKC //; apply ltnW.
        rewrite leq_add2l bertogna_edf_interference_in_non_full_processors //.
        by apply/andP; split; [by rewrite -has_count | by done].
      Qed.

      (* 8) Note that lemma (7) only refers to interference within subaffinity (alpha' tsk).
            To reason about the interference incurred by job j in its complete affinity,
            we prove that an exceeding interference on affinity (alpha tsk) also
            implies an exceeding interference on the subaffinity (alpha' tsk). *)
      Lemma bertogna_edf_interference_on_subaffinity :
        forall delta,
          \sum_(tsk_k <- other_tasks_in alpha) x tsk_k >= delta * #|alpha tsk| ->
          \sum_(tsk_k <- other_tasks_in alpha') x tsk_k >= delta * #|alpha' tsk|.
      Proof.
        have ALL := bertogna_edf_all_cpus_in_affinity_busy.
        have SUB := bertogna_edf_all_cpus_in_subaffinity_busy.
        rename H_at_least_one_cpu into NONEMPTY',
               H_job_of_tsk into JOBtsk, H_affinity_subset into SUBSET,
               H_all_jobs_from_taskset into FROMTS.
        intros delta LE.
        rewrite ALL in LE.
        apply leq_trans with (n := X * #|alpha' tsk|); last by apply SUB.
        rewrite leq_mul2r in LE;  move: LE => /orP [/eqP EMPTY | LEx];
          last by rewrite leq_mul2r; apply/orP; right.
        assert (NONEMPTY: #|alpha tsk| > 0).
        {
          apply leq_trans with (n := #|alpha' tsk|);
            last by apply leq_subaffinity, SUBSET; rewrite -JOBtsk FROMTS.
          by apply NONEMPTY'; rewrite -JOBtsk FROMTS.
        }
        by rewrite EMPTY ltnn in NONEMPTY.
      Qed.

      (* 9) Next, using lemmas (0), (3), (7) and (8), 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_in (alpha' tsk) 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 SUB := bertogna_edf_interference_on_subaffinity.
        have ALLBUSY := bertogna_edf_all_cpus_in_affinity_busy.
        have TOOMUCH := bertogna_edf_too_much_interference.
        rename H_rt_bounds_contains_all_tasks into UNZIP,
               H_job_of_tsk into JOBtsk,
               H_all_jobs_from_taskset into FROMTS,
               H_response_time_is_fixed_point into REC.
        apply leq_trans with (n := \sum_(tsk_other <- other_tasks_in alpha')
                                     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.
          assert (FILTER: filter (other_task_in (alpha' tsk)) (unzip1 rt_bounds) =
                          filter (other_task_in (alpha' tsk)) ts).
            by f_equal.
          unfold other_tasks_in; rewrite -FILTER; clear FILTER.
          rewrite -[\sum_(_ <- rt_bounds | _)_]big_filter.
          assert (SUBST: [seq i <- rt_bounds
                 | let '(tsk_other, _) := i in
                   other_task_in (alpha' tsk) tsk_other] =
                         [seq i <- rt_bounds
                           | other_task_in (alpha' tsk) (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 := #|alpha' tsk|);
          first by apply H_at_least_one_cpu; rewrite -JOBtsk FROMTS.
        rewrite -(ltn_add2l (task_cost tsk)) -REC; last first. 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; rewrite -JOBtsk FROMTS.
        apply EXCEEDS, SUB.
        apply leq_trans with (n := X * #|alpha tsk|); last by rewrite ALLBUSY.
        by rewrite leq_mul2r; apply/orP; right; apply TOOMUCH.
      Qed.

      (* 10) 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_in (alpha' tsk) 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 [X in _ <= X]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);
              [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.

    (* Using the lemmas above, we now prove that any response-time bound
       obtained from the analysis is safe. *)
    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.

      (* Then, R bounds the response-time of tsk. *)
      Theorem bertogna_cirinei_response_time_bound_edf :
        response_time_bounded_by tsk R.
      Proof.
        intros j ARRj JOBtsk.

        (* First, rewrite the claim in terms of the *absolute* response-time bound (arrival + R) *)
        remember (job_arrival j + 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 + R0 < job_arrival j + R' ->
                            service sched j0 (job_arrival j0 + 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 + R')) eqn:NOTCOMP;
          first by done.
        apply negbT in NOTCOMP; exfalso.

        (* Next, we derive a contradiction using the previous lemmas. *)
        exploit (bertogna_edf_exists_task_that_exceeds_bound 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.
        have BASICBOUND := bertogna_edf_workload_bounds_interference R' j BEFOREok tsk_other R_other HP.
        have EDFBOUND := (bertogna_edf_specific_bound_holds tsk' R' 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 ResponseTimeAnalysisEDF.


Require Import Coq.Lists.List.
Require Import Coq.Lists.SetoidList.
Require Import Coq.Lists.SetoidPermutation.
Require Import Coq.Classes.Morphisms.
Require Import Coq.Sorting.Sorted.
Require Import Crypto.Util.Tactics.SplitInContext.

Local Set Implicit Arguments.

Local Ltac t' :=
  repeat first [ progress cbv [Proper respectful impl flip] in *
               | progress intros
               | progress invlist HdRel
               | progress invlist Sorted
               | progress invlist StronglySorted
               | progress split_iff
               | solve [ eauto ] ].
Local Ltac t :=
  first [ induction 1; progress repeat constructor; t'
        | intro; t ].

Global Instance HdRel_Proper_impl A R
  : Proper ((R ==> R ==> impl) ==> R ==> eqlistA R ==> impl) (@HdRel A).
Proof. t. Qed.
Global Instance HdRel_Proper_flip_impl A R
  : Proper ((R ==> R ==> flip impl) ==> R ==> eqlistA R ==> flip impl) (@HdRel A).
Proof. t. Qed.
Global Instance HdRel_Proper_iff A R
  : Proper ((R ==> R ==> iff) ==> R ==> eqlistA R ==> iff) (@HdRel A).
Proof. t. Qed.
Global Instance HdRel_Proper_impl_sym A R {_: Symmetric R}
  : Proper ((R ==> R ==> impl) ==> R ==> flip (eqlistA R) ==> impl) (@HdRel A).
Proof. t. Qed.
Global Instance HdRel_Proper_flip_impl_sym A R {_: Symmetric R}
  : Proper ((R ==> R ==> flip impl) ==> R ==> flip (eqlistA R) ==> flip impl) (@HdRel A).
Proof. t. Qed.
Global Instance HdRel_Proper_iff_sym A R {_: Symmetric R}
  : Proper ((R ==> R ==> iff) ==> R ==> flip (eqlistA R) ==> iff) (@HdRel A).
Proof. t. Qed.
Global Instance Sorted_Proper_impl A R
  : Proper ((R ==> R ==> impl) ==> eqlistA R ==> impl) (@Sorted A).
Proof. t. eapply HdRel_Proper_impl; eassumption. Qed.
Global Instance Sorted_Proper_flip_impl A R
  : Proper ((R ==> R ==> flip impl) ==> eqlistA R ==> flip impl) (@Sorted A).
Proof. t. eapply HdRel_Proper_flip_impl; eassumption. Qed.
Global Instance Sorted_Proper_iff A R
  : Proper ((R ==> R ==> iff) ==> eqlistA R ==> iff) (@Sorted A).
Proof.
  repeat intro; split; [ eapply Sorted_Proper_impl | eapply Sorted_Proper_flip_impl ]; try eassumption; t'.
Qed.
Global Instance Sorted_Proper_impl_sym A R {_: Symmetric R}
  : Proper ((R ==> R ==> impl) ==> flip (eqlistA R) ==> impl) (@Sorted A).
Proof. t. eapply HdRel_Proper_impl_sym; (idtac + symmetry); eassumption. Qed.
Global Instance Sorted_Proper_flip_impl_sym A R {_: Symmetric R}
  : Proper ((R ==> R ==> flip impl) ==> flip (eqlistA R) ==> flip impl) (@Sorted A).
Proof. t. eapply HdRel_Proper_flip_impl_sym; (idtac + symmetry); eassumption. Qed.
Global Instance Sorted_Proper_iff_sym A R {_: Symmetric R}
  : Proper ((R ==> R ==> iff) ==> flip (eqlistA R) ==> iff) (@Sorted A).
Proof.
  repeat intro; split; [ eapply Sorted_Proper_impl_sym | eapply Sorted_Proper_flip_impl_sym ]; try eassumption; t'.
Qed.


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

Require Export CoRN.algebra.CSemiGroups.
Require Import CoRN.model.semigroups.Nsemigroup.
Require Export CoRN.model.setoids.Npossetoid.

(**
** Examples of semi-groups:  $\langle$#⟨#[Npos],[[+]]$\rangle$#⟩# and $\langle$#⟨#[Npos],[[*]]$\rangle$#⟩#
*** $\langle$#⟨#[Npos],[[+]]$\rangle$#⟩#
The positive natural numbers form together with addition a subsemigroup
 of the semigroup of the natural numbers with addition.
*)

Definition Npos_as_CSemiGroup := Build_SubCSemiGroup
 nat_as_CSemiGroup NposP plus_resp_Npos.

(**
*** $\langle$#⟨#[Npos],[[*]]$\rangle$#⟩#
Also together with multiplication, the positive numbers form a semigroup.
*)

Lemma Nposmult_is_CSemiGroup : is_CSemiGroup Npos Npos_mult.
Proof.
 unfold is_CSemiGroup in |- *.
 unfold associative in |- *.
 unfold Npos_mult in |- *.
 simpl in |- *.
 intros x y z.
 case x.
 case y.
 case z.
 simpl in |- *.
 intros a pa b pb c pc.
 auto with arith.
Qed.

Definition Nposmult_as_CSemiGroup := Build_CSemiGroup
 Npos Npos_mult Nposmult_is_CSemiGroup.


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

Require Export CoRN.model.rings.Qring.
Require Import CoRN.algebra.CFields.

(**
** Example of a field: $\langle$#⟨#[Q],[[+]],[[*]]$\rangle$#⟩#
As we have seen, there is a inverse for the multiplication for non-zeroes.
So, [Q] not only forms a ring, but even a field.
*)

Lemma Q_is_CField : is_CField Q_as_CRing Qinv_dep.
Proof.
 red in |- *.
 intro.
 unfold is_inverse in |- *.
 apply Qinv_is_inv.
Qed.

Definition Q_as_CField := Build_CField _ _ Q_is_CField Qinv_strext.

Canonical Structure Q_as_CField.


Load LFindLoad.
From lfind Require Import LFind.
From QuickChick Require Import QuickChick.
From adtind Require Import goal33.

Derive Show for natural.

              Derive Arbitrary for natural.

              Instance Dec_Eq_natural : Dec_Eq natural.

              Proof. dec_eq. Qed.

Lemma conj20eqsynthconj1 : forall  (lv0 : natural) (lv1 : natural) (lv2 : natural), (@eq natural (plus lv0 (plus lv1 lv2)) (plus (plus lv1 lv2) lv0)).
Admitted.
QuickChick conj20eqsynthconj1.


From Test Require Import tactic.

Section FOFProblem.

Variable Universe : Set.
Variable UniverseElement : Universe.

Variable wd_ : Universe -> Universe -> Prop.
Variable col_ : Universe -> Universe -> Universe -> Prop.

Variable col_swap1_1 : (forall A B C : Universe, (col_ A B C -> col_ B A C)).
Variable col_swap2_2 : (forall A B C : Universe, (col_ A B C -> col_ B C A)).
Variable col_triv_3 : (forall A B : Universe, col_ A B B).
Variable wd_swap_4 : (forall A B : Universe, (wd_ A B -> wd_ B A)).
Variable col_trans_5 : (forall P Q A B C : Universe, ((wd_ P Q /\ (col_ P Q A /\ (col_ P Q B /\ col_ P Q C))) -> col_ A B C)).

Theorem pipo_6 : (forall A C Aprime Bprime Cprime O : Universe, ((wd_ A O /\ (wd_ C O /\ (wd_ Bprime O /\ (wd_ Cprime O /\ (wd_ Aprime O /\ (wd_ A Aprime /\ (col_ O A C /\ (col_ O A A /\ (col_ O Aprime Bprime /\ (col_ O Bprime Cprime /\ col_ A Cprime O)))))))))) -> col_ O A Aprime)).
Proof.
  time tac.
Qed.

End FOFProblem.


Load LFindLoad.
From lfind Require Import LFind.
From QuickChick Require Import QuickChick.
From adtind Require Import goal33.

Derive Show for natural.

              Derive Arbitrary for natural.

              Instance Dec_Eq_natural : Dec_Eq natural.

              Proof. dec_eq. Qed.

Lemma conj12synthconj1 : forall  (lv0 : natural) (lv1 : natural) (lv2 : natural), (@eq natural (plus lv0 (plus (mult lv0 lv1) lv2)) (plus (plus lv2 lv0) (mult lv1 lv0))).
Admitted.
QuickChick conj12synthconj1.


Require Import Leapfrog.Benchmarks.ProofHeader.
Require Import Leapfrog.Benchmarks.Memory.

Require Import Coq.Arith.PeanoNat.

Require Import Leapfrog.Utils.FunctionalFP.

Notation A := TallSelf.aut.
Notation conf := (P4automaton.configuration (P4A.interp A)).
Notation start_left :=  MemoryTall.start.
Notation start_right := MemoryTall.start.

Definition r_states : {r : Reachability.state_pairs A & Reachability.reachable_states_wit start_left start_right r}.
  econstructor.
  unfold Reachability.reachable_states_wit.
  solve_fp_wit.
Defined.

Lemma init_states_wf:
  Reachability.valid_state_pair (Reachability.build_state_pair A start_left start_right).
Proof.
  vm_compute; Lia.lia.
Qed.

Definition top : Relations.rel conf :=
  fun q1 q2 => List.In (conf_to_state_template q1, conf_to_state_template q2) (projT1 r_states).

Definition top' : Relations.rel (state_template A) :=
  fun q1 q2 => List.In (q1, q2) (projT1 r_states).

Declare ML Module "mirrorsolve".

Lemma prebisim_mpls_unroll:
  forall q1 q2,
    interp_conf_rel' {| cr_st := {|
                        cs_st1 := {|
                          st_state := inl (inl (start_left));
                          st_buf_len := 0;
                        |};
                        cs_st2 := {|
                          st_state := inl (inr (start_right));
                          st_buf_len := 0;
                        |};
                      |};
                      cr_ctx := BCEmp;
                      cr_rel := btrue;
                    |} q1 q2 ->
  pre_bisimulation A
                    (wp (projT1 r_states))
                    top
                    []
                    (mk_init _ _ _ _ A start_left start_right)
                    q1 q2.
Proof.
  intros.

  pose proof (Reachability.reachable_states_wit_conv init_states_wf (projT2 r_states)) as Hr.

  unfold mk_init.
  rewrite Hr.
  clear Hr.

  set (foo := (List.nodup (conf_rel_eq_dec (a:=A)) (mk_partition _ _ _ _ _ _))).
  vm_compute in foo.
  subst foo.

  (* time "build phase" repeat (time "single step" run_bisim' top top' r_states interp_compile_simplify). *)
  time "build phase" repeat (time "single step" run_bisim top top' (projT1 r_states)).
  time "close phase" close_bisim top'.
Time Admitted.


(** * SfLib_J: Software Foundations ライブラリ *)

(** Here we collect together several useful definitions and theorems
    from Basics.v, List.v, Poly.v, Ind.v, and Logic.v that are not
    already in the Coq standard library.  From now on we can [Import]
    or [Export] this file, instead of cluttering our environment with
    all the examples and false starts in those files. *)
(** ここでは、Basics.v, List.v, Poly.v, Ind.v, and Logic.vの中から、使い勝手のよい定義や定理でCoqのスタンダードライブラリに含まれていないものをを集めてみました。これ以降、環境を色々な証明で散らかす代わりに、このライブラリファイルを[Import]、[Export]するだけで済むようになります。 *)

(** * Coq スタンダードライブラリから *)

Require Omega.   (* needed for using the [omega] tactic *)
Require Export Bool.
Require Export List.
Require Export Arith.
Require Export Arith.EqNat.  (* Contains [beq_nat], among other things *)

(** * Basics.vから *)

Definition admit {T: Type} : T.  Admitted.

Require String. Open Scope string_scope.

Ltac move_to_top x :=
  match reverse goal with
  | H : _ |- _ => try move x after H
  end.

Tactic Notation "assert_eq" ident(x) constr(v) :=
  let H := fresh in
  assert (x = v) as H by reflexivity;
  clear H.

Tactic Notation "Case_aux" ident(x) constr(name) :=
  first [
    set (x := name); move_to_top x
  | assert_eq x name; move_to_top x
  | fail 1 "because we are working on a different case" ].

Tactic Notation "Case" constr(name) := Case_aux Case name.
Tactic Notation "SCase" constr(name) := Case_aux SCase name.
Tactic Notation "SSCase" constr(name) := Case_aux SSCase name.
Tactic Notation "SSSCase" constr(name) := Case_aux SSSCase name.
Tactic Notation "SSSSCase" constr(name) := Case_aux SSSSCase name.
Tactic Notation "SSSSSCase" constr(name) := Case_aux SSSSSCase name.
Tactic Notation "SSSSSSCase" constr(name) := Case_aux SSSSSSCase name.
Tactic Notation "SSSSSSSCase" constr(name) := Case_aux SSSSSSSCase name.

Fixpoint ble_nat (n m : nat) : bool :=
  match n with
  | O => true
  | S n' =>
      match m with
      | O => false
      | S m' => ble_nat n' m'
      end
  end.

Theorem andb_true_elim1 : forall b c,
  andb b c = true -> b = true.
Proof.
  intros b c H.
  destruct b.
  Case "b = true".
    reflexivity.
  Case "b = false".
    rewrite <- H. reflexivity.
Qed.

Theorem andb_true_elim2 : forall b c,
  andb b c = true -> c = true.
Proof.
  intros b c H.
  destruct b.
  Case "b = true".
    apply H.
  Case "b = false".
    inversion H.
Qed.

Theorem beq_nat_sym : forall (n m : nat),
  beq_nat n m = beq_nat m n.
Proof.
  intros n.
  induction n as [| n'];
    intros m; induction m as [| m']; try (reflexivity).
  SCase "m = S m'".
    apply (IHn' m').
Qed.

(* Poly.vから *)

Notation "[ ]" := nil.
Notation "[ x , .. , y ]" := (cons x .. (cons y []) ..).
Notation "x ++ y" := (app x y)
                     (at level 60, right associativity).

(** * Props.vから *)

Inductive ev : nat -> Prop :=
  | ev_0 : ev O
  | ev_SS : forall n:nat, ev n -> ev (S (S n)).

(** * Logic.vから *)

Theorem andb_true : forall b c,
  andb b c = true -> b = true /\ c = true.
Proof.
  intros b c H.
  destruct b.
    destruct c.
      apply conj. reflexivity. reflexivity.
      inversion H.
    inversion H.  Qed.

Theorem not_eq_beq_false : forall n n' : nat,
     n <> n' ->
     beq_nat n n' = false.
Proof.
  induction n; destruct n'; simpl; intros; try reflexivity.
  induction H; reflexivity.
  apply IHn.
  intro H'; rewrite H' in *; apply H.
  reflexivity.
Qed.

Theorem ex_falso_quodlibet : forall (P:Prop),
  False -> P.
Proof.
  intros P contra.
  inversion contra.
Qed.

Theorem SSev_even : forall n,
  ev (S (S n)) -> ev n.
Proof.
  intros n E.
  inversion E as [| n' E'].
  apply E'.
Qed.

Theorem ev_not_ev_S : forall n,
  ev n -> ~ ev (S n).
Proof.
  unfold not.
  intros n Hevn HevSn.
  induction Hevn as [| n'].
  Case "n = 0".                             (* ev 0 *)
     inversion HevSn.
  Case "n = SSn'".                          (* ev SSn' *)
    apply IHHevn.
    apply SSev_even.
    apply HevSn.
Qed.

Theorem O_le_n : forall n,
  0 <= n.
Proof.
  intros n.
  induction n as [| n'].
  Case "n = 0".                             (* 0 <= 0 *)
    apply le_n.
  Case "n = S n'".                          (* 0 <= Sn' *)
    apply le_S.
    apply IHn'.
Qed.

Theorem n_le_m__Sn_le_Sm : forall n m,
  n <= m -> S n <= S m.
Proof.
  intros n m H.
  induction H as [| m'].
  Case "m = n".                             (* Sn <= Sn *)
    apply le_n.
  Case "m = S m'".                          (* Sn <= SSm' *)
    apply le_S.
    apply IHle.
Qed.
(*
補足説明：
H : n <= m から、
m = n なら、  n <= n   つまり、n = n  となり、等号の場合
m = Sm' なら、n <= Sm' つまり、n < m' となり、不等号の場合
サブゴールはもとのゴールに m = n や m = Sm' を代入したもの。
*)

Lemma ble_Sn_Sm__ble_n_m : forall n m,
  ble_nat (S n) (S m) = true -> ble_nat n m = true.
Proof.
  intros n m H.
  simpl.
  apply H.
Qed.

Theorem ble_nat_true : forall n m,
  ble_nat n m = true -> n <= m.
Proof.
  intros n m.
  generalize dependent m.
  induction n as [| n'].
  Case "n = 0".                             (* forall m : nat, ble_nat 0 m = true -> 0 <= m *)
    intros n H.
    apply O_le_n.
  Case "n = Sn'".                          (*  forall m : nat, ble_nat (S n) m = true -> S n <= m *)
    intros m H.
    induction m as [| m'].
    SCase "m = 0".                          (* S n' <= 0 *)
      inversion H.
    SCase "m = Sm'".                        (* S n' <= S m' *)
      apply n_le_m__Sn_le_Sm.
      apply IHn'.
      apply H.
Qed.

Lemma n_le_m__n_le_Sm : forall n m,
  n <= m -> n <= S m.
Proof.
  intros n m H.
  (* 補足：induction n. induction m ではうまくいかない。 *)
  induction H as [| m'].                    (* !!!! *)
  Case "m = n".                             (* n <= Sn *)
    apply le_S.
    apply le_n.
  Case "m = Sm'".                           (* n <= SSm' *)
    apply le_S.
    apply IHle.
Qed.

Lemma Sn_le_m__n_le_m : forall n m,
  S n <= m -> n <= m.
Proof.
  intros n m H.
  induction H as [| m'].
  Case "m = S n".                           (* n <= Sn *)
    apply le_S.
    apply le_n.
  Case "m = m'".                            (* n <= Sm' *)
    apply n_le_m__n_le_Sm.
    apply IHle.
Qed.

Lemma Sn_le_Sm__n_le_m : forall n m,
  S n <= S m -> n <= m.
Proof.
  intros n m.
  generalize dependent n.
  induction m as [| m'].
  (* ここまでは、ヒント。 *)
  Case "m = 0".                             (* forall n : nat, S n <= 1 -> n <= 0 *)
  intros n H.
    induction n as [| n'].
    SCase "n = 0".                          (* 0 <= 0 *)
      apply le_n.
    SCase "n = Sn'".                        (* Sn' <= 0 *)
      inversion H.
      inversion H1.
  (* inversion でゴールが変わらなくても、あきらめてはいけない。
     *)
  Case "m = Sm'".                           (* forall n : nat, S n <= S (S m') -> n <= S m' *)
     intros n.
     induction n as [| n'].
     SCase "n = 0".                         (* 1 <= S (S m') -> 0 <= S m' *)
       intros H.
       apply O_le_n.

     SCase "n = Sn'".                       (* S (S n') <= S (S m') -> S n' <= S m' *)
       intros H.
       inversion H as [H1| m'' H2].
       SSCase "SSm' = SSn'".                (* Sm' <= Sm', H1 : n' = m' *)
         apply le_n.
       SSCase "SSm = Sm''".                 (* Sn' <= Sm', H1 : m'' = Sm' *)
         apply Sn_le_m__n_le_m.
         apply H2.
Qed.

Theorem ble_nat_false : forall n m,
  ble_nat n m = false -> ~(n <= m).
Proof.
  induction n as [| n'].
  Case "n = 0".
    intros m H.
    inversion H.
  Case "n = Sn'".
    destruct m as [| m'].
    SCase "m = 0".
      unfold not.
      intros H H0.
      inversion H0.
    SCase "m = Sm'".
      unfold not.
      intros Hnle HSnleSm.
      assert (n' <= m') as Hassert.
      SSCase "HAssert".
        apply Sn_le_Sm__n_le_m.
        apply HSnleSm.
     inversion Hnle.
     apply (IHn' m' Hnle).
     apply Hassert.
Qed.

Inductive appears_in (n : nat) : list nat -> Prop :=
| ai_here : forall l, appears_in n (n::l)
| ai_later : forall m l, appears_in n l -> appears_in n (m::l).

Definition relation (X:Type) := X -> X -> Prop.

Definition partial_function {X: Type} (R: relation X) :=
  forall x y1 y2 : X, R x y1 -> R x y2 -> y1 = y2.

Inductive next_nat (n:nat) : nat -> Prop :=
  | nn : next_nat n (S n).

Inductive total_relation : nat -> nat -> Prop :=
  tot : forall n m : nat, total_relation n m.

Inductive empty_relation : nat -> nat -> Prop := .

Inductive refl_step_closure (X:Type) (R: relation X)
                            : X -> X -> Prop :=
  | rsc_refl  : forall (x : X),
                 refl_step_closure X R x x
  | rsc_step : forall (x y z : X),
                    R x y ->
                    refl_step_closure X R y z ->
                    refl_step_closure X R x z.
Implicit Arguments refl_step_closure [[X]].

Tactic Notation "rsc_cases" tactic(first) ident(c) :=
  first;
  [ Case_aux c "rsc_refl" | Case_aux c "rsc_step" ].

Theorem rsc_R : forall (X:Type) (R:relation X) (x y : X),
       R x y -> refl_step_closure R x y.
Proof.
  intros X R x y r.
  apply rsc_step with y.
  apply r.
  apply rsc_refl.
Qed.

Theorem rsc_trans :
  forall (X:Type) (R: relation X) (x y z : X),
      refl_step_closure R x y  ->
      refl_step_closure R y z ->
      refl_step_closure R x z.
Proof.
  intros X R x y z.
  intros HRxy HRyz.
  rsc_cases (induction HRxy as [|z' x y]) Case.
  Case "rsc_refl".                          (* (1) refl_step_closure R x z *)
    apply HRyz.

  Case "rsc_step".                          (* (1) refl_step_closure R z' z *)
    apply (rsc_step X R z' x z).
    apply H.                                (* (2) R z' x *)
    apply IHHRxy.                           (* (2) refl_step_closure R x z *)
    apply HRyz.
Qed.

(* Identifiers and polymorphic partial maps. *)
Inductive id : Type :=
  Id : nat -> id.

Definition beq_id id1 id2 :=
  match (id1, id2) with
    (Id n1, Id n2) => beq_nat n1 n2
  end.

Theorem beq_id_refl : forall i,
  true = beq_id i i.
Proof.
  intros. destruct i.
  apply beq_nat_refl.  Qed.

Theorem beq_id_eq : forall i1 i2,
  true = beq_id i1 i2 -> i1 = i2.
Proof.
  intros i1 i2 H.
  destruct i1. destruct i2.
  apply beq_nat_eq in H. subst.
  reflexivity.  Qed.

Theorem beq_id_false_not_eq : forall i1 i2,
  beq_id i1 i2 = false -> i1 <> i2.
Proof.
  intros i1 i2 H.
  destruct i1. destruct i2.
  apply beq_nat_false in H.
  intros C. apply H. inversion C. reflexivity.  Qed.

Theorem not_eq_beq_id_false : forall i1 i2,
  i1 <> i2 -> beq_id i1 i2 = false.
Proof.
  intros i1 i2 H.
  destruct i1. destruct i2.
  assert (n <> n0).
    intros C. subst. apply H. reflexivity.
  apply not_eq_beq_false. assumption.  Qed.

Theorem beq_id_sym: forall i1 i2,
  beq_id i1 i2 = beq_id i2 i1.
Proof.
  intros i1 i2. destruct i1. destruct i2. apply beq_nat_sym. Qed.

Definition partial_map (A:Type) := id -> option A.

Definition empty {A:Type} : partial_map A := (fun _ => None).

Definition extend {A:Type} (Gamma : partial_map A) (x:id) (T : A) :=
  fun x' => if beq_id x x' then Some T else Gamma x'.

Lemma extend_eq : forall A (ctxt: partial_map A) x T,
  (extend ctxt x T) x = Some T.
Proof.
  intros. unfold extend. rewrite <- beq_id_refl. auto.
Qed.

Lemma extend_neq : forall A (ctxt: partial_map A) x1 T x2,
  beq_id x2 x1 = false ->
  (extend ctxt x2 T) x1 = ctxt x1.
Proof.
  intros. unfold extend. rewrite H. auto.
Qed.

Lemma extend_shadow : forall A (ctxt: partial_map A) t1 t2 x1 x2,
  extend (extend ctxt x2 t1) x2 t2 x1 = extend ctxt x2 t2 x1.
Proof with auto.
  intros. unfold extend. destruct (beq_id x2 x1)...
Qed.

(** * 使い勝手のいいタクティックをいくつか *)

Tactic Notation "solve_by_inversion_step" tactic(t) :=
  match goal with
  | H : _ |- _ => solve [ inversion H; subst; t ]
  end
  || fail "because the goal is not solvable by inversion.".

Tactic Notation "solve" "by" "inversion" "1" :=
  solve_by_inversion_step idtac.
Tactic Notation "solve" "by" "inversion" "2" :=
  solve_by_inversion_step (solve by inversion 1).
Tactic Notation "solve" "by" "inversion" "3" :=
  solve_by_inversion_step (solve by inversion 2).
Tactic Notation "solve" "by" "inversion" :=
  solve by inversion 1.

(* END *)


(****************************************************************************)
(*                                                                          *)
(*                                                                          *)
(*                            Solange Coupet-Grimal                         *)
(*                                                                          *)
(*                                                                          *)
(*           Laboratoire d'Informatique Fondamentale de Marseille           *)
(*                   CMI-Technopole de Chateau-Gombert                      *)
(*                       39, Rue F. Joliot Curie                            *)
(*                       13453 MARSEILLE Cedex 13                           *)
(*                    Solange.Coupet@cmi.univ-mrs.fr                        *)
(*                                                                          *)
(*                                                                          *)
(*                                Coq V7.0                                  *)
(*                             Juillet  2002                                *)
(*                                                                          *)
(****************************************************************************)
(*                               congruence.v                               *)
(****************************************************************************)

Section congruence.

Require Export safety.
Variables (state label : Set) (transition : label -> relation state)
  (init_state : state -> Prop).

Notation Stream := (stream state) (only parsing).
Notation State_formula := (state_formula state) (only parsing).
Notation Stream_formula := (stream_formula state) (only parsing).
Notation Safe := (safe init_state transition) (only parsing).

(***************************************************************************)

Lemma lift_imp :
 forall P Q : state_formula state,
 (forall s : state, P s -> Q s) ->
 forall str : stream state,
 state2stream_formula P str -> state2stream_formula Q str.

unfold state2stream_formula in |- *; auto.
Qed.

Lemma lift_implies_stream :
 forall P Q : stream_formula state,
 (forall str : stream state, P str -> Q str) ->
 forall str : stream state, implies P Q str.
unfold implies in |- *; intros P Q H.
cofix; intro str; case str; clear str.
intros s str; constructor; auto.
Qed.

Lemma lift_implies_state :
 forall P Q : state_formula state,
 (forall s : state, P s -> Q s) ->
 forall str : stream state,
 implies (state2stream_formula P) (state2stream_formula Q) str.

intros P Q H str; apply lift_implies_stream; clear str.
intros str H'.
apply lift_imp with (P := P); assumption.
Qed.

Lemma implies_eventually :
 forall (P Q : stream_formula state) (str : stream state),
 implies P Q str -> eventually P str -> eventually Q str.
intros P Q str H1 H2.
generalize H1; clear H1.
elim H2; clear H2; clear str.
intros str H1 H2.
unfold implies in H2.
inversion H2.
constructor 1.
apply H.
rewrite H3; assumption.
intros s str H_P H_rec H_implies.
constructor 2.
apply H_rec.
inversion_clear H_implies.
auto.
Qed.

Lemma congruence_eventually :
 forall (P Q : stream_formula state) (str : stream state),
 implies P Q str -> implies (eventually P) (eventually Q) str.

unfold implies in |- *; intros P Q H str.
apply
 always_assumption with (Q := fun str0 : stream state => P str0 -> Q str0);
 auto.
clear str; intros str H_always H_ev.
apply implies_eventually with (P := P); auto.
Qed.

Lemma implies_always :
 forall (P Q : stream_formula state) (str : stream state),
 implies P Q str -> always P str -> always Q str.

intros P Q.
cofix.
 intro str; case str; clear str.
intros s str H1 H2.
constructor.
inversion_clear H2.
inversion_clear H1.
auto.
apply implies_always.
inversion_clear H1.
auto.
inversion H2; auto.
Qed.

Lemma congruence_always :
 forall (P Q : stream_formula state) (str : stream state),
 implies P Q str -> implies (always P) (always Q) str.

unfold implies in |- *; intros P Q H str.
apply
 always_assumption with (Q := fun str0 : stream state => P str0 -> Q str0);
 auto.
clear str; intros str H_always H_al.
apply implies_always with (P := P); auto.
Qed.

Lemma implies_infinitely_often :
 forall (P Q : stream_formula state) (str : stream state),
 implies P Q str -> infinitely_often P str -> infinitely_often Q str.

unfold infinitely_often in |- *.
intros P Q str H_implies H_always.
apply implies_always with (P := eventually P); try assumption.
unfold implies in |- *; unfold implies in H_implies.
apply always_assumption with (Q := fun str : stream state => P str -> Q str).
intros; apply implies_eventually with (P := P) (Q := Q); auto.
assumption.
 Qed.

Lemma congruence_infinitely_often :
 forall (P Q : stream_formula state) (str : stream state),
 implies P Q str -> implies (infinitely_often P) (infinitely_often Q) str.

unfold implies in |- *; intros P Q H str.
apply
 always_assumption with (Q := fun str0 : stream state => P str0 -> Q str0);
 auto.
clear str; intros str H_always H_inf.
apply implies_infinitely_often with (P := P); auto.
Qed.

Lemma invariant_implies :
 forall P Q I : stream_formula state,
 (forall str : stream state, always I str -> P str -> Q str) ->
 forall str : stream state, always I str -> implies P Q str.

intros P Q I H str H'.
unfold implies in |- *.
apply always_assumption with (Q := I); assumption.

Qed.

Lemma inv_implies_inf_often :
 forall P Q I : stream_formula state,
 (forall str : stream state, always I str -> P str -> Q str) ->
 forall str : stream state,
 always I str -> infinitely_often P str -> infinitely_often Q str.

intros P Q I H str Inv H_inf.
apply implies_infinitely_often with (P := P); try assumption.
apply invariant_implies with (I := I); assumption.
Qed.

Lemma implies_until :
 forall (P P' Q Q' : stream_formula state) (str : stream state),
 implies P P' str -> implies Q Q' str -> until P Q str -> until P' Q' str.

intros P P' Q Q' str HP HQ H.
generalize HP HQ; clear HP HQ.
elim H; clear H; clear str.
intros str HQ HP Himplie.
constructor 1.
inversion Himplie.
apply H.
rewrite H1; auto.
intros s str HP Huntil H_rec HIP HIQ.
constructor 2.
inversion HIP; auto.
apply H_rec.
inversion HIP; auto.
inversion HIQ; auto.
Qed.

Lemma implies_until_state :
 forall P P' Q Q' : state_formula state,
 (forall s : state, P s -> P' s) ->
 (forall s : state, Q s -> Q' s) ->
 forall str : stream state,
 until (state2stream_formula P) (state2stream_formula Q) str ->
 until (state2stream_formula P') (state2stream_formula Q') str.

intros P P' Q Q' H_P_P' H_Q_Q' str H.
apply
 implies_until
  with (P := state2stream_formula P) (Q := state2stream_formula Q);
 try assumption.
apply lift_implies_state with (P := P); assumption.
apply lift_implies_state with (P := Q); assumption.
Qed.

Lemma implies_safe :
 forall P Q : stream_formula state,
 (forall str : stream state, implies P Q str) ->
 safe init_state transition P -> safe init_state transition Q.

unfold safe in |- *.
intros P Q imp_P_Q H_P str run_str.
apply implies_always with (P := P); auto.
Qed.

End congruence.


(*|
###########################################
I need help defining a concatenation in Coq
###########################################

:Link: https://stackoverflow.com/q/35947749
|*)

(*|
Question
********

I need to define a concatenation function, first some context, I
define the set "accepts"
|*)

Inductive accepts : Set :=
| True  : accepts
| fun_m : accepts -> accepts -> accepts
| n_fun : nat -> accepts -> accepts.

(*|
Then I need to be able to manipulate a very specific subset of
accepts: the first and last ones on the list, so ``True`` and
``n_fun`` only. I do it with a mix of inductive and record like this:
|*)

Inductive n_sub : accepts -> Prop :=
| a1 : n_sub True
| a2 : forall (n : nat) (A : accepts), n_sub A -> n_sub (n_fun n A).

Record sub : Set := mk_s {A : accepts ; WS : n_sub A}.

(*|
As you might see this will give me strings of natural numbers followed
by ``True``, exclusively, so I want to deal with the subset of accepts
that yields ``n ... k True``. Consider I have two of this strings, I
want to define the function that sends ``ab... True`` and ``xy...
True`` into ``ab...xy... True``.
|*)

Fail Fixpoint concatenate (A0 A1 : accepts) (x : n_sub A0) (y : n_sub A1) : accepts
  := match x, y with
     | a1, q => B
     | a2 n A0 x, y => n_fun n (concatenate A0 A1)
     end. (* .fails *)

(*|
Clearly, this doesn't work... I have tried 100 variations of this:
using the accepts directly and sending the things to void, using the
record inside, mixing the accepts and the sub in different variations,
etc, etc... I'm just out of ideas and need someone to help me fix this
concatenate, please! Thank you in advance for your help!
|*)

(*|
Answer (jbapple)
****************

Sometimes it is helpful to write computable predicates, rather than
inductive ones (my ``ok``, below, vs. your ``n_sub``).
|*)

Reset Initial. (* .none *)
Inductive accepts :=
| valid : accepts
| fun_m : accepts -> accepts -> accepts
| n_fun : nat -> accepts -> accepts.

Fixpoint ok x :=
  match x with
  | valid => true
  | n_fun _ y => ok y
  | _ => false
  end.

(*|
Since ``ok`` is computable, you can use it for all sorts of things
later you might care about, but you can also use it in proofs (see
below).
|*)

Fixpoint concat x y :=
  match x with
  | valid => y
  | n_fun z zs => n_fun z (concat zs y)
  | _ => y
  end.

(*|
``concat`` punts on non-``ok`` input. Later, I'll show a more
strictly-typed version, ``concatLegit``.
|*)

Lemma concatOk : forall x y,
    ok x = true -> ok y = true -> ok (concat x y) = true.
Proof. induction x; auto. Qed.

Definition legit := { x : accepts & ok x = true }.

Definition concatLegit (x y : legit) : legit.
Proof.
  destruct x as [x p]. destruct y as [y q].
  exists (concat x y).
  apply concatOk; auto.
Defined.

Print concatLegit. (* .unfold *)

(*|
Answer (galas)
****************

The problem here is that you are trying to pattern-match on a thing
whose type lives in ``Prop`` to generate something of type ``accepts``
which lives in ``Set``. This is not allowed by Coq's type system. What
you have to do is pattern-match on the things of type ``accepts`` and
then use the properties to dismiss the impossible cases.

Here I'll use the interactive mode. This allows me to only define the
part of the computation I am interested in using ``refine`` and
leaving blank (using ``_``) the parts I will deal with later on.

Because some irrelevant branches might appear when inspecting ``A0``,
I need to generalise the return type: instead of building an
``accepts``, I'll build a proof that ``n_sub a -> accepts`` where
``a`` is whatever ``A0`` was matched to.

.. coq:: none
|*)

Reset Initial.

Inductive accepts : Set :=
| True  : accepts
| fun_m : accepts -> accepts -> accepts
| n_fun : nat -> accepts -> accepts.

Inductive n_sub : accepts -> Prop :=
| a1 : n_sub True
| a2 : forall (n : nat) (A : accepts), n_sub A -> n_sub (n_fun n A).

(*||*)

Fixpoint concatenate (A0 A1 : accepts) (x : n_sub A0) (y : n_sub A1) : accepts.
Proof.
  refine
    ((match A0 as a return n_sub a -> accepts with
      | True        => fun _      => A1
      | n_fun n A0' => fun Hn_fun => n_fun n (concatenate A0' A1 _ y)
      | _           => _
      end) x).

(*|
I now am left with two proofs: I need to define the case I left empty
but that is rather easy: the assumption ``n_sub (fun_m a a0)`` is
contradictory! I can prove ``False`` by inverting it:
|*)

  - intro Hf. apply False_rec. inversion Hf.

(*|
Now, I have to prove that ``n_sub A0'`` holds given the assumption
``Hn_fun`` that ``n_sub (n_fun n A0')`` holds true. Once more
``inversion`` will do the trick:
|*)

  - inversion Hn_fun. assumption.

(*|
And that's it! The tricky part here is to identify the hypothesis that
needs to be generalised and use the appropriate ``as ... return ...``
in the `dependent pattern-matching
<https://coq.inria.fr/refman/Reference-Manual020.html#sec644>`__. The
rest is made quite convenient by the use of the interactive mode and
the help of ``refine`` to build incomplete proof terms.
|*)


Inductive testor :=
  | Constr1 : list testor -> testor
  | Constr2 : testor -> testor.


From Hammer Require Import Hammer.

Require Import Wf_nat.
Require Import BinInt.
Require Import Zcompare.
Require Import Zorder.
Require Import Bool.
Local Open Scope Z_scope.

Notation iter := @Z.iter (compat "8.3").

Lemma iter_nat_of_Z : forall n A f x, 0 <= n ->
Z.iter n f x = iter_nat (Z.abs_nat n) A f x.
Proof. hammer_hook "Zmisc" "Zmisc.iter_nat_of_Z".
intros n A f x; case n; auto.
intros p _; unfold Z.iter, Z.abs_nat; apply Pos2Nat.inj_iter.
intros p abs; case abs; trivial.
Qed.