Theory Lexicographic_BFS

(*<*)
theory Lexicographic_BFS
  imports
    "HOL-Library.List_Lexorder"
    "Collections.ICF_Refine_Monadic"
    "Tree_Decomposition.Graph"
begin
(*>*)

section Preliminaries
subsection Triples
text ‹Three indices meaning term‹c› picked before term‹b›, picked before term‹a›.›

abbreviation "triple σ ci bi ai ≡ ci < bi ∧ bi < ai ∧ ai < length σ"

subsection Lists
lemma nth_not_mem_take_if_ge: "⟦i ≤ j; j < length xs; distinct xs⟧ ⟹ xs ! j ∉ set (take i xs)"
  by (metis distinct_take id_take_nth_drop not_distinct_conv_prefix set_take_subset_set_take 
      subset_code(1))

text ‹We compare lists lexicographically.›
lemma list_lt_iff_ind_lt: 
  fixes xs::"('c::linorder list)"
  assumes len_eq: "length xs = length ys"
  shows "xs < ys ⟷ (∃ i < length xs. xs ! i < ys ! i ∧ (∀j<i . xs ! j = ys ! j))"
  using len_eq
proof (induct xs ys rule: list_induct2)
  case Nil thus ?case by simp
next
  ― ‹Shorthand for conclusion›
  let ?exists_first_less = "λ xs ys. ∃i<length xs. xs ! i < ys ! i ∧ (∀j<i. xs ! j = ys ! j)"
  case (Cons x xs y ys) 
  from Cons show ?case
  proof (intro iffI)
  next 
    assume "?exists_first_less (x#xs) (y#ys)"
    then obtain i where i_hyp: 
      "i<length (x#xs)" 
      "(x#xs) ! i < (y#ys)!i"  
      "∀j<i. (x # xs) ! j = (y # ys) ! j"
      by blast
    then show "x # xs < y # ys"
    proof (cases i)
      case (Suc k)
      with i_hyp len_eq have "k < length xs"  
        and "xs ! k < ys ! k"  
        and "∀ j < k . xs ! j = ys ! j"
        by auto
      with Cons.hyps have "xs < ys" 
        by blast

      moreover from i_hyp Suc len_eq have "x = y" 
        by auto

      ultimately show ?thesis 
        by simp
    qed (simp add: i_hyp)
  next
    assume "x # xs < y # ys"
    with Cons.prems Cons_less_Cons consider "x < y" | (non_triv) "x = y" "xs < ys" 
      by blast
    then show "?exists_first_less (x#xs) (y#ys)"
    proof cases
      case non_triv
      have **: "∀ j < length xs . (x # xs) ! Suc j = xs ! j"  
        by simp
      with Cons.hyps non_triv obtain i 
        where "i < length xs" "xs!i < ys!i" 
          and *: "∀ j<i . xs ! j = ys ! j" 
        by blast
      hence "(x # xs) ! 0 = (y # ys) ! 0" 
        using ‹x =y› 
        by simp
      moreover have "∀ z zs . ∀ i < length zs . zs ! i = (z # zs) ! Suc i" 
        by simp
      hence "∀ j < i . (x # xs) ! Suc j = (y # ys) ! Suc j" 
        using * ‹i < length xs› ‹length xs = length ys› 
        by auto
      ultimately have "∀ j < Suc i . (x#xs) ! j = (y # ys) ! j" 
        by (metis Suc_less_eq old.nat.exhaust)

      with ‹i < length xs› ‹xs!i < ys ! i› show ?thesis 
        by (intro exI[where x="Suc i"]) simp
    qed (auto)
  qed
qed

lemma prev_lt_if_ind_gt:
  fixes xs :: "'c::linorder list"
  assumes "length xs = length ys"
    and "i < length xs"
    and "xs ≤ ys"
    and "xs!i > ys!i"
  shows "∃ j < i . xs!j < ys!j"
  using assms(1,3,4) by (metis list_lt_iff_ind_lt not_less_iff_gr_or_eq order_le_imp_less_or_eq)

context Graph
begin

abbreviation is_arc :: "'a ⇒ 'a ⇒ bool" (infixl "∼" 60) where "v∼w ≡ (v,w) ∈ E"
abbreviation is_not_arc :: "'a ⇒ 'a ⇒ bool" (infixl "∼*" 60) where "v ∼* w ≡ ¬ v∼w"

section ‹Implementation and Characterization›

