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

Module ResponseTimeAnalysisEDF.

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

  (* In this section, we prove that any fixed point in Bertogna and
     Cirinei's RTA for EDF scheduling is a safe response-time bound.
     This analysis can be 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.

    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.

    (* 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 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 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 arr_seq sched.
    Hypothesis H_edf_policy: respects_JLFP_policy job_arrival job_cost 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.

    (* ... where 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 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_other R,
        (tsk_other, R) \in rt_bounds -> R <= task_deadline tsk_other.

    (* 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 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, ... *)
      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 the task set, ...*)
        Lemma bertogna_edf_tsk_other_in_ts: tsk_other \in ts.
        Proof.
          rewrite set_mem -H_rt_bounds_contains_all_tasks.
          by 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) (arr_seq0 := arr_seq)
            (job_arrival0 := job_arrival) (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 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 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_(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 CONSTR.
        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_cost0 := job_cost) (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.
          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 CONSTR; 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 CONSTR // -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); first by done.
        {
          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.

      (* 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,
          job_arrival j <= t < job_arrival j + R ->
          backlogged job_arrival job_cost 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_job_of_tsk into JOBtsk,
               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.
        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 arr_seq sched.
        apply PLAT with (j := j); try (by done);
          first by apply PARAMS; rewrite -JOBtsk; apply FROMTS.
        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 + R0); try (by done).
        {
          rewrite 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_ltn_trans with (n := t); last by done.
          apply leq_trans with (n := job_arrival j0 + task_period tsk0); last by done.
          rewrite leq_add2l; apply leq_trans with (n := task_deadline tsk0); first by apply NOMISS.
          by apply RESTR; rewrite -TSK0 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 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) 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.
          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.
        apply DIFFTASK with (t := t); try (by done); first by auto.
        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_all_previous_jobs_completed_on_time into BEFOREok,
               H_tasks_miss_no_deadlines into NOMISS, H_jobs_come_from_arrival_sequence into FROMSEQ,
               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 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 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_(job_arrival j <= t < job_arrival j + 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 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 sched j1 t).
          {
            apply scheduled_implies_pending; try by done.
            by apply/existsP; exists cpu; apply/eqP.
          }
          assert (PENDING2: pending job_arrival job_cost 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)
            (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) &&
                     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 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.
            apply leq_trans with (n := x tsk_k); first 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 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' 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 ResponseTimeAnalysisEDF.


Require Import List.
Require Import Arith.
Require Import Program.

Require Import Axioms.
Require Import TypeSyntax.

Set Implicit Arguments.

Definition context := fun g => list (type g).

Inductive In (A:Set) : nat -> list A -> A -> Set :=
| in_cons1 : forall x l,
  In 0 (cons x l) x
| in_cons2 : forall n l x y,
  In n l x ->
  In (S n) (cons y l) x.

Definition context_shift1 : forall g, context g -> context (S g) :=
 fun g ctxt => map (@shift1 g) ctxt.

Inductive term : forall g, context g -> type g -> Set :=
| t_var : forall g (ctxt:context g) i ty,
  In i ctxt ty ->
  term ctxt ty

| t_app : forall g (ctxt:context g) ty1 ty2,
  term ctxt (ty_arr ty1 ty2) ->
  term ctxt ty1 ->
  term ctxt ty2

| t_abs : forall g (ctxt:context g) ty1 ty2,
  term (ty1::ctxt) ty2 ->
  term ctxt (ty_arr ty1 ty2)

| t_tyabs : forall g (ctxt:context g) ty,
  term (context_shift1 ctxt) ty ->
  term ctxt (ty_forall ty)

| t_tyapp : forall g (ctxt:context g) ty1 ty2,
  term ctxt (ty_forall ty1) ->
  term ctxt (type_subst1 ty1 ty2).


Require Import CT.Algebra.Rng.
Require Import CT.Category.

(** * Rngs form a category.

*)
Program Definition RngCategory (T : Type) : Category :=
  {| ob := @Rng T;
     mor := RngHomomorphism;
     comp := fun _ _ _ => rng_hom_composition;
     id := fun _ => rng_hom_id;
     assoc := fun _ _ _ _ => rng_hom_composition_assoc
  |}.
Next Obligation.
Proof.
  symmetry.
  apply rng_hom_composition_assoc.
Qed.
Next Obligation.
Proof. apply rng_hom_eq. reflexivity. Qed.
Next Obligation.
Proof. apply rng_hom_eq. reflexivity. Qed.


Require Export Coq.micromega.Lia CoqRecon.Util.Base.
Require Import Coq.Relations.Relation_Operators
        Coq.Wellfounded.Lexicographic_Product
        Coq.Logic.FunctionalExtensionality Wf_nat.

Reserved Notation "x ⊏ y" (at level 70, no associativity).
Reserved Notation "x ≤ y" (at level 70, no associativity).

Section Prod.
  Context {A B : Type}.

  Definition nondep_prod '((a,b) : A * B) : {_ : A & B} := existT _ a b.

  Section WF.
    Variable R : A * B -> A * B -> Prop.
    Variable S : {_ : A & B} -> {_ : A & B} -> Prop.

    Hypothesis HRS : forall a b a' b',
        R (a,b) (a',b') <-> S (existT _ a b) (existT _ a' b').

    Lemma prod_acc : forall a b,
        Acc R (a,b) <-> Acc S (existT _ a b).
    Proof.
      intros a b; split; intros H.
      - remember (a, b) as ab;
          generalize dependent b;
          generalize dependent a.
        induction H as [[a' b'] _ IH];
          intros a b Heq; inv Heq; subst.
        constructor. intros [a' b'] HS.
        rewrite <- HRS in HS. firstorder.
      - remember (existT _ a b) as ab;
          generalize dependent b;
          generalize dependent a.
        induction H as [[a' b'] _ IH];
          intros a b Heq; inv Heq; subst.
        constructor. intros [a' b'] HR.
        rewrite HRS in HR. firstorder.
    Qed.

    Local Hint Resolve prod_acc : core.

    Lemma prod_wf :
      well_founded R <->
      well_founded S.
    Proof.
      unfold well_founded. split; intros H [a b].
      - rewrite <- prod_acc; auto.
      - rewrite prod_acc; auto.
    Qed.
  End WF.
End Prod.

Definition lex_prod {A B : Type}
           (leA : A -> A -> Prop) (leB : B -> B -> Prop)
           (p p' : A * B) : Prop :=
  lexprod A (fun _ => B) leA (fun _ => leB) (nondep_prod p) (nondep_prod p').

Definition le_pair : nat * nat -> nat * nat -> Prop := lex_prod lt le.

Notation "p1 ≤ p2" := (le_pair p1 p2) : type_scope.

Definition lt_pair_le
           '((m,n) : nat * nat) '((m',n') : nat * nat) : Prop := (m, S n) ≤ (m', n').

Definition lt_pair : nat * nat -> nat * nat -> Prop := lex_prod lt lt.

Notation "p1 ⊏ p2" := (lt_pair p1 p2) : type_scope.

Lemma lt_pair_spec : forall p p' : nat * nat,
    p ⊏ p' <-> lt_pair_le p p'.
Proof.
  intros [m n] [m' n']; unfold "⊏", lt_pair_le, "≤", lex_prod.
  split; intros H; inv H.
  - left; assumption.
  - right; assumption.
  - left; assumption.
  - right; assumption.
Qed.

Local Hint Resolve lt_wf : core.

Theorem wf_lt_pair : well_founded lt_pair.
Proof.
  rewrite prod_wf with
      (S := lexprod nat (fun _ => nat) lt (fun _ => lt))
    by intuition.
  apply wf_lexprod; auto.
Qed.


(*
  Reduction from:
    Turing Machine Halting (HaltTM 1)
  to:
    Halting of one counter machines (CM1_HALT)
*)

(** ** HaltTM 1 reduces to CM1_HALT  *)

From Undecidability.Synthetic Require Import Definitions ReducibilityFacts.

Require Import Undecidability.TM.TM.

Require Import Undecidability.FRACTRAN.Reductions.HaltTM_1_to_FRACTRAN_HALTING.

From Undecidability.MinskyMachines
  Require Import FRACTRAN_to_MMA2 MMA2_to_MM2.

From Undecidability.CounterMachines
  Require Import CM1 MM2_HALTING_to_CM1_HALT.

(* Many-one reduction from Turing machine halting to
  one counter machine halting *)
Theorem reduction : HaltTM 1 ⪯ CM1_HALT.
Proof.
  apply (reduces_transitive HaltTM_to_FRACTRAN_REG_HALTING).
  apply (reduces_transitive FRACTRAN_REG_MMA2_HALTING).
  apply (reduces_transitive MMA2_MM2_HALTING).
  exact MM2_HALTING_to_CM1_HALT.reduction.
Qed.


Require Import Crypto.Arithmetic.PrimeFieldTheorems.
Require Import Crypto.Specific.solinas64_2e468m17_9limbs.Synthesis.

(* TODO : change this to field once field isomorphism happens *)
Definition square :
  { square : feBW_loose -> feBW_tight
  | forall a, phiBW_tight (square a) = F.mul (phiBW_loose a) (phiBW_loose a) }.
Proof.
  Set Ltac Profiling.
  Time synthesize_square ().
  Show Ltac Profile.
Time Defined.

Print Assumptions square.


(************************************************************************)
(* Copyright 2006 Milad Niqui                                           *)
(* This file is distributed under the terms of the                      *)
(* GNU Lesser General Public License Version 2.1                        *)
(* A copy of the license can be found at                                *)
(*                  <http://www.gnu.org/licenses>                       *)
(************************************************************************)

(** Formalisation of the quadratic algorithm

<<
quadratic xi (x:xs) (y:ys) | (Incl_T_L_dec xi)  = LL : quadratic (LL_inv o xi) (x:xs) (y:ys)
                           | (Incl_T_R_dec xi)  = RR : quadratic (RR_inv o xi) (x:xs) (y:ys)
                           | (Incl_T_M_dec xi)  = MM : quadratic (MM_inv o xi) (x:xs) (y:ys)
                           | otherwise = quadratic (xi o_l x o_r y) xs ys
>>

*)

Require Import digits.

Inductive emits_q : Tensor -> Reals -> Reals -> Prop :=
  | emits_q_L : forall (xi:Tensor) (alpha beta:Reals), Incl_T xi LL -> emits_q xi alpha beta
  | emits_q_R : forall (xi:Tensor) (alpha beta:Reals), Incl_T xi RR -> emits_q xi alpha beta
  | emits_q_M : forall (xi:Tensor) (alpha beta:Reals), Incl_T xi MM -> emits_q xi alpha beta
  | emits_q_absorbs : forall (xi:Tensor) (alpha beta:Reals),
              		  emits_q (right_product (left_product xi (hd alpha)) (hd beta)) (tl alpha) (tl beta) ->
                          emits_q xi alpha beta.

Scheme emits_q_ind_dep := Induction for emits_q Sort Prop.

Lemma emits_q_absorbs_inv: forall xi (alpha beta:Reals), ~(Incl_T xi LL)-> ~(Incl_T xi RR) -> ~(Incl_T xi MM) ->
             emits_q xi alpha beta -> emits_q (right_product (left_product xi (hd alpha)) (hd beta)) (tl alpha) (tl beta).
Proof.
 destruct 4; trivial; contradiction.
Defined.

Fixpoint modulus_q (xi:Tensor) (alpha beta:Reals) (H1:emits_q xi alpha beta) {struct H1}
        : prodT Digit (prodT Tensor (prodT Reals Reals)) :=
   match Incl_T_dec_D xi LL with
   | left _ => pairT LL (pairT (m_product inv_LL xi) (pairT alpha beta))
   | right H_emission_L =>
       match Incl_T_dec_D xi RR with
       | left _ => pairT RR (pairT (m_product inv_RR xi) (pairT alpha beta))
       | right H_emission_R =>
           match Incl_T_dec_D xi MM with
           | left _ => pairT MM (pairT (m_product inv_MM xi) (pairT alpha beta))
           | right H_emission_M =>
               modulus_q (right_product (left_product xi (hd alpha)) (hd beta)) (tl alpha) (tl beta)
                 (emits_q_absorbs_inv xi alpha beta H_emission_L H_emission_R H_emission_M H1)
           end
       end
   end.

Lemma modulus_q_PI:forall xi alpha beta H1 H2,  modulus_q xi alpha beta H1 = modulus_q xi alpha beta H2.
Proof.
 intros xi alpha beta H1.
 pattern alpha, beta, H1.
 elim H1 using emits_q_ind_dep;
 clear H1 xi;
   [ intros xi alpha0 beta0 i H2; generalize i
   | intros xi alpha0 beta0 i H2; generalize i
   | intros xi alpha0 beta0 i H2; generalize i
   | intros xi alpha0 beta0 f H H2; generalize f H
   ];
   pattern alpha0, beta0, H2;
   elim H2 using emits_q_ind_dep;
   first
    [ intros xi0 alpha' beta' H_primity H_primity'; simpl; case (Incl_T_dec_D xi0 LL); intro; trivial; contradiction
    | intros xi0 alpha' beta' H_primity H_primity'; simpl; case (Incl_T_dec_D xi0 RR); intro; trivial; contradiction
    | intros xi0 alpha' beta' H_primity H_primity'; simpl; case (Incl_T_dec_D xi0 MM); intro; trivial; contradiction
    | intros; contradiction]  ||
    (intro xi0; intros; simpl;
      case (Incl_T_dec_D xi0 LL); intro; contradiction ||
	case (Incl_T_dec_D xi0 RR); intro; contradiction ||
	  case (Incl_T_dec_D xi0 MM); intro; contradiction ||
	    trivial).
Defined.

Lemma modulus_q_PI_strong:forall xi xi' alpha beta alpha' beta' H1 H2, xi=xi'->alpha=alpha' -> beta = beta' ->
   modulus_q xi alpha beta H1 = modulus_q xi' alpha' beta' H2.
Proof.
 intros; subst; apply modulus_q_PI.
Defined.

Lemma modulus_q_L:forall (xi:Tensor) (alpha beta:Reals) (t: emits_q xi alpha beta),(Incl_T xi LL) ->
                 modulus_q xi alpha beta t=pairT LL (pairT (m_product inv_LL xi) (pairT alpha beta)).
Proof.
 intros xi alpha beta t t_l.
 transitivity (modulus_q xi alpha beta (emits_q_L _ _ _ t_l)).
 apply modulus_q_PI.
 simpl;
  case (Incl_T_dec_D xi LL); try contradiction;
   intros; reflexivity.
Defined.

Lemma modulus_q_R:forall (xi:Tensor) (alpha beta:Reals) (t: emits_q xi alpha beta), ~(Incl_T xi LL) ->  (Incl_T xi RR) ->
                 modulus_q xi alpha beta t=pairT RR (pairT (m_product inv_RR xi) (pairT alpha beta)).
Proof.
 intros xi alpha beta t t_l t_r.
 transitivity (modulus_q xi alpha beta (emits_q_R _ _ _ t_r)).
 apply modulus_q_PI.
 simpl;
   case (Incl_T_dec_D xi LL); try contradiction;
     case (Incl_T_dec_D xi RR); try contradiction;
      intros; reflexivity.
Defined.

Lemma modulus_q_M:forall (xi:Tensor) (alpha beta:Reals) (t: emits_q xi alpha beta),~(Incl_T xi LL)->~(Incl_T xi RR)->(Incl_T xi MM)->
                 modulus_q xi alpha beta t=pairT MM (pairT (m_product inv_MM xi) (pairT alpha beta)).
Proof.
 intros xi alpha beta t t_l t_r t_m.
 transitivity (modulus_q xi alpha beta (emits_q_M _ _ _ t_m)).
 apply modulus_q_PI.
 simpl;
 case (Incl_T_dec_D xi LL); try contradiction;
  case (Incl_T_dec_D xi RR); try contradiction;
   case (Incl_T_dec_D xi MM); try contradiction;
    intros; reflexivity.
Defined.

Lemma modulus_q_absorbs:forall (xi:Tensor) (alpha beta:Reals) (t: emits_q xi alpha beta),~(Incl_T xi LL)->~(Incl_T xi RR)->~(Incl_T xi MM)->
  forall t', modulus_q xi alpha beta t = modulus_q (right_product (left_product xi (hd alpha)) (hd beta)) (tl alpha) (tl beta) t'.
Proof.
 intros xi alpha beta t t_l t_r t_m t'.
 transitivity (modulus_q xi alpha beta (emits_q_absorbs _ _ _ t')).
 apply modulus_q_PI.
 simpl.
 case (Incl_T_dec_D xi LL); try contradiction;
  case (Incl_T_dec_D xi RR); try contradiction;
   case (Incl_T_dec_D xi MM); try contradiction;
    intros _; reflexivity.
Defined.

Inductive step_productive_q : nat -> Tensor -> Reals -> Reals -> Prop :=
 |  step_productive_q_O : forall (xi:Tensor) (alpha beta:Reals), emits_q xi alpha beta -> step_productive_q O xi alpha beta
 |  step_productive_q_S : forall n (xi:Tensor) (alpha beta:Reals) (h:emits_q xi alpha beta),
             step_productive_q n (fstT (sndT (modulus_q xi alpha beta h)))
              (fstT (sndT (sndT (modulus_q xi alpha beta h)))) (sndT (sndT (sndT (modulus_q xi alpha beta h)))) ->
              step_productive_q (S n) xi alpha beta.

Lemma step_productive_q_inv_1: forall n (xi:Tensor) (alpha beta:Reals),
     step_productive_q n xi alpha beta -> emits_q xi alpha beta.
Proof.
 intros.
 destruct H; trivial.
Defined.

Lemma step_productive_q_S_inv_2: forall n (xi:Tensor) (alpha beta:Reals) (h:emits_q xi alpha beta),
         step_productive_q (S n) xi alpha beta ->
         step_productive_q n (fstT (sndT (modulus_q xi alpha beta h)))
                 (fstT (sndT (sndT (modulus_q xi alpha beta h)))) (sndT (sndT (sndT (modulus_q xi alpha beta h)))).
Proof.
 exact (
fun (n : nat) (xi : Tensor) (alpha beta : Reals) (h : emits_q xi alpha beta)
  (H : step_productive_q (S n) xi alpha beta) =>
let H0 :=
  match
    H in (step_productive_q n0 t r r0)
    return
      (n0 = S n ->
       t = xi ->
       r = alpha ->
       r0 = beta ->
       step_productive_q n (fstT (sndT (modulus_q xi alpha beta h)))
         (fstT (sndT (sndT (modulus_q xi alpha beta h))))
         (sndT (sndT (sndT (modulus_q xi alpha beta h)))))
  with
  | step_productive_q_O xi0 alpha0 beta0 H0 =>
      fun (H1 : 0 = S n) (H2 : xi0 = xi) (H3 : alpha0 = alpha)
        (H4 : beta0 = beta) =>
      let H :=
        (let H0 :=
           eq_ind 0
             (fun e : nat => match e with
                             | O => True
                             | S _ => False
                             end) I (S n) H1 in
         False_ind
           (xi0 = xi ->
            alpha0 = alpha ->
            beta0 = beta ->
            emits_q xi0 alpha0 beta0 ->
            step_productive_q n (fstT (sndT (modulus_q xi alpha beta h)))
              (fstT (sndT (sndT (modulus_q xi alpha beta h))))
              (sndT (sndT (sndT (modulus_q xi alpha beta h))))) H0) H2 H3
          H4 in
      H H0
  | step_productive_q_S n0 xi0 alpha0 beta0 h0 H0 =>
      fun (H1 : S n0 = S n) (H2 : xi0 = xi) (H3 : alpha0 = alpha)
        (H4 : beta0 = beta) =>
      let H :=
        (let H0 :=
           f_equal (fun e : nat => match e with
                                   | O => n0
                                   | S n => n
                                   end) H1 in
         eq_ind n
           (fun n0 : nat =>
            xi0 = xi ->
            alpha0 = alpha ->
            beta0 = beta ->
            step_productive_q n0
              (fstT (sndT (modulus_q xi0 alpha0 beta0 h0)))
              (fstT (sndT (sndT (modulus_q xi0 alpha0 beta0 h0))))
              (sndT (sndT (sndT (modulus_q xi0 alpha0 beta0 h0)))) ->
            step_productive_q n (fstT (sndT (modulus_q xi alpha beta h)))
              (fstT (sndT (sndT (modulus_q xi alpha beta h))))
              (sndT (sndT (sndT (modulus_q xi alpha beta h)))))
           (fun H2 : xi0 = xi =>
            let H :=
              eq_ind xi
                (fun t : Tensor =>
                 forall h0 : emits_q t alpha0 beta0,
                 alpha0 = alpha ->
                 beta0 = beta ->
                 step_productive_q n
                   (fstT (sndT (modulus_q t alpha0 beta0 h0)))
                   (fstT (sndT (sndT (modulus_q t alpha0 beta0 h0))))
                   (sndT (sndT (sndT (modulus_q t alpha0 beta0 h0)))) ->
                 step_productive_q n
                   (fstT (sndT (modulus_q xi alpha beta h)))
                   (fstT (sndT (sndT (modulus_q xi alpha beta h))))
                   (sndT (sndT (sndT (modulus_q xi alpha beta h)))))
                (fun (h0 : emits_q xi alpha0 beta0)
                   (H3 : alpha0 = alpha) (H4 : beta0 = beta)
                   (H1 : step_productive_q n
                           (fstT (sndT (modulus_q xi alpha0 beta0 h0)))
                           (fstT
                              (sndT (sndT (modulus_q xi alpha0 beta0 h0))))
                           (sndT
                              (sndT (sndT (modulus_q xi alpha0 beta0 h0))))) =>
                 (let H :=
                    eq_ind_r
                      (fun beta0 : Reals =>
                       forall h0 : emits_q xi alpha0 beta0,
                       step_productive_q n
                         (fstT (sndT (modulus_q xi alpha0 beta0 h0)))
                         (fstT (sndT (sndT (modulus_q xi alpha0 beta0 h0))))
                         (sndT (sndT (sndT (modulus_q xi alpha0 beta0 h0)))) ->
                       step_productive_q n
                         (fstT (sndT (modulus_q xi alpha beta h)))
                         (fstT (sndT (sndT (modulus_q xi alpha beta h))))
                         (sndT (sndT (sndT (modulus_q xi alpha beta h)))))
                      (fun h0 : emits_q xi alpha0 beta =>
                       let H :=
                         eq_ind_r
                           (fun alpha0 : Reals =>
                            forall h0 : emits_q xi alpha0 beta,
                            step_productive_q n
                              (fstT (sndT (modulus_q xi alpha0 beta h0)))
                              (fstT
                                 (sndT (sndT (modulus_q xi alpha0 beta h0))))
                              (sndT
                                 (sndT (sndT (modulus_q xi alpha0 beta h0)))) ->
                            step_productive_q n
                              (fstT (sndT (modulus_q xi alpha beta h)))
                              (fstT
                                 (sndT (sndT (modulus_q xi alpha beta h))))
                              (sndT
                                 (sndT (sndT (modulus_q xi alpha beta h)))))
                           (fun h0 : emits_q xi alpha beta =>
                            eq_ind_r
                              (fun
                                 p : prodT Digit
                                       (prodT Tensor (prodT Reals Reals)) =>
                               step_productive_q n
                                 (fstT (sndT (modulus_q xi alpha beta h0)))
                                 (fstT
                                    (sndT
                                       (sndT (modulus_q xi alpha beta h0))))
                                 (sndT
                                    (sndT
                                       (sndT (modulus_q xi alpha beta h0)))) ->
                               step_productive_q n (fstT (sndT p))
                                 (fstT (sndT (sndT p)))
                                 (sndT (sndT (sndT p))))
                              (fun
                                 H1 : step_productive_q n
                                        (fstT
                                           (sndT
                                              (modulus_q xi alpha beta h0)))
                                        (fstT
                                           (sndT
                                              (sndT
                                                 (modulus_q xi alpha beta
                                                  h0))))
                                        (sndT
                                           (sndT
                                              (sndT
                                                 (modulus_q xi alpha beta
                                                  h0)))) => H1)
                              (modulus_q_PI xi alpha beta h h0)) H3 in
                       H h0) H4 in
                  H h0) H1) xi0 (sym_eq H2) in
            H h0) n0 (sym_eq H0)) H2 H3 H4 in
      H H0
  end in
H0 (refl_equal (S n)) (refl_equal xi) (refl_equal alpha) (refl_equal beta)
).
Defined.

(** #<em>#Productivity predicate#</em># *)

Inductive productive_q : Tensor -> Reals -> Reals ->Prop :=
  |  productive_q_absorbs : forall (xi:Tensor) (alpha beta:Reals),
      (forall n, step_productive_q n xi alpha beta) -> productive_q xi alpha beta.

Lemma productive_q_emits_q:forall xi alpha beta,productive_q xi alpha beta -> emits_q xi alpha beta.
Proof.
 destruct 1.
 apply step_productive_q_inv_1 with O; trivial.
Defined.

Lemma modulus_q_productive_q: forall xi alpha beta (h:emits_q xi alpha beta),
  let xi':=fstT (sndT (modulus_q xi alpha beta h)) in
   let alpha':=fstT (sndT (sndT (modulus_q xi alpha beta h))) in
    let beta':=sndT (sndT (sndT (modulus_q xi alpha beta h))) in
      productive_q xi alpha beta -> productive_q xi' alpha' beta'.
Proof.
 intros xi alpha beta h xi' alpha' beta' h_p_alpha_beta.
 constructor.
 intro n.
 inversion h_p_alpha_beta.
 generalize (H (S n)).
 subst xi'.
 subst alpha'.
 subst beta'.
 apply step_productive_q_S_inv_2.
Defined.

(** Definition of the quadratic algorithm *)

CoFixpoint quadratic (xi:Tensor) (alpha beta:Reals) (H :productive_q xi alpha beta) : Reals :=
  Cons (fstT (modulus_q xi alpha beta (productive_q_emits_q xi alpha beta H)))
       (quadratic (fstT (sndT (modulus_q xi alpha beta (productive_q_emits_q xi alpha beta H))))
                  (fstT (sndT (sndT (modulus_q xi alpha beta (productive_q_emits_q xi alpha beta H)))))
		  (sndT (sndT (sndT (modulus_q xi alpha beta (productive_q_emits_q xi alpha beta H)))))
                  (modulus_q_productive_q xi alpha beta (productive_q_emits_q xi alpha beta H) H)).

(** At this point one can uncomment the following two lines in order to extract to Haskell.
<<
Extraction Language Haskell.
Extraction "Xquadratic.hs" quadratic.
>>
*)

(** We now prove the cofixed point equations of the quadratic algorithm *)

Lemma quadratic_unfolded:forall xi alpha beta p, quadratic xi alpha beta p =
    Cons (fstT (modulus_q xi alpha beta (productive_q_emits_q xi alpha beta p)))
       (quadratic (fstT (sndT (modulus_q xi alpha beta (productive_q_emits_q xi alpha beta p))))
                  (fstT (sndT (sndT (modulus_q xi alpha beta (productive_q_emits_q xi alpha beta p)))))
		  (sndT (sndT (sndT (modulus_q xi alpha beta (productive_q_emits_q xi alpha beta p)))))
                  (modulus_q_productive_q xi alpha beta (productive_q_emits_q xi alpha beta p) p)).
Proof.
 intros;
 rewrite (unfold_Stream (quadratic xi alpha beta p));
 reflexivity.
Defined.

Lemma quadratic_EPI_strong:forall xi xi' alpha alpha' beta beta' p p', xi=xi'->alpha=alpha'->beta=beta'->
                bisim (quadratic xi alpha beta p)  (quadratic xi' alpha' beta' p').
Proof.
 cofix.
 intros;
 rewrite quadratic_unfolded;
 rewrite (quadratic_unfolded _ _ _ p');
 constructor; simpl;
 [ idtac
 |  apply quadratic_EPI_strong
 ];
 rewrite (modulus_q_PI_strong _ _ _ _ _ _ (productive_q_emits_q xi alpha beta p) (productive_q_emits_q xi' alpha' beta' p')); trivial.
Defined.

Lemma quadratic_EPI:forall xi alpha beta p p', bisim (quadratic xi alpha beta p)  (quadratic xi alpha beta p').
Proof.
 intros xi alpha beta p p'; apply quadratic_EPI_strong; reflexivity.
Defined.

Lemma quadratic_absorbs :forall xi alpha beta (p:productive_q xi alpha beta), ~(Incl_T xi LL)->~(Incl_T xi RR)->~(Incl_T xi MM)->
                forall p', bisim (quadratic xi alpha beta p)  (quadratic (right_product (left_product xi (hd alpha)) (hd beta)) (tl alpha) (tl beta) p').
Proof.
 intros xi alpha beta p t_l t_r t_m p'.
 rewrite quadratic_unfolded.
 rewrite (quadratic_unfolded (right_product (left_product xi (hd alpha)) (hd beta))).
 generalize (productive_q_emits_q _ _ _ p); intros t.
 generalize (modulus_q_productive_q xi alpha beta t p).
 rewrite (modulus_q_absorbs _ _ _ t t_l t_r t_m (emits_q_absorbs_inv _ _ _ t_l t_r t_m t)).
  rewrite (modulus_q_PI _ _ _ (emits_q_absorbs_inv xi alpha beta t_l t_r t_m t)
                       (productive_q_emits_q (right_product (left_product xi (hd alpha)) (hd beta)) (tl alpha) (tl beta) p')).
 constructor; simpl; trivial; apply quadratic_EPI.
Defined.

Lemma quadratic_emits_L :forall xi alpha beta (p:productive_q xi alpha beta), (Incl_T xi LL) ->
                forall p', bisim (quadratic xi alpha beta p)  (Cons LL (quadratic (m_product inv_LL xi) alpha beta p')).
Proof.
 intros xi alpha beta p t_l p'.
 rewrite quadratic_unfolded.
 rewrite (quadratic_unfolded (m_product inv_LL xi)).
 generalize (productive_q_emits_q _ _ _ p); intros t.
 generalize (modulus_q_productive_q xi alpha beta t p).

 rewrite (modulus_q_L _ _ _ t t_l).
 intros.
 constructor; simpl; trivial.
 rewrite <- quadratic_unfolded;
 apply quadratic_EPI.
Defined.

Lemma quadratic_emits_R :forall xi alpha beta (p:productive_q xi alpha beta), ~(Incl_T xi LL) -> (Incl_T xi RR) ->
                forall p', bisim (quadratic xi alpha beta p)  (Cons RR (quadratic (m_product inv_RR xi) alpha beta p')).
Proof.
 intros xi alpha beta p t_l t_r p'.
 rewrite quadratic_unfolded.
 rewrite (quadratic_unfolded (m_product inv_RR xi)).
 generalize (productive_q_emits_q _ _ _ p); intros t.
 generalize (modulus_q_productive_q xi alpha beta t p).

 rewrite (modulus_q_R _ _ _ t t_l t_r).
 intros.
 constructor; simpl; trivial.
  rewrite <- quadratic_unfolded;
  apply quadratic_EPI.
Defined.

Lemma quadratic_emits_M :forall xi alpha beta (p:productive_q xi alpha beta), ~(Incl_T xi LL) -> ~(Incl_T xi RR) -> (Incl_T xi MM) ->
                forall p', bisim (quadratic xi alpha beta p)  (Cons MM (quadratic (m_product inv_MM xi) alpha beta p')).
Proof.
 intros xi alpha beta p t_l t_r t_m p'.
 rewrite quadratic_unfolded.
 rewrite (quadratic_unfolded (m_product inv_MM xi)).
 generalize (productive_q_emits_q _ _ _ p); intros t.
 generalize (modulus_q_productive_q xi alpha beta t p).

 rewrite (modulus_q_M _ _ _ t t_l t_r t_m).
 intros.
 constructor; simpl; trivial.
  rewrite <- quadratic_unfolded;
  apply quadratic_EPI.
Defined.


From Undecidability.MinskyMachines Require Import MM_computable MM_sss.
From Undecidability.FRACTRAN Require Import FRACTRAN_computable mm_fractran prime_seq.
From Undecidability.Shared.Libs.DLW Require Import gcd prime vec.

Require Import Nat Arith Lia List.

Lemma prime_qs n : prime (qs n).
Proof.
  eapply nthprime_prime.
Qed.

Opaque ps qs.

Lemma exp_const i m : exp i (Vector.const 0 m) = 1.
Proof.
  induction m in i |- *; cbn.
  - reflexivity.
  - now rewrite IHm.
Qed.

Lemma exp_app {n} (v : Vector.t nat n) i m (w : Vector.t nat m) :
  exp i (Vector.append v w) = exp i v * exp (i + n) w.
Proof.
  induction v in i, m, w |- *; cbn.
  - now rewrite !Nat.add_0_r.
  - rewrite IHv. ring_simplify. do 2 f_equal. lia.
Qed.

Theorem MM_computable_to_FRACTRAN_computable {k} (R : Vector.t nat k -> nat -> Prop) :
  MM_computable R -> FRACTRAN_computable R.
Proof.
  intros (n & P & H).
  eapply FRACTRAN_computable_iff. setoid_rewrite eval_iff in H.
  pose proof (mm_fractran_n_strong P) as (P' & regP & HP1 & HP2).
  exists P'. setoid_rewrite H. clear H. split. 1: eapply regP.
  setoid_rewrite FRACTRAN_sss.eval_iff. fold plus.
  intros v. split.
  - intros m. fold plus in *. intros (j & v' & H).
    edestruct HP1 as [j' Hj'].
    + eexists. eapply H.
    + rewrite FRACTRAN_sss.eval_iff in Hj'.
      unfold encode_state in Hj'. cbn in *.
      rewrite !PeanoNat.Nat.add_0_r in *.
      exists (ps j' * exp 2 v').
      split.
      * replace (ps j' * exp 2 v' * PeanoNat.Nat.pow (qs 1) m)
        with (ps j' * (PeanoNat.Nat.pow (qs 1) m) * exp 2 v') by lia.
        now rewrite exp_app, exp_const, Nat.mul_1_r, !Nat.mul_assoc in Hj'.
      * intros [Hp | Hp] % prime_div_mult. 3: eapply prime_qs.
        -- now eapply qs_ps_div in Hp.
        -- eapply qs_exp_div in Hp. 2: lia. eauto.
  - specialize (HP2 (0 ## (Vector.append v (Vector.const 0 n)))). cbn in HP2.
    rewrite Nat.add_0_r, exp_app, exp_const, Nat.mul_1_r in HP2.
    intros ((c & w) & H) % HP2. revert H.
    eapply (Vector.caseS' w). clear w. intros m w H.
    exists m, c, w. cbn. eapply H.
Qed.


(*

It is inconsistent in Coq to have Erasable, with its injectivity
axiom, work over all Types.  This is shown using Hurkens paradox, as
pointed out by Robert Dockins on the Coq-club email list.  Below is a
version of his proof.

However, note that this proof won't work if Erasable is Set->Prop
insetead of Type->Prop, as then Erasable Prop wouldn't be valid.  Hugo
Herbelin, also on the Coq-club email list, suggested limiting Erasable
to Set->Prop and using -impredicative-set.  It turns out that all of
the mindless-coding results work just as well when Erasable is limited
to Set, whether or not one uses -impredicative-set.  Adding
-impredicative-set increases the expressiveness of Set, so it might be
useful in the future.

*)

(*Erasable must be over Type, not Set, for Hurkens to show an inconsistency:*)
Inductive Erasable(A : Type) : Prop := erasable: A -> Erasable A.
Arguments erasable [A] _.
Axiom Erasable_inj : forall {A : Type}{a b : A}, erasable a=erasable b -> a=b.

Require Hurkens.

Definition Hurkens_paradox :=
  Hurkens.NoRetractFromSmallPropositionToProp.paradox.

Definition er_out (X:Erasable Prop) : Prop :=
  exists P:Prop, (X = erasable P) /\ P.

Theorem inconsistent : False.
Proof.
  apply (Hurkens_paradox (Erasable Prop) (@erasable Prop) er_out).
  - intros A H.
    red in H.
    destruct H as [P [H1 H2]].
    apply Erasable_inj in H1.
    subst A.
    exact H2.
  - intros A H.
    red.
    exists A.
    split.
    + reflexivity.
    + exact H.
Qed.

Check inconsistent.
Print Assumptions inconsistent.


Require Import Coq.Logic.Classical_Prop.
Require Import Coq.Logic.Classical_Pred_Type.
Require Import Coq.Classes.RelationClasses.
Require Import Coq.Relations.Relation_Definitions.
Require Import Logic.GeneralLogic.Base.
Require Import Logic.GeneralLogic.KripkeModel.
Require Import Logic.GeneralLogic.Semantics.Kripke.
Require Import Logic.MinimunLogic.Syntax.
Require Import Logic.MinimunLogic.Semantics.Kripke.

Local Open Scope logic_base.
Local Open Scope syntax.
Local Open Scope kripke_model.
Import KripkeModelFamilyNotation.
Import KripkeModelNotation_Intuitionistic.

Section Sound_Kripke.

Context {L: Language}
        {minL: MinimunLanguage L}
        {MD: Model}
        {kMD: KripkeModel MD}
        {M: Kmodel}
        {R: Relation (Kworlds M)}
        {po_R: PreOrder Krelation}
        {SM: Semantics L MD}
        {kiSM: KripkeIntuitionisticSemantics L MD M SM}
        {kminSM: KripkeMinimunSemantics L MD M SM}.

Lemma sound_modus_ponens:
  forall x y: expr,
    forall m,
      KRIPKE: M, m |= (x --> y) -> KRIPKE: M, m |= x -> KRIPKE: M, m |= y.
Proof.
  intros.
  rewrite sat_impp in H.
  specialize (H m).
  apply H; auto.
  reflexivity.
Qed.

Lemma sound_axiom1:
  forall x y: expr,
    forall m,
      KRIPKE: M, m |= x --> y --> x.
Proof.
  intros.
  rewrite sat_impp; intros.
  rewrite sat_impp; intros.
  eapply sat_mono; eauto.
Qed.

Lemma sound_axiom2:
  forall x y z: expr,
    forall m,
      KRIPKE: M, m |= (x --> y --> z) --> (x --> y) --> (x --> z).
Proof.
  intros.
  rewrite sat_impp; intros.
  rewrite sat_impp; intros.
  rewrite sat_impp; intros.
  assert (n <= n1) by (etransitivity; eauto).

  rewrite sat_impp in H0.
  specialize (H0 n1 H5 H4).
  rewrite sat_impp in H2.
  specialize (H2 n1 H3 H4).

  rewrite sat_impp in H0.
  specialize (H0 n1 ltac:(reflexivity) H2).
  auto.
Qed.

End Sound_Kripke.


(** * Classification of the Σ Type *)
(** In this file, we classify the basic structure of Σ types ([sigT],
    [sig], and [ex], in Coq).  In particular, we classify equalities
    of dependent pairs (inhabitants of Σ types), so that when we have
    an equality between two such pairs, or when we want such an
    equality, we have a systematic way of reducing such equalities to
    equalities at simpler types. *)
Require Import Crypto.Util.Equality.
Require Import Crypto.Util.GlobalSettings.

Local Arguments projT1 {_ _} _.
Local Arguments projT2 {_ _} _.
Local Arguments proj1_sig {_ _} _.
Local Arguments proj1_sig {_ _} _.
Local Arguments f_equal {_ _} _ {_ _} _.

(** ** Equality for [sigT] *)
Section sigT.

  (** *** Projecting an equality of a pair to equality of the first components *)
  Definition pr1_path {A} {P : A -> Type} {u v : sigT P} (p : u = v)
  : projT1 u = projT1 v
    := f_equal (@projT1 _ _) p.

  (** *** Projecting an equality of a pair to equality of the second components *)
  Definition pr2_path {A} {P : A -> Type} {u v : sigT P} (p : u = v)
  : eq_rect _ _ (projT2 u) _ (pr1_path p) = projT2 v.
  Proof.
    destruct p; reflexivity.
  Defined.

  (** *** Equality of [sigT] is itself a [sigT] *)
  Definition path_sigT_uncurried {A : Type} {P : A -> Type} (u v : sigT P)
             (pq : sigT (fun p : projT1 u = projT1 v => eq_rect _ _ (projT2 u) _ p = projT2 v))
  : u = v.
  Proof.
    destruct u as [u1 u2], v as [v1 v2]; simpl in *.
    destruct pq as [p q].
    destruct q; simpl in *.
    destruct p; reflexivity.
  Defined.

  (** *** Curried version of proving equality of sigma types *)
  Definition path_sigT {A : Type} {P : A -> Type} (u v : sigT P)
             (p : projT1 u = projT1 v) (q : eq_rect _ _ (projT2 u) _ p = projT2 v)
  : u = v
    := path_sigT_uncurried u v (existT _ p q).

  (** *** Equality of [sigT] when the property is an hProp *)
  Definition path_sigT_hprop {A P} (P_hprop : forall (x : A) (p q : P x), p = q)
             (u v : @sigT A P)
             (p : projT1 u = projT1 v)
    : u = v
    := path_sigT u v p (P_hprop _ _ _).

  (** *** Equivalence of equality of [sigT] with a [sigT] of equality *)
  (** We could actually use [IsIso] here, but for simplicity, we
      don't.  If we wanted to deal with proofs of equality of Σ types
      in dependent positions, we'd need it. *)
  Definition path_sigT_uncurried_iff {A P}
             (u v : @sigT A P)
    : u = v <-> (sigT (fun p : projT1 u = projT1 v => eq_rect _ _ (projT2 u) _ p = projT2 v)).
  Proof.
    split; [ intro; subst; exists eq_refl; reflexivity | apply path_sigT_uncurried ].
  Defined.

  (** *** Induction principle for [@eq (sigT _)] *)
  Definition path_sigT_rect {A P} {u v : @sigT A P} (Q : u = v -> Type)
             (f : forall p q, Q (path_sigT u v p q))
    : forall p, Q p.
  Proof. intro p; specialize (f (pr1_path p) (pr2_path p)); destruct u, p; exact f. Defined.
  Definition path_sigT_rec {A P u v} (Q : u = v :> @sigT A P -> Set) := path_sigT_rect Q.
  Definition path_sigT_ind {A P u v} (Q : u = v :> @sigT A P -> Prop) := path_sigT_rec Q.

  (** *** Equivalence of equality of [sigT] involving hProps with equality of the first components *)
  Definition path_sigT_hprop_iff {A P} (P_hprop : forall (x : A) (p q : P x), p = q)
             (u v : @sigT A P)
    : u = v <-> (projT1 u = projT1 v)
    := conj (f_equal projT1) (path_sigT_hprop P_hprop u v).

  (** *** Non-dependent classification of equality of [sigT] *)
  Definition path_sigT_nondep {A B : Type} (u v : @sigT A (fun _ => B))
             (p : projT1 u = projT1 v) (q : projT2 u = projT2 v)
  : u = v
    := @path_sigT _ _ u v p (eq_trans (transport_const _ _) q).

  (** *** Classification of transporting across an equality of [sigT]s *)
  Lemma eq_rect_sigT {A x} {P : A -> Type} (Q : forall a, P a -> Prop) (u : sigT (Q x)) {y} (H : x = y)
  : eq_rect x (fun a => sigT (Q a)) u y H
    = existT
        (Q y)
        (eq_rect x P (projT1 u) y H)
        match H in (_ = y) return Q y (eq_rect x P (projT1 u) y H) with
          | eq_refl => projT2 u
        end.
  Proof.
    destruct H, u; reflexivity.
  Defined.

  (** *** η Principle for [sigT] *)
  Definition sigT_eta {A P} (p : { a : A & P a })
    : p = existT _ (projT1 p) (projT2 p).
  Proof. destruct p; reflexivity. Defined.

  (** *** Boolean equality for [sigT] *)
  Definition sigT_beq {A A' P P'} (eqA : A -> A' -> bool) (eqP : forall a a', P a -> P' a' -> bool) (p : { a : A & P a }) (q : { a' : A' & P' a' })
    : bool
    := andb (eqA (projT1 p) (projT1 q)) (eqP _ _ (projT2 p) (projT2 q)).

  Lemma sigT_dec_bl {A P}
        (eqA : A -> A -> bool) (eqP : forall a a', P a -> P a' -> bool)
        (blA : forall a a', eqA a a' = true -> a = a')
        (blP : forall a p p', eqP a a p p' = true -> p = p')
        {p q}
    : sigT_beq eqA eqP p q = true -> p = q.
  Proof.
    destruct p as [a p], q as [a' q]; cbv.
    specialize (blA a a'); specialize (blP a p).
    destruct (eqA a a') eqn:H'; [ specialize (blA eq_refl) | discriminate ]; subst.
    intro H''; specialize (blP _ H''); subst; reflexivity.
  Qed.

  Lemma sigT_dec_lb {A P}
        (eqA : A -> A -> bool) (eqP : forall a a', P a -> P a' -> bool)
        (lbA : forall a a', a = a' -> eqA a a' = true)
        (lbP : forall a p p', p = p' -> eqP a a p p' = true)
        {p q}
    : p = q -> sigT_beq eqA eqP p q = true.
  Proof.
    intro; subst q; destruct p as [a p]; cbv in *.
    specialize (lbA a a eq_refl); specialize (lbP a p p eq_refl).
    now rewrite lbA, lbP.
  Qed.

  Lemma sigT_dec_bl_hprop {A P}
        (eqA : A -> A -> bool)
        (blA : forall a a', eqA a a' = true -> a = a')
        (P_hprop : forall (x : A) (p q : P x), p = q)
        {p q}
    : @sigT_beq A A P P eqA (fun _ _ _ _ => true) p q = true -> p = q.
  Proof. apply sigT_dec_bl; eauto. Qed.

  Lemma sigT_dec_lb_hprop {A P}
        (eqA : A -> A -> bool)
        (lbA : forall a a', a = a' -> eqA a a' = true)
        (P_hprop : forall (x : A) (p q : P x), p = q)
        {p q}
    : p = q -> @sigT_beq A A P P eqA (fun _ _ _ _ => true) p q = true.
  Proof. apply sigT_dec_lb; eauto. Qed.

  Definition sigT_eq_dec {A P}
             (eqA : A -> A -> bool) (eqP : forall a a', P a -> P a' -> bool)
             (blA : forall a a', eqA a a' = true -> a = a')
             (blP : forall a p p', eqP a a p p' = true -> p = p')
             (lbA : forall a a', a = a' -> eqA a a' = true)
             (lbP : forall a p p', p = p' -> eqP a a p p' = true)
             (p q : { a : A & P a })
    : {p = q} + {p <> q}.
  Proof.
    destruct (sigT_beq eqA eqP p q) eqn:H; [ left | right; intro H' ].
    { eapply sigT_dec_bl; eassumption. }
    { eapply sigT_dec_lb in H'; [ | eassumption.. ].
      generalize (eq_trans (eq_sym H) H'); clear; abstract discriminate. }
  Defined.
End sigT.

(** ** Equality for [sig] *)
Section sig.
  Definition proj1_sig_path {A} {P : A -> Prop} {u v : sig P} (p : u = v)
  : proj1_sig u = proj1_sig v
    := f_equal (@proj1_sig _ _) p.

  Definition proj2_sig_path {A} {P : A -> Prop} {u v : sig P} (p : u = v)
  : eq_rect _ _ (proj2_sig u) _ (proj1_sig_path p) = proj2_sig v.
  Proof.
    destruct p; reflexivity.
  Defined.

  Definition path_sig_uncurried {A : Type} {P : A -> Prop} (u v : sig P)
             (pq : {p : proj1_sig u = proj1_sig v | eq_rect _ _ (proj2_sig u) _ p = proj2_sig v})
  : u = v.
  Proof.
    destruct u as [u1 u2], v as [v1 v2]; simpl in *.
    destruct pq as [p q].
    destruct q; simpl in *.
    destruct p; reflexivity.
  Defined.

  Definition path_sig {A : Type} {P : A -> Prop} (u v : sig P)
             (p : proj1_sig u = proj1_sig v) (q : eq_rect _ _ (proj2_sig u) _ p = proj2_sig v)
  : u = v
    := path_sig_uncurried u v (exist _ p q).

  Definition path_sig_rect {A P} {u v : @sig A P} (Q : u = v -> Type)
             (f : forall p q, Q (path_sig u v p q))
    : forall p, Q p.
  Proof. intro p; specialize (f (proj1_sig_path p) (proj2_sig_path p)); destruct u, p; exact f. Defined.
  Definition path_sig_rec {A P u v} (Q : u = v :> @sig A P -> Set) := path_sig_rect Q.
  Definition path_sig_ind {A P u v} (Q : u = v :> @sig A P -> Prop) := path_sig_rec Q.

  Definition path_sig_hprop {A} {P : A -> Prop} (P_hprop : forall (x : A) (p q : P x), p = q)
             (u v : @sig A P)
             (p : proj1_sig u = proj1_sig v)
    : u = v
    := path_sig u v p (P_hprop _ _ _).

  Definition path_sig_uncurried_iff {A} {P : A -> Prop}
             (u v : @sig A P)
    : u = v <-> (sig (fun p : proj1_sig u = proj1_sig v => eq_rect _ _ (proj2_sig u) _ p = proj2_sig v)).
  Proof.
    split; [ intro; subst; exists eq_refl; reflexivity | apply path_sig_uncurried ].
  Defined.

  Definition path_sig_hprop_iff {A} {P : A -> Prop} (P_hprop : forall (x : A) (p q : P x), p = q)
             (u v : @sig A P)
    : u = v <-> (proj1_sig u = proj1_sig v)
    := conj (f_equal proj1_sig) (path_sig_hprop P_hprop u v).

  Lemma eq_rect_sig {A x} {P : A -> Type} (Q : forall a, P a -> Prop) (u : sig (Q x)) {y} (H : x = y)
  : eq_rect x (fun a => sig (Q a)) u y H
    = exist
        (Q y)
        (eq_rect x P (proj1_sig u) y H)
        match H in (_ = y) return Q y (eq_rect x P (proj1_sig u) y H) with
          | eq_refl => proj2_sig u
        end.
  Proof.
    destruct H, u; reflexivity.
  Defined.

  (** *** η Principle for [sig] *)
  Definition sig_eta {A P} (p : { a : A | P a })
    : p = exist _ (proj1_sig p) (proj2_sig p).
  Proof. destruct p; reflexivity. Defined.

  (** *** Boolean equality for [sig] *)
  Definition sig_beq {A A'} {P P' : _ -> Prop} (eqA : A -> A' -> bool) (eqP : forall a a', P a -> P' a' -> bool) (p : { a : A | P a }) (q : { a' : A' | P' a' })
    : bool
    := andb (eqA (proj1_sig p) (proj1_sig q)) (eqP _ _ (proj2_sig p) (proj2_sig q)).

  Lemma sig_dec_bl {A} {P : A -> Prop}
        (eqA : A -> A -> bool) (eqP : forall a a', P a -> P a' -> bool)
        (blA : forall a a', eqA a a' = true -> a = a')
        (blP : forall a p p', eqP a a p p' = true -> p = p')
        {p q}
    : sig_beq eqA eqP p q = true -> p = q.
  Proof.
    destruct p as [a p], q as [a' q]; cbv.
    specialize (blA a a'); specialize (blP a p).
    destruct (eqA a a') eqn:H'; [ specialize (blA eq_refl) | discriminate ]; subst.
    intro H''; specialize (blP _ H''); subst; reflexivity.
  Qed.

  Lemma sig_dec_lb {A} {P : A -> Prop}
        (eqA : A -> A -> bool) (eqP : forall a a', P a -> P a' -> bool)
        (lbA : forall a a', a = a' -> eqA a a' = true)
        (lbP : forall a p p', p = p' -> eqP a a p p' = true)
        {p q}
    : p = q -> sig_beq eqA eqP p q = true.
  Proof.
    intro; subst q; destruct p as [a p]; cbv in *.
    specialize (lbA a a eq_refl); specialize (lbP a p p eq_refl).
    now rewrite lbA, lbP.
  Qed.

  Lemma sig_dec_bl_hprop {A} {P : A -> Prop}
        (eqA : A -> A -> bool)
        (blA : forall a a', eqA a a' = true -> a = a')
        (P_hprop : forall (x : A) (p q : P x), p = q)
        {p q}
    : @sig_beq A A P P eqA (fun _ _ _ _ => true) p q = true -> p = q.
  Proof. apply sig_dec_bl; eauto. Qed.

  Lemma sig_dec_lb_hprop {A} {P : A -> Prop}
        (eqA : A -> A -> bool)
        (lbA : forall a a', a = a' -> eqA a a' = true)
        (P_hprop : forall (x : A) (p q : P x), p = q)
        {p q}
    : p = q -> @sig_beq A A P P eqA (fun _ _ _ _ => true) p q = true.
  Proof. apply sig_dec_lb; eauto. Qed.

  Definition sig_eq_dec {A} {P : A -> Prop}
             (eqA : A -> A -> bool) (eqP : forall a a', P a -> P a' -> bool)
             (blA : forall a a', eqA a a' = true -> a = a')
             (blP : forall a p p', eqP a a p p' = true -> p = p')
             (lbA : forall a a', a = a' -> eqA a a' = true)
             (lbP : forall a p p', p = p' -> eqP a a p p' = true)
             (p q : { a : A | P a })
    : {p = q} + {p <> q}.
  Proof.
    destruct (sig_beq eqA eqP p q) eqn:H; [ left | right; intro H' ].
    { eapply sig_dec_bl; eassumption. }
    { eapply sig_dec_lb in H'; [ | eassumption.. ].
      generalize (eq_trans (eq_sym H) H'); clear; abstract discriminate. }
  Defined.
End sig.

(** ** Equality for [ex] *)
Section ex.
  Definition path_ex_uncurried' {A : Type} (P : A -> Prop) {u1 v1 : A} {u2 : P u1} {v2 : P v1}
             (pq : exists p : u1 = v1, eq_rect _ _ u2 _ p = v2)
  : ex_intro P u1 u2 = ex_intro P v1 v2.
  Proof.
    destruct pq as [p q].
    destruct q; simpl in *.
    destruct p; reflexivity.
  Defined.

  Definition path_ex' {A : Type} {P : A -> Prop} (u1 v1 : A) (u2 : P u1) (v2 : P v1)
             (p : u1 = v1) (q : eq_rect _ _ u2 _ p = v2)
  : ex_intro P u1 u2 = ex_intro P v1 v2
    := path_ex_uncurried' P (ex_intro _ p q).

  Definition path_ex'_hprop {A} {P : A -> Prop} (P_hprop : forall (x : A) (p q : P x), p = q)
             (u1 v1 : A) (u2 : P u1) (v2 : P v1)
             (p : u1 = v1)
    : ex_intro P u1 u2 = ex_intro P v1 v2
    := path_ex' u1 v1 u2 v2 p (P_hprop _ _ _).

  Lemma eq_rect_ex {A x} {P : A -> Type} (Q : forall a, P a -> Prop) (u : ex (Q x)) {y} (H : x = y)
  : eq_rect x (fun a => ex (Q a)) u y H
    = match u with
        | ex_intro u1 u2
          => ex_intro
               (Q y)
               (eq_rect x P u1 y H)
               match H in (_ = y) return Q y (eq_rect x P u1 y H) with
                 | eq_refl => u2
               end
      end.
  Proof.
    destruct H, u; reflexivity.
  Defined.
End ex.

(** ** Useful Tactics *)
(** *** [inversion_sigma] *)
(** The built-in [inversion] will frequently leave equalities of
    dependent pairs.  When the first type in the pair is an hProp or
    otherwise simplifies, [inversion_sigma] is useful; it will replace
    the equality of pairs with a pair of equalities, one involving a
    term casted along the other.  This might also prove useful for
    writing a version of [inversion] / [dependent destruction] which
    does not lose information, i.e., does not turn a goal which is
    provable into one which requires axiom K / UIP.  *)
Ltac simpl_proj_exist_in H :=
  repeat match type of H with
         | context G[proj1_sig (exist _ ?x ?p)]
           => let G' := context G[x] in change G' in H
         | context G[proj2_sig (exist _ ?x ?p)]
           => let G' := context G[p] in change G' in H
         | context G[projT1 (existT _ ?x ?p)]
           => let G' := context G[x] in change G' in H
         | context G[projT2 (existT _ ?x ?p)]
           => let G' := context G[p] in change G' in H
         end.
Ltac induction_sigma_in_as_using H H0 H1 rect :=
  induction H as [H0 H1] using (rect _ _ _ _);
  simpl_proj_exist_in H0;
  simpl_proj_exist_in H1.
Ltac induction_sigma_in_using H rect :=
  let H0 := fresh H in
  let H1 := fresh H in
  induction_sigma_in_as_using H H0 H1 rect.
Ltac inversion_sigma_step :=
  match goal with
  | [ H : _ = exist _ _ _ |- _ ]
    => induction_sigma_in_using H @path_sig_rect
  | [ H : _ = existT _ _ _ |- _ ]
    => induction_sigma_in_using H @path_sigT_rect
  | [ H : exist _ _ _ = _ |- _ ]
    => induction_sigma_in_using H @path_sig_rect
  | [ H : existT _ _ _ = _ |- _ ]
    => induction_sigma_in_using H @path_sigT_rect
  end.
Ltac inversion_sigma := repeat inversion_sigma_step.


(*** Coq coding by choukh, Aug 2022 ***)

Require Import Lib Ch3.
From Coq.Sets Require Import Powerset.
From Category.Algebra Require Import Monoid.
From Category.Theory Require Import Functor.
From Category.Instance Require Import Cat Coq Sets Proset.
From Category.Construction Require Import Subcategory Slice.
Local Existing Instance is_setoid.

(** 4.1 **)
Check (@Functor : Category → Category → Type).
Check (@Id : ∀ C : Category, C ⟶ C).
Check (@Compose : ∀ C D E : Category, D ⟶ E → C ⟶ D → C ⟶ E).

Check (Cat : obj[Cat]).
Check (Cat : Cat).

Fact Functor_eta : Functor = @Functor Cat Cat.
Proof. reflexivity. Qed.

(** 4.2 **)

(* forgetful funtor from Gph to Coq *)
Program Example F : Gph ⟶ Coq := {|
  fobj := @vertex;
  fmap := @αᵥ;
|}.

(* power funtor on Sets *)
Program Example P : Sets ⟶ Sets := {|
  fobj A := {|
    carrier := { p : A → Type & ∀ x y, x ≈ y → p x ↔ p y };
    is_setoid := {| equiv p q := ∀ x, ``p x ↔ ``q x |}
  |};
  fmap A B f := {|
    morphism p := existT _ (λ b, ∃ a, ``p a ∧ f a ≈ b) _
  |}
|}.
Next Obligation. equivalence; firstorder. Defined.
Next Obligation.
  split; intros [c H]; exists c; intuition; rewrites; reflexivity.
Defined.
Next Obligation. proper; firstorder. Defined.
Next Obligation. proper; rewrites; reflexivity. Defined.
Next Obligation. split. firstorder. now exists x1. Defined.
Next Obligation.
  split; intros [b [H fb]].
  - exists (g b). split; trivial. now exists b.
  - destruct H as [c [H gc]]. exists c. split; trivial.
    rewrite <- fb. now apply f.
Defined.

(** 4.3 **)
Check (@Full: ∀ C D : Category, C ⟶ D → Type).
Check (@Faithful : ∀ C D : Category, C ⟶ D → Type).

(** 4.4 **)

Check (Subcategory : Category → Type).
Check (Subcategory.Sub : ∀ C : Category, Subcategory C → Category).

Program Definition Preₛ : Subcategory Cat := {|
  sobj C := ∃ R, @RelationClasses.PreOrder C R
    ∧ (∀ x y, R x y ↔ x ~> y) (* arrow represents R *)
    ∧ (∀ x y (f g : x ~> y), f ≈ g); (* at most one arrow *)
  (* preorder homomorphism *)
  shom C D Rc Rd F := ∀ x y : C, ``Rc x y → ``Rd (F x) (F y);
|}.

Definition Pre : Category := Sub Cat Preₛ.

Program Definition Monₛ : Subcategory Cat := {|
  sobj C :=
    (* single object *)
    (∃ _ : C, ∀ x y : C, x = y) ∧
    (* homset is a monoid *)
    ∀ x : C, ∃ mon : @Monoid (x ~> x) (homset x x),
      @mempty _ (homset x x) mon ≈ id[x] ∧
      ∀ f g : x ~> x, @mappend _ (homset x x) mon f g ≈ f ∘ g;
  shom _ _ _ _ F :=
    (* monoid homomorphism *)
    (∀ x, fmap[F] id[x] ≈ id[fobj x]) ∧
    (∀ x, ∀ (f g : x ~> x), fmap[F] (f ∘ g) ≈ fmap[F] f ∘ fmap[F] g)
|}.
Next Obligation. split.
  - intros a. now rewrite e.
  - intros a F G. now rewrite e0.
Defined.

Definition Mon : Category := Sub Cat Monₛ.

Check (Subcategory.Full : ∀ C : Category, Subcategory C → Type).

Fact Preₛ_Full : Subcategory.Full Cat Preₛ.
Proof.
  intros C D [Rc Hc] [Rd Hd] F x y. simpl.
  intros Rxy. apply Hd, F, Hc, Rxy.
Qed.

Fact Monₛ_Full : Subcategory.Full Cat Monₛ.
Proof. intros C D oc od F. split; intros a. apply F. apply fmap_comp. Qed.

Check (Incl : ∀ (C : Category) (S : Subcategory C), Sub C S ⟶ C).

Section Inclusion.
Variable C : Category.
Variable S : Subcategory C.

Definition Incl := Incl C S.
Check (Incl : Sub C S ⟶ C).

Fact Incl_Faithful : Faithful Incl.
Proof. now split. Qed.

Lemma Incl_Full (sf: Subcategory.Full C S) : Functor.Full Incl.
Proof.
  unfold Subcategory.Full in sf.
  construct. exists g. apply sf.
  proper. all:reflexivity.
Qed.

(* This is the same lemma in lib *)
Check (Full_Implies_Full_Functor : ∀ (C : Category) (S : Subcategory C),
  Subcategory.Full C S → Full (Subcategory.Incl C S)).

End Inclusion.

Fact Pre_Incl_Full : Full (Incl Preₛ).
Proof. apply Incl_Full, Preₛ_Full. Qed.

Fact Mon_Incl_Full : Full (Incl Monₛ).
Proof. apply Incl_Full, Monₛ_Full. Qed.

(** 4.5 **)

Section Slice.
Variable A B C : Set.
Variable f : A → bool.
Variable g : B → bool.
Variable h : C → bool.

Let ℂ := Coq ̸ bool.
Check (obj[ℂ] = ∃ T, T → bool).

Let a : ℂ := (A; f).
Let b : ℂ := (B; g).
Let c : ℂ := (C; h).

Check ((a ~> a) = ∃ F : A → A, ∀ x : A, f x = f (F x)).
Check ((a ~> b) = ∃ F : A → B, ∀ x : A, f x = g (F x)).

Fact id_ℂ (d : ℂ) (x : ``d) : (``id[d]) x = x.
Proof. trivial. Qed.

Variable F : a ~> b.
Variable G : b ~> c.
Check (``(G ∘ F) : A → C).

End Slice.