theory Connectivity
  imports
    Walk
begin

(* TODO *)
definition connected :: "('a, 'b) multigraph \<Rightarrow> bool" where
  "connected G \<equiv> True"

locale connected_multigraph = finite_multigraph +
  assumes connected: "connected G"

(* TODO *)
definition biconnected :: "('a, 'b) multigraph \<Rightarrow> bool" where
  "biconnected G \<equiv> True"

locale biconnected_multigraph = finite_multigraph +
  assumes biconnected: "biconnected G"

(**)
(* QUESTION: Define via tbd? *)
definition (in other) connected_component where
  "connected_component G u = {v. reachable G u v}"

(* TODO: Rename. *)
lemma (in other) connected_component_refl:
  assumes "v \<in> V G"
  shows "v \<in> connected_component G v"
  using assms
  by (auto simp add: connected_component_def intro: reachable_refl)

lemma (in other) connected_component_non_empty:
  assumes "v \<in> V G"
  shows "connected_component G v \<noteq> {}"
  using assms
  by (auto intro: connected_component_refl)

lemma (in other) connected_component_subset:
  shows "connected_component G v \<subseteq> V G"
  sorry

(* QUESTION: Allow {} by removing v\<in>V G? *)
definition (in other) connected_components where
  "connected_components G \<equiv> {C. \<exists>v\<in>V G. C = connected_component G v}"

lemma (in other) connected_components_image_cong:
  shows "connected_components G = connected_component G ` V G"
  by (auto simp add: connected_components_def)

lemma (in other) connected_component_non_empty_2:
  assumes "C \<in> connected_components G"
  shows "C \<noteq> {}"
  using assms
  by (auto simp add: connected_components_def dest: connected_component_non_empty)

lemma (in other) connected_componentE:
  assumes "C \<in> connected_components G"
  obtains v where
    "connected_component G v = C"
  using assms
  by (auto simp add: connected_components_image_cong)

lemma (in other) connected_component_subset_2:
  assumes "C \<in> connected_components G"
  shows "C \<subseteq> V G"
  using assms connected_component_subset
  by (auto simp add: connected_components_def)

lemma (in other)
  assumes "C \<in> connected_components G"
  assumes "u \<in> C"
  assumes "{u, v} \<in> endpoints ` G"
  shows "v \<in> C"
  sorry

(* TODO: Rename. *)
lemma (in other) connected_component_1:
  assumes "C \<in> connected_components (idk_4 G X)"
  assumes "u \<in> C"
  assumes "{u, v} \<in> endpoints ` G"
  shows "v \<in> C \<union> X"
  sorry

lemma (in other) connected_components_disjoint:
  assumes "C1 \<in> connected_components G"
  assumes "C2 \<in> connected_components G"
  assumes "C2 \<noteq> C1"
  shows "C1 \<inter> C2 = {}"
  sorry

definition (in other) connected' :: "('a, 'b) multigraph \<Rightarrow> 'b set \<Rightarrow> bool" where
  "connected' G X \<equiv> X \<subseteq> V G \<and> (\<forall>u v. u \<in> X \<and> v \<in> X \<and> v \<noteq> u \<longrightarrow> reachable (idk_2 G X) u v)"