text ‹The LexBFS algorithm, adapted as closely as possible from Algorithm 1 of Corneil et al.~cite‹CorneilHPT24›:›
definition lexbfs where "lexbfs = do { 
  (i, U, ℒ, σ) ← WHILET (λ(i, U, ℒ, σ). U ≠ {}) (λ(i, U, ℒ, σ). do {
    x <- RES {x ∈ U. ℒ x = Max (ℒ ` U)};
    let U = U - {x};
    let ℒ = (λy. if y ∈ U ∧ x ∼ y then ℒ y @ [i] else ℒ y);
    RETURN (i - 1, U, ℒ, σ @ [x]) 
}) (card V, V, λ _ . [], []);
  RETURN σ 
}"

text ‹The LexBFS property.›
definition "lexbfs_prop σ ≡
  ∀ ic ib ia. triple σ ic ib ia ∧ σ!ic ∼ σ!ia ∧ σ!ic ∼* σ!ib 
    ⟶ (∃id<ic.  σ!id ∼* σ!ia  ∧  σ!id ∼ σ!ib)"

text ‹For term‹lexbfs_prop› to be an actual characterization, we need the additional assumption that
the elements of term‹σ› correspond precisely to the vertices of term‹V›.›
definition "is_lexbfs σ ⟷ distinct σ ∧ set σ = V ∧ lexbfs_prop σ"


section ‹Soundness›
text ‹In this section we prove soundness of the LexBFS algorithm with respect to the specification
term‹is_lexbfs›. In other words, we show term‹lexbfs ≤ SPEC is_lexbfs›.›


subsection ‹The binary algorithm and its soundness›

text ‹The algorithm with term‹ℒ› replaced by the binary label function term‹ℬ›. We will, however,
define the algorithm's invariants before defining the algorithm.›
text ‹Convention: We use term‹ℬ› for the binary label function, and term‹ℒ› for the ordinary label function.›

definition "partition_V U σ ≡ distinct σ ∧ U ∪ set σ = V ∧ U ∩ set σ = {}"
lemma partition_V_empty[simp]: "partition_V V []"
  by (simp add: partition_V_def)

lemma U_finite_if_partition_V: "partition_V U σ ⟹ finite U"
  by (metis partition_V_def Un_upper1 finite_subset finite_vertex_set)

lemma len_sigma_if_partition_V: "partition_V U σ ⟹ length σ = card (set σ)"
  by (metis partition_V_def distinct_card)

lemma card_V_split_if_partition_V: "partition_V U σ ⟹ card V = card U + length σ" 
  using card_Un_disjoint[where A=U and B="set σ"]
  by (auto simp add: partition_V_def U_finite_if_partition_V len_sigma_if_partition_V)

text ‹This states that, if we look at any element text‹y ∈ σ›
and term‹x› later than term‹y› (either to the right of term‹y› in term‹σ›, or not in term‹σ› at all),
then term‹x› must have a less-or-equal term‹ℬ›-label value, if we truncate term‹ℬ› to the point where term‹y› was added.›

definition "label_le_earlier ℬ σ ≡
  ∀iy<length σ. ∀x∈V - set (take iy σ). take iy (ℬ (σ ! iy)) ≥ take iy (ℬ x)"

lemma label_le_earlierD[simp]:
  "⟦label_le_earlier ℬ σ; iy < length σ; x ∈ V - set (take iy σ)⟧ 
  ⟹ take iy (ℬ (σ!iy)) ≥ take iy (ℬ x)"
  by (simp add: label_le_earlier_def)



text ‹States that each entry of term‹ℬ x› determines whether a particular
vertex in term‹σ› is connected to term‹x› or not.›
definition "label_iff_connected ℬ σ ≡ ∀ ix<length σ. ∀y. (ℬ y)!ix ⟷ (σ!ix)∼y"
lemma label_iff_connectedD[simp]:
  "⟦label_iff_connected ℬ σ; iy < length σ⟧ ⟹ ℬ x!iy ⟷ (σ!iy)∼x"
  by (simp add: label_iff_connected_def)

definition "label_len_eq ℬ σ ≡ ∀ x . length (ℬ x) = length σ"
text ‹This simp rule chooses term‹length σ› as simplest representation, and helps a lot in
automating the proofs.›
lemma len_eq_sigma_if_label_len_eq[simp]: "label_len_eq ℬ σ ⟹ length (ℬ x) = length σ"
  by (simp add: label_len_eq_def)

lemma len_take_eq_if_label_len_eq: 
  "label_len_eq ℬ σ ⟹ length (take i (ℬ x)) = length (take i (ℬ y))"  
  by simp


text ‹Combining the invariants.›
definition "lexbfs_bin_INV ≡ λ(U, ℬ, σ) .
  partition_V U σ
  ∧ label_le_earlier ℬ σ
  ∧ label_iff_connected ℬ σ
  ∧ label_len_eq ℬ σ"

text ‹The refine WHILE procedure requires writing term‹lexbfs_bin_INV› as a function on a tuple.
This unfortunately turns unfolding term‹lexbfs_bin_INV› into a case statement with a single case.
This lemma automatically unfolds term‹lexbfs_bin_INV› into the auxiliary invariants.›
lemma INV_iff[iff]: 
  "lexbfs_bin_INV (U, ℬ, σ) 
  ⟷ partition_V U σ ∧ label_le_earlier ℬ σ ∧ label_iff_connected ℬ σ ∧ label_len_eq ℬ σ"
  by (simp add: lexbfs_bin_INV_def)


text ‹Finally, the binary version of the LexBFS algorithm.›
definition lexbfs_bin where "lexbfs_bin = do {
      (U, ℬ, σ) ← WHILET⇗lexbfs_bin_INV⇖ (λ(U, ℬ, σ). U ≠ {}) (λ(U, ℬ, σ). do {
      x <- RES {x ∈ U. ℬ x = Max (ℬ ` U)};
      let U = U - {x};
      let ℬ = (λy. ℬ y @ [x∼y]);
      RETURN (U, ℬ, σ @ [x])
}) (V, λ _ . [], []);
     RETURN σ 
}"



subsubsection ‹Preservation of invariants›
text ‹We start with the main point of the invariants -- if the invariants hold for the terminal
case (where term‹U = {}›), then the output satisfies term‹is_lexbfs›. The remaining work will then be showing
that the invariants are preserved.›
lemma lexbfs_prop_if_INV:
  assumes eq_V: "partition_V {} σ" 
    and aux1: "label_le_earlier ℬ σ" 
    and aux2: "label_iff_connected ℬ σ" 
    and aux3: "label_len_eq ℬ σ" 
  shows "lexbfs_prop σ" 
  unfolding lexbfs_prop_def
proof (intro allI impI)
  fix ic ib ia 
  let ?a = "σ!ia" and ?b = "σ!ib" and ?c = "σ!ic" 
    and ?ℬ_b = "λx . take ib (ℬ x)" ― ‹term‹ℬ› function truncated at moment before text‹?b› added›
  assume "triple σ ic ib ia ∧  ?c ∼ ?a ∧ ?c ∼* ?b"
  hence triple: "triple σ ic ib ia" and "?c ∼ ?a" "?c ∼* ?b" 
    by simp_all
  from triple eq_V have "?a ∉ set (take ib σ)" 
    using partition_V_def 
    by (simp add: nth_not_mem_take_if_ge)
  with triple eq_V have "?a ∈ V - set (take ib σ)"  
    using partition_V_def 
    by auto
  with aux1 triple have "?ℬ_b ?b ≥ ?ℬ_b ?a" 
    by simp 

  moreover from aux2 triple ‹?c∼?a› ‹?c∼*?b› have "ℬ ?b !ic < ℬ ?a !ic" 
    by simp
  with triple have "?ℬ_b ?b !ic < ?ℬ_b ?a !ic" 
    by simp  

  moreover from aux3 triple have "ic < length (?ℬ_b ?b)"
    by simp

  ultimately have "∃ id < ic . ?ℬ_b ?b !id > ?ℬ_b ?a !id"
    by (metis aux3 len_take_eq_if_label_len_eq prev_lt_if_ind_gt)
  then obtain id where "id < ic" "?ℬ_b ?a !id < ?ℬ_b ?b !id" 
    by metis
  from ‹id < ic› triple have ‹triple σ id ib ia› 
    by simp
  let ?d = "σ!id"
  from ‹?ℬ_b ?a !id < ?ℬ_b ?b !id› ‹triple σ id ib ia› have "ℬ ?a !id < ℬ ?b !id" 
    by simp
  with ‹triple σ id ib ia›  aux2 have "?d∼?b ∧ ?d∼*?a" 
    by simp
  with ‹id < ic› show "∃id<ic. σ!id ∼* σ!ia ∧ σ!id ∼ σ!ib" 
    by metis
qed


lemma is_lexbfs_if_INV: 
  "lexbfs_bin_INV ({}, ℬ, σ) ⟹ is_lexbfs σ"
  unfolding is_lexbfs_def using lexbfs_prop_if_INV partition_V_def 
  by blast


text ‹The following lemmas show that if an auxiliary invariant holds, then it also holds during the
next step of the while loop.›
lemma partition_V_next:
  "⟦partition_V U σ; x ∈ U⟧ ⟹ partition_V (U - {x}) (σ@[x])"
  by (auto simp add: partition_V_def)

lemma label_le_earlier_next: 
  assumes partition: "partition_V U σ"
    and aux1: "label_le_earlier ℬ σ" 
    and aux3: "label_len_eq ℬ σ"
    and "ℬ a = Max (ℬ ` U)"
  shows "label_le_earlier (λy. ℬ y @[a∼y]) (σ@[a])"
  unfolding label_le_earlier_def 