lemma (in other) connected'_empty:
  shows "connected' G {}"
  by (simp add: connected'_def)

lemma (in other) connected'_singleton:
  assumes "v \<in> V G"
  shows "connected' G {v}"
  using assms
  by (simp add: connected'_def)

(*
definition (in other) connected' :: "('a, 'b) multigraph \<Rightarrow> 'b set \<Rightarrow> bool" where
  "connected' G X \<equiv> X \<noteq> {} \<and> (\<forall>u v. u \<in> X \<and> v \<in> X \<longrightarrow> reachable (idk_2 G X) u v)"
*)

(*
lemma (in other) connected'D:
  assumes "connected' G X"
  shows
    "X \<noteq> {}"
    "\<forall>u v. u \<in> X \<and> v \<in> X \<longrightarrow> reachable (idk_2 G X) u v"
  using assms
  by (simp_all add: connected'_def)
*)

(*
lemma (in other) connected'I:
  assumes "X \<noteq> {}"
  assumes "\<forall>u v. u \<in> X \<and> v \<in> X \<longrightarrow> reachable (idk_2 G X) u v"
  shows "connected' G X"
  using assms
  by (simp add: connected'_def)
*)

lemma (in other) connected'_subset_connected_component:
  assumes "connected' G X"
  obtains C where
    "C \<in> connected_components G"
    "X \<subseteq> C"
  sorry

lemma (in other) connected'_subset:
  assumes "connected' G X"
  shows "X \<subseteq> V G"
  using assms
  by (blast elim: connected'_subset_connected_component dest: connected_component_subset_2)

(* QUESTION: Generalize to arbitrary walks in idk_2 (X \<union> Y)? *)
lemma (in other) connected'_2:
  assumes "connected' G X"
  assumes "x \<in> X"
  assumes "connected' G Y"
  assumes "y \<in> Y"
  assumes "(\<epsilon>, {x, y}) \<in> G"
  shows "connected' G (X \<union> Y)"
  sorry

lemma (in other) connected'_3:
  assumes "connected' G X"
  assumes "x \<in> X"
  assumes "connected' G Y"
  assumes "y \<in> Y"
  assumes "{x, y} \<in> endpoints ` G"
  shows "connected' G (X \<union> Y)"
  sorry

lemma (in other) connected'_1:
  assumes "connected' G X"
  assumes "X \<inter> Y = {}"
  shows "connected' (idk_4 G Y) X"
  sorry

(* QUESTION: Generalize to arbitrary walks? *)
(*
lemma (in other) connected'_not_connected_componentE:
  assumes "connected' G X"
  assumes "X \<notin> connected_components G"
  obtains x y where
    "x \<in> X"
    "{x, y} \<in> endpoints ` idk_2 G (connected_component G x)"
    "y \<in> connected_component G x"
    "y \<notin> X"
  sorry
*)

(*
lemma (in other) connected'_not_connected_componentE_2:
  assumes "connected' G X"
  assumes "X \<notin> connected_components G"
  obtains x y where
    "x \<in> X"
    "{x, y} \<in> endpoints ` G"
    "y \<in> V G"
    "y \<notin> X"
  using assms idk_2_subset connected_component_subset
  by (blast elim: connected'_not_connected_componentE)
*)

lemma (in other) connected_component_10:
  assumes "C \<in> connected_components (idk_4 G X)"
  shows "V (E G C) \<subseteq> C \<union> X"
  sorry

lemma (in other) connected'_99:
  assumes "connected' G Y"
  assumes "connected' G (X \<union> Y)"
  assumes "connected' G (Y \<union> Z)"
  shows "connected' G (X \<union> Y \<union> Z)"
  using assms
  sorry

lemma (in other) connected'_100:
  assumes "connected' G X"
  assumes "finite \<Y>"
  assumes "\<forall>Y\<in>\<Y>. connected' G Y"
  assumes "\<forall>Y\<in>\<Y>. \<exists>x\<in>X. \<exists>y\<in>Y. {x, y} \<in> endpoints ` G"
  shows "connected' G (X \<union> \<Union> \<Y>)"
  using assms(2-)
proof (induct \<Y> rule: finite.induct)
  case emptyI
  show ?case
    using assms(1)
    by simp
next
  case (insertI \<Y> Y)
  have "connected' G (Y \<union> X)"
  proof -
    have
      "connected' G Y"
      "\<exists>x\<in>X. \<exists>y\<in>Y. {x, y} \<in> endpoints ` G"
      using insertI.prems
      by blast+
    thus ?thesis
      using assms(1)
      by (blast intro: connected'_3)
  qed
  moreover have "connected' G (X \<union> \<Union> \<Y>)"
  proof -
    have
      "\<forall>Y\<in>\<Y>. connected' G Y"
      "\<forall>Y\<in>\<Y>. \<exists>x\<in>X. \<exists>y\<in>Y. {x, y} \<in> endpoints ` G"
      using insertI.prems
      by blast+
    thus ?thesis
      using assms(1)
      by (intro insertI.hyps)
  qed
  ultimately show ?case
    using assms(1)
    by (auto simp add: Un_assoc Un_left_commute dest: connected'_99)
qed

lemma (in other) connected_component_71:
  assumes "C \<in> connected_components G"
  assumes "v \<in> C"
  shows "connected_component G v = C"
proof -
  have "v \<in> V G"
    using assms
    by (fast dest: connected_component_subset_2)
  thus ?thesis
    using assms
    by
      (fastforce
        simp add: connected_components_image_cong
        dest: connected_components_disjoint
        intro: connected_component_refl)
qed

lemma (in other) connected_component_72:
  assumes "C \<in> connected_components G"
  assumes "u \<in> C"
  assumes "v \<in> C"
  obtains p where
    "walk (idk_2 G C) p u v"
  sorry

lemma (in other) connected'_supergraph:
  assumes "G \<subseteq> G'"
  assumes "connected' G X"
  shows "connected' G' X"
  using assms
  sorry

end


section {* \isaheader{Nested DFS (HPY improvement)} *}
theory Nested_DFS
imports
  "../../Refine_Dflt"
  Buchi_Graph_Basic
  Succ_Graph
  "../../Lib/Code_Target_ICF"
begin

text {*
  Implementation of a nested DFS algorithm for accepting cycle detection
  using the refinement framework. The algorithm uses the improvement of
  [HPY96], i.e., it reports a cycle if the inner DFS finds a path back to
  the stack of the outer DFS.

  The algorithm returns a witness in case that an accepting cycle is detected.
*}

subsection "Tools for DFS Algorithms"

subsubsection "Invariants"
definition "gen_dfs_pre E U S V u0 \<equiv>
  E``U \<subseteq> U   (* Upper bound is closed under transitions *)
  \<and> finite U (* Upper bound is finite *)
  \<and> V \<subseteq> U    (* Visited set below upper bound *)
  \<and> u0 \<in> U   (* Start node in upper bound *)
  \<and> E``(V-S) \<subseteq> V (* Visited nodes closed under reachability, or on stack *)
  \<and> u0\<notin>V     (* Start node not yet visited *)
  \<and> S \<subseteq> V    (* Stack is visited *)
  \<and> (\<forall>v\<in>S. (v,u0)\<in>(E\<inter>S\<times>UNIV)\<^sup>*) (* u0 reachable from stack, only over stack *)
  "

definition "gen_dfs_var U \<equiv> finite_psupset U"

definition "gen_dfs_fe_inv E U S V0 u0 it V brk \<equiv>
  (\<not>brk \<longrightarrow> E``(V-S) \<subseteq> V)  (* Visited set closed under reachability *)
  \<and> E``{u0} - it \<subseteq> V     (* Successors of u0 visited *)
  \<and> V0 \<subseteq> V               (* Visited set increasing *)
  \<and> V \<subseteq> V0 \<union> (E - UNIV\<times>S)\<^sup>* `` (E``{u0} - it - S) (* All visited
                                                     nodes reachable *)
"

definition "gen_dfs_post E U S V0 u0 V brk \<equiv>
  (\<not>brk \<longrightarrow> E``(V-S) \<subseteq> V) (* Visited set closed under reachability *)
  \<and> u0 \<in> V               (* u0 visited *)
  \<and> V0 \<subseteq> V               (* Visited set increasing *)
  \<and> V \<subseteq> V0 \<union> (E - UNIV\<times>S)\<^sup>* `` {u0} (* All visited nodes reachable *)
"

subsubsection "Invariant Preservation"
lemma gen_dfs_pre_initial:
  assumes "finite (E\<^sup>*``{v0})"
  assumes "v0\<in>U"
  shows "gen_dfs_pre E (E\<^sup>*``{v0}) {} {} v0"
  using assms unfolding gen_dfs_pre_def
  apply auto
  done

lemma gen_dfs_pre_imp_wf:
  assumes "gen_dfs_pre E U S V u0"
  shows "wf (gen_dfs_var U)"
  using assms unfolding gen_dfs_pre_def gen_dfs_var_def by auto

lemma gen_dfs_pre_imp_fin:
  assumes "gen_dfs_pre E U S V u0"
  shows "finite (E `` {u0})"
  apply (rule finite_subset[where B="U"])
  using assms unfolding gen_dfs_pre_def
  by auto

text {* Inserted @{text "u0"} on stack and to visited set*}
lemma gen_dfs_pre_imp_fe:
  assumes "gen_dfs_pre E U S V u0"
  shows "gen_dfs_fe_inv E U (insert u0 S) (insert u0 V) u0
    (E``{u0}) (insert u0 V) False"
  using assms unfolding gen_dfs_pre_def gen_dfs_fe_inv_def
  apply auto
  done

lemma gen_dfs_fe_inv_pres_visited:
  assumes "gen_dfs_pre E U S V u0"
  assumes "gen_dfs_fe_inv E U (insert u0 S) (insert u0 V) u0 it V' False"
  assumes "t\<in>it" "it\<subseteq>E``{u0}" "t\<in>V'"
  shows "gen_dfs_fe_inv E U (insert u0 S) (insert u0 V) u0 (it-{t}) V' False"
  using assms unfolding gen_dfs_fe_inv_def
  apply auto
  done

lemma gen_dfs_upper_aux:
  assumes "(x,y)\<in>E'\<^sup>*"
  assumes "(u0,x)\<in>E"
  assumes "u0\<in>U"
  assumes "E'\<subseteq>E"
  assumes "E``U \<subseteq> U"
  shows "y\<in>U"
  using assms
  by induct auto

lemma gen_dfs_fe_inv_imp_var:
  assumes "gen_dfs_pre E U S V u0"
  assumes "gen_dfs_fe_inv E U (insert u0 S) (insert u0 V) u0 it V' False"
  assumes "t\<in>it" "it\<subseteq>E``{u0}" "t\<notin>V'"
  shows "(V',V) \<in> gen_dfs_var U"
  using assms unfolding gen_dfs_fe_inv_def gen_dfs_pre_def gen_dfs_var_def
  apply (clarsimp simp add: finite_psupset_def)
  apply (blast dest: gen_dfs_upper_aux)
  done

lemma gen_dfs_fe_inv_imp_pre:
  assumes "gen_dfs_pre E U S V u0"
  assumes "gen_dfs_fe_inv E U (insert u0 S) (insert u0 V) u0 it V' False"
  assumes "t\<in>it" "it\<subseteq>E``{u0}" "t\<notin>V'"
  shows "gen_dfs_pre E U (insert u0 S) V' t"
  using assms unfolding gen_dfs_fe_inv_def gen_dfs_pre_def
  apply clarsimp
  apply (intro conjI)
  apply (blast dest: gen_dfs_upper_aux)
  apply blast
  apply blast
  apply blast
  apply clarsimp
  apply (rule rtrancl_into_rtrancl[where b=u0])
  apply (auto intro: set_rev_mp[OF _ rtrancl_mono[where r="E \<inter> S \<times> UNIV"]]) []
  apply blast
  done

lemma gen_dfs_post_imp_fe_inv:
  assumes "gen_dfs_pre E U S V u0"
  assumes "gen_dfs_fe_inv E U (insert u0 S) (insert u0 V) u0 it V' False"
  assumes "t\<in>it" "it\<subseteq>E``{u0}" "t\<notin>V'"
  assumes "gen_dfs_post E U (insert u0 S) V' t V'' cyc"
  shows "gen_dfs_fe_inv E U (insert u0 S) (insert u0 V) u0 (it-{t}) V'' cyc"
  using assms unfolding gen_dfs_fe_inv_def gen_dfs_post_def gen_dfs_pre_def
  apply clarsimp
  apply (intro conjI)
  apply blast
  apply blast
  apply blast
  apply (erule order_trans)
  apply simp
  apply (rule conjI)
    apply (erule order_trans[
      where y="insert u0 (V \<union> (E - UNIV \<times> insert u0 S)\<^sup>*
        `` (E `` {u0} - it - insert u0 S))"])
    apply blast

    apply (cases cyc)
      apply simp
      apply blast

      apply simp
      apply blast
  done

lemma gen_dfs_post_aux:
  assumes 1: "(u0,x)\<in>E"
  assumes 2: "(x,y)\<in>(E - UNIV \<times> insert u0 S)\<^sup>*"
  assumes 3: "S\<subseteq>V" "x\<notin>V"
  shows "(u0, y) \<in> (E - UNIV \<times> S)\<^sup>*"
proof -
  from 1 3 have "(u0,x)\<in>(E - UNIV \<times> S)" by blast
  also have "(x,y)\<in>(E - UNIV \<times> S)\<^sup>*"
    apply (rule_tac set_rev_mp[OF 2 rtrancl_mono])
    by auto
  finally show ?thesis .
qed

lemma gen_dfs_fe_imp_post_brk:
  assumes "gen_dfs_pre E U S V u0"
  assumes "gen_dfs_fe_inv E U (insert u0 S) (insert u0 V) u0 it V' True"
  assumes "it\<subseteq>E``{u0}"
  shows "gen_dfs_post E U S V u0 V' True"
  using assms unfolding gen_dfs_pre_def gen_dfs_fe_inv_def gen_dfs_post_def
  apply clarify
  apply (intro conjI)
  apply simp
  apply simp
  apply simp
  apply clarsimp
  apply (blast intro: gen_dfs_post_aux)
  done

lemma gen_dfs_fe_inv_imp_post:
  assumes "gen_dfs_pre E U S V u0"
  assumes "gen_dfs_fe_inv E U (insert u0 S) (insert u0 V) u0 {} V' cyc"
  assumes "cyc\<longrightarrow>cyc'"
  shows "gen_dfs_post E U S V u0 V' cyc'"
  using assms unfolding gen_dfs_pre_def gen_dfs_fe_inv_def gen_dfs_post_def
  apply clarsimp
  apply (intro conjI)
  apply blast
  apply (auto intro: gen_dfs_post_aux) []
  done

lemma gen_dfs_pre_imp_post_brk:
  assumes "gen_dfs_pre E U S V u0"
  shows "gen_dfs_post E U S V u0 (insert u0 V) True"
  using assms unfolding gen_dfs_pre_def gen_dfs_post_def
  apply auto
  done

subsubsection "Consequences of Postcondition"
lemma gen_dfs_post_imp_reachable:
  assumes "gen_dfs_pre E U S V0 u0"
  assumes "gen_dfs_post E U S V0 u0 V brk"
  shows "V \<subseteq> V0 \<union> E\<^sup>*``{u0}"
  using assms unfolding gen_dfs_post_def gen_dfs_pre_def
  apply clarsimp
  apply (blast intro: set_rev_mp[OF _ rtrancl_mono])
  done

lemma gen_dfs_post_imp_complete:
  assumes "gen_dfs_pre E U {} V0 u0"
  assumes "gen_dfs_post E U {} V0 u0 V False"
  shows "V0 \<union> E\<^sup>*``{u0} \<subseteq> V"
  using assms unfolding gen_dfs_post_def gen_dfs_pre_def
  apply clarsimp
  apply (blast dest: Image_closed_trancl)
  done

lemma gen_dfs_post_imp_eq:
  assumes "gen_dfs_pre E U {} V0 u0"
  assumes "gen_dfs_post E U {} V0 u0 V False"
  shows "V = V0 \<union> E\<^sup>*``{u0}"
  using gen_dfs_post_imp_reachable[OF assms] gen_dfs_post_imp_complete[OF assms]
  by blast

lemma gen_dfs_post_imp_below_U:
  assumes "gen_dfs_pre E U S V0 u0"
  assumes "gen_dfs_post E U S V0 u0 V False"
  shows "V \<subseteq> U"
  using assms unfolding gen_dfs_pre_def gen_dfs_post_def
  apply clarsimp
  apply (blast intro: set_rev_mp[OF _ rtrancl_mono] dest: Image_closed_trancl)
  done

subsection "Abstract Algorithm"

subsubsection {* Inner (red) DFS *}

text {* A witness of the red algorithm is a node on the stack and a path
  to this node *}
type_synonym 'v red_witness = "('v list \<times> 'v) option"
text {* Prepend node to red witness *}
fun prep_wit_red :: "'v \<Rightarrow> 'v red_witness \<Rightarrow> 'v red_witness" where
  "prep_wit_red v None = None"
| "prep_wit_red v (Some (p,u)) = Some (v#p,u)"

text {*
  Initial witness for node @{text "u"} with onstack successor @{text "v"}
  *}
definition red_init_witness :: "'v \<Rightarrow> 'v \<Rightarrow> 'v red_witness" where
  "red_init_witness u v = Some ([u],v)"

definition red_dfs where
  "red_dfs E onstack V u \<equiv>
    REC\<^sub>T (\<lambda>D (V,u). do {
      let V=insert u V;

      (* Check whether we have a successor on stack *)
      brk \<leftarrow> FOREACH\<^sub>C (E``{u}) (\<lambda>brk. brk=None)
        (\<lambda>t _. if t\<in>onstack then RETURN (red_init_witness u t) else RETURN None)
        None;

      (* Recurse for successors *)
      case brk of
        None \<Rightarrow>
          FOREACH\<^sub>C (E``{u}) (\<lambda>(V,brk). brk=None)
            (\<lambda>t (V,_).
              if t\<notin>V then do {
                (V,brk) \<leftarrow> D (V,t);
                RETURN (V,prep_wit_red u brk)
              } else RETURN (V,None))
            (V,None)
      | _ \<Rightarrow> RETURN (V,brk)
    }) (V,u)
  "

text {*
  A witness of the blue DFS may be in two different phases, the @{text "REACH"}
  phase is before the node on the stack has actually been popped, and the
  @{text "CIRC"} phase is after the node on the stack has been popped.

  @{text "REACH v p u p'"}: \begin{description}
  \item[@{text "v"}] accepting node
  \item[@{text "p"}] path from @{text "v"} to @{text "u"}
  \item[@{text "u"}] node on stack
  \item[@{text "p'"}] path from current node to @{text "v"}
  \end{description}

  @{text "CIRC v pc pr"}: \begin{description}
  \item[@{text "v"}] accepting node
  \item[@{text "pc"}] path from @{text "v"} to @{text "v"}
  \item[@{text "pr"}] path from current node to @{text "v"}
  \end{description}
*}
datatype 'v blue_witness =
  NO_CYC
| REACH "'v" "'v list" "'v" "'v list"
| CIRC "'v" "'v list" "'v list"

text {* Prepend node to witness *}
primrec prep_wit_blue :: "'v \<Rightarrow> 'v blue_witness \<Rightarrow> 'v blue_witness" where
  "prep_wit_blue u0 NO_CYC = NO_CYC"
| "prep_wit_blue u0 (REACH v p u p') = (
  if u0=u then
    CIRC v (p@u#p') (u0#p')
  else
    REACH v p u (u0#p')
  )"
| "prep_wit_blue u0 (CIRC v pc pr) = CIRC v pc (u0#pr)"

text {* Initialize blue witness *}
fun init_wit_blue :: "'v \<Rightarrow> 'v red_witness \<Rightarrow> 'v blue_witness" where
  "init_wit_blue u0 None = NO_CYC"
| "init_wit_blue u0 (Some (p,u)) = (
  if u=u0 then
    CIRC u0 p []
  else REACH u0 p u [])"

text {* Extract result from witness *}
definition "extract_res cyc
  \<equiv> (case cyc of CIRC v pc pr \<Rightarrow> Some (v,pc,pr) | _ \<Rightarrow> None)"

subsubsection {* Outer (Blue) DFS *}
definition blue_dfs
  :: "('a\<times>'a) set \<Rightarrow> 'a set \<Rightarrow> 'a \<Rightarrow> ('a\<times>'a list\<times>'a list) option nres"
  where
  "blue_dfs E A s \<equiv> do {
    (_,_,_,cyc) \<leftarrow> REC\<^sub>T (\<lambda>D (blues,reds,onstack,s). do {
      let blues=insert s blues;
      let onstack=insert s onstack;
      (blues,reds,onstack,cyc) \<leftarrow>
      FOREACH\<^sub>C (E``{s}) (\<lambda>(_,_,_,cyc). cyc=NO_CYC)
        (\<lambda>t (blues,reds,onstack,cyc).
          if t\<notin>blues then do {
            (blues,reds,onstack,cyc) \<leftarrow> D (blues,reds,onstack,t);
            RETURN (blues,reds,onstack,(prep_wit_blue s cyc))
          } else RETURN (blues,reds,onstack,cyc))
        (blues,reds,onstack,NO_CYC);

      (reds,cyc) \<leftarrow>
      if cyc=NO_CYC \<and> s\<in>A then do {
        (reds,rcyc) \<leftarrow> red_dfs E onstack reds s;
        RETURN (reds, init_wit_blue s rcyc)
      } else RETURN (reds,cyc);

      let onstack=onstack - {s};
      RETURN (blues,reds,onstack,cyc)
    }) ({},{},{},s);
    RETURN (extract_res cyc)
  }
  "

subsection "Correctness"

text {* Additional invariant to be maintained between calls of red dfs *}
definition "red_dfs_inv E U reds onstack \<equiv>
  E``U \<subseteq> U           (* Upper bound is closed under transitions *)
  \<and> finite U         (* Upper bound is finite *)
  \<and> reds \<subseteq> U         (* Red set below upper bound *)
  \<and> E``reds \<subseteq> reds   (* Red nodes closed under reachability *)
  \<and> E``reds \<inter> onstack = {} (* No red node with edge to stack *)
"

lemma red_dfs_inv_initial:
  assumes "finite (E\<^sup>*``{v0})"
  shows "red_dfs_inv E (E\<^sup>*``{v0}) {} {}"
  using assms unfolding red_dfs_inv_def
  apply auto
  done

text {* Correctness of the red DFS. *}
theorem red_dfs_correct:
  fixes v0 u0 :: 'v
  assumes PRE:
    "red_dfs_inv E U reds onstack"
    "u0\<in>U"
    "u0\<notin>reds"
  shows "red_dfs E onstack reds u0
    \<le> SPEC (\<lambda>(reds',cyc). case cyc of
      Some (p,v) \<Rightarrow> v\<in>onstack \<and> p\<noteq>[] \<and> path E u0 p v
    | None \<Rightarrow>
        red_dfs_inv E U reds' onstack
        \<and> u0\<in>reds'
        \<and> reds' \<subseteq> reds \<union> E\<^sup>* `` {u0}
  )"
proof -
  let ?dfs_red = "
    REC\<^sub>T (\<lambda>D (V,u). do {
      let V=insert u V;

      (* Check whether we have a successor on stack *)
      brk \<leftarrow> FOREACH\<^sub>C (E``{u}) (\<lambda>brk. brk=None)
        (\<lambda>t _. if t\<in>onstack then
            RETURN (red_init_witness u t)
          else RETURN None)
        None;

      (* Recurse for successors *)
      case brk of
        None \<Rightarrow>
          FOREACH\<^sub>C (E``{u}) (\<lambda>(V,brk). brk=None)
            (\<lambda>t (V,_).
              if t\<notin>V then do {
                (V,brk) \<leftarrow> D (V,t);
                RETURN (V,prep_wit_red u brk)
              } else RETURN (V,None))
            (V,None)
      | _ \<Rightarrow> RETURN (V,brk)
    }) (V,u)
"
  let "REC\<^sub>T ?body ?init" = "?dfs_red"

  def pre \<equiv> "\<lambda>S (V,u0). gen_dfs_pre E U S V u0 \<and> E``V \<inter> onstack = {}"
  def post \<equiv> "\<lambda>S (V0,u0) (V,cyc). gen_dfs_post E U S V0 u0 V (cyc\<noteq>None)
    \<and> (case cyc of None \<Rightarrow> E``V \<inter> onstack = {}
      | Some (p,v) \<Rightarrow> v\<in>onstack \<and> p\<noteq>[] \<and> path E u0 p v)
    "

  def fe_inv \<equiv> "\<lambda>S V0 u0 it (V,cyc).
    gen_dfs_fe_inv E U S V0 u0 it V (cyc\<noteq>None)
    \<and> (case cyc of None \<Rightarrow> E``V \<inter> onstack = {}
      | Some (p,v) \<Rightarrow> v\<in>onstack \<and> p\<noteq>[] \<and> path E u0 p v)
    "

  from PRE have GENPRE: "gen_dfs_pre E U {} reds u0"
    unfolding red_dfs_inv_def gen_dfs_pre_def
    by auto
  with PRE have PRE': "pre {} (reds,u0)"
    unfolding pre_def red_dfs_inv_def
    by auto

  have IMP_POST: "SPEC (post {} (reds,u0))
    \<le> SPEC (\<lambda>(reds',cyc). case cyc of
      Some (p,v) \<Rightarrow> v\<in>onstack \<and> p\<noteq>[] \<and> path E u0 p v
    | None \<Rightarrow>
        red_dfs_inv E U reds' onstack
        \<and> u0\<in>reds'
        \<and> reds' \<subseteq> reds \<union> E\<^sup>* `` {u0})"
    apply (clarsimp split: option.split)
    apply (intro impI conjI allI)
    apply simp_all
  proof -
    fix reds' p v
    assume "post {} (reds,u0) (reds',Some (p,v))"
    thus "v\<in>onstack" and "p\<noteq>[]" and "path E u0 p v"
      unfolding post_def by auto
  next
    fix reds'
    assume "post {} (reds, u0) (reds', None)"
    hence GPOST: "gen_dfs_post E U {} reds u0 reds' False"
      and NS: "E``reds' \<inter> onstack = {}"
      unfolding post_def by auto

    from GPOST show "u0\<in>reds'" unfolding gen_dfs_post_def by auto

    show "red_dfs_inv E U reds' onstack"
      unfolding red_dfs_inv_def
      apply (intro conjI)
      using GENPRE[unfolded gen_dfs_pre_def]
      apply (simp_all) [2]
      apply (rule gen_dfs_post_imp_below_U[OF GENPRE GPOST])
      using GPOST[unfolded gen_dfs_post_def] apply simp
      apply fact
      done

    from GPOST show "reds' \<subseteq> reds \<union> E\<^sup>* `` {u0}"
      unfolding gen_dfs_post_def by auto
  qed

  {
    fix \<sigma> S
    assume INV0: "pre S \<sigma>"
    have "REC\<^sub>T ?body \<sigma>
      \<le> SPEC (post S \<sigma>)"

      apply (rule RECT_rule_arb[where
        pre="pre" and
        V="gen_dfs_var U <*lex*> {}" and
        arb="S"
        ])

      apply refine_mono

      using INV0[unfolded pre_def] apply (auto intro: gen_dfs_pre_imp_wf) []

      apply fact

      apply (rename_tac D S u)
      apply (intro refine_vcg)

      (* First foreach loop, checking for onstack-successor*)
      apply (rule_tac I="\<lambda>it cyc.
        (case cyc of None \<Rightarrow> (E``{b} - it) \<inter> onstack = {}
          | Some (p,v) \<Rightarrow> (v\<in>onstack \<and> p\<noteq>[] \<and> path E b p v))"
        in FOREACHc_rule)
      apply (auto simp add: pre_def gen_dfs_pre_imp_fin) []
      apply auto []
      apply (auto
        split: option.split
        simp: red_init_witness_def intro: path1) []

      apply (intro refine_vcg)

      (* Second foreach loop, iterating over sucessors *)
      apply (rule_tac I="fe_inv (insert b S) (insert b a) b" in
        FOREACHc_rule
      )
      apply (auto simp add: pre_def gen_dfs_pre_imp_fin) []

      apply (auto simp add: pre_def fe_inv_def gen_dfs_pre_imp_fe) []

      apply (intro refine_vcg)

      (* Recursive call *)
      apply (rule order_trans)
      apply (rprems)
      apply (clarsimp simp add: pre_def fe_inv_def)
      apply (rule gen_dfs_fe_inv_imp_pre, assumption+) []
      apply (auto simp add: pre_def fe_inv_def intro: gen_dfs_fe_inv_imp_var) []

      apply (clarsimp simp add: pre_def post_def fe_inv_def
        split: option.split_asm prod.split_asm
        ) []
        apply (blast intro: gen_dfs_post_imp_fe_inv)
        apply (blast intro: gen_dfs_post_imp_fe_inv path_prepend)

      apply (auto simp add: pre_def post_def fe_inv_def
        intro: gen_dfs_fe_inv_pres_visited) []

      apply (auto simp add: pre_def post_def fe_inv_def
        intro: gen_dfs_fe_inv_imp_post) []

      apply (auto simp add: pre_def post_def fe_inv_def
        intro: gen_dfs_fe_imp_post_brk) []

      apply (auto simp add: pre_def post_def fe_inv_def
        intro: gen_dfs_pre_imp_post_brk) []

      apply (auto simp add: pre_def post_def fe_inv_def
        intro: gen_dfs_pre_imp_post_brk) []

      done
  } note GEN=this

  note GEN[OF PRE']
  also note IMP_POST
  finally show ?thesis
    unfolding red_dfs_def .
qed

text {* Main theorem: Correctness of the blue DFS *}
theorem blue_dfs_correct:
  fixes v0 :: 'v
  assumes FIN[simp,intro!]: "finite (E\<^sup>*``{v0})"
  shows "blue_dfs E A v0 \<le> SPEC (\<lambda>r.
    case r of None \<Rightarrow> \<not>has_acc_cycle E A v0
  | Some (v,pc,pv) \<Rightarrow> is_acc_cycle E A v0 v pv pc)"
proof -
  let ?ndfs = "
  do {
    (_,_,_,cyc) \<leftarrow> REC\<^sub>T (\<lambda>D (blues,reds,onstack,s). do {
      let blues=insert s blues;
      let onstack=insert s onstack;
      (blues,reds,onstack,cyc) \<leftarrow>
      FOREACH\<^sub>C (E``{s}) (\<lambda>(_,_,_,cyc). cyc=NO_CYC)
        (\<lambda>t (blues,reds,onstack,cyc).
          if t\<notin>blues then do {
            (blues,reds,onstack,cyc) \<leftarrow> D (blues,reds,onstack,t);
            RETURN (blues,reds,onstack,(prep_wit_blue s cyc))
          } else RETURN (blues,reds,onstack,cyc))
        (blues,reds,onstack,NO_CYC);

      (reds,cyc) \<leftarrow>
      if cyc=NO_CYC \<and> s\<in>A then do {
        (reds,rcyc) \<leftarrow> red_dfs E onstack reds s;
        RETURN (reds, init_wit_blue s rcyc)
      } else RETURN (reds,cyc);

      let onstack=onstack - {s};
      RETURN (blues,reds,onstack,cyc)
    }) ({},{},{},s);
    RETURN (case cyc of NO_CYC \<Rightarrow> None | CIRC v pc pr \<Rightarrow> Some (v,pc,pr))
  }"
  let "do {_ \<leftarrow> REC\<^sub>T ?body ?init; _}" = "?ndfs"

  let ?U = "E\<^sup>*``{v0}"

  def add_inv \<equiv> "\<lambda>blues reds onstack.
    \<not>(\<exists>v\<in>(blues-onstack)\<inter>A. (v,v)\<in>E\<^sup>+)  (* No cycles over finished,
                                           accepting states *)
    \<and> reds \<subseteq> blues                     (* Red nodes are also blue *)
    \<and> reds \<inter> onstack = {}              (* No red nodes on stack *)
    \<and> red_dfs_inv E ?U reds onstack"

  def cyc_post \<equiv> "\<lambda>blues reds onstack u0 cyc. (case cyc of
      NO_CYC \<Rightarrow> add_inv blues reds onstack
    | REACH v p u p' \<Rightarrow> v\<in>A \<and> u\<in>onstack-{u0} \<and> p\<noteq>[]
      \<and> path E v p u \<and> path E u0 p' v
    | CIRC v pc pr \<Rightarrow> v\<in>A \<and> pc\<noteq>[] \<and> path E v pc v \<and> path E u0 pr v
    )"

  def pre \<equiv> "\<lambda>(blues,reds,onstack,u).
    gen_dfs_pre E ?U onstack blues u \<and> add_inv blues reds onstack"

  def post \<equiv> "\<lambda>(blues0,reds0::'v set,onstack0,u0) (blues,reds,onstack,cyc).
    onstack = onstack0
    \<and> gen_dfs_post E ?U onstack0 blues0 u0 blues (cyc\<noteq>NO_CYC)
    \<and> cyc_post blues reds onstack u0 cyc"

  def fe_inv \<equiv> "\<lambda>blues0 u0 onstack0 it (blues,reds,onstack,cyc).
    onstack=onstack0
    \<and> gen_dfs_fe_inv E ?U onstack0 blues0 u0 it blues (cyc\<noteq>NO_CYC)
    \<and> cyc_post blues reds onstack u0 cyc"

  have GENPRE: "gen_dfs_pre E ?U {} {} v0"
    apply (auto intro: gen_dfs_pre_initial)
    done
  hence PRE': "pre ({},{},{},v0)"
    unfolding pre_def add_inv_def
    apply (auto intro: red_dfs_inv_initial)
    done

  {
    fix blues reds onstack cyc
    assume "post ({},{},{},v0) (blues,reds,onstack,cyc)"
    hence "case cyc of NO_CYC \<Rightarrow> \<not>has_acc_cycle E A v0
      | REACH _ _ _ _ \<Rightarrow> False
      | CIRC v pc pr \<Rightarrow> is_acc_cycle E A v0 v pr pc"
      unfolding post_def cyc_post_def
      apply (cases cyc)
      using gen_dfs_post_imp_eq[OF GENPRE, of blues]
      apply (auto simp: add_inv_def has_acc_cycle_def) []
      apply auto []
      apply (auto simp: is_acc_cycle_def) []
      done
  } note IMP_POST = this

  {
    fix onstack blues u0 reds
    assume "pre (blues,reds,onstack,u0)"
    hence "fe_inv (insert u0 blues) u0 (insert u0 onstack) (E``{u0})
      (insert u0 blues,reds,insert u0 onstack,NO_CYC)"
      unfolding fe_inv_def add_inv_def cyc_post_def
      apply clarsimp
      apply (intro conjI)
      apply (simp add: pre_def gen_dfs_pre_imp_fe)
      apply (auto simp: pre_def add_inv_def) []
      apply (auto simp: pre_def add_inv_def) []
      defer
      apply (auto simp: pre_def add_inv_def) []
      apply (unfold pre_def add_inv_def red_dfs_inv_def gen_dfs_pre_def) []
      apply clarsimp
      apply blast

      apply (auto simp: pre_def add_inv_def gen_dfs_pre_def) []
      done
  } note PRE_IMP_FE = this

  have [simp]: "\<And>u cyc. prep_wit_blue u cyc = NO_CYC \<longleftrightarrow> cyc=NO_CYC"
    by (case_tac cyc) auto

  {
    fix blues0 reds0 onstack0 u0
      blues reds onstack blues' reds' onstack'
      cyc it t
    assume PRE: "pre (blues0,reds0,onstack0,u0)"
    assume FEI: "fe_inv (insert u0 blues0) u0 (insert u0 onstack0)
        it (blues,reds,onstack,NO_CYC)"
    assume IT: "t\<in>it" "it\<subseteq>E``{u0}" "t\<notin>blues"
    assume POST: "post (blues,reds,onstack, t) (blues',reds',onstack',cyc)"
    note [simp del] = path_simps
    have "fe_inv (insert u0 blues0) u0 (insert u0 onstack0) (it-{t})
      (blues',reds',onstack',prep_wit_blue u0 cyc)"
      unfolding fe_inv_def
      using PRE FEI IT POST
      unfolding fe_inv_def post_def pre_def
      apply (clarsimp)
      apply (intro allI impI conjI)
      apply (blast intro: gen_dfs_post_imp_fe_inv)
      unfolding cyc_post_def
      apply (auto split: blue_witness.split_asm intro: path_conc path_prepend)
      done
  } note FE_INV_PRES=this

  {
    fix blues reds onstack u0
    assume "pre (blues,reds,onstack,u0)"
    hence "(v0,u0)\<in>E\<^sup>*"
      unfolding pre_def gen_dfs_pre_def by auto
  } note PRE_IMP_REACH = this

  {
    fix blues0 reds0 onstack0 u0 blues reds onstack
    assume A: "pre (blues0,reds0,onstack0,u0)"
       "fe_inv (insert u0 blues0) u0 (insert u0 onstack0)
        {} (blues,reds,onstack,NO_CYC)"
       "u0\<in>A"
    have "u0\<notin>reds" using A
      unfolding fe_inv_def add_inv_def pre_def cyc_post_def
      apply auto
      done
  } note FE_IMP_RED_PRE = this

  {
    fix blues0 reds0 onstack0 u0 blues reds onstack rcyc reds'
    assume PRE: "pre (blues0,reds0,onstack0,u0)"
    assume FEI: "fe_inv (insert u0 blues0) u0 (insert u0 onstack0)
        {} (blues,reds,onstack,NO_CYC)"
    assume ACC: "u0\<in>A"
    assume SPECR: "case rcyc of
      Some (p,v) \<Rightarrow> v\<in>onstack \<and> p\<noteq>[] \<and> path E u0 p v
    | None \<Rightarrow>
        red_dfs_inv E ?U reds' onstack
        \<and> u0\<in>reds'
        \<and> reds' \<subseteq> reds \<union> E\<^sup>* `` {u0}"
    have "post (blues0,reds0,onstack0,u0)
      (blues,reds',onstack - {u0},init_wit_blue u0 rcyc)"
      unfolding post_def add_inv_def cyc_post_def
      apply (clarsimp)
      apply (intro conjI)
    proof goal_cases
      from PRE FEI show OS0[symmetric]: "onstack - {u0} = onstack0"
        by (auto simp: pre_def fe_inv_def add_inv_def gen_dfs_pre_def) []

      from PRE FEI have "u0\<in>onstack"
        unfolding pre_def gen_dfs_pre_def fe_inv_def gen_dfs_fe_inv_def
        by auto

      from PRE FEI
      show POST: "gen_dfs_post E (E\<^sup>* `` {v0}) onstack0 blues0 u0 blues
        (init_wit_blue u0 rcyc \<noteq> NO_CYC)"
        by (auto simp: pre_def fe_inv_def intro: gen_dfs_fe_inv_imp_post)

      case 3

      from FEI have [simp]: "onstack=insert u0 onstack0"
        unfolding fe_inv_def by auto
      from FEI have "u0\<in>blues" unfolding fe_inv_def gen_dfs_fe_inv_def by auto

      show ?case
        apply (cases rcyc)
        apply (simp_all add: split_paired_all)
      proof -
        assume [simp]: "rcyc=None"
        show "(\<forall>v\<in>(blues - (onstack0 - {u0})) \<inter> A. (v, v) \<notin> E\<^sup>+) \<and>
          reds' \<subseteq> blues \<and>
          reds' \<inter> (onstack0 - {u0}) = {} \<and>
          red_dfs_inv E (E\<^sup>* `` {v0}) reds' (onstack0 - {u0})"
        proof (intro conjI)
          from SPECR have RINV: "red_dfs_inv E ?U reds' onstack"
            and "u0\<in>reds'"
            and REDS'R: "reds' \<subseteq> reds \<union> E\<^sup>*``{u0}"
            by auto

          from RINV show
            RINV': "red_dfs_inv E (E\<^sup>* `` {v0}) reds' (onstack0 - {u0})"
            unfolding red_dfs_inv_def by auto

          from RINV'[unfolded red_dfs_inv_def] have
            REDS'CL: "E``reds' \<subseteq> reds'"
            and DJ': "E `` reds' \<inter> (onstack0 - {u0}) = {}" by auto

          from RINV[unfolded red_dfs_inv_def] have
            DJ: "E `` reds' \<inter> (onstack) = {}" by auto

          show "reds' \<subseteq> blues"
          proof
            fix v assume "v\<in>reds'"
            with REDS'R have "v\<in>reds \<or> (u0,v)\<in>E\<^sup>*" by blast
            thus "v\<in>blues" proof
              assume "v\<in>reds"
              moreover with FEI have "reds\<subseteq>blues"
                unfolding fe_inv_def add_inv_def cyc_post_def by auto
              ultimately show ?thesis ..
            next
              from POST[unfolded gen_dfs_post_def OS0] have
                CL: "E `` (blues - (onstack0 - {u0})) \<subseteq> blues" and "u0\<in>blues"
                by auto
              from PRE FEI have "onstack0 \<subseteq> blues"
                unfolding pre_def fe_inv_def gen_dfs_pre_def gen_dfs_fe_inv_def
                by auto

              assume "(u0,v)\<in>E\<^sup>*"
              thus "v\<in>blues"
              proof (cases rule: rtrancl_last_visit[where S="onstack - {u0}"])
                case no_visit
                thus "v\<in>blues" using `u0\<in>blues` CL
                  by induct (auto elim: rtranclE)
              next
                case (last_visit_point u)
                then obtain uh where "(u0,uh)\<in>E\<^sup>*" and "(uh,u)\<in>E"
                  by (metis tranclD2)
                with REDS'CL DJ' `u0\<in>reds'` have "uh\<in>reds'"
                  by (auto dest: Image_closed_trancl)
                with DJ' `(uh,u)\<in>E` `u \<in> onstack - {u0}` have False
                  by simp blast
                thus ?thesis ..
              qed
            qed
          qed

          show "\<forall>v\<in>(blues - (onstack0 - {u0})) \<inter> A. (v, v) \<notin> E\<^sup>+"
          proof
            fix v
            assume A: "v \<in> (blues - (onstack0 - {u0})) \<inter> A"
            show "(v,v)\<notin>E\<^sup>+" proof (cases "v=u0")
              assume "v\<noteq>u0"
              with A have "v\<in>(blues - (insert u0 onstack)) \<inter> A" by auto
              with FEI show ?thesis
                unfolding fe_inv_def add_inv_def cyc_post_def by auto
            next
              assume [simp]: "v=u0"
              show ?thesis proof
                assume "(v,v)\<in>E\<^sup>+"
                then obtain uh where "(u0,uh)\<in>E\<^sup>*" and "(uh,u0)\<in>E"
                  by (auto dest: tranclD2)
                with REDS'CL DJ `u0\<in>reds'` have "uh\<in>reds'"
                  by (auto dest: Image_closed_trancl)
                with DJ `(uh,u0)\<in>E` `u0 \<in> onstack` show False by blast
              qed
            qed
          qed

          show "reds' \<inter> (onstack0 - {u0}) = {}"
          proof (rule ccontr)
            assume "reds' \<inter> (onstack0 - {u0}) \<noteq> {}"
            then obtain v where "v\<in>reds'" and "v\<in>onstack0" and "v\<noteq>u0" by auto

            from `v\<in>reds'` REDS'R have "v\<in>reds \<or> (u0,v)\<in>E\<^sup>*"
              by auto
            thus False proof
              assume "v\<in>reds"
              with FEI[unfolded fe_inv_def add_inv_def cyc_post_def]
                `v\<in>onstack0`
              show False by auto
            next
              assume "(u0,v)\<in>E\<^sup>*"
              with `v\<noteq>u0` obtain uh where "(u0,uh)\<in>E\<^sup>*" and "(uh,v)\<in>E"
                by (auto elim: rtranclE)
              with REDS'CL DJ `u0\<in>reds'` have "uh\<in>reds'"
                by (auto dest: Image_closed_trancl)
              with DJ `(uh,v)\<in>E` `v \<in> onstack0` show False by simp blast
            qed
          qed
        qed
      next
        fix u p
        assume [simp]: "rcyc = Some (p,u)"
        show "(u = u0 \<longrightarrow> u0 \<in> A \<and> p \<noteq> [] \<and> path E u0 p u0) \<and>
          (u \<noteq> u0 \<longrightarrow> u0 \<in> A \<and> u \<in> onstack0 \<and> p \<noteq> [] \<and> path E u0 p u)"
        proof (intro conjI impI)
          show "u0\<in>A" by fact
          show "u0\<in>A" by fact
          from SPECR show
            "u\<noteq>u0 \<Longrightarrow> u\<in>onstack0"
            "p\<noteq>[]"
            "p\<noteq>[]"
            "path E u0 p u"
            "u=u0 \<Longrightarrow> path E u0 p u0"
            by auto
        qed
      qed
    qed
  } note RED_IMP_POST = this

  {
    fix blues0 reds0 onstack0 u0 blues reds onstack and cyc :: "'v blue_witness"
    assume PRE: "pre (blues0,reds0,onstack0,u0)"
    and FEI: "fe_inv (insert u0 blues0) u0 (insert u0 onstack0)
        {} (blues,reds,onstack,NO_CYC)"
    and FC[simp]: "cyc=NO_CYC"
    and NCOND: "u0\<notin>A"

    from PRE FEI have OS0: "onstack0 = onstack - {u0}"
      by (auto simp: pre_def fe_inv_def add_inv_def gen_dfs_pre_def) []

    from PRE FEI have "u0\<in>onstack"
      unfolding pre_def gen_dfs_pre_def fe_inv_def gen_dfs_fe_inv_def
      by auto
    with OS0 have OS1: "onstack = insert u0 onstack0" by auto

    have "post (blues0,reds0,onstack0,u0) (blues,reds,onstack - {u0},NO_CYC)"
      apply (clarsimp simp: post_def cyc_post_def) []
      apply (intro conjI impI)
      apply (simp add: OS0)
      using PRE FEI apply (auto
        simp: pre_def fe_inv_def intro: gen_dfs_fe_inv_imp_post) []

      using FEI[unfolded fe_inv_def cyc_post_def] unfolding add_inv_def
      apply clarsimp
      apply (intro conjI)
      using NCOND apply auto []
      apply auto []
      apply (clarsimp simp: red_dfs_inv_def, blast) []
      done
  } note NCOND_IMP_POST=this

  {
    fix blues0 reds0 onstack0 u0 blues reds onstack it
      and cyc :: "'v blue_witness"
    assume PRE: "pre (blues0,reds0,onstack0,u0)"
    and FEI: "fe_inv (insert u0 blues0) u0 (insert u0 onstack0)
        it (blues,reds,onstack,cyc)"
    and NC: "cyc\<noteq>NO_CYC"
    and IT: "it\<subseteq>E``{u0}"
    from PRE FEI have OS0: "onstack0 = onstack - {u0}"
      by (auto simp: pre_def fe_inv_def add_inv_def gen_dfs_pre_def) []

    from PRE FEI have "u0\<in>onstack"
      unfolding pre_def gen_dfs_pre_def fe_inv_def gen_dfs_fe_inv_def
      by auto
    with OS0 have OS1: "onstack = insert u0 onstack0" by auto

    have "post (blues0,reds0,onstack0,u0) (blues,reds,onstack - {u0},cyc)"
      apply (clarsimp simp: post_def) []
      apply (intro conjI impI)
      apply (simp add: OS0)
      using PRE FEI IT NC apply (auto
        simp: pre_def fe_inv_def intro: gen_dfs_fe_imp_post_brk) []
      using FEI[unfolded fe_inv_def] NC
      unfolding cyc_post_def
      apply (auto split: blue_witness.split simp: OS1) []
      done
  } note BREAK_IMP_POST = this

  {
    fix \<sigma>
    assume INV0: "pre \<sigma>"
    have "REC\<^sub>T ?body \<sigma>
      \<le> SPEC (post \<sigma>)"

      apply (intro refine_vcg
        RECT_rule[where pre="pre"
        and V="gen_dfs_var ?U <*lex*> {}"]
      )
      apply refine_mono
      apply (blast intro!: gen_dfs_pre_imp_wf[OF GENPRE])
      apply (rule INV0)

      (* Foreach loop *)
      apply (rule_tac
        I="fe_inv (insert bb a) bb (insert bb ab)"
        in FOREACHc_rule')

      apply (auto simp add: pre_def gen_dfs_pre_imp_fin) []

      apply (blast intro: PRE_IMP_FE)

      apply (intro refine_vcg)

      (* Recursive call *)
      apply (rule order_trans)
      apply (rprems)
      apply (clarsimp simp add: pre_def fe_inv_def cyc_post_def)
      apply (rule gen_dfs_fe_inv_imp_pre, assumption+) []
      apply (auto simp add: pre_def fe_inv_def intro: gen_dfs_fe_inv_imp_var) []

      apply (auto intro: FE_INV_PRES) []

      apply (auto simp add: pre_def post_def fe_inv_def
        intro: gen_dfs_fe_inv_pres_visited) []

      apply (intro refine_vcg)

      (* Nested DFS call *)
      apply (rule order_trans)
      apply (rule red_dfs_correct[where U="E\<^sup>* `` {v0}"])
      apply (auto simp add: fe_inv_def add_inv_def cyc_post_def) []
      apply (auto intro: PRE_IMP_REACH) []
      apply (auto dest: FE_IMP_RED_PRE) []

      apply (intro refine_vcg)
      apply clarsimp
      apply (rule RED_IMP_POST, assumption+) []

      apply (clarsimp, blast intro: NCOND_IMP_POST) []

      apply (intro refine_vcg)
      apply simp

      apply (clarsimp, blast intro: BREAK_IMP_POST) []
      done
  } note GEN=this

  show ?thesis
    unfolding blue_dfs_def extract_res_def
    apply (intro refine_vcg)
    apply (rule order_trans)
    apply (rule GEN)
    apply fact
    apply (intro refine_vcg)
    apply clarsimp
    apply (drule IMP_POST)
    apply (simp split: blue_witness.split_asm)
    done
qed

subsection "Refinement"

subsubsection {* Setup for Custom Datatypes *}
text {* This effort can be automated, but currently, such an automation is
  not yet implemented *}
abbreviation "red_wit_rel \<equiv> \<langle>\<langle>\<langle>nat_rel\<rangle>list_rel,nat_rel\<rangle>prod_rel\<rangle>option_rel"
abbreviation "wit_res_rel \<equiv>
  \<langle>\<langle>nat_rel,\<langle>\<langle>nat_rel\<rangle>list_rel,\<langle>nat_rel\<rangle>list_rel\<rangle>prod_rel\<rangle>prod_rel\<rangle>option_rel"
abbreviation "i_red_wit \<equiv> \<langle>\<langle>\<langle>i_nat\<rangle>\<^sub>ii_list,i_nat\<rangle>\<^sub>ii_prod\<rangle>\<^sub>ii_option"
abbreviation "i_res \<equiv>
  \<langle>\<langle>i_nat,\<langle>\<langle>i_nat\<rangle>\<^sub>ii_list,\<langle>i_nat\<rangle>\<^sub>ii_list\<rangle>\<^sub>ii_prod\<rangle>\<^sub>ii_prod\<rangle>\<^sub>ii_option"

abbreviation "blue_wit_rel \<equiv> (Id::(nat blue_witness \<times> _) set)"
consts i_blue_wit :: interface

term extract_res

lemma [autoref_itype]:
  "NO_CYC ::\<^sub>i i_blue_wit"
  "op = ::\<^sub>i i_blue_wit \<rightarrow>\<^sub>i i_blue_wit \<rightarrow>\<^sub>i i_bool"
  "init_wit_blue ::\<^sub>i i_nat \<rightarrow>\<^sub>i i_red_wit \<rightarrow>\<^sub>i i_blue_wit"
  "prep_wit_blue ::\<^sub>i i_nat \<rightarrow>\<^sub>i i_blue_wit \<rightarrow>\<^sub>i i_blue_wit"
  "red_init_witness ::\<^sub>i i_nat \<rightarrow>\<^sub>i i_nat \<rightarrow>\<^sub>i i_red_wit"
  "prep_wit_red ::\<^sub>i i_nat \<rightarrow>\<^sub>i i_red_wit \<rightarrow>\<^sub>i i_red_wit"
  "extract_res ::\<^sub>i i_blue_wit \<rightarrow>\<^sub>i i_res"
  by auto

context begin interpretation autoref_syn .

lemma autoref_wit[autoref_rules_raw]:
  "(NO_CYC,NO_CYC)\<in>blue_wit_rel"
  "(op =, op =) \<in> blue_wit_rel \<rightarrow> blue_wit_rel \<rightarrow> bool_rel"
  "(init_wit_blue, init_wit_blue) \<in> nat_rel \<rightarrow> red_wit_rel \<rightarrow> blue_wit_rel"
  "(prep_wit_blue,prep_wit_blue)\<in>nat_rel \<rightarrow> blue_wit_rel \<rightarrow> blue_wit_rel"
  "(red_init_witness, red_init_witness) \<in> nat_rel\<rightarrow>nat_rel\<rightarrow>red_wit_rel"
  "(prep_wit_red,prep_wit_red) \<in> nat_rel \<rightarrow> red_wit_rel \<rightarrow> red_wit_rel"
  "(extract_res,extract_res) \<in> blue_wit_rel \<rightarrow> wit_res_rel"
  by simp_all

subsubsection {* Actual Refinement*}

schematic_goal red_dfs_impl_refine_aux:
  (*notes [[goals_limit = 1]]*)
  fixes u'::"nat" and V'::"nat set"
  notes [autoref_tyrel] =
    ty_REL[where 'a="nat set" and R="\<langle>nat_rel\<rangle>iam_set_rel"]
  assumes [autoref_rules]:
    "(u,u')\<in>nat_rel"
    "(V,V')\<in>\<langle>nat_rel\<rangle>iam_set_rel"
    "(onstack,onstack')\<in>\<langle>nat_rel\<rangle>iam_set_rel"
    "(E,E')\<in>\<langle>nat_rel\<rangle>slg_rel"
  shows "(RETURN (?f::?'c), red_dfs E' onstack' V' u') \<in> ?R"
  apply -
  unfolding red_dfs_def
  apply (autoref_monadic)
  done

concrete_definition red_dfs_impl uses red_dfs_impl_refine_aux
prepare_code_thms red_dfs_impl_def
declare red_dfs_impl.refine[autoref_higher_order_rule, autoref_rules]

schematic_goal ndfs_impl_refine_aux:
  fixes s::"nat"
  notes [autoref_tyrel] =
    ty_REL[where 'a="nat set" and R="\<langle>nat_rel\<rangle>iam_set_rel"]
  assumes [autoref_rules]:
    "(succi,E)\<in>\<langle>nat_rel\<rangle>slg_rel"
    "(Ai,A)\<in>\<langle>nat_rel\<rangle>iam_set_rel"
  notes [autoref_rules] = IdI[of s]
  shows "(RETURN (?f::?'c), blue_dfs E A s) \<in> \<langle>?R\<rangle>nres_rel"
  unfolding blue_dfs_def
  apply (autoref_monadic (trace))
  done

concrete_definition ndfs_impl for succi Ai s uses ndfs_impl_refine_aux
prepare_code_thms ndfs_impl_def
export_code ndfs_impl in SML

term "\<lambda>E A v0. ndfs_impl (succ_of_list_impl E) (acc_of_list_impl A) v0"

term nat_of_integer

definition "succ_of_list_impl_int \<equiv>
  succ_of_list_impl o map (\<lambda>(u,v). (nat_of_integer u, nat_of_integer v))"

definition "acc_of_list_impl_int \<equiv>
  acc_of_list_impl o map nat_of_integer"

export_code
  ndfs_impl
  succ_of_list_impl_int
  acc_of_list_impl_int
  nat_of_integer
  integer_of_nat
  in SML module_name HPY_new
  file "nested_dfs.sml"

ML_val {*
  @{code ndfs_impl} (@{code succ_of_list_impl_int} [(1,2),(2,3),(2,7),(7,1)])
    (@{code acc_of_list_impl_int} [7]) (@{code nat_of_integer} 1)

*}

schematic_goal ndfs_impl_refine_aux_old:
  fixes s::"nat"
  assumes [autoref_rules]:
    "(succi,E)\<in>\<langle>nat_rel\<rangle>slg_rel"
    "(Ai,A)\<in>\<langle>nat_rel\<rangle>dflt_rs_rel"
  notes [autoref_rules] = IdI[of s]
  shows "(RETURN (?f::?'c), blue_dfs E A s) \<in> \<langle>?R\<rangle>nres_rel"
  unfolding blue_dfs_def red_dfs_def
  using [[autoref_trace]]
  apply (autoref_monadic)
  done

end


subsubsection \<open>Wrap-Up: Combining all equations\<close>

theory All_Equations
  imports All_Equations_Invariance

begin

context register_machine
begin

definition all_equations_relation :: "polynomial \<Rightarrow> polynomial \<Rightarrow> polynomial \<Rightarrow> polynomial
  \<Rightarrow> polynomial \<Rightarrow> polynomial \<Rightarrow> polynomial \<Rightarrow> polynomial list \<Rightarrow> polynomial list \<Rightarrow> polynomial list
  \<Rightarrow> relation" ("[ALLEQ] _ _ _ _ _ _ _ _ _ _") where
  "[ALLEQ] a q b c d e f r z s
         \<equiv> LARY (\<lambda>ll. all_equations (ll!0!0) (ll!0!1) (ll!0!2) (ll!0!3) (ll!0!4) (ll!0!5) (ll!0!6)
                                     (nth (ll!1)) (nth (ll!2)) (nth (ll!3)))
                                     [[a, q, b, c, d, e, f], r, z, s]"

lemma all_equations_dioph:
  fixes A f e d c b q :: polynomial
  fixes r z s :: "polynomial list"
  assumes "length r = n" "length z = n" "length s = Suc m"
  defines "DR \<equiv> [ALLEQ] A q b c d e f r z s"
  shows "is_dioph_rel DR"
proof -
  define DS where "DS \<equiv> ([REG] A b q r z s)
                     [\<and>] ([STATE] b e q z s)
                     [\<and>] ([MASK] c d e f r z)
                     [\<and>] ([CONST] b c d e f q)
                     [\<and>] [MISC] A c q"

  have "eval DS a = eval DR a" for a
    unfolding DR_def DS_def all_equations_relation_def all_equations_def
    unfolding register_equations_relation_def state_equations_relation_def
      mask_equations_relation_def rm_constant_equations_def rm_miscellaneous_equations_def
    by (simp add: defs)

  moreover have "is_dioph_rel DS"
    unfolding DS_def apply (rule and_dioph)+
    apply (simp_all add: rm_constant_equations_dioph rm_miscellaneous_equations_dioph)
    using assms reg_dioph[of r z s A b q] state_equations_dioph[of s z b e q]
          mask_equations_relation_dioph[of r z c d e f] by metis+

  ultimately show ?thesis using is_dioph_rel_def by auto
qed

definition rm_equations :: "nat \<Rightarrow> bool" where
  "rm_equations a \<equiv> \<exists> q :: nat.
                      \<exists> b c d e f :: nat.
                      \<exists> r z :: register \<Rightarrow> nat.
                      \<exists> s :: state \<Rightarrow> nat.
                      all_equations a q b c d e f r z s"

definition rm_equations_relation :: "polynomial \<Rightarrow> relation" ("[RM] _") where
  "[RM] A \<equiv> UNARY (rm_equations) A"

(* Correct assumptions: Need validity of p *)

lemma rm_dioph:
  fixes A
  fixes ic :: configuration
  defines "DR \<equiv> [RM] A"
  shows "is_dioph_rel DR"
proof -
  define q b c d e f where "q \<equiv> Param 0" and
                           "b \<equiv> Param 1" and
                           "c \<equiv> Param 2" and
                           "d \<equiv> Param 3" and
                           "e \<equiv> Param 4" and
                           "f \<equiv> Param 5"

  define r where "r \<equiv> map Param [6..<n + 6]"
  define z where "z \<equiv> map Param [n+6..<2*n + 6]"
  define s where "s \<equiv> map Param [2*n + 6..<2*n + 6 + m + 1]"

  define number_of_ex_vars where "number_of_ex_vars \<equiv> 2*n + 6 + m + 1"

  define A' where "A' \<equiv> push_param A number_of_ex_vars"

  define DS where "DS \<equiv> [\<exists>number_of_ex_vars] [ALLEQ] A' q b c d e f r z s"

  have "length r = n" and "length z = n" and "length s = Suc m"
    unfolding r_def z_def s_def by auto

  have "eval DS a = eval DR a" for a
  proof (rule)
    assume "eval DS a"
    then obtain ks where
      ks_length: "number_of_ex_vars = length ks" and
      ALLEQ: "eval ([ALLEQ] A' q b c d e f r z s) (push_list a ks)"
      unfolding DS_def by (auto simp add: defs)

    define q' b' c' d' e' f' where "q' \<equiv> ks!0" and
                                   "b' \<equiv> ks!1" and
                                   "c' \<equiv> ks!2" and
                                   "d' \<equiv> ks!3" and
                                   "e' \<equiv> ks!4" and
                                   "f' \<equiv> ks!5"

    define r_list where "r_list \<equiv> (take n (drop 6 ks))"
    define z_list where "z_list \<equiv> (take n (drop (6+n) ks))"
    define s_list where "s_list \<equiv> (drop (6 + 2*n) ks)"

    define r' where "r' \<equiv> (!) r_list"
    define z' where "z' \<equiv> (!) z_list"
    define s' where "s' \<equiv> (!) s_list"

    have A: "peval A' (push_list a ks) = peval A a" for a
      using ks_length push_push_simp unfolding A'_def by auto

    have q: "peval q (push_list a ks) = q'"
      unfolding q_def q'_def push_list_def using ks_length unfolding number_of_ex_vars_def by auto
    have b: "peval b (push_list a ks) = b'"
      unfolding b_def b'_def push_list_def using ks_length unfolding number_of_ex_vars_def by auto
    have c: "peval c (push_list a ks) = c'"
      unfolding c_def c'_def push_list_def using ks_length unfolding number_of_ex_vars_def by auto
    have d: "peval d (push_list a ks) = d'"
      unfolding d_def d'_def push_list_def using ks_length unfolding number_of_ex_vars_def by auto
    have e: "peval e (push_list a ks) = e'"
      unfolding e_def e'_def push_list_def using ks_length unfolding number_of_ex_vars_def by auto
    have f: "peval f (push_list a ks) = f'"
      unfolding f_def f'_def push_list_def using ks_length unfolding number_of_ex_vars_def by auto

    have r: "(!) (map (\<lambda>P. peval P (push_list a ks)) r) x = (!) r_list x" if "x < n" for x
      unfolding r_def r_list_def using that unfolding push_list_def
      using ks_length unfolding number_of_ex_vars_def by auto

    have z: "(map (\<lambda>P. peval P (push_list a ks)) z) ! x = z_list ! x" if "x < n" for x
      unfolding z_def z_list_def using that unfolding push_list_def
      using ks_length unfolding number_of_ex_vars_def by (auto simp add: add.commute)

    have s: "(map (\<lambda>P. peval P (push_list a ks)) s) ! x = s_list ! x" if "x < Suc m" for x
      unfolding s_def s_list_def using that unfolding push_list_def
      using ks_length unfolding number_of_ex_vars_def by (auto simp add: add.commute)

    have "all_equations (peval A a) q' b' c' d' e' f' r' z' s'"
      using ALLEQ unfolding all_equations_relation_def apply (simp add: defs)
      unfolding A q b c d e f
      using all_equations_invariance[of
                                     "(!) (map (\<lambda>P. peval P (push_list a ks)) r)" r'
                                     "(!) (map (\<lambda>P. peval P (push_list a ks)) z)" z'
                                     "(!) (map (\<lambda>P. peval P (push_list a ks)) s)" s'
                                     "peval A a" q' b' c' d' e' f'] r z s
      using r'_def s'_def z'_def by fastforce

    thus "eval DR a"
      unfolding DR_def rm_equations_def rm_equations_relation_def by (auto simp: defs) (blast)
  next
    assume "eval DR a"
    then obtain q' b' c' d' e' f' r' z' s' where
         all_eq: "all_equations (peval A a) q' b' c' d' e' f' r' z' s'"
    unfolding DR_def rm_equations_def rm_equations_relation_def by (auto simp: defs)

    define r_list where "r_list \<equiv> map r' [0..<n]"
    define z_list where "z_list \<equiv> map z' [0..<n]"
    define s_list where "s_list \<equiv> map s' [0..<Suc m]"

    define ks where "ks \<equiv> [q', b', c', d', e', f'] @ r_list @ z_list @ s_list"

    have "number_of_ex_vars = length ks"
      unfolding number_of_ex_vars_def ks_def r_list_def z_list_def s_list_def by auto

    have A: "peval A' (push_list a ks) = peval A a" for a
      unfolding A'_def
      using push_push_simp[of A ks a] unfolding \<open>number_of_ex_vars = length ks\<close> by auto

    have q: "peval q (push_list a ks) = q'"
      unfolding q_def ks_def push_list_def by auto
    have b: "peval b (push_list a ks) = b'"
      unfolding b_def ks_def push_list_def by auto
    have c: "peval c (push_list a ks) = c'"
      unfolding c_def ks_def push_list_def by auto
    have d: "peval d (push_list a ks) = d'"
      unfolding d_def ks_def push_list_def by auto
    have e: "peval e (push_list a ks) = e'"
      unfolding e_def ks_def push_list_def by auto
    have f: "peval f (push_list a ks) = f'"
      unfolding f_def ks_def push_list_def by auto

    have r: "(map (\<lambda>P. peval P (push_list a ks)) r) ! x = r' x" if "x < n" for x
      using that unfolding ks_def r_list_def r_def push_list_def
      using nth_append[of "map r' [0..<n]" "z_list @ s_list"] by auto

    have z: "(map (\<lambda>P. peval P (push_list a ks)) z) ! x = z' x" if "x < n" for x
      using that unfolding ks_def z_list_def r_list_def z_def push_list_def apply simp
      using nth_append[of "map r' [0..<n] @ map z' [0..<n]" "s_list"]
      by (metis add_diff_cancel_left' gen_length_def length_code length_map length_upt
          not_add_less1 nth_append nth_map_upt)

    have s: "(map (\<lambda>P. peval P (push_list a ks)) s) ! x = s' x" if "x < Suc m" for x
      using that unfolding ks_def r_list_def z_list_def s_list_def s_def push_list_def apply simp
      using nth_append[of "map r' [0..<n] @ map z' [0..<n]" "map s' [0..<m] @ [s' m]" "(2 * n + x)"]
      by (auto) (metis (mono_tags, lifting) add_cancel_left_left diff_zero length_map length_upt
          less_antisym nth_append nth_append_length nth_map_upt)

    have "eval ([ALLEQ] A' q b c d e f r z s) (push_list a ks)"
      using all_eq unfolding all_equations_relation_def apply (simp add: defs)
      unfolding A q b c d e f
      using all_equations_invariance[of "(!) (map (\<lambda>P. peval P (push_list a ks)) r)" r'
                                        "(!) (map (\<lambda>P. peval P (push_list a ks)) z)" z'
                                        "(!) (map (\<lambda>P. peval P (push_list a ks)) s)" s'
                                        "peval A a" q' b' c' d' e' f'] r z s
      using r_list_def s_list_def z_list_def by auto

    thus "eval DS a"
      unfolding DS_def using \<open>number_of_ex_vars = length ks\<close> by (auto)
  qed

  moreover have "is_dioph_rel DS"
    unfolding DS_def
    using all_equations_dioph \<open>length r = n\<close> \<open>length z = n\<close> \<open>length s = Suc m\<close> assms
    by (auto simp: dioph)

  ultimately show ?thesis
    using is_dioph_rel_def by auto

qed

end

end


(* This Isabelle theory is produced using the TIP tool offered at the following website:
     https://github.com/tip-org/tools
   This file was originally provided as part of TIP benchmark at the following website:
     https://github.com/tip-org/benchmarks
   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly
   to make it compatible with Isabelle2017.*)
  theory TIP_list_concat_map_bind
imports "../../Test_Base"
begin

datatype 'a list = nil2 | cons2 "'a" "'a list"

fun x :: "'a list => 'a list => 'a list" where
"x (nil2) y2 = y2"
| "x (cons2 z2 xs) y2 = cons2 z2 (x xs y2)"

fun y :: "'a list => ('a => 'b list) => 'b list" where
"y (nil2) y2 = nil2"
| "y (cons2 z2 xs) y2 = x (y2 z2) (y xs y2)"

fun map :: "('a => 'b) => 'a list => 'b list" where
"map f (nil2) = nil2"
| "map f (cons2 y2 xs) = cons2 (f y2) (map f xs)"

fun concat :: "('a list) list => 'a list" where
"concat (nil2) = nil2"
| "concat (cons2 y2 xs) = x y2 (concat xs)"

theorem property0 :
  "((concat (map f xs)) = (y xs f))"
  oops

end


theory Attic
imports VDMToolkit
begin

section \<open>Well foundedness study on bounded @{text nat_term}\<close>

abbreviation \<open>NAT_MAX \<equiv> 2\<close>

definition
  nat_term :: \<open>(\<nat> \<times> \<nat>) VDMSet\<close>
  where
  \<open>nat_term \<equiv> { (m, n) . n = Suc m \<and> n < NAT_MAX }\<close>

lemma l_nat_term_eq: \<open>nat_term = { (0, 1) }\<close> (*, (1, 2) }\<close> , (2, 3), (3, 4) }\<close>*)
  apply (simp add: nat_term_def, safe)
  by (simp_all)

definition
  nat_fin_psub :: \<open>(((\<nat> \<times> \<nat>) VDMSet) \<times> ((\<nat> \<times> \<nat>) VDMSet)) VDMSet\<close>
  where
(*\<open>nat_fin_psub \<equiv> finite_psubset :: ((\<nat> \<times> \<nat>) VDMSet \<times> (\<nat> \<times> \<nat>) VDMSet) VDMSet\<close> *)
  \<open>nat_fin_psub \<equiv> {(A, B). A \<subset> B \<and> finite B \<and> B \<subseteq> nat_term }\<close>

(*
lemma l_nat_fin_psub_eq1: \<open>{({(0, 1)}, {(0, 1), (1, 2)}), ({(1, 2)}, {(0, 1), (1, 2)}), ({}, {(0, 1), (1, 2)}), ({}, {(0, 1)}), ({}, {(1, 2)})} \<subseteq> nat_fin_psub\<close>
  apply (intro subsetI)
  unfolding nat_fin_psub_def
  apply (simp add: case_prod_beta)
  apply (elim disjE, simp_all add: l_nat_term_eq)
  by blast+

lemma l_nat_fin_psub_eq2:\<open>nat_fin_psub \<subseteq> {({(0, 1)}, {(0, 1), (1, 2)}), ({(1, 2)}, {(0, 1), (1, 2)}), ({}, {(0, 1), (1, 2)}), ({}, {(0, 1)}), ({}, {(1, 2)})}\<close>
  apply (intro subsetI, simp_all add: nat_fin_psub_def case_prod_beta)
  apply (elim conjE)
  apply clarsimp
  apply (simp add: subset_eq[of _ \<open>nat_term\<close>])
  apply (erule_tac x=\<open>(aa,ba)\<close> in ballE)
   apply (simp add: l_nat_term_eq)
   apply (elim disjE conjE, simp)
  thm impCE impE
  apply (rule prod_eqI, simp_all)
  apply (simp add: l_nat_term_eq)
   apply (metis (no_types, lifting) l_nat_term_eq leD order_less_imp_le singletonD subset_empty subset_iff)
  by (metis One_nat_def l_nat_term_eq leD order_less_imp_le subset_empty subset_singletonD)

  apply (simp add: subset_eq[of _ \<open>nat_term\<close>])
  nitpick
  sorry

lemma \<open>nat_fin_psub = {({(0, 1)}, {(0, 1), (1, 2)}), ({(1, 2)}, {(0, 1), (1, 2)}), ({}, {(0, 1), (1, 2)}), ({}, {(0, 1)}), ({}, {(1, 2)})}\<close>
  apply (rule equalityI)
   apply (rule l_nat_fin_psub_eq2)
  apply (rule l_nat_fin_psub_eq1)
  done

*)

lemma \<open>nat_fin_psub = {({}, {(0, 1)})}\<close>
  apply (intro equalityI subsetI, simp_all add: nat_fin_psub_def case_prod_beta)
   defer
   apply (simp add: l_nat_term_eq l_psubset_insert)
  apply (rule prod_eqI, simp_all)
   apply (metis (no_types, lifting) l_nat_term_eq leD order_less_imp_le singletonD subset_empty subset_iff)
  by (metis One_nat_def l_nat_term_eq leD order_less_imp_le subset_empty subset_singletonD)

definition
  nat_lex_nat :: \<open>(((\<nat> \<times> \<nat>) set \<times> \<nat>) \<times> (((\<nat> \<times> \<nat>) set) \<times> \<nat>)) set\<close>
  where
  \<open>nat_lex_nat \<equiv> nat_fin_psub <*lex*> nat_term\<close>

lemma \<open>x \<in> nat_lex_nat\<close>
  using[[show_types]]
  oops
lemma \<open>((a, b), (a', b')) \<in> nat_lex_nat\<close>
  using[[show_types]]
  oops

lemma \<open>nat_lex_nat =
      {(({}, 0),
        ({(0, 1)}, 0)
       ),
       (({}, 0),
        ({(0, 1)}, 1)
       ),
       (({}, 1),
        ({(0, 1)}, 0)
       ),
       (({}, 1),
        ({(0, 1)}, 1)
       )}\<close>
  apply (intro equalityI subsetI, simp_all)
   defer
   apply (simp add: nat_lex_nat_def)
   apply (elim disjE, simp_all add: nat_fin_psub_def nat_term_def, blast+)
   apply (simp add: nat_lex_nat_def)
  unfolding lex_prod_def
  apply (simp add: case_prod_beta)
  apply (elim disjE conjE, simp add: nat_fin_psub_def)
   apply clarsimp
  oops

lemma "x < y \<Longrightarrow> (x, y) \<in> less_than"
  using less_than_def less_than_iff pred_nat_def by presburger

definition lex_prod' :: "('a \<times>'a) set \<Rightarrow> ('b \<times> 'b) set \<Rightarrow> (('a \<times> 'b) \<times> ('a \<times> 'b)) set"
    (infixr "<*lexi*>" 80)
    where "ra <*lexi*> rb = {((a, b), (a', b')). (a, a') \<in> ra } \<union>
                            {((a, b), (a', b')). a = a' \<and> (b, b') \<in> rb}"

lemma lex_prod_equiv: "(ra <*lex*> rb) = (ra <*lexi*>rb)"
  by (safe, simp_all add: lex_prod_def lex_prod'_def)

subsection \<open>General version for all VDM set-recursive functions\<close>

definition
  gen_fin_psub :: \<open>(('a \<times> 'a) VDMSet \<times> ('a \<times> 'a) VDMSet) VDMSet\<close>
  where
  \<open>gen_fin_psub \<equiv> finite_psubset\<close>

definition
  gen_lex_nat :: \<open>((('a \<times> 'a) VDMSet \<times> \<nat>) \<times> ('a \<times> 'a) VDMSet \<times> \<nat>) VDMSet\<close>
  where
  \<open>gen_lex_nat \<equiv> gen_fin_psub <*lex*> pred_nat\<close>

lemma "wf gen_lex_nat"
  by (simp add: gen_fin_psub_def gen_lex_nat_def wf_lex_prod wf_pred_nat)

lemma l_pre_sumset_empty[simp]: "pre_sumset {}"
  by (simp add: pre_sumset_def)

lemma "pre_sumset {} \<Longrightarrow> sumset_dom {}"
  by (meson empty_iff sumset.domintros)

definition
  sumset_term' ::"(VDMNat VDMSet \<times> VDMNat VDMSet) set" where
  "sumset_term' \<equiv> finite_psubset \<inter> { (s1, s2) . pre_sumset s1 \<and> pre_sumset s2 }"

definition
  sumset_term'' ::"(VDMNat VDMSet \<times> VDMNat VDMSet) set" where
  "sumset_term'' \<equiv> finite_psubset \<inter> { (s, s - {(SOME e . e \<in> s)})| s . s \<noteq> {} \<and> pre_sumset s }"

lemma l_sumset_term_not_empty: "sumset_term = {}"
   unfolding sumset_term_def
   apply (intro equalityI subsetI)
    apply simp_all
   unfolding finite_psubset_def
   apply (simp add: case_prod_beta)
   apply (elim conjE exE)
   apply safe
   apply simp
   oops

lemma l_sumset_term'_wf: "wf sumset_term'"
  by (metis inf_le1 sumset_term'_def wf_finite_psubset wf_subset)

lemma l_sumset_term''_wf: "wf sumset_term''"
  by (simp add: sumset_term''_def wf_Int1)

lemma l_pre_sumset_some: "pre_sumset x \<Longrightarrow> x \<noteq> {} \<Longrightarrow> pre_sumset (x - {SOME e. e \<in> x})"
  unfolding pre_sumset_def inv_VDMSet_def
  by (metis Diff_empty Diff_insert0 finite_Diff insert_Diff l_inv_SetElems_Cons)

lemma l_sumset_term'_iff[iff]: "(y, x) \<in> sumset_term' \<longleftrightarrow> (pre_sumset y \<and> pre_sumset x \<and> y \<subset> x)"
  apply (rule iffI)
   apply (simp add: sumset_term'_def)
  by (simp add: l_pre_sumset_finite sumset_term'_def)

lemma l_sumset_term_iff[iff]: "((x - {SOME e . e \<in> x}), x) \<in> sumset_term \<longleftrightarrow> (pre_sumset (x - {SOME e . e \<in> x}) \<and> pre_sumset x \<and> x \<noteq> {})"
  apply (rule iffI)
   apply (simp add: sumset_term_def l_pre_sumset_some)
  apply (simp add: sumset_term_def pre_sumset_def inv_VDMSet_def)
  apply (intro psubsetI)
   apply fastforce
  by (metis Diff_iff singletonI some_in_eq)

lemma "s \<noteq> {} \<Longrightarrow> pre_sumset s \<Longrightarrow> ({}, s) \<in> sumset_term"
  apply (simp add: sumset_term_def l_pre_sumset_finite )
  oops

(*
lemma "pre_sumset (insert e s) \<Longrightarrow> sumset_dom (insert e s)"
  thm wf_induct
      wf_induct[OF l_sumset_term_wf]
      wf_induct[OF l_sumset_term_wf, of "\<lambda> x . sumset_dom (insert e x)"]
  apply (rule      wf_induct[OF l_sumset_term_wf, of "\<lambda> x . sumset_dom (insert e x)"]
  )
  apply (simp add: l_sumset_term_iff)
  apply (erule_tac x=y in allE
  apply (rule sumset.domintros)
  apply (erule notE)
  oops
*)

  find_theorems name:"_dom" -name:VDMToolkit -name:Transfer -name:Map

  thm sumset.domintros
  thm sumset_rel.intros
  find_theorems name: accp
  find_theorems name: accp name:Wellfounded
  find_theorems "_Collect"
  find_consts name:sumset_rel

lemma "(sumset_dom s) \<longleftrightarrow> (s \<in> Wellfounded.acc { (x, y). (sumset_rel x y) })"
  by (simp add: accp_eq_acc)

lemma "s \<in> Wellfounded.acc { (x, y). (sumset_rel x y) }"
  apply (rule accI, simp)
  find_theorems "sumset_rel"
  thm sumset_rel.intros

lemma "sumset_rel = lfp (\<lambda>p x1 x2. \<exists>s x. x1 = s - {x} \<and> x2 = s \<and> s \<noteq> {} \<and> x = (SOME x. x \<in> s))"
  apply (intro ext, simp add: lfp_def)
  apply (intro iffI allI impI)
   defer

(*     (lfp (\<lambda>(p (x1 x2)). ((x1 = (x2 - {(SOME x. (x \<in> x2))})) \<and> (x2 \<noteq> {}))) x xa) *)

(* (\<forall> e \<in> s . e \<ge> 0) \<Longrightarrow> ...(s - {SOME e \<in> s}, s) \<in> ?R.... \<Longrightarrow> sumset_dom s*)
lemma "pre_sumset s \<Longrightarrow> sumset_dom s"
    (*
  apply (rule wf_induct)
   1. pre_sumset s \<Longrightarrow> wf ?r
 2. \<And>x. pre_sumset s \<Longrightarrow> \<forall>y. (y, x) \<in> ?r \<longrightarrow> y \<Longrightarrow> x
    *)
(*
  apply (rule wf_induct[of _ \<open>\<lambda> x . sumset_dom x\<close> s])
  goal (2 subgoals):
   1. pre_sumset s \<Longrightarrow> wf ?r
   2. \<And>x. pre_sumset s \<Longrightarrow> \<forall>y. (y, x) \<in> ?r \<longrightarrow> sumset_dom y \<Longrightarrow> sumset_dom x
*)
  thm wf_induct
      wf_induct[of _ \<open>\<lambda> x . sumset_dom x\<close> s]
      l_sumset_term''_wf
      wf_subset
      wf_induct[OF l_sumset_term''_wf, of \<open>\<lambda> x . sumset_dom (x - {SOME e . e \<in> x})\<close> s]
  apply (rule wf_induct[OF l_sumset_term''_wf, of \<open>\<lambda> x . sumset_dom (x - {SOME e . e \<in> x})\<close> s])
  apply (erule_tac x=x in allE)
  apply (elim impE)
   apply (simp add: sumset_term_def)
  find_theorems name:induc name:fin name:set
  oops

lemma "pre_sumset s \<Longrightarrow> sumset_dom s"
  apply (rule wf_induct[OF l_sumset_term_wf, of \<open>\<lambda> x . sumset_dom x\<close> s])
  apply (erule_tac x=x in allE)
  apply (elim impE)
   apply (simp add: sumset_term_def)

definition
  sumset_call :: \<open>(VDMNat VDMSet) \<Rightarrow> (VDMNat VDMSet)\<close>
  where
  \<open>sumset_call s \<equiv> if s = {} then {} else s - {(SOME e . e \<in> s)}\<close>

(* r = result of (f(s), f(s-{e})) for all s, or the computation of sumset with its <lex> for pred_nat?
   f = the result of the parameter decrease for f, or the decreasing measure for sumset?
definition inv_image :: "'b rel \<Rightarrow> ('a \<Rightarrow> 'b) \<Rightarrow> 'a rel"
  where "inv_image r f = {(x, y). (f x, f y) \<in> r}"
*)
definition
  sumset_lex_nat :: \<open>(((VDMNat \<times> VDMNat) VDMSet \<times> \<nat>) \<times> (VDMNat \<times> VDMNat) VDMSet \<times> \<nat>) VDMSet\<close>
  where
  \<open>sumset_lex_nat \<equiv> gen_fin_psub <*lex*> pred_nat\<close>

declare [[show_brackets]]
definition
(*  sumset_lex_nat :: \<open>(((VDMNat \<times> VDMNat) VDMSet \<times> \<nat>) \<times> (VDMNat \<times> VDMNat) VDMSet \<times> \<nat>) VDMSet\<close>
  where
*)
  sumset_lex_nat' :: \<open>(((VDMNat \<times> VDMNat) set \<times> ((VDMNat \<times> VDMNat) set \<times> \<nat>)) \<times> ((VDMNat \<times> VDMNat) set \<times> ((VDMNat \<times> VDMNat) set \<times> \<nat>))) set\<close>
  where
  \<open>sumset_lex_nat' \<equiv> gen_fin_psub <*lex*> gen_fin_psub <*lex*> pred_nat\<close>

lemma l_sumset_lex_nat_wf: "wf sumset_lex_nat"
  by (simp add: gen_fin_psub_def sumset_lex_nat_def wf_lex_prod wf_pred_nat)

lemma l_sumset_lex_nat'_wf: "wf sumset_lex_nat'"
  by (metis gen_fin_psub_def l_sumset_lex_nat_wf sumset_lex_nat'_def sumset_lex_nat_def wf_finite_psubset wf_lex_prod)

term "sumset_lex_nat"
term "inv_image sumset_lex_nat"
term "inv_image sumset_lex_nat'"

(*lemma "sumset_term \<subseteq> inv_image sumset_lex_nat sumset_call"
 *)

thm sumset.domintros
thm sumset.pinduct

lemma "pre_sumset s \<Longrightarrow> sumset_dom s"
  thm sumset.domintros
  apply (rule sumset.domintros)
  apply (elim notE)
  find_theorems name:induc name:fin name:set

lemma "pre_sumset s \<Longrightarrow> sumset_dom s"
proof -
  { fix s :: "VDMNat VDMSet"
    have "pre_sumset s \<longrightarrow> sumset_dom s" (is "?P s \<longrightarrow> ?Q s")
      term "?P"
      term "?Q"
    proof (rule wf_induct[OF l_sumset_term_wf])
      fix x :: "VDMNat VDMSet"
      assume ih: "(\<forall>y. (((y, x) \<in> sumset_term) \<longrightarrow> (?P y \<longrightarrow> ?Q y)))"
      show "?P x \<longrightarrow> ?Q x"
      proof
        assume P: "?P x"
        show "?Q x"
        thm sumset.domintros
        proof (rule sumset.domintros)
          thm sumset.cases
          using sumset.cases
definition
  sumset_lex :: "((\<nat> set \<times> (\<nat> \<times> \<nat>) set \<times> \<nat>) \<times> \<nat> set \<times> (\<nat> \<times> \<nat>) set \<times> \<nat>) set"
  where
  "sumset_lex \<equiv> (finite_psubset :: (nat VDMSet \<times> nat VDMSet) VDMSet)
                 <*lex*> (finite_psubset :: ((nat \<times> nat) VDMSet \<times> (nat \<times> nat) VDMSet) VDMSet)
                 <*lex*> pred_nat"

lemma l1: "wf (finite_psubset :: (VDMNat VDMSet \<times> VDMNat VDMSet) VDMSet)"
  using wf_finite_psubset by blast

lemma l2: "wf (finite_psubset :: ((VDMNat \<times> VDMNat) VDMSet \<times> (VDMNat \<times> VDMNat) VDMSet) VDMSet)"
  using wf_finite_psubset by blast

lemma l3: "wf ((finite_psubset :: (VDMNat VDMSet \<times> VDMNat VDMSet) VDMSet)
               <*lex*> (finite_psubset :: ((VDMNat \<times> VDMNat) VDMSet \<times> (VDMNat \<times> VDMNat) VDMSet) VDMSet)
               <*lex*> pred_nat)"
  by (simp add: wf_lex_prod wf_pred_nat)

theorem sumset_termination:
  \<open>\<lbrakk>pre_sumset s\<rbrakk> \<Longrightarrow> sumset_dom s\<close>
  thm wf_induct wf
lemma lsum_set_domain_empty[simp]: "pre_sumset {}"
  unfolding pre_sumset_def
  by simp

lemma lsum_empty_set_zero: "sumset {} = 0"
  thm ex_in_conv empty_iff all_not_in_conv equals0D
  find_theorems name:sumset
  apply (subst sumset.psimps)
   apply (meson empty_iff sumset.domintros)
  by simp

lemma lsum_set_dom_inv: "sumset_dom s \<Longrightarrow> pre_sumset s"
  find_theorems name:sumset
  apply (frule sumset.psimps)
  apply (simp split: if_splits)
  oops

 (*
  unfolding pre_sumset_def inv_VDMNat_def inv_SetElems_def
  apply (induct rule: sumset.pinduct)
  apply (case_tac "s = {}", simp_all)
  apply (simp add: ex_in_conv[symmetric])
  apply (safe)
  apply (erule_tac x=x in ballE)
   apply simp+
  nitpick
   apply (meson empty_iff sumset.domintros)
  apply (cut_tac accI[of _ "sumset_rel"])
*)

lemma lsum_set_inv_dom: "pre_sumset s \<Longrightarrow> sumset_dom s"
  apply (insert accp_wfPD[of sumset_rel s])
  unfolding wfP_def wf_def
  apply simp
  apply (cases "s = {}")
   apply (meson empty_iff sumset.domintros)
  apply (intro sumset.domintros)
  apply (simp add: sumset.psimps)
  oops

lemma "finite (SIGMA a:A. B a)"
  using [[show_types]]
  thm finite_set_choice
  thm finite_set_choice[of "{0,1,2,3::nat}"  "(\<lambda> x y . x < y)"]
  oops

  find_consts "'a set \<Rightarrow> 'a list"
  find_consts name:sorted_key_list_of_set
(*Set_Idioms, Mapping, Countable_Set*)
lemma lsum_set_result_is_nat:
  "inv_SetElems inv_VDMNat s \<Longrightarrow> inv_VDMNat (sumset s)"
  unfolding inv_VDMNat_def inv_SetElems_def
  apply (induct s rule: sumset.pinduct)

end