proof safe
  fix iy x 
  let ?y = "(σ @ [a]) !iy" ― ‹Vertex obtained from index term‹iy››
  let ?ℬ_next = "λz . ℬ z @[a∼z]" ― ‹term‹ℬ› updated by appending whether vertex is connected to term‹a››
  assume "iy < length (σ @ [a])" 
    and "x ∉ set (take iy (σ @ [a]))" 
    and "x ∈ V"
  show "take iy (?ℬ_next x) ≤ take iy (?ℬ_next ?y)" 
  proof cases
    assume "length σ = iy" 
    with partition ‹x ∈ V› ‹x ∉ set (take iy (σ@[a]))›  have "x ∈ U" 
      by (auto simp add: partition_V_def)
    with ‹ℬ a = Max (ℬ ` U)› have "ℬ x  ≤ ℬ a" 
      using partition 
      by (simp add: U_finite_if_partition_V)

    moreover from ‹length σ = iy› aux3 have "∀ z . take iy (?ℬ_next z) = ℬ z"
      by simp

    moreover from ‹length σ = iy› have "?y = a" 
      by auto

    ultimately show ?thesis 
      by simp
  next
    assume "length σ ≠ iy"
    with ‹iy < length (σ @ [a])› have "iy < length σ" 
      by simp
    with aux1 ‹x ∈ V› ‹x ∉ set (take iy (σ @ [a]))› have "take iy (ℬ ?y) ≥ take iy (ℬ x)" 
      by simp
    with ‹iy < length σ› aux3 show ?thesis 
      by simp
  qed
qed


lemma label_iff_connected_next: 
  assumes aux2: "label_iff_connected ℬ σ" and aux3: "label_len_eq ℬ σ"
  shows "label_iff_connected (λy. ℬ y @[a∼y]) (σ@[a])"
  unfolding label_iff_connected_def
proof (intro allI impI)
  fix iy x assume "iy < length (σ@[a])"
  then consider (lt) "iy < length σ" | (eq) "iy = length σ" 
    by fastforce
  thus "(ℬ x @[a∼x])!iy = (σ@[a])!iy ∼x"
  proof cases
    case lt
    with aux2 aux3 show ?thesis 
      by simp
  next 
    case eq
    with aux3 have "length (ℬ x) = iy" 
      by simp
    with eq show ?thesis 
      by (metis nth_append_length)
  qed
qed


lemma label_len_eq_next:
  "label_len_eq ℬ σ ⟹ label_len_eq (λy. ℬ y @ [x∼y]) (σ@[x])"
  unfolding label_len_eq_def 
  by simp

subsection ‹Soundness of term‹lexbfs_bin››
proposition lexbfs_bin_sound: "lexbfs_bin ≤ SPEC is_lexbfs" 
  unfolding lexbfs_bin_def  
  apply (refine_vcg WHILEIT_rule[where I="lexbfs_bin_INV" and R="measure (λ (U, ℬ, σ) . card U)"])
  subgoal ― ‹Wellfoundedness of measure›
    by simp           
  subgoal ― ‹Initialization: term‹lexbfs_bin_INV› holds for initial state›
    by (simp add: partition_V_def label_le_earlier_def 
        label_iff_connected_def label_len_eq_def) 
  subgoal ― ‹Preservation: term‹lexbfs_bin_INV› preserved at each WHILE-step›
    by (auto simp add: partition_V_next label_le_earlier_next 
        label_iff_connected_next label_len_eq_next)
  subgoal ― ‹Termination: measure strictly decreases› 
    by clarify (simp add: U_finite_if_partition_V card_gt_0_iff)
  subgoal ― ‹Soundness: term‹lexbfs_bin_INV› on terminal state implies term‹is_lexbfs››
    by (auto simp add: is_lexbfs_if_INV)
  done


subsection ‹term‹lexbfs› refines term‹lexbfs_bin››
text ‹For ease, we use an intermediate algorithm, where each label is also updated outside of term‹U›.›
definition lexbfs_helper where "lexbfs_helper = do {
      (i, U, ℒ, σ) ← WHILET (λ(i, U, ℒ, σ). U ≠ {}) (λ(i, U, ℒ, σ). do {
       x <- RES {x ∈ U. ℒ x = Max (ℒ ` U)};
       let U = U - {x};
       ― ‹Also updates vertices already checked›
       let ℒ = (λy. if x ∼ y then ℒ y @ [i] else ℒ y);
       RETURN (i - 1, U, ℒ, σ @ [x])
}) (card V, V, λ _ . [], []);
     RETURN σ 
}"


text ‹Transforms the list of Booleans by placing term‹V›-index on term‹True›, and removing term‹False›.›
fun transform_bin :: "nat ⇒ bool list ⇒ nat list" where
  "transform_bin _ [] = []" |
  "transform_bin n (False#xs) = transform_bin (n-1) xs"|
  "transform_bin n (True#xs) = n # transform_bin (n-1) xs"


lemma transform_bin_split[simp]: "transform_bin n (xs @ ys) = transform_bin n xs @ transform_bin (n - length xs) ys"
  by (induct n xs rule: transform_bin.induct) simp_all

lemma hd_transform_bin_le[dest]: "transform_bin n xs = a # as ⟹ a ≤ n"
  by (induction n xs rule: transform_bin.induct) simp_all

text ‹A rephrasing of term‹transform_bin (Suc n) (x#xs)› and term‹transform_bin (Suc n) (y#ys)›,
  when term‹x<y›, i.e. term‹x=False› and term‹y=True›.›
lemma transform_bin_decreasing[simp]: "transform_bin n xs < Suc n # transform_bin n ys" 
  by (cases "transform_bin n xs") auto

proposition transform_bin_le_iff: 
  "⟦length xs = length ys; length ys ≤ n⟧ ⟹  xs ≤ ys ⟷ transform_bin n xs ≤ transform_bin n ys"
proof (induct xs ys arbitrary: n rule: list_induct2)
  case (Cons x xs y ys)
  thus ?case proof (cases n)
    case (Suc k) ― ‹term‹n = Suc k››
    with Cons have hyp: "transform_bin k xs ≤ transform_bin k ys ⟷ xs ≤ ys" 
      by simp
    from Cons_le_Cons have
      "x#xs ≤ y#ys ⟷ x < y ∨ x = y ∧ xs ≤ ys" 
      "¬ x#xs ≤ y#ys ⟷ x > y ∨ x = y ∧ xs > ys" 
      by auto
    moreover {
      assume  "x<y"  
      hence "transform_bin n (x#xs) < transform_bin n (y#ys)" 
        by (simp add: Suc)
      hence   "transform_bin n (x#xs) ≤ transform_bin n (y#ys)" 
        by simp
    }
    moreover { 
      assume "x=y" "xs≤ys"
      with hyp have "transform_bin n (x#xs) ≤ transform_bin n (y#ys)" 
        by (auto simp add: Suc)
    }
    moreover {
      assume "x=y" "xs > ys"
      with hyp have "transform_bin n (x#xs) > transform_bin n (y#ys)" 
        by (auto simp add: Suc)
    }
    moreover {
      assume  "x>y"  
      hence "transform_bin n (x#xs) > transform_bin n (y#ys)" 
        by (simp add: Suc)
    }
    ultimately show ?thesis using not_le by blast
  qed simp
qed simp

text ‹Maps the binary label function term‹ℬ› to the ordinary label function term‹ℒ›,
  except this term‹ℒ› also updates value of vertices already processed.›
abbreviation "transform_B ℬ x ≡ transform_bin (card V) (ℬ x)"

lemma transform_B_refl_Max: "⟦partition_V U σ; label_len_eq ℬ σ; x ∈ U⟧ 
  ⟹ ℬ x = Max (ℬ ` U) ⟷  transform_B ℬ x = Max (transform_B ℬ ` U)"
  using transform_bin_le_iff[where xs = "ℬ _" and ys ="ℬ _" and n="card V"]
  by (simp add: card_V_split_if_partition_V  U_finite_if_partition_V len_sigma_if_partition_V 
      eq_Max_iff memb_imp_not_empty)


text ‹Note: The term‹Id› allows us to specify what relation these algorithms are equal through.
So the outer monad (that returns term‹σ› after while loop exits) is completely equal, while the WHILE
loops are refined through the relation below.›
abbreviation "R_helper_bin ≡ {(b, (U, ℬ, σ)). b = (card U, U, transform_B ℬ, σ)}"

lemma lexbfs_helper_refines_lexbfs_bin: "lexbfs_helper ≤ ⇓ Id lexbfs_bin"
  unfolding lexbfs_helper_def lexbfs_bin_def
  apply (refine_rcg WHILET_refine'[where R = R_helper_bin])
  subgoal ― ‹Initialization: Initial states related›
    by simp
  subgoal ― ‹Termination: Related states exit WHILE loop at same time›
    by simp
  subgoal ― ‹Step: Related states refine› 
    by (auto simp add: transform_B_refl_Max) 
  subgoal ― ‹Preservation: WHILE loop preserves relation›
    by (auto simp add: card_V_split_if_partition_V)
  subgoal ― ‹Return: Related states return same list at end›
    by simp
  done

text ‹The relation that identifies term‹lexbfs_helper› and term‹lexbfs›. Note that this relation is symmetric,
so we can reuse it later when we show term‹lexbfs_helper ≤ lexbfs›.›
abbreviation "R_lexbfs_helper ≡ {((i, U, ℒ, σ), (i', U', ℒ', σ')) . 
  i = i' ∧ U = U' ∧ σ = σ' ∧ (∀ x ∈ U' . ℒ x = ℒ' x)}"

lemma lexbfs_refines_lexbfs_helper: "lexbfs ≤ ⇓ Id lexbfs_helper"
  unfolding lexbfs_def lexbfs_helper_def
  by (refine_rcg  WHILET_refine[where R = R_lexbfs_helper]) auto 

subsection ‹Soundness of term‹lexbfs››
text ‹Combining the previous results, and using transitivity of refinement, we can now show that
LexBFS is sound with regard to the specification term‹is_lexbfs›. In other words: Any list that can be
produced by the term‹lexbfs› algorithm satisfies the term‹lexbfs_prop›.›
theorem lexbfs_sound: "lexbfs ≤ SPEC is_lexbfs"
  using 
    lexbfs_bin_sound 
    lexbfs_helper_refines_lexbfs_bin
    lexbfs_refines_lexbfs_helper
  by simp



section ‹Completeness›
subsection ‹Completeness of term‹lexbfs_bin››
subsubsection ‹Reconstructing the state of term‹lexbfs_bin››
text ‹By definition of the binary label-function term‹ℬ›, and as indicated by the invariant
term‹label_iff_connected›, it is possible and easy to obtain term‹ℬ› from the currently picked vertices term‹σ›.›
definition "construct_B σ y ≡  map (λx. x∼y) σ"

lemma construct_B_empty[simp]: "construct_B [] = (λ _ . []) "
  unfolding construct_B_def 
  by simp_all

lemma construct_B_tail[simp]: "construct_B (σ@[x]) y = construct_B σ y @ [x∼y]"
  by (simp add: construct_B_def)

text ‹The constructed term‹ℬ› automatically satisfies two of our auxiliary invariants:
term‹label_len_eq› and term‹label_iff_connected›.›
lemma construct_B_iff_connected: 
  "i < length σ ⟹ construct_B σ a ! i < construct_B σ b ! i ⟷ σ!i ∼* a ∧ σ!i ∼b"
  by (simp add: construct_B_def)

lemma construct_B_label_iff_connected: "label_iff_connected (construct_B σ) σ"
  by (simp add: construct_B_def label_iff_connected_def)

text ‹By making this a simp rule, we also easily obtain that
  term‹length (construct_B σ x) = length (construct_B σ y)›,
  for any term‹x›, term‹y›.›
lemma construct_B_len_eq_sigma[simp]: "length (construct_B σ x) = length σ"
  by (simp add: construct_B_def)

lemma construct_B_len_eq[simp]: "label_len_eq (construct_B σ) σ"
  by (simp add: label_len_eq_def)


text ‹Reconstruction of term‹U› given the currently picked vertices term‹σ›. We hide this behind a definition,
as being able to control what is expanded through the simp rules below is very useful in the
@{method refine_rcg} proofs, as those have a lot of assumptions and statements in them.›
definition "U_at σ ≡ V - set σ"

lemma U_at_finite[simp]: "finite (U_at σ)"
  by (simp add: finite_vertex_set U_at_def)

lemma U_at_eq_rest: "is_lexbfs (σ @ σ_rest) ⟹ U_at σ = set σ_rest"
  by (auto simp add: U_at_def is_lexbfs_def)

lemma U_at_not_empty: "is_lexbfs (σ @ a # σ_rest) ⟹ U_at σ ≠ {}"
  by (auto simp add: U_at_def is_lexbfs_def)

lemma U_at_empty[simp]: "is_lexbfs σ ⟹ U_at σ = {}"
  by (simp add: is_lexbfs_def U_at_def)

lemma U_at_empty_eq_V[simp]: "U_at [] = V"
  by (simp add: U_at_def)

lemma U_at_next: "x ∈ U_at σ ⟹ U_at (σ @ [x]) = U_at σ - {x}"
  by (auto simp add: U_at_def)

text ‹We also add an abbreviation for the reconstructed state.›
abbreviation "bin_state_at σ ≡ (U_at σ, construct_B σ, σ)"



text ‹By ∗‹candidate› we mean that it can be picked in a given step of the algorithm.›
abbreviation "candidates σ ≡ {x ∈ U_at σ . construct_B σ x = Max (construct_B σ ` U_at σ)}"



text ‹This shows that it is always possible to pick a next element to add to term‹σ›, i.e. that the
algorithm can't fail.›
lemma obtains_candidate: assumes "is_lexbfs (σ @ a # σ_rest)"
  obtains x where "x ∈ candidates σ"
proof atomize_elim
  from assms have "finite (U_at σ)" "U_at σ ≠ {}" 
    by(simp_all add: U_at_eq_rest)
  thus "∃x. x ∈ candidates σ"
    by (metis (mono_tags, lifting) obtains_MAX mem_Collect_eq)
qed

text ‹The main lemma of this section -- if a full list satisfies the LexBFS property, then
any element inside this list is a possible pick by the algorithm, if we reconstruct the state from
the elements preceding it. This is the major step in showing completeness of the Binary LexBFS,
i.e. that any list satisfying term‹is_lexbfs› can be produced by term‹lexbfs_bin›. The proof follows the
mathematical proof from Brandst{\"{a}}dt et al.~cite‹DraganNB97›.›
lemma candidate_if_is_lexbfs:
  assumes is_lexbfs: "is_lexbfs (σ @ a # σ_rest)" (is "is_lexbfs ?σ_all")
  shows "a ∈ candidates σ"
proof (rule ccontr)
  let ?ia = "length σ" and ?ℬ = "construct_B σ"
  let ?a = "?σ_all!?ia"
  assume "a ∉ candidates σ" ― ‹Contradiction-assumption›

  moreover from is_lexbfs have "U_at σ = set (a # σ_rest)"
    by (simp add: U_at_eq_rest)

  moreover from is_lexbfs obtain x where "x ∈ candidates σ"
    using obtains_candidate 
    by blast

  ultimately have "x ∈ set σ_rest" by auto
  then obtain i where "i < length σ_rest" "σ_rest!i = x" 
    by (meson in_set_conv_nth)
  hence "?σ_all! (length σ + Suc i) = x" (is "?x = x")
    by (metis nth_Cons_Suc nth_append_length_plus)
  let ?ix = "length σ + Suc i"
  from ‹U_at σ = set (a # σ_rest)› have "a ∈ U_at σ"
    by simp
  with ‹x ∈ candidates σ› ‹a ∉ candidates σ› have "?ℬ a < ?ℬ x"
    by (fastforce simp add: order_less_le)  
  hence "?ℬ ?a < ?ℬ ?x"
    using ‹?x = x›
    by simp
  then obtain ib
    where "ib < length σ" 
      and "?ℬ ?a ! ib < ?ℬ ?x ! ib" 
      and "∀ j < ib . ?ℬ ?a ! j = ?ℬ ?x ! j"
    by (metis list_lt_iff_ind_lt construct_B_len_eq_sigma)
  let ?b = "?σ_all!ib"  
  from ‹ib < length σ› ‹?ℬ ?a ! ib < ?ℬ ?x ! ib› have "?b ∼ ?x" and "?b ∼* ?a"
    using construct_B_iff_connected
    by fastforce+

  moreover from  ‹i < length σ_rest› ‹ib < length σ› have "triple ?σ_all ib ?ia ?ix"
    by simp

  ultimately obtain iz where "iz < ib" "?σ_all!iz ∼* ?x" "?σ_all!iz ∼ ?a" 
    using is_lexbfs lexbfs_prop_def unfolding is_lexbfs_def
    by blast
  hence "?ℬ ?a ! iz > ?ℬ ?x ! iz" using ‹ib < length σ› 
    using construct_B_iff_connected
    by fastforce
  thus False using ‹∀j<ib. ?ℬ ?a ! j = ?ℬ ?x ! j› ‹iz < ib› 
    by simp
qed



subsubsection ‹Preservation of the constructed state›


text ‹For this step, we want to talk about specific steps of the ∗‹binary› algorithm.
In the following, we need to show that the reconstructed state is preserved at each step,
i.e. that what we reconstruct corresponds to what the algorithm outputs. For this, it will be
useful to be able to keep parts of the loop from unfolding, and enabling starting the algorithm at
a separate step, hence the three sub-definitions in the following.›
definition "bin_step ≡ λ (U, ℬ, σ) . do {
  x <- RES {x ∈ U . ℬ x = Max (ℬ ` U)};
  let U = U - {x};
  let ℬ = (λy . ℬ y @ [x ∼ y]);
  RETURN (U, ℬ, σ @ [x])
}"

definition "bin_loop ≡  WHILET (λ(U, ℬ, σ) . U ≠ {}) bin_step"

text ‹Note that, disregarding the added invariant, text‹lexbfs_bin_in_steps = lexbfs_bin›. We therefore
name any theorem relating to text‹lexbfs_bin_in_steps› with the name text‹lexbfs_bin›. At the end, when we
have shown LexBFS to be correct (i.e. sound and complete), we will use this to prove that
text‹lexbfs_bin_in_steps = lexbfs_bin›.›
definition "lexbfs_bin_in_steps ≡ do {
  (U, ℬ, σ) <- bin_loop (bin_state_at []);
  RETURN σ
}"

text ‹We also need that term‹bin_loop› cannot fail. This amounts to just carefully unfolding the
definition the right amount, as it follows from term‹U› being finite and not empty.›
lemma nofail_bin_loop: "finite U ⟹ nofail (bin_loop (U, ℬ, σ))"
  apply (induct "card U" arbitrary: U ℬ σ)
  subgoal by (simp add: bin_loop_def WHILET_unfold) 
  subgoal 
    by (subst bin_loop_def,
        subst WHILET_unfold,
        subst bin_loop_def[symmetric],
        simp add: pw_bind_nofail bin_step_def)
  done

text ‹The following are many lemmas that show that
the possible results starting at the constructed state at term‹σ @ [a]› are contained in the
results starting at term‹σ›.›

text ‹Abbreviation for term‹inres›, that flips order and adds infix notation, to make results
more readable. Note that the text‹∈› is bold, unlike normal set-membership.›
abbreviation inres_rev (infix "∈" 50) where "inres_rev x y ≡ inres y x "

text ‹Next element in list can be picked by term‹bin_step›.›
lemma inres_bin_step_if_is_lexbfs: 
  "is_lexbfs (σ @ a#σ') ⟹ bin_state_at (σ @ [a]) ∈ bin_step (bin_state_at σ)"
  using candidate_if_is_lexbfs
  by(auto simp add: U_at_next bin_step_def pw_bind_inres)

text ‹Full list can be output, starting at any split.›
lemma inres_bin_loop_if_is_lexbfs: 
  "is_lexbfs (σ @ σ') ⟹ bin_state_at (σ @ σ') ∈ bin_loop (bin_state_at σ)"
proof (induct σ' arbitrary: σ)
  case (Cons a σ' σ) ― ‹Full list is term‹σ @ a#σ'›, induction hypothesis applies to term‹σ @ [a]››
  then have "bin_step (bin_state_at σ) ⤜ bin_loop ≤ bin_loop (bin_state_at σ)"
    by(simp add: WHILET_unfold bin_loop_def U_at_not_empty)

  moreover from Cons.prems have "bin_state_at (σ @ [a]) ∈ bin_step (bin_state_at σ)"
    using inres_bin_step_if_is_lexbfs 
    by simp

  ultimately have "bin_loop (bin_state_at (σ @ [a])) ≤ bin_loop (bin_state_at σ)"
    by (auto simp add: pw_bind_le_iff nofail_bin_loop finite_vertex_set)

  moreover from Cons have "bin_state_at (σ @ a#σ') ∈ bin_loop (bin_state_at (σ @ [a]))"
    by (metis append.assoc append_Cons empty_append_eq_id)

  ultimately show  "bin_state_at (σ @ a # σ') ∈ bin_loop (bin_state_at σ)"
    by (simp add: pwD2) 
qed (simp add: WHILET_unfold is_lexbfs_def bin_loop_def)

text ‹Full list is valid output.›
lemma inres_lexbfs_bin_if_is_lexbfs: "is_lexbfs σ ⟹ σ ∈ lexbfs_bin_in_steps"
  using inres_bin_loop_if_is_lexbfs[of "[]" σ]
  by (auto simp add: pw_bind_inres lexbfs_bin_in_steps_def)

lemma lexbfs_bin_complete: "SPEC is_lexbfs ≤ lexbfs_bin_in_steps"
  by (simp add: lhs_step_SPEC[folded inres_def] inres_lexbfs_bin_if_is_lexbfs)



subsection ‹term‹lexbfs_bin› refines term‹lexbfs››
text ‹The inverse sequence of refinements.
We construct the ordinary label function term‹ℒ› by first constructing term‹ℬ›, and then transforming it.›
abbreviation "R_bin_helper ≡ {((U, ℬ, σ), b).
  b = (card U, U, transform_B (construct_B σ), σ) ∧ 
  ℬ = construct_B σ ∧ 
  U = U_at σ ∧ 
  partition_V U σ}"

lemma lexbfs_bin_refines_lexbfs_helper: "lexbfs_bin_in_steps ≤ ⇓ Id lexbfs_helper"
  unfolding lexbfs_helper_def lexbfs_bin_in_steps_def bin_loop_def bin_step_def
  apply (refine_rcg WHILET_refine[where R = "R_bin_helper"])
  subgoal by (simp) 
  subgoal by simp 
  subgoal by (auto simp add: transform_B_refl_Max) 
  subgoal by (auto simp add: partition_V_next U_at_next card_V_split_if_partition_V)
  subgoal by simp
  done


lemma lexbfs_helper_refines_lexbfs: "lexbfs_helper ≤ ⇓ Id lexbfs"
  unfolding lexbfs_def lexbfs_helper_def 
  by (refine_rcg WHILET_refine[where R = "R_lexbfs_helper"]) auto


subsection ‹Completeness of term‹lexbfs››
theorem lexbfs_complete: "SPEC is_lexbfs ≤ lexbfs"
  using 
    lexbfs_helper_refines_lexbfs
    lexbfs_bin_refines_lexbfs_helper
    lexbfs_bin_complete
  by simp

section ‹Correctness›
corollary lexbfs_correct: "lexbfs = SPEC is_lexbfs"
  using lexbfs_complete lexbfs_sound 
  by simp

text ‹By squeezing the different algorithms in between term‹lexbfs› and term‹SPEC is_lexbfs›, we can show they
are all equivalent. In particular, none of the algorithms can fail.›
corollary lexbfs_equiv: 
  "lexbfs = lexbfs_bin"
  "lexbfs = lexbfs_helper"
  "lexbfs = lexbfs_bin_in_steps"
  using
    lexbfs_bin_complete
    lexbfs_bin_refines_lexbfs_helper
    lexbfs_helper_refines_lexbfs_bin
    lexbfs_bin_sound
    lexbfs_correct
  by simp_all

corollary lexbfs_nofail:
  "nofail lexbfs"
  "nofail lexbfs_helper"
  "nofail lexbfs_bin"
  "nofail lexbfs_bin_in_steps"
  using lexbfs_correct lexbfs_equiv
  by simp_all

end ― ‹Graph locale end›

(*<*)
end
(*>*